@shware/workflow 6.0.0 → 6.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +86 -32
  2. package/dist/client.cjs +34 -11
  3. package/dist/client.cjs.map +1 -1
  4. package/dist/client.d.cts +16 -2
  5. package/dist/client.d.cts.map +1 -1
  6. package/dist/client.d.mts +16 -2
  7. package/dist/client.d.mts.map +1 -1
  8. package/dist/client.mjs +34 -11
  9. package/dist/client.mjs.map +1 -1
  10. package/dist/cloudflare/index.cjs +2 -2
  11. package/dist/cloudflare/index.mjs +2 -2
  12. package/dist/email-sender.cjs +2 -1
  13. package/dist/email-sender.cjs.map +1 -1
  14. package/dist/email-sender.d.cts +4 -3
  15. package/dist/email-sender.d.cts.map +1 -1
  16. package/dist/email-sender.d.mts +4 -3
  17. package/dist/email-sender.d.mts.map +1 -1
  18. package/dist/email-sender.mjs +2 -1
  19. package/dist/email-sender.mjs.map +1 -1
  20. package/dist/email.cjs +38 -10
  21. package/dist/email.cjs.map +1 -1
  22. package/dist/email.d.cts +43 -12
  23. package/dist/email.d.cts.map +1 -1
  24. package/dist/email.d.mts +43 -12
  25. package/dist/email.d.mts.map +1 -1
  26. package/dist/email.mjs +36 -11
  27. package/dist/email.mjs.map +1 -1
  28. package/dist/engine/ports.d.cts +6 -0
  29. package/dist/engine/ports.d.cts.map +1 -1
  30. package/dist/engine/ports.d.mts +6 -0
  31. package/dist/engine/ports.d.mts.map +1 -1
  32. package/dist/host/channels.cjs +17 -1
  33. package/dist/host/channels.cjs.map +1 -1
  34. package/dist/host/channels.d.cts.map +1 -1
  35. package/dist/host/channels.d.mts.map +1 -1
  36. package/dist/host/channels.mjs +17 -1
  37. package/dist/host/channels.mjs.map +1 -1
  38. package/dist/host/http.cjs +39 -4
  39. package/dist/host/http.cjs.map +1 -1
  40. package/dist/host/http.d.cts +1 -1
  41. package/dist/host/http.d.cts.map +1 -1
  42. package/dist/host/http.d.mts +1 -1
  43. package/dist/host/http.d.mts.map +1 -1
  44. package/dist/host/http.mjs +40 -5
  45. package/dist/host/http.mjs.map +1 -1
  46. package/dist/host/ingest.cjs +49 -1
  47. package/dist/host/ingest.cjs.map +1 -1
  48. package/dist/host/ingest.d.cts +28 -0
  49. package/dist/host/ingest.d.cts.map +1 -1
  50. package/dist/host/ingest.d.mts +28 -0
  51. package/dist/host/ingest.d.mts.map +1 -1
  52. package/dist/host/ingest.mjs +47 -2
  53. package/dist/host/ingest.mjs.map +1 -1
  54. package/dist/index.cjs +3 -0
  55. package/dist/index.d.cts +2 -2
  56. package/dist/index.d.mts +2 -2
  57. package/dist/index.mjs +2 -2
  58. package/dist/react-email.cjs +6 -5
  59. package/dist/react-email.cjs.map +1 -1
  60. package/dist/react-email.d.cts.map +1 -1
  61. package/dist/react-email.d.mts.map +1 -1
  62. package/dist/react-email.mjs +6 -5
  63. package/dist/react-email.mjs.map +1 -1
  64. package/dist/reporting/observer.cjs +3 -1
  65. package/dist/reporting/observer.cjs.map +1 -1
  66. package/dist/reporting/observer.d.cts +2 -1
  67. package/dist/reporting/observer.d.cts.map +1 -1
  68. package/dist/reporting/observer.d.mts +2 -1
  69. package/dist/reporting/observer.d.mts.map +1 -1
  70. package/dist/reporting/observer.mjs +3 -1
  71. package/dist/reporting/observer.mjs.map +1 -1
  72. package/dist/reporting/tracking.cjs +3 -0
  73. package/dist/reporting/tracking.cjs.map +1 -1
  74. package/dist/reporting/tracking.d.cts +2 -0
  75. package/dist/reporting/tracking.d.cts.map +1 -1
  76. package/dist/reporting/tracking.d.mts +2 -0
  77. package/dist/reporting/tracking.d.mts.map +1 -1
  78. package/dist/reporting/tracking.mjs +3 -1
  79. package/dist/reporting/tracking.mjs.map +1 -1
  80. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ingest.mjs","names":[],"sources":["../../src/host/ingest.ts"],"sourcesContent":["import { murmur3 } from '../engine/bucket';\nimport {\n DEVICES_UPDATED_EVENT,\n evaluateCondition,\n matchesWhere,\n profileUpdatedEvent,\n} from '../engine/condition';\nimport { RECIPIENT_PROPERTY } from '../engine/recipient';\nimport { semanticHash } from '../hash';\nimport { BundleIR, type ConditionIR, type TriggerIR } from '../ir';\nimport { JourneyFactSource } from '../store/facts';\nimport {\n type BundleVersion,\n type JourneyStore,\n type ProfileProps,\n SchemaMismatchError,\n type SegmentTriggerRoute,\n type SuppressionChange,\n UserErasedError,\n} from '../store/index';\nimport {\n InstanceNotFoundError,\n type JourneyEnv,\n type JourneyParams,\n WAKE_EVENT_TYPE,\n type WorkflowInstanceLike,\n} from './platform';\n\n/**\n * Ingest: what the host does with what comes in, HTTP aside (that is `http.ts`). An incoming\n * event does four things: it is stored, it wakes waiting instances, it is matched against event\n * triggers, and it re-evaluates segment-trigger membership. An identify merges a profile, which\n * wakes the waits on the properties it patched and re-evaluates segment triggers too. Plus\n * devices, subscriptions, erasure, the segment sweep and bundle deploys.\n *\n * Storage goes through a JourneyStore; every entry point takes the one the host opened.\n */\n\n/**\n * The fast answer for a user with an erasure tombstone (being erased, or erased for good): every\n * ingest-side entry point starts here and does no work for them. The gate itself is the store's\n * conditional write, which throws the same error when the tombstone lands after this check.\n */\nasync function refuseIfErased(store: JourneyStore, userId: string): Promise<void> {\n if ((await store.erasureState(userId)) !== 'none') throw new UserErasedError(userId);\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\n): Promise<IngestResult> {\n if (input.event.startsWith('$')) {\n throw new Error(`event name '${input.event}' is reserved ('$' prefix is internal)`);\n }\n // Also reached from a running instance's send_event: an erased user's instances are stopped\n // before the erase, so one that still gets here is refused like any other writer\n await refuseIfErased(store, input.userId);\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\n/**\n * Wake every instance of the user waiting on any of `events`, once each: an instance subscribed\n * to several of them (a wait on two profile properties, patched together) gets one wake-up, and\n * the payload names the first event it matched.\n */\nexport async function wakeSubscribers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n events: readonly string[]\n): Promise<number> {\n const handles = new Map<string, string>(); // handle → the event that matched it first\n for (const event of events) {\n for (const handle of await store.findWakeHandles(userId, event)) {\n if (!handles.has(handle)) handles.set(handle, event);\n }\n }\n let woke = 0;\n for (const [handle, event] of handles) {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(handle);\n } catch (error) {\n // Unknown instance (errored out without cleanup): drop the dangling subscription. Any\n // other failure (a database blip) keeps it: deleting would silence the wait for good\n if (error instanceof InstanceNotFoundError) await store.unsubscribe(handle);\n else console.warn(`[workflow] looking up ${handle} to wake it failed`, error);\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 route.version\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; version?: string }[]>(\n segments.map((name) => [name, []])\n );\n for (const route of routes) {\n const list = bySegment.get(route.segment) ?? [];\n list.push({\n workflow: route.workflow,\n hash: route.hash,\n ...(route.version === undefined ? {} : { version: route.version }),\n });\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(\n env,\n store,\n route.workflow,\n route.hash,\n userId,\n ts,\n { event: '$segment_entry', payload: { segment: segmentId } },\n route.version\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/** How many users one sweep page evaluates: a unit of resumable work (AWS checkpoints each). */\nexport const SWEEP_PAGE_SIZE = 500;\n\n/**\n * What the sweep does before it looks at any user: the runtime's own upkeep (AWS: unconfirmed\n * starts, executions that ended unseen) and the erasures left unfinished (an instance would not\n * stop). A failure of either is logged, never fatal: the pages still run. Users whose erasure is\n * still pending afterwards are skipped by every page (`sweepSegmentsPaged`).\n */\nexport async function sweepMaintenance(env: JourneyEnv, store: JourneyStore): Promise<void> {\n try {\n await env.JOURNEY.maintain?.();\n } catch (error) {\n console.error('[workflow] runtime maintenance failed', error);\n }\n // Erasures left pending (an admitted instance would not stop, or is still draining): retried\n // until every one of them is confirmed stopped and the data is gone\n for (const userId of await store.pendingErasures()) {\n try {\n await eraseUser(env, userId, store, Date.now());\n } catch (error) {\n // Still pending: the next sweep tries again, and the rest of this one goes on\n console.error(`[workflow] erasure of ${userId} failed`, error);\n }\n }\n}\n\nexport interface SweepPage {\n /** Users evaluated on this page (those being erased are listed but skipped). */\n users: number;\n /** Journeys the segments' entries started on this page. */\n started: string[];\n /** The last user id listed, to resume past (`after`); undefined when the page was empty. */\n lastUserId?: string | undefined;\n /** Whether the page was full, so another may follow. */\n more: boolean;\n}\n\n/**\n * One page of the sweep: the users after `after` (ascending, at most `limit`), every deployed\n * segment evaluated for each. The pages are what makes the sweep resumable — a host whose run\n * can be cut short (a Lambda timeout) checkpoints each one and replays the checkpointed pages\n * instead of starting over; `sweepSegments` is the plain loop over them.\n */\nexport async function sweepSegmentsPaged(\n env: JourneyEnv,\n store: JourneyStore,\n page: { after?: string | undefined; limit?: number | undefined; now?: number | undefined }\n): Promise<SweepPage> {\n const now = page.now ?? Date.now();\n const limit = page.limit ?? SWEEP_PAGE_SIZE;\n const segments = (await store.listSegments()).map((segment) => segment.id);\n const routes = await store.listSegmentTriggers();\n // Read per page, not once up front: an erasure requested since the last page is honored too\n const erasing = new Set(await store.pendingErasures());\n const listed = await store.listUserIds({ after: page.after, limit });\n const lastUserId = listed.at(-1);\n // A store that ignores `after` would hand back the same page forever: refuse to loop on it.\n // Equality only — the order is the store's collation, which JavaScript's `<` does not know\n if (page.after !== undefined && lastUserId === page.after) {\n throw new Error(`listUserIds did not advance past ${page.after}: the store ignores 'after'`);\n }\n const users = listed.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 return { users: users.length, started, lastUserId, more: listed.length >= limit };\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 page by page (`sweepSegmentsPaged`): fine for thousands, a large audience wants\n * SQL-side evaluation.\n */\nexport async function sweepSegments(\n env: JourneyEnv,\n store: JourneyStore,\n now = Date.now()\n): Promise<SweepResult> {\n await sweepMaintenance(env, store);\n let users = 0;\n const started: string[] = [];\n let after: string | undefined;\n for (;;) {\n const page = await sweepSegmentsPaged(env, store, { after, limit: SWEEP_PAGE_SIZE, now });\n users += page.users;\n started.push(...page.started);\n if (!page.more || page.lastUserId === undefined) break;\n after = page.lastUserId;\n }\n const sizes = await store.reporting.snapshotSegments(now);\n return { users, 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 /** The code version whose bundle routed this start, read with the hash (see TriggerRoute). */\n version?: string\n): Promise<string | null> {\n const instanceId = buildInstanceId(workflow, hash, userId, ts);\n const params: JourneyParams = { workflowId: workflow, contentHash: hash, userId, trigger };\n const execution = await env.JOURNEY.plan?.({ id: instanceId, params, ts, version });\n\n const outcome = await store.enterJourney({ workflow, userId, instanceId, hash, ts, execution });\n if (outcome === null) {\n // Already entered and still alive — unless its start never got through: this retry is the\n // first chance to finish it\n await env.JOURNEY.resume?.({ workflow, userId });\n return null;\n }\n\n try {\n await env.JOURNEY.create({ id: instanceId, params });\n } catch (error) {\n // A recorded start stays: the runtime may have taken it, and a retry with the same name\n // and payload finds that execution instead of starting a second one\n if (execution !== undefined) throw 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 host 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\n): Promise<IdentifyResult> {\n await refuseIfErased(store, userId);\n const ts = Date.now();\n const merged = await store.mergeProfile(userId, props);\n // A property wait subscribes to its own property's channel (see relevantEvents): only the\n // waits on what this patch touched wake up\n const woke = await wakeSubscribers(\n env,\n store,\n userId,\n Object.keys(props).map(profileUpdatedEvent)\n );\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\n): Promise<{ ok: true; woke: number }> {\n await refuseIfErased(store, device.userId);\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/** Workflow instance states that will never run another step. */\nconst STOPPED_STATUSES = new Set(['complete', 'errored', 'terminated']);\n\n/**\n * Stop one admitted instance for good; true once it is known not to run again: terminated, or\n * already in a terminal state (terminate refuses those). Any other failure is not taken for\n * \"already gone\": it answers false, and the erasure waits for a retry.\n *\n * An admitted instance the platform no longer knows counts as stopped too — but only an\n * admitted one. Admission is the runner's first act, so an admitted instance did reach the\n * runtime: not found now means it finished and was evicted. An entry that is not admitted is\n * never passed here: for it, not found may just as well mean its `create` is still in flight.\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 (error instanceof InstanceNotFoundError) 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 are\n * known not to run erase their data. The tombstone is already committed, so no new entry,\n * event, profile or device of theirs lands meanwhile.\n *\n * An entry's runner admits itself before its first effect (`admitInstance`, mutually exclusive\n * with the tombstone's commit), which splits the running instances in two:\n *\n * - not admitted: nothing of it has run, and nothing will — a `create` still in flight, or a\n * runner invoked later, meets the tombstone at admission and exits. No stop is needed, and\n * none would be reliable: the platform may not know the instance yet.\n * - admitted: it did reach the runtime and must be stopped (`stopInstance`), or it would write\n * rows back after the erase. One that will not stop leaves the erasure pending.\n *\n * Erasing nothing until then keeps the entries that name the instances still to stop, so a\n * retry can finish the job. The tombstone outlives the erase (`erased_at`), which is what makes\n * a repeat idempotent and a late write harmless. There is no straggler to come back for: every\n * write about a user runs in the user's locked transaction, the same lock the tombstone takes,\n * so a write either committed before the tombstone — and `forgetUser` deletes it here — or\n * waited for the lock and is refused by the tombstone it then sees.\n */\nasync function eraseUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore,\n now: number\n): Promise<{ erased: boolean; pending: string[] }> {\n const pending: string[] = [];\n for (const { instanceId, admitted } of await store.runningInstances(userId)) {\n if (!admitted) continue;\n if (!(await stopInstance(env, instanceId))) pending.push(instanceId);\n }\n if (pending.length > 0) return { erased: false, pending };\n await store.forgetUser(userId, now);\n return { erased: true, pending };\n}\n\n/**\n * Forget a user (a deleted account): the tombstone is committed first, then the erasure carried\n * out. `erased: true` means every admitted runner of theirs was confirmed stopped, the entries\n * never admitted can never run, and the data is deleted — for good, with no time window and no\n * second pass: the tombstone commits under the user's lock, which every write about the user\n * also takes, so nothing of theirs can land after it. An admitted instance that will not stop\n * leaves it pending — nothing erased yet — and the scheduled sweep retries it; `erased: false`\n * says so. A user already erased answers `erased: true` again, with nothing to do.\n */\nexport async function forgetUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore,\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, now)) };\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\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\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 * Whether the routes now point at this bundle: always for a forced deploy, false for a\n * versioned one when a version as new or newer is already live (nothing was swapped).\n */\n applied: boolean;\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/**\n * Bundle deploy, terraform-apply style: workflow bodies first (content-addressed, so a failed\n * deploy leaves only harmless orphans), then the routing swap. With a `version` the swap happens\n * only over an older live version (`replaceRoutesIfNewer`) — how journeyWorker applies the bundle\n * compiled into it; without one it is forced, whatever is live.\n */\nexport async function deployBundle(\n env: JourneyEnv,\n bundle: unknown,\n store: JourneyStore,\n version?: BundleVersion\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 let applied = true;\n if (version === undefined) await store.replaceRoutes(parsed);\n else applied = await store.replaceRoutesIfNewer(parsed, version);\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 applied,\n };\n}\n\n/* ------------------------------- subscriptions ------------------------------- */\n\n/** The channels a user opts out of per topic: `suppression` rows are keyed by (user, channel, topic). */\nexport const SUBSCRIPTION_CHANNELS = ['email', 'push'] as const;\nexport type SubscriptionChannel = (typeof SUBSCRIPTION_CHANNELS)[number];\n\n/**\n * Where a user stands with one channel: `true` is subscribed, per topic and for the channel as\n * a whole. The two are independent records: `all: false` masks every topic, whatever `topics`\n * says about it, and `all: true` does not switch a topic back on.\n */\nexport interface ChannelSubscriptions<T extends string = string> {\n /**\n * False once the user opted out of the whole channel (all email, all push). No topic is sent\n * while it is false, however `topics` reads, so a consumer treats it as masking every topic.\n */\n all: boolean;\n /**\n * Each declared topic: false once the user opted out of it on this channel. A topic's flag is\n * its own record, answered as it is even while `all` is false, and it stays false when `all`\n * turns true again until a patch names the topic.\n */\n topics: Record<T, boolean>;\n}\n\n/**\n * A user's subscriptions, topic × channel — what `GET /subscriptions/:userId` answers. Every\n * channel lists every declared topic: a topic is a content category, and the user chooses per\n * channel whether to get it.\n */\nexport interface Subscriptions<T extends string = string> {\n email: ChannelSubscriptions<T>;\n push: ChannelSubscriptions<T>;\n}\n\n/** One channel's part of a patch: only what changes. */\nexport interface ChannelSubscriptionsPatch<T extends string = string> {\n all?: boolean;\n topics?: Partial<Record<T, boolean>>;\n}\n\n/**\n * What `PUT /subscriptions/:userId` takes: only what changes; an omitted channel or field stays\n * as it is. `all: true` clears the channel-wide opt-out only — a topic opted out on its own stays\n * off until the patch names it (a \"subscribe to all\" sends `all: true` plus every topic `true`).\n */\nexport interface SubscriptionsPatch<T extends string = string> {\n email?: ChannelSubscriptionsPatch<T>;\n push?: ChannelSubscriptionsPatch<T>;\n}\n\n/** One field of a patch refused, with the path the producer can fix. */\nexport interface SubscriptionsIssue {\n path: string;\n message: string;\n}\n\n/**\n * A subscriptions patch as it arrives over HTTP: untrusted JSON, read field by field and never\n * cast. Every topic must be one the bundle declares — the engine's list, not the caller's word.\n */\nexport function parseSubscriptionsPatch(\n body: unknown,\n topics: readonly string[]\n): { ok: true; patch: SubscriptionsPatch } | { ok: false; issues: SubscriptionsIssue[] } {\n const issues: SubscriptionsIssue[] = [];\n const object = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n if (!object(body)) return { ok: false, issues: [{ path: '', message: 'must be an object' }] };\n const known = new Set(topics);\n const patch: SubscriptionsPatch = {};\n for (const [channel, value] of Object.entries(body)) {\n if (!(SUBSCRIPTION_CHANNELS as readonly string[]).includes(channel)) {\n issues.push({ path: channel, message: 'not a subscription channel' });\n continue;\n }\n if (!object(value)) {\n issues.push({ path: channel, message: 'must be an object' });\n continue;\n }\n const part: ChannelSubscriptionsPatch = {};\n for (const [field, setting] of Object.entries(value)) {\n if (field === 'all') {\n if (typeof setting === 'boolean') part.all = setting;\n else issues.push({ path: `${channel}.all`, message: 'must be a boolean' });\n } else if (field === 'topics') {\n if (!object(setting)) {\n issues.push({ path: `${channel}.topics`, message: 'must be an object' });\n continue;\n }\n const chosen: Record<string, boolean> = {};\n for (const [topic, subscribed] of Object.entries(setting)) {\n if (!known.has(topic)) {\n issues.push({ path: `${channel}.topics.${topic}`, message: 'not a declared topic' });\n } else if (typeof subscribed !== 'boolean') {\n issues.push({ path: `${channel}.topics.${topic}`, message: 'must be a boolean' });\n } else {\n chosen[topic] = subscribed;\n }\n }\n part.topics = chosen;\n } else {\n issues.push({ path: `${channel}.${field}`, message: 'unknown field' });\n }\n }\n patch[channel as SubscriptionChannel] = part;\n }\n return issues.length > 0 ? { ok: false, issues } : { ok: true, patch };\n}\n\nasync function readSubscriptions(\n store: JourneyStore,\n userId: string,\n topics: readonly string[]\n): Promise<Subscriptions> {\n const read = async (channel: SubscriptionChannel): Promise<ChannelSubscriptions> => {\n const suppressed = new Set(await store.listSuppressions(userId, channel));\n return {\n all: !suppressed.has(null),\n topics: Object.fromEntries(topics.map((topic) => [topic, !suppressed.has(topic)])),\n };\n };\n return { email: await read('email'), push: await read('push') };\n}\n\n/** The user's subscriptions over the declared `topics`; a user with an erasure tombstone is refused. */\nexport async function getSubscriptions(\n store: JourneyStore,\n userId: string,\n topics: readonly string[]\n): Promise<Subscriptions> {\n await refuseIfErased(store, userId);\n return readSubscriptions(store, userId, topics);\n}\n\n/**\n * Apply a patch — each field given sets or clears the matching opt-out, one transaction per\n * channel — and answer the subscriptions as they now stand. A change of a channel's `all` is a\n * change of its reachability, so the waits reading it wake, both ways: an\n * `exitWhen: not(reachable('email'))` fires on the opt-out, and a wait for the channel to become\n * reachable resumes on the opt-in. Email waits key on the address property, push waits on the\n * device channel (`reachable('push')` subscribes to device changes).\n */\nexport async function setSubscriptions(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n patch: SubscriptionsPatch,\n topics: readonly string[],\n now = Date.now()\n): Promise<Subscriptions> {\n await refuseIfErased(store, userId);\n for (const channel of SUBSCRIPTION_CHANNELS) {\n const part = patch[channel];\n if (part === undefined) continue;\n const changes: SuppressionChange[] = [];\n if (part.all !== undefined) changes.push({ topic: null, suppressed: !part.all });\n for (const [topic, subscribed] of Object.entries(part.topics ?? {})) {\n if (subscribed !== undefined) changes.push({ topic, suppressed: !subscribed });\n }\n if (changes.length === 0) continue;\n await store.updateSuppressions(userId, channel, changes, now);\n if (part.all !== undefined) {\n const wake =\n channel === 'push'\n ? DEVICES_UPDATED_EVENT\n : profileUpdatedEvent(RECIPIENT_PROPERTY.email ?? 'email');\n await wakeSubscribers(env, store, userId, [wake]);\n }\n }\n return readSubscriptions(store, userId,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AAI,SAAS,KAAA,GAAW;EACxB,MAAM,UAA+B,CAAC;EACtC,IAAI,KAAK,QAAQ,KAAA,GAAW,QAAQ,KAAK;GAAE,OAAO;GAAM,YAAY,CAAC,KAAK;EAAI,CAAC;EAC/E,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,GAChE,IAAI,eAAe,KAAA,GAAW,QAAQ,KAAK;GAAE;GAAO,YAAY,CAAC;EAAW,CAAC;EAE/E,IAAI,QAAQ,WAAW,GAAG;EAC1B,MAAM,MAAM,mBAAmB,QAAQ,SAAS,SAAS,GAAG;EAC5D,IAAI,KAAK,QAAQ,KAAA,GAKf,MAAM,gBAAgB,KAAK,OAAO,QAAQ,CAHxC,YAAY,SACR,wBACA,oBAAoB,mBAAmB,SAAS,OAAO,CACd,CAAC;CAEpD;CACA,OAAO,kBAAkB,OAAO,QAAQ,MAAM;AAChD"}
1
+ {"version":3,"file":"ingest.mjs","names":[],"sources":["../../src/host/ingest.ts"],"sourcesContent":["import { murmur3 } from '../engine/bucket';\nimport {\n DEVICES_UPDATED_EVENT,\n evaluateCondition,\n matchesWhere,\n profileUpdatedEvent,\n} from '../engine/condition';\nimport { RECIPIENT_PROPERTY } from '../engine/recipient';\nimport { semanticHash } from '../hash';\nimport { BundleIR, type ConditionIR, type TriggerIR } from '../ir';\nimport { isMessageId } from '../reporting/tracking';\nimport { JourneyFactSource } from '../store/facts';\nimport {\n type BundleVersion,\n type JourneyStore,\n type ProfileProps,\n SchemaMismatchError,\n type SegmentTriggerRoute,\n type SuppressionChange,\n UserErasedError,\n} from '../store/index';\nimport {\n InstanceNotFoundError,\n type JourneyEnv,\n type JourneyParams,\n WAKE_EVENT_TYPE,\n type WorkflowInstanceLike,\n} from './platform';\n\n/**\n * Ingest: what the host does with what comes in, HTTP aside (that is `http.ts`). An incoming\n * event does four things: it is stored, it wakes waiting instances, it is matched against event\n * triggers, and it re-evaluates segment-trigger membership. An identify merges a profile, which\n * wakes the waits on the properties it patched and re-evaluates segment triggers too. Plus\n * devices, subscriptions, erasure, the segment sweep and bundle deploys.\n *\n * Storage goes through a JourneyStore; every entry point takes the one the host opened.\n */\n\n/**\n * The fast answer for a user with an erasure tombstone (being erased, or erased for good): every\n * ingest-side entry point starts here and does no work for them. The gate itself is the store's\n * conditional write, which throws the same error when the tombstone lands after this check.\n */\nasync function refuseIfErased(store: JourneyStore, userId: string): Promise<void> {\n if ((await store.erasureState(userId)) !== 'none') throw new UserErasedError(userId);\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\n): Promise<IngestResult> {\n if (input.event.startsWith('$')) {\n throw new Error(`event name '${input.event}' is reserved ('$' prefix is internal)`);\n }\n // Also reached from a running instance's send_event: an erased user's instances are stopped\n // before the erase, so one that still gets here is refused like any other writer\n await refuseIfErased(store, input.userId);\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\n/**\n * Wake every instance of the user waiting on any of `events`, once each: an instance subscribed\n * to several of them (a wait on two profile properties, patched together) gets one wake-up, and\n * the payload names the first event it matched.\n */\nexport async function wakeSubscribers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n events: readonly string[]\n): Promise<number> {\n const handles = new Map<string, string>(); // handle → the event that matched it first\n for (const event of events) {\n for (const handle of await store.findWakeHandles(userId, event)) {\n if (!handles.has(handle)) handles.set(handle, event);\n }\n }\n let woke = 0;\n for (const [handle, event] of handles) {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(handle);\n } catch (error) {\n // Unknown instance (errored out without cleanup): drop the dangling subscription. Any\n // other failure (a database blip) keeps it: deleting would silence the wait for good\n if (error instanceof InstanceNotFoundError) await store.unsubscribe(handle);\n else console.warn(`[workflow] looking up ${handle} to wake it failed`, error);\n continue;\n }\n try {\n await instance.sendEvent({ type: WAKE_EVENT_TYPE, payload: { event } });\n woke++;\n } catch (error) {\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 const message = error instanceof Error ? error.message : String(error);\n console.warn(`[workflow] waking ${handle} on ${event} failed: ${message}`);\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 route.version\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; version?: string }[]>(\n segments.map((name) => [name, []])\n );\n for (const route of routes) {\n const list = bySegment.get(route.segment) ?? [];\n list.push({\n workflow: route.workflow,\n hash: route.hash,\n ...(route.version === undefined ? {} : { version: route.version }),\n });\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(\n env,\n store,\n route.workflow,\n route.hash,\n userId,\n ts,\n { event: '$segment_entry', payload: { segment: segmentId } },\n route.version\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/** How many users one sweep page evaluates: a unit of resumable work (AWS checkpoints each). */\nexport const SWEEP_PAGE_SIZE = 500;\n\n/**\n * What the sweep does before it looks at any user: the runtime's own upkeep (AWS: unconfirmed\n * starts, executions that ended unseen) and the erasures left unfinished (an instance would not\n * stop). A failure of either is logged, never fatal: the pages still run. Users whose erasure is\n * still pending afterwards are skipped by every page (`sweepSegmentsPaged`).\n */\nexport async function sweepMaintenance(env: JourneyEnv, store: JourneyStore): Promise<void> {\n try {\n await env.JOURNEY.maintain?.();\n } catch (error) {\n console.error('[workflow] runtime maintenance failed', error);\n }\n // Erasures left pending (an admitted instance would not stop, or is still draining): retried\n // until every one of them is confirmed stopped and the data is gone\n for (const userId of await store.pendingErasures()) {\n try {\n await eraseUser(env, userId, store, Date.now());\n } catch (error) {\n // Still pending: the next sweep tries again, and the rest of this one goes on\n console.error(`[workflow] erasure of ${userId} failed`, error);\n }\n }\n}\n\nexport interface SweepPage {\n /** Users evaluated on this page (those being erased are listed but skipped). */\n users: number;\n /** Journeys the segments' entries started on this page. */\n started: string[];\n /** The last user id listed, to resume past (`after`); undefined when the page was empty. */\n lastUserId?: string | undefined;\n /** Whether the page was full, so another may follow. */\n more: boolean;\n}\n\n/**\n * One page of the sweep: the users after `after` (ascending, at most `limit`), every deployed\n * segment evaluated for each. The pages are what makes the sweep resumable — a host whose run\n * can be cut short (a Lambda timeout) checkpoints each one and replays the checkpointed pages\n * instead of starting over; `sweepSegments` is the plain loop over them.\n */\nexport async function sweepSegmentsPaged(\n env: JourneyEnv,\n store: JourneyStore,\n page: { after?: string | undefined; limit?: number | undefined; now?: number | undefined }\n): Promise<SweepPage> {\n const now = page.now ?? Date.now();\n const limit = page.limit ?? SWEEP_PAGE_SIZE;\n const segments = (await store.listSegments()).map((segment) => segment.id);\n const routes = await store.listSegmentTriggers();\n // Read per page, not once up front: an erasure requested since the last page is honored too\n const erasing = new Set(await store.pendingErasures());\n const listed = await store.listUserIds({ after: page.after, limit });\n const lastUserId = listed.at(-1);\n // A store that ignores `after` would hand back the same page forever: refuse to loop on it.\n // Equality only — the order is the store's collation, which JavaScript's `<` does not know\n if (page.after !== undefined && lastUserId === page.after) {\n throw new Error(`listUserIds did not advance past ${page.after}: the store ignores 'after'`);\n }\n const users = listed.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 return { users: users.length, started, lastUserId, more: listed.length >= limit };\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 page by page (`sweepSegmentsPaged`): fine for thousands, a large audience wants\n * SQL-side evaluation.\n */\nexport async function sweepSegments(\n env: JourneyEnv,\n store: JourneyStore,\n now = Date.now()\n): Promise<SweepResult> {\n await sweepMaintenance(env, store);\n let users = 0;\n const started: string[] = [];\n let after: string | undefined;\n for (;;) {\n const page = await sweepSegmentsPaged(env, store, { after, limit: SWEEP_PAGE_SIZE, now });\n users += page.users;\n started.push(...page.started);\n if (!page.more || page.lastUserId === undefined) break;\n after = page.lastUserId;\n }\n const sizes = await store.reporting.snapshotSegments(now);\n return { users, 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 /** The code version whose bundle routed this start, read with the hash (see TriggerRoute). */\n version?: string\n): Promise<string | null> {\n const instanceId = buildInstanceId(workflow, hash, userId, ts);\n const params: JourneyParams = { workflowId: workflow, contentHash: hash, userId, trigger };\n const execution = await env.JOURNEY.plan?.({ id: instanceId, params, ts, version });\n\n const outcome = await store.enterJourney({ workflow, userId, instanceId, hash, ts, execution });\n if (outcome === null) {\n // Already entered and still alive — unless its start never got through: this retry is the\n // first chance to finish it\n await env.JOURNEY.resume?.({ workflow, userId });\n return null;\n }\n\n try {\n await env.JOURNEY.create({ id: instanceId, params });\n } catch (error) {\n // A recorded start stays: the runtime may have taken it, and a retry with the same name\n // and payload finds that execution instead of starting a second one\n if (execution !== undefined) throw 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 host 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\n): Promise<IdentifyResult> {\n await refuseIfErased(store, userId);\n const ts = Date.now();\n const merged = await store.mergeProfile(userId, props);\n // A property wait subscribes to its own property's channel (see relevantEvents): only the\n // waits on what this patch touched wake up\n const woke = await wakeSubscribers(\n env,\n store,\n userId,\n Object.keys(props).map(profileUpdatedEvent)\n );\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\n): Promise<{ ok: true; woke: number }> {\n await refuseIfErased(store, device.userId);\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/** Workflow instance states that will never run another step. */\nconst STOPPED_STATUSES = new Set(['complete', 'errored', 'terminated']);\n\n/**\n * Stop one admitted instance for good; true once it is known not to run again: terminated, or\n * already in a terminal state (terminate refuses those). Any other failure is not taken for\n * \"already gone\": it answers false, and the erasure waits for a retry.\n *\n * An admitted instance the platform no longer knows counts as stopped too — but only an\n * admitted one. Admission is the runner's first act, so an admitted instance did reach the\n * runtime: not found now means it finished and was evicted. An entry that is not admitted is\n * never passed here: for it, not found may just as well mean its `create` is still in flight.\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 (error instanceof InstanceNotFoundError) 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 are\n * known not to run erase their data. The tombstone is already committed, so no new entry,\n * event, profile or device of theirs lands meanwhile.\n *\n * An entry's runner admits itself before its first effect (`admitInstance`, mutually exclusive\n * with the tombstone's commit), which splits the running instances in two:\n *\n * - not admitted: nothing of it has run, and nothing will — a `create` still in flight, or a\n * runner invoked later, meets the tombstone at admission and exits. No stop is needed, and\n * none would be reliable: the platform may not know the instance yet.\n * - admitted: it did reach the runtime and must be stopped (`stopInstance`), or it would write\n * rows back after the erase. One that will not stop leaves the erasure pending.\n *\n * Erasing nothing until then keeps the entries that name the instances still to stop, so a\n * retry can finish the job. The tombstone outlives the erase (`erased_at`), which is what makes\n * a repeat idempotent and a late write harmless. There is no straggler to come back for: every\n * write about a user runs in the user's locked transaction, the same lock the tombstone takes,\n * so a write either committed before the tombstone — and `forgetUser` deletes it here — or\n * waited for the lock and is refused by the tombstone it then sees.\n */\nasync function eraseUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore,\n now: number\n): Promise<{ erased: boolean; pending: string[] }> {\n const pending: string[] = [];\n for (const { instanceId, admitted } of await store.runningInstances(userId)) {\n if (!admitted) continue;\n if (!(await stopInstance(env, instanceId))) pending.push(instanceId);\n }\n if (pending.length > 0) return { erased: false, pending };\n await store.forgetUser(userId, now);\n return { erased: true, pending };\n}\n\n/**\n * Forget a user (a deleted account): the tombstone is committed first, then the erasure carried\n * out. `erased: true` means every admitted runner of theirs was confirmed stopped, the entries\n * never admitted can never run, and the data is deleted — for good, with no time window and no\n * second pass: the tombstone commits under the user's lock, which every write about the user\n * also takes, so nothing of theirs can land after it. An admitted instance that will not stop\n * leaves it pending — nothing erased yet — and the scheduled sweep retries it; `erased: false`\n * says so. A user already erased answers `erased: true` again, with nothing to do.\n */\nexport async function forgetUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore,\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, now)) };\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\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\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 * Whether the routes now point at this bundle: always for a forced deploy, false for a\n * versioned one when a version as new or newer is already live (nothing was swapped).\n */\n applied: boolean;\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/**\n * Bundle deploy, terraform-apply style: workflow bodies first (content-addressed, so a failed\n * deploy leaves only harmless orphans), then the routing swap. With a `version` the swap happens\n * only over an older live version (`replaceRoutesIfNewer`) — how journeyWorker applies the bundle\n * compiled into it; without one it is forced, whatever is live.\n */\nexport async function deployBundle(\n env: JourneyEnv,\n bundle: unknown,\n store: JourneyStore,\n version?: BundleVersion\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 let applied = true;\n if (version === undefined) await store.replaceRoutes(parsed);\n else applied = await store.replaceRoutesIfNewer(parsed, version);\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 applied,\n };\n}\n\n/* ------------------------------- subscriptions ------------------------------- */\n\n/** The channels a user opts out of per topic: `suppression` rows are keyed by (user, channel, topic). */\nexport const SUBSCRIPTION_CHANNELS = ['email', 'push'] as const;\nexport type SubscriptionChannel = (typeof SUBSCRIPTION_CHANNELS)[number];\n\n/**\n * Where a user stands with one channel: `true` is subscribed, per topic and for the channel as\n * a whole. The two are independent records: `all: false` masks every topic, whatever `topics`\n * says about it, and `all: true` does not switch a topic back on.\n */\nexport interface ChannelSubscriptions<T extends string = string> {\n /**\n * False once the user opted out of the whole channel (all email, all push). No topic is sent\n * while it is false, however `topics` reads, so a consumer treats it as masking every topic.\n */\n all: boolean;\n /**\n * Each declared topic: false once the user opted out of it on this channel. A topic's flag is\n * its own record, answered as it is even while `all` is false, and it stays false when `all`\n * turns true again until a patch names the topic.\n */\n topics: Record<T, boolean>;\n}\n\n/**\n * A user's subscriptions, topic × channel — what `GET /subscriptions/:userId` answers. Every\n * channel lists every declared topic: a topic is a content category, and the user chooses per\n * channel whether to get it.\n */\nexport interface Subscriptions<T extends string = string> {\n email: ChannelSubscriptions<T>;\n push: ChannelSubscriptions<T>;\n}\n\n/** One channel's part of a patch: only what changes. */\nexport interface ChannelSubscriptionsPatch<T extends string = string> {\n all?: boolean;\n topics?: Partial<Record<T, boolean>>;\n}\n\n/**\n * What `PUT /subscriptions/:userId` takes: only what changes; an omitted channel or field stays\n * as it is. `all: true` clears the channel-wide opt-out only — a topic opted out on its own stays\n * off until the patch names it (a \"subscribe to all\" sends `all: true` plus every topic `true`).\n */\nexport interface SubscriptionsPatch<T extends string = string> {\n email?: ChannelSubscriptionsPatch<T>;\n push?: ChannelSubscriptionsPatch<T>;\n}\n\n/** One field of a patch refused, with the path the producer can fix. */\nexport interface SubscriptionsIssue {\n path: string;\n message: string;\n}\n\n/**\n * A subscriptions patch as it arrives over HTTP: untrusted JSON, read field by field and never\n * cast. Every topic must be one the bundle declares — the engine's list, not the caller's word.\n */\nexport function parseSubscriptionsPatch(\n body: unknown,\n topics: readonly string[]\n): { ok: true; patch: SubscriptionsPatch } | { ok: false; issues: SubscriptionsIssue[] } {\n const issues: SubscriptionsIssue[] = [];\n const object = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n if (!object(body)) return { ok: false, issues: [{ path: '', message: 'must be an object' }] };\n const known = new Set(topics);\n const patch: SubscriptionsPatch = {};\n for (const [channel, value] of Object.entries(body)) {\n if (!(SUBSCRIPTION_CHANNELS as readonly string[]).includes(channel)) {\n issues.push({ path: channel, message: 'not a subscription channel' });\n continue;\n }\n if (!object(value)) {\n issues.push({ path: channel, message: 'must be an object' });\n continue;\n }\n const part: ChannelSubscriptionsPatch = {};\n for (const [field, setting] of Object.entries(value)) {\n if (field === 'all') {\n if (typeof setting === 'boolean') part.all = setting;\n else issues.push({ path: `${channel}.all`, message: 'must be a boolean' });\n } else if (field === 'topics') {\n if (!object(setting)) {\n issues.push({ path: `${channel}.topics`, message: 'must be an object' });\n continue;\n }\n const chosen: Record<string, boolean> = {};\n for (const [topic, subscribed] of Object.entries(setting)) {\n if (!known.has(topic)) {\n issues.push({ path: `${channel}.topics.${topic}`, message: 'not a declared topic' });\n } else if (typeof subscribed !== 'boolean') {\n issues.push({ path: `${channel}.topics.${topic}`, message: 'must be a boolean' });\n } else {\n chosen[topic] = subscribed;\n }\n }\n part.topics = chosen;\n } else {\n issues.push({ path: `${channel}.${field}`, message: 'unknown field' });\n }\n }\n patch[channel as SubscriptionChannel] = part;\n }\n return issues.length > 0 ? { ok: false, issues } : { ok: true, patch };\n}\n\nasync function readSubscriptions(\n store: JourneyStore,\n userId: string,\n topics: readonly string[]\n): Promise<Subscriptions> {\n const read = async (channel: SubscriptionChannel): Promise<ChannelSubscriptions> => {\n const suppressed = new Set(await store.listSuppressions(userId, channel));\n return {\n all: !suppressed.has(null),\n topics: Object.fromEntries(topics.map((topic) => [topic, !suppressed.has(topic)])),\n };\n };\n return { email: await read('email'), push: await read('push') };\n}\n\n/** The user's subscriptions over the declared `topics`; a user with an erasure tombstone is refused. */\nexport async function getSubscriptions(\n store: JourneyStore,\n userId: string,\n topics: readonly string[]\n): Promise<Subscriptions> {\n await refuseIfErased(store, userId);\n return readSubscriptions(store, userId, topics);\n}\n\n/**\n * Apply a patch — each field given sets or clears the matching opt-out, one transaction per\n * channel — and answer the subscriptions as they now stand. A change of a channel's `all` is a\n * change of its reachability, so the waits reading it wake, both ways: an\n * `exitWhen: not(reachable('email'))` fires on the opt-out, and a wait for the channel to become\n * reachable resumes on the opt-in. Email waits key on the address property, push waits on the\n * device channel (`reachable('push')` subscribes to device changes).\n */\nexport async function setSubscriptions(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n patch: SubscriptionsPatch,\n topics: readonly string[],\n now = Date.now()\n): Promise<Subscriptions> {\n await refuseIfErased(store, userId);\n for (const channel of SUBSCRIPTION_CHANNELS) {\n const part = patch[channel];\n if (part === undefined) continue;\n const changes: SuppressionChange[] = [];\n if (part.all !== undefined) changes.push({ topic: null, suppressed: !part.all });\n for (const [topic, subscribed] of Object.entries(part.topics ?? {})) {\n if (subscribed !== undefined) changes.push({ topic, suppressed: !subscribed });\n }\n if (changes.length === 0) continue;\n await store.updateSuppressions(userId, channel, changes, now);\n if (part.all !== undefined) {\n const wake =\n channel === 'push'\n ? DEVICES_UPDATED_EVENT\n : profileUpdatedEvent(RECIPIENT_PROPERTY.email ?? 'email');\n await wakeSubscribers(env, store, userId, [wake]);\n }\n }\n return readSubscriptions(store, userId, topics);\n}\n\n/** The copy a message-scoped request came from: the channel it went out on, and its topic. */\nexport interface MessageOrigin<T extends string = string> {\n channel: SubscriptionChannel;\n topic: T;\n}\n\n/**\n * A user's subscriptions reached through one of their copies — what\n * `GET` / `PUT /subscriptions/by-message/:messageId` answer: the record, plus which channel and\n * topic that copy belonged to, so a preference page opened from an email can highlight it.\n */\nexport interface MessageSubscriptions<T extends string = string> extends Subscriptions<T> {\n message: MessageOrigin<T>;\n}\n\n/**\n * The recipient of a topic copy, by the copy's id. The id is the capability: a UUID nobody can\n * guess, the same trust `/t/u/<message>` runs on. Undefined — a 404 — for an id that names no\n * copy (never sent, or erased with its user by `forgetUser`), and for a transactional one, which\n * has nothing to opt out of; the same rule as `/t/u`. A push copy's `push_<platform>` channel\n * reads as `push`, the channel its subscriptions are keyed on.\n */\nexport async function resolveMessageOwner(\n store: JourneyStore,\n messageId: string\n): Promise<{ userId: string; message: MessageOrigin } | undefined> {\n if (!isMessageId(messageId)) return undefined;\n const found = await store.reporting.lookupMessage(messageId);\n if (found === undefined) return undefined;\n const { userId, topic } = found;\n // A transactional copy has no topic, and a Slack or Discord copy no subscriptions at all\n if (topic === null) return undefined;\n const channel =\n found.channel === 'email' ? 'email' : found.channel.startsWith('push') ? 'push' : undefined;\n if (channel === undefined) return undefined;\n return { userId, message: { channel, topic } };\n}\n\n/** `getSubscriptions` for the copy's recipient, with the copy's channel and topic; undefined when `resolveMessageOwner` is. */\nexport async function getSubscriptionsByMessage(\n store: JourneyStore,\n messageId: string,\n topics: readonly string[]\n): Promise<MessageSubscriptions | undefined> {\n const owner = await resolveMessageOwner(store, messageId);\n if (owner === undefined) return undefined;\n return { ...(await getSubscriptions(store, owner.userId, topics)), message: owner.message };\n}\n\n/** `setSubscriptions` for the copy's recipient, answering as `getSubscriptionsByMessage` does; undefined when `resolveMessageOwner` is. */\nexport async function setSubscriptionsByMessage(\n env: JourneyEnv,\n store: JourneyStore,\n messageId: string,\n patch: SubscriptionsPatch,\n topics: readonly string[],\n now = Date.now()\n): Promise<MessageSubscriptions | undefined> {\n const owner = await resolveMessageOwner(store, messageId);\n if (owner === undefined) return undefined;\n return {\n ...(await setSubscriptions(env, store, owner.userId, patch, topics, now)),\n message: owner.message,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,eAAe,eAAe,OAAqB,QAA+B;CAChF,IAAK,MAAM,MAAM,aAAa,MAAM,MAAO,QAAQ,MAAM,IAAI,gBAAgB,MAAM;AACrF;AAiCA,eAAsB,YACpB,KACA,OACA,OACuB;CACvB,IAAI,MAAM,MAAM,WAAW,GAAG,GAC5B,MAAM,IAAI,MAAM,eAAe,MAAM,MAAM,uCAAuC;CAIpF,MAAM,eA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L,GAAI,MAAM,iBAAiB,KAAK,OAAO,MAAM,QAAQ,OAAO,QAAQ,GAAG;EACvE,SAAS,MAAM;CACjB;AACF"}
package/dist/index.cjs CHANGED
@@ -29,6 +29,7 @@ exports.IR_VERSION = require_ir.IR_VERSION;
29
29
  exports.MetaIR = require_ir.MetaIR;
30
30
  exports.NodeIR = require_ir.NodeIR;
31
31
  exports.NodeMetaIR = require_ir.NodeMetaIR;
32
+ exports.PREVIEW_MESSAGE_ID = require_email.PREVIEW_MESSAGE_ID;
32
33
  exports.PropValueIR = require_ir.PropValueIR;
33
34
  exports.PropertyOperatorIR = require_ir.PropertyOperatorIR;
34
35
  exports.ScalarIR = require_ir.ScalarIR;
@@ -47,6 +48,7 @@ exports.apnsEnvironment = require_config.apnsEnvironment;
47
48
  exports.assertEmailAddress = require_email.assertEmailAddress;
48
49
  exports.assertEmailConfig = require_email.assertEmailConfig;
49
50
  exports.assertEmailMetadata = require_email.assertEmailMetadata;
51
+ exports.assertHttpUrl = require_email.assertHttpUrl;
50
52
  exports.assertSupportedSchema = require_templates.assertSupportedSchema;
51
53
  exports.assertTemplateTopic = require_email.assertTemplateTopic;
52
54
  exports.assertUnsubscribeUrl = require_email.assertUnsubscribeUrl;
@@ -93,6 +95,7 @@ exports.or = require_dsl_condition.or;
93
95
  exports.parseTemplateProps = require_templates.parseTemplateProps;
94
96
  exports.performed = require_dsl_condition.performed;
95
97
  exports.plan = require_plan.plan;
98
+ exports.preferencesLink = require_email.preferencesLink;
96
99
  exports.pushTemplate = require_templates.pushTemplate;
97
100
  exports.reachable = require_dsl_condition.reachable;
98
101
  exports.registryValidator = require_templates.registryValidator;
package/dist/index.d.cts CHANGED
@@ -10,10 +10,10 @@ import { GoalOptions, WorkflowBuilder, WorkflowDefinition, workflow } from "./ds
10
10
  import { compileBundle } from "./dsl/bundle.cjs";
11
11
  import "./dsl/index.cjs";
12
12
  import { Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DeclaredOutput, EventPayload, ProfilePatch, SubscriptionsDefinition, Topic, checkEvent, defineContract, isContract } from "./contract.cjs";
13
- import { EmailAddress, EmailConfig, ResolvedEmail, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertTemplateTopic, assertUnsubscribeUrl, formatEmailAddress, isUnsubscribeLink, mimeAddress, resolveEmail } from "./email.cjs";
13
+ import { EmailAddress, EmailConfig, EmailRenderOptions, PREVIEW_MESSAGE_ID, ResolvedEmail, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertHttpUrl, assertTemplateTopic, assertUnsubscribeUrl, formatEmailAddress, isUnsubscribeLink, mimeAddress, preferencesLink, resolveEmail } from "./email.cjs";
14
14
  import { AnyTemplate, CHANNEL_OF, ChannelTemplate, DiscordContent, DiscordTemplate, EmailMetadata, EmailTemplate, EmailTemplateBase, EmailTemplateDefinition, EmailTemplateTopic, PropsSchema, PushContent, PushTemplate, PushTemplateBase, PushTemplateDefinition, ResolvedProps, SlackContent, SlackTemplate, TemplateChannel, TemplateIssue, TemplateRegistry, TemplateTopic, TemplateValidationError, WebhookTemplateDefinition, assertSupportedSchema, discordTemplate, emailTemplate, indexTemplates, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSlackTemplate, isTemplate, lookupTemplate, parseTemplateProps, pushTemplate, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, slackTemplate, templatesFor } from "./templates.cjs";
15
15
  import { JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, resolveRuntime } from "./runtime.cjs";
16
16
  import { ApnsConfig, ConfigCompileError, DatabaseConfig, FcmConfig, JourneyConfig, JourneyConfigDefinition, WebPushConfig, apnsEnvironment, compileConfig, defineConfig, isConfig } from "./config.cjs";
17
17
  import { canonicalJSON, fullHash, semanticHash, sha256Hex, stripMeta, stripProvenance } from "./hash.cjs";
18
18
  import { BundlePlan, ChangeStatus, NodeChange, ResourceChange, WorkflowChange, isSemanticChange, plan } from "./plan.cjs";
19
- export { type ActionContext, type ActionHandler, ActionIR, type ActionRef, AnyTemplate, ApnsConfig, type BranchArm, type BranchCase, BundleIR, BundlePlan, CHANNEL_OF, ChangeStatus, type Channel, ChannelIR, ChannelTemplate, type Condition, ConditionIR, ConfigCompileError, Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DatabaseConfig, type DateTime, DeclaredOutput, DiscordContent, DiscordTemplate, type Duration, DurationIR, EmailAddress, EmailConfig, EmailMetadata, EmailTemplate, EmailTemplateBase, EmailTemplateDefinition, EmailTemplateTopic, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, EventPayload, type EventRef, type EventRefs, type EventTriggerOptions, FcmConfig, type Flow, type FlowBuilder, GoalIR, type GoalOptions, IR_VERSION, JourneyConfig, JourneyConfigDefinition, JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, type MessageArgs, MetaIR, NodeChange, NodeIR, NodeMetaIR, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, ProfilePatch, type PropInput, PropValueIR, PropertyOperatorIR, type PropsInput, type PropsOf, PropsSchema, PushContent, type PushOptions, PushTemplate, PushTemplateBase, PushTemplateDefinition, ResolvedEmail, ResolvedProps, ResourceChange, ScalarIR, type SegmentDefinition, SegmentIR, type SegmentRef, SlackContent, SlackTemplate, SourceLocIR, type SubFlow, SubscriptionsDefinition, SubscriptionsIR, TemplateChannel, type TemplateFactory, TemplateIR, TemplateIssue, type TemplateRef, TemplateRegistry, TemplateTopic, TemplateValidationError, type TimeOfDay, Topic, type TriggerFactory, TriggerIR, type TriggerRef, type UserPropertyBase, type UserPropertyRef, UserPropertyRefIR, type UserRefs, WebPushConfig, WebhookTemplateDefinition, type Weekday, WeekdayIR, type WorkflowBuilder, WorkflowChange, type WorkflowDefinition, WorkflowIR, action, and, apnsEnvironment, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertSupportedSchema, assertTemplateTopic, assertUnsubscribeUrl, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, indexTemplates, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, isTemplate, isUnsubscribeLink, lookupTemplate, lt, lte, mimeAddress, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveEmail, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templatesFor, trigger, user, workflow };
19
+ export { type ActionContext, type ActionHandler, ActionIR, type ActionRef, AnyTemplate, ApnsConfig, type BranchArm, type BranchCase, BundleIR, BundlePlan, CHANNEL_OF, ChangeStatus, type Channel, ChannelIR, ChannelTemplate, type Condition, ConditionIR, ConfigCompileError, Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DatabaseConfig, type DateTime, DeclaredOutput, DiscordContent, DiscordTemplate, type Duration, DurationIR, EmailAddress, EmailConfig, EmailMetadata, EmailRenderOptions, EmailTemplate, EmailTemplateBase, EmailTemplateDefinition, EmailTemplateTopic, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, EventPayload, type EventRef, type EventRefs, type EventTriggerOptions, FcmConfig, type Flow, type FlowBuilder, GoalIR, type GoalOptions, IR_VERSION, JourneyConfig, JourneyConfigDefinition, JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, type MessageArgs, MetaIR, NodeChange, NodeIR, NodeMetaIR, PREVIEW_MESSAGE_ID, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, ProfilePatch, type PropInput, PropValueIR, PropertyOperatorIR, type PropsInput, type PropsOf, PropsSchema, PushContent, type PushOptions, PushTemplate, PushTemplateBase, PushTemplateDefinition, ResolvedEmail, ResolvedProps, ResourceChange, ScalarIR, type SegmentDefinition, SegmentIR, type SegmentRef, SlackContent, SlackTemplate, SourceLocIR, type SubFlow, SubscriptionsDefinition, SubscriptionsIR, TemplateChannel, type TemplateFactory, TemplateIR, TemplateIssue, type TemplateRef, TemplateRegistry, TemplateTopic, TemplateValidationError, type TimeOfDay, Topic, type TriggerFactory, TriggerIR, type TriggerRef, type UserPropertyBase, type UserPropertyRef, UserPropertyRefIR, type UserRefs, WebPushConfig, WebhookTemplateDefinition, type Weekday, WeekdayIR, type WorkflowBuilder, WorkflowChange, type WorkflowDefinition, WorkflowIR, action, and, apnsEnvironment, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertHttpUrl, assertSupportedSchema, assertTemplateTopic, assertUnsubscribeUrl, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, indexTemplates, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, isTemplate, isUnsubscribeLink, lookupTemplate, lt, lte, mimeAddress, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, preferencesLink, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveEmail, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templatesFor, trigger, user, workflow };
package/dist/index.d.mts CHANGED
@@ -10,10 +10,10 @@ import { GoalOptions, WorkflowBuilder, WorkflowDefinition, workflow } from "./ds
10
10
  import { compileBundle } from "./dsl/bundle.mjs";
11
11
  import "./dsl/index.mjs";
12
12
  import { Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DeclaredOutput, EventPayload, ProfilePatch, SubscriptionsDefinition, Topic, checkEvent, defineContract, isContract } from "./contract.mjs";
13
- import { EmailAddress, EmailConfig, ResolvedEmail, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertTemplateTopic, assertUnsubscribeUrl, formatEmailAddress, isUnsubscribeLink, mimeAddress, resolveEmail } from "./email.mjs";
13
+ import { EmailAddress, EmailConfig, EmailRenderOptions, PREVIEW_MESSAGE_ID, ResolvedEmail, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertHttpUrl, assertTemplateTopic, assertUnsubscribeUrl, formatEmailAddress, isUnsubscribeLink, mimeAddress, preferencesLink, resolveEmail } from "./email.mjs";
14
14
  import { AnyTemplate, CHANNEL_OF, ChannelTemplate, DiscordContent, DiscordTemplate, EmailMetadata, EmailTemplate, EmailTemplateBase, EmailTemplateDefinition, EmailTemplateTopic, PropsSchema, PushContent, PushTemplate, PushTemplateBase, PushTemplateDefinition, ResolvedProps, SlackContent, SlackTemplate, TemplateChannel, TemplateIssue, TemplateRegistry, TemplateTopic, TemplateValidationError, WebhookTemplateDefinition, assertSupportedSchema, discordTemplate, emailTemplate, indexTemplates, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSlackTemplate, isTemplate, lookupTemplate, parseTemplateProps, pushTemplate, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, slackTemplate, templatesFor } from "./templates.mjs";
15
15
  import { JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, resolveRuntime } from "./runtime.mjs";
16
16
  import { ApnsConfig, ConfigCompileError, DatabaseConfig, FcmConfig, JourneyConfig, JourneyConfigDefinition, WebPushConfig, apnsEnvironment, compileConfig, defineConfig, isConfig } from "./config.mjs";
17
17
  import { canonicalJSON, fullHash, semanticHash, sha256Hex, stripMeta, stripProvenance } from "./hash.mjs";
18
18
  import { BundlePlan, ChangeStatus, NodeChange, ResourceChange, WorkflowChange, isSemanticChange, plan } from "./plan.mjs";
19
- export { type ActionContext, type ActionHandler, ActionIR, type ActionRef, AnyTemplate, ApnsConfig, type BranchArm, type BranchCase, BundleIR, BundlePlan, CHANNEL_OF, ChangeStatus, type Channel, ChannelIR, ChannelTemplate, type Condition, ConditionIR, ConfigCompileError, Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DatabaseConfig, type DateTime, DeclaredOutput, DiscordContent, DiscordTemplate, type Duration, DurationIR, EmailAddress, EmailConfig, EmailMetadata, EmailTemplate, EmailTemplateBase, EmailTemplateDefinition, EmailTemplateTopic, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, EventPayload, type EventRef, type EventRefs, type EventTriggerOptions, FcmConfig, type Flow, type FlowBuilder, GoalIR, type GoalOptions, IR_VERSION, JourneyConfig, JourneyConfigDefinition, JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, type MessageArgs, MetaIR, NodeChange, NodeIR, NodeMetaIR, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, ProfilePatch, type PropInput, PropValueIR, PropertyOperatorIR, type PropsInput, type PropsOf, PropsSchema, PushContent, type PushOptions, PushTemplate, PushTemplateBase, PushTemplateDefinition, ResolvedEmail, ResolvedProps, ResourceChange, ScalarIR, type SegmentDefinition, SegmentIR, type SegmentRef, SlackContent, SlackTemplate, SourceLocIR, type SubFlow, SubscriptionsDefinition, SubscriptionsIR, TemplateChannel, type TemplateFactory, TemplateIR, TemplateIssue, type TemplateRef, TemplateRegistry, TemplateTopic, TemplateValidationError, type TimeOfDay, Topic, type TriggerFactory, TriggerIR, type TriggerRef, type UserPropertyBase, type UserPropertyRef, UserPropertyRefIR, type UserRefs, WebPushConfig, WebhookTemplateDefinition, type Weekday, WeekdayIR, type WorkflowBuilder, WorkflowChange, type WorkflowDefinition, WorkflowIR, action, and, apnsEnvironment, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertSupportedSchema, assertTemplateTopic, assertUnsubscribeUrl, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, indexTemplates, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, isTemplate, isUnsubscribeLink, lookupTemplate, lt, lte, mimeAddress, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveEmail, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templatesFor, trigger, user, workflow };
19
+ export { type ActionContext, type ActionHandler, ActionIR, type ActionRef, AnyTemplate, ApnsConfig, type BranchArm, type BranchCase, BundleIR, BundlePlan, CHANNEL_OF, ChangeStatus, type Channel, ChannelIR, ChannelTemplate, type Condition, ConditionIR, ConfigCompileError, Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DatabaseConfig, type DateTime, DeclaredOutput, DiscordContent, DiscordTemplate, type Duration, DurationIR, EmailAddress, EmailConfig, EmailMetadata, EmailRenderOptions, EmailTemplate, EmailTemplateBase, EmailTemplateDefinition, EmailTemplateTopic, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, EventPayload, type EventRef, type EventRefs, type EventTriggerOptions, FcmConfig, type Flow, type FlowBuilder, GoalIR, type GoalOptions, IR_VERSION, JourneyConfig, JourneyConfigDefinition, JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, type MessageArgs, MetaIR, NodeChange, NodeIR, NodeMetaIR, PREVIEW_MESSAGE_ID, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, ProfilePatch, type PropInput, PropValueIR, PropertyOperatorIR, type PropsInput, type PropsOf, PropsSchema, PushContent, type PushOptions, PushTemplate, PushTemplateBase, PushTemplateDefinition, ResolvedEmail, ResolvedProps, ResourceChange, ScalarIR, type SegmentDefinition, SegmentIR, type SegmentRef, SlackContent, SlackTemplate, SourceLocIR, type SubFlow, SubscriptionsDefinition, SubscriptionsIR, TemplateChannel, type TemplateFactory, TemplateIR, TemplateIssue, type TemplateRef, TemplateRegistry, TemplateTopic, TemplateValidationError, type TimeOfDay, Topic, type TriggerFactory, TriggerIR, type TriggerRef, type UserPropertyBase, type UserPropertyRef, UserPropertyRefIR, type UserRefs, WebPushConfig, WebhookTemplateDefinition, type Weekday, WeekdayIR, type WorkflowBuilder, WorkflowChange, type WorkflowDefinition, WorkflowIR, action, and, apnsEnvironment, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertHttpUrl, assertSupportedSchema, assertTemplateTopic, assertUnsubscribeUrl, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, indexTemplates, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, isTemplate, isUnsubscribeLink, lookupTemplate, lt, lte, mimeAddress, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, preferencesLink, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveEmail, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templatesFor, trigger, user, workflow };
package/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import { action } from "./dsl/action.mjs";
4
4
  import { event, user } from "./dsl/refs.mjs";
5
5
  import { template } from "./dsl/template.mjs";
6
6
  import { and, between, contains, eq, exists, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment } from "./dsl/condition.mjs";
7
- import { assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertTemplateTopic, assertUnsubscribeUrl, formatEmailAddress, isUnsubscribeLink, mimeAddress, resolveEmail } from "./email.mjs";
7
+ import { PREVIEW_MESSAGE_ID, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertHttpUrl, assertTemplateTopic, assertUnsubscribeUrl, formatEmailAddress, isUnsubscribeLink, mimeAddress, preferencesLink, resolveEmail } from "./email.mjs";
8
8
  import { CHANNEL_OF, TemplateValidationError, assertSupportedSchema, discordTemplate, emailTemplate, indexTemplates, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSlackTemplate, isTemplate, lookupTemplate, parseTemplateProps, pushTemplate, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, slackTemplate, templatesFor } from "./templates.mjs";
9
9
  import { flow } from "./dsl/flow.mjs";
10
10
  import { trigger } from "./dsl/trigger.mjs";
@@ -15,4 +15,4 @@ import { ConfigCompileError, apnsEnvironment, compileConfig, defineConfig, isCon
15
15
  import { ContractValidationError, checkEvent, defineContract, isContract } from "./contract.mjs";
16
16
  import { isSemanticChange, plan } from "./plan.mjs";
17
17
  import { resolveRuntime } from "./runtime.mjs";
18
- export { ActionIR, BundleIR, CHANNEL_OF, ChannelIR, ConditionIR, ConfigCompileError, ContractValidationError, DurationIR, GoalIR, IR_VERSION, MetaIR, NodeIR, NodeMetaIR, PropValueIR, PropertyOperatorIR, ScalarIR, SegmentIR, SourceLocIR, SubscriptionsIR, TemplateIR, TemplateValidationError, TriggerIR, UserPropertyRefIR, WeekdayIR, WorkflowIR, action, and, apnsEnvironment, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertSupportedSchema, assertTemplateTopic, assertUnsubscribeUrl, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, indexTemplates, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, isTemplate, isUnsubscribeLink, lookupTemplate, lt, lte, mimeAddress, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveEmail, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templatesFor, trigger, user, workflow };
18
+ export { ActionIR, BundleIR, CHANNEL_OF, ChannelIR, ConditionIR, ConfigCompileError, ContractValidationError, DurationIR, GoalIR, IR_VERSION, MetaIR, NodeIR, NodeMetaIR, PREVIEW_MESSAGE_ID, PropValueIR, PropertyOperatorIR, ScalarIR, SegmentIR, SourceLocIR, SubscriptionsIR, TemplateIR, TemplateValidationError, TriggerIR, UserPropertyRefIR, WeekdayIR, WorkflowIR, action, and, apnsEnvironment, assertEmailAddress, assertEmailConfig, assertEmailMetadata, assertHttpUrl, assertSupportedSchema, assertTemplateTopic, assertUnsubscribeUrl, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, indexTemplates, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, isTemplate, isUnsubscribeLink, lookupTemplate, lt, lte, mimeAddress, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, preferencesLink, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveEmail, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templatesFor, trigger, user, workflow };
@@ -14,9 +14,10 @@ let react_dom_server = require("react-dom/server");
14
14
  * parsed against the template's schema before the component renders — a
15
15
  * failure throws TemplateValidationError and nothing renders — and the
16
16
  * component renders as an element inside an `EmailProvider` carrying the
17
- * template's resolved metadata (`resolveEmail` against the config's `email`),
18
- * so hooks and context work and a layout's `useEmailContext()` reads the
19
- * unsubscribe link the email is sent with; the render returns that metadata
17
+ * template's resolved metadata (`resolveEmail` against the config's `email`
18
+ * and the copy's message id, when the sender has one), so hooks and context
19
+ * work and a layout's `useEmailContext()` reads the unsubscribe and
20
+ * preferences links the email is sent with; the render returns that metadata
20
21
  * with the subject and HTML, for the sender. Rendering
21
22
  * streams and waits for every Suspense boundary (`allReady`) — react-email's
22
23
  * `<Tailwind>` suspends while it compiles the classes, which synchronous
@@ -27,10 +28,10 @@ let react_dom_server = require("react-dom/server");
27
28
  const DOCTYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
28
29
  function registryRenderer(emails, config) {
29
30
  const index = require_templates.indexTemplates("email", emails);
30
- return async (id, props) => {
31
+ return async (id, props, options) => {
31
32
  const template = require_templates.lookupTemplate(index, "email", id);
32
33
  const parsed = require_templates.parseTemplateProps(template, props);
33
- const email = require_email.resolveEmail(template, config);
34
+ const email = require_email.resolveEmail(template, config, options);
34
35
  const element = (0, react.createElement)(require_email_context.EmailProvider, { email }, (0, react.createElement)(template.component, parsed));
35
36
  return {
36
37
  ...email,
@@ -1 +1 @@
1
- {"version":3,"file":"react-email.cjs","names":["indexTemplates","lookupTemplate","parseTemplateProps","resolveEmail","createElement","EmailProvider","renderToReadableStream"],"sources":["../src/react-email.ts"],"sourcesContent":["import { type ComponentType, type ReactElement, createElement } from 'react';\nimport { renderToReadableStream } from 'react-dom/server';\nimport { type EmailConfig, resolveEmail } from './email';\nimport { EmailProvider } from './email-context';\nimport type { EmailRenderer } from './email-sender';\nimport {\n type EmailTemplate,\n indexTemplates,\n lookupTemplate,\n parseTemplateProps,\n} from './templates';\n\n/**\n * `@shware/workflow/react-email` — an EmailRenderer over the project's email\n * registry (`react-dom` is an optional peer dependency; import this subpath\n * only when you use it).\n *\n * The registry holds `emailTemplate({...})` definitions, looked up by their `id`. Props are\n * parsed against the template's schema before the component renders — a\n * failure throws TemplateValidationError and nothing renders — and the\n * component renders as an element inside an `EmailProvider` carrying the\n * template's resolved metadata (`resolveEmail` against the config's `email`),\n * so hooks and context work and a layout's `useEmailContext()` reads the\n * unsubscribe link the email is sent with; the render returns that metadata\n * with the subject and HTML, for the sender. Rendering\n * streams and waits for every Suspense boundary (`allReady`) — react-email's\n * `<Tailwind>` suspends while it compiles the classes, which synchronous\n * static markup cannot wait for — then prepends the XHTML doctype react-email\n * uses. @react-email/render itself is avoided because its Workers build\n * statically imports prettier and html-to-text for options never used here.\n */\n\nconst DOCTYPE =\n '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">';\n\nexport function registryRenderer(\n emails: Readonly<Record<string, EmailTemplate>>,\n config?: EmailConfig\n): EmailRenderer {\n const index = indexTemplates('email', emails);\n return async (id, props) => {\n const template = lookupTemplate(index, 'email', id);\n const parsed = parseTemplateProps(template, props);\n const email = resolveEmail(template, config);\n const element = createElement(\n EmailProvider,\n { email },\n createElement(template.component as ComponentType<object>, parsed)\n );\n return { ...email, subject: template.subject, html: DOCTYPE + (await renderToHtml(element)) };\n };\n}\n\n/** Render to a string once every Suspense boundary has resolved; a rendering error rejects. */\nasync function renderToHtml(element: ReactElement): Promise<string> {\n let failure: unknown;\n const stream = await renderToReadableStream(element, {\n onError: (error) => {\n failure = error;\n },\n });\n await stream.allReady;\n const html = await new Response(stream).text();\n if (failure !== undefined) {\n throw failure instanceof Error ? failure : new Error('email render failed', { cause: failure });\n }\n // Streaming a document adds what static markup did not: an HTML5 doctype (the caller prepends\n // the XHTML one email clients expect) and React 19's image preload hints, which mean nothing in\n // an email. Both are dropped, as @react-email/render does.\n return html\n .replace(/^<!DOCTYPE html>/i, '')\n .replace(/<link rel=\"preload\" as=\"image\"[^>]*\\/>/g, '');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,UACJ;AAEF,SAAgB,iBACd,QACA,QACe;CACf,MAAM,QAAQA,kBAAAA,eAAe,SAAS,MAAM;CAC5C,OAAO,OAAO,IAAI,UAAU;EAC1B,MAAM,WAAWC,kBAAAA,eAAe,OAAO,SAAS,EAAE;EAClD,MAAM,SAASC,kBAAAA,mBAAmB,UAAU,KAAK;EACjD,MAAM,QAAQC,cAAAA,aAAa,UAAU,MAAM;EAC3C,MAAM,WAAA,GAAUC,MAAAA,cAAAA,CACdC,sBAAAA,eACA,EAAE,MAAM,IAAA,GACRD,MAAAA,cAAAA,CAAc,SAAS,WAAoC,MAAM,CACnE;EACA,OAAO;GAAE,GAAG;GAAO,SAAS,SAAS;GAAS,MAAM,UAAW,MAAM,aAAa,OAAO;EAAG;CAC9F;AACF;;AAGA,eAAe,aAAa,SAAwC;CAClE,IAAI;CACJ,MAAM,SAAS,OAAA,GAAME,iBAAAA,uBAAAA,CAAuB,SAAS,EACnD,UAAU,UAAU;EAClB,UAAU;CACZ,EACF,CAAC;CACD,MAAM,OAAO;CACb,MAAM,OAAO,MAAM,IAAI,SAAS,MAAM,CAAC,CAAC,KAAK;CAC7C,IAAI,YAAY,KAAA,GACd,MAAM,mBAAmB,QAAQ,UAAU,IAAI,MAAM,uBAAuB,EAAE,OAAO,QAAQ,CAAC;CAKhG,OAAO,KACJ,QAAQ,qBAAqB,EAAE,CAAC,CAChC,QAAQ,2CAA2C,EAAE;AAC1D"}
1
+ {"version":3,"file":"react-email.cjs","names":["indexTemplates","lookupTemplate","parseTemplateProps","resolveEmail","createElement","EmailProvider","renderToReadableStream"],"sources":["../src/react-email.ts"],"sourcesContent":["import { type ComponentType, type ReactElement, createElement } from 'react';\nimport { renderToReadableStream } from 'react-dom/server';\nimport { type EmailConfig, resolveEmail } from './email';\nimport { EmailProvider } from './email-context';\nimport type { EmailRenderer } from './email-sender';\nimport {\n type EmailTemplate,\n indexTemplates,\n lookupTemplate,\n parseTemplateProps,\n} from './templates';\n\n/**\n * `@shware/workflow/react-email` — an EmailRenderer over the project's email\n * registry (`react-dom` is an optional peer dependency; import this subpath\n * only when you use it).\n *\n * The registry holds `emailTemplate({...})` definitions, looked up by their `id`. Props are\n * parsed against the template's schema before the component renders — a\n * failure throws TemplateValidationError and nothing renders — and the\n * component renders as an element inside an `EmailProvider` carrying the\n * template's resolved metadata (`resolveEmail` against the config's `email`\n * and the copy's message id, when the sender has one), so hooks and context\n * work and a layout's `useEmailContext()` reads the unsubscribe and\n * preferences links the email is sent with; the render returns that metadata\n * with the subject and HTML, for the sender. Rendering\n * streams and waits for every Suspense boundary (`allReady`) — react-email's\n * `<Tailwind>` suspends while it compiles the classes, which synchronous\n * static markup cannot wait for — then prepends the XHTML doctype react-email\n * uses. @react-email/render itself is avoided because its Workers build\n * statically imports prettier and html-to-text for options never used here.\n */\n\nconst DOCTYPE =\n '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">';\n\nexport function registryRenderer(\n emails: Readonly<Record<string, EmailTemplate>>,\n config?: EmailConfig\n): EmailRenderer {\n const index = indexTemplates('email', emails);\n return async (id, props, options) => {\n const template = lookupTemplate(index, 'email', id);\n const parsed = parseTemplateProps(template, props);\n const email = resolveEmail(template, config, options);\n const element = createElement(\n EmailProvider,\n { email },\n createElement(template.component as ComponentType<object>, parsed)\n );\n return { ...email, subject: template.subject, html: DOCTYPE + (await renderToHtml(element)) };\n };\n}\n\n/** Render to a string once every Suspense boundary has resolved; a rendering error rejects. */\nasync function renderToHtml(element: ReactElement): Promise<string> {\n let failure: unknown;\n const stream = await renderToReadableStream(element, {\n onError: (error) => {\n failure = error;\n },\n });\n await stream.allReady;\n const html = await new Response(stream).text();\n if (failure !== undefined) {\n throw failure instanceof Error ? failure : new Error('email render failed', { cause: failure });\n }\n // Streaming a document adds what static markup did not: an HTML5 doctype (the caller prepends\n // the XHTML one email clients expect) and React 19's image preload hints, which mean nothing in\n // an email. Both are dropped, as @react-email/render does.\n return html\n .replace(/^<!DOCTYPE html>/i, '')\n .replace(/<link rel=\"preload\" as=\"image\"[^>]*\\/>/g, '');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAM,UACJ;AAEF,SAAgB,iBACd,QACA,QACe;CACf,MAAM,QAAQA,kBAAAA,eAAe,SAAS,MAAM;CAC5C,OAAO,OAAO,IAAI,OAAO,YAAY;EACnC,MAAM,WAAWC,kBAAAA,eAAe,OAAO,SAAS,EAAE;EAClD,MAAM,SAASC,kBAAAA,mBAAmB,UAAU,KAAK;EACjD,MAAM,QAAQC,cAAAA,aAAa,UAAU,QAAQ,OAAO;EACpD,MAAM,WAAA,GAAUC,MAAAA,cAAAA,CACdC,sBAAAA,eACA,EAAE,MAAM,IAAA,GACRD,MAAAA,cAAAA,CAAc,SAAS,WAAoC,MAAM,CACnE;EACA,OAAO;GAAE,GAAG;GAAO,SAAS,SAAS;GAAS,MAAM,UAAW,MAAM,aAAa,OAAO;EAAG;CAC9F;AACF;;AAGA,eAAe,aAAa,SAAwC;CAClE,IAAI;CACJ,MAAM,SAAS,OAAA,GAAME,iBAAAA,uBAAAA,CAAuB,SAAS,EACnD,UAAU,UAAU;EAClB,UAAU;CACZ,EACF,CAAC;CACD,MAAM,OAAO;CACb,MAAM,OAAO,MAAM,IAAI,SAAS,MAAM,CAAC,CAAC,KAAK;CAC7C,IAAI,YAAY,KAAA,GACd,MAAM,mBAAmB,QAAQ,UAAU,IAAI,MAAM,uBAAuB,EAAE,OAAO,QAAQ,CAAC;CAKhG,OAAO,KACJ,QAAQ,qBAAqB,EAAE,CAAC,CAChC,QAAQ,2CAA2C,EAAE;AAC1D"}
@@ -1 +1 @@
1
- {"version":3,"file":"react-email.d.cts","names":[],"sources":["../src/react-email.ts"],"mappings":";;;wBAmCgB,iBACd,QAAQ,SAAS,eAAe,iBAChC,SAAS,cACR"}
1
+ {"version":3,"file":"react-email.d.cts","names":[],"sources":["../src/react-email.ts"],"mappings":";;;wBAoCgB,iBACd,QAAQ,SAAS,eAAe,iBAChC,SAAS,cACR"}
@@ -1 +1 @@
1
- {"version":3,"file":"react-email.d.mts","names":[],"sources":["../src/react-email.ts"],"mappings":";;;wBAmCgB,iBACd,QAAQ,SAAS,eAAe,iBAChC,SAAS,cACR"}
1
+ {"version":3,"file":"react-email.d.mts","names":[],"sources":["../src/react-email.ts"],"mappings":";;;wBAoCgB,iBACd,QAAQ,SAAS,eAAe,iBAChC,SAAS,cACR"}
@@ -13,9 +13,10 @@ import { renderToReadableStream } from "react-dom/server";
13
13
  * parsed against the template's schema before the component renders — a
14
14
  * failure throws TemplateValidationError and nothing renders — and the
15
15
  * component renders as an element inside an `EmailProvider` carrying the
16
- * template's resolved metadata (`resolveEmail` against the config's `email`),
17
- * so hooks and context work and a layout's `useEmailContext()` reads the
18
- * unsubscribe link the email is sent with; the render returns that metadata
16
+ * template's resolved metadata (`resolveEmail` against the config's `email`
17
+ * and the copy's message id, when the sender has one), so hooks and context
18
+ * work and a layout's `useEmailContext()` reads the unsubscribe and
19
+ * preferences links the email is sent with; the render returns that metadata
19
20
  * with the subject and HTML, for the sender. Rendering
20
21
  * streams and waits for every Suspense boundary (`allReady`) — react-email's
21
22
  * `<Tailwind>` suspends while it compiles the classes, which synchronous
@@ -26,10 +27,10 @@ import { renderToReadableStream } from "react-dom/server";
26
27
  const DOCTYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
27
28
  function registryRenderer(emails, config) {
28
29
  const index = indexTemplates("email", emails);
29
- return async (id, props) => {
30
+ return async (id, props, options) => {
30
31
  const template = lookupTemplate(index, "email", id);
31
32
  const parsed = parseTemplateProps(template, props);
32
- const email = resolveEmail(template, config);
33
+ const email = resolveEmail(template, config, options);
33
34
  const element = createElement(EmailProvider, { email }, createElement(template.component, parsed));
34
35
  return {
35
36
  ...email,
@@ -1 +1 @@
1
- {"version":3,"file":"react-email.mjs","names":[],"sources":["../src/react-email.ts"],"sourcesContent":["import { type ComponentType, type ReactElement, createElement } from 'react';\nimport { renderToReadableStream } from 'react-dom/server';\nimport { type EmailConfig, resolveEmail } from './email';\nimport { EmailProvider } from './email-context';\nimport type { EmailRenderer } from './email-sender';\nimport {\n type EmailTemplate,\n indexTemplates,\n lookupTemplate,\n parseTemplateProps,\n} from './templates';\n\n/**\n * `@shware/workflow/react-email` — an EmailRenderer over the project's email\n * registry (`react-dom` is an optional peer dependency; import this subpath\n * only when you use it).\n *\n * The registry holds `emailTemplate({...})` definitions, looked up by their `id`. Props are\n * parsed against the template's schema before the component renders — a\n * failure throws TemplateValidationError and nothing renders — and the\n * component renders as an element inside an `EmailProvider` carrying the\n * template's resolved metadata (`resolveEmail` against the config's `email`),\n * so hooks and context work and a layout's `useEmailContext()` reads the\n * unsubscribe link the email is sent with; the render returns that metadata\n * with the subject and HTML, for the sender. Rendering\n * streams and waits for every Suspense boundary (`allReady`) — react-email's\n * `<Tailwind>` suspends while it compiles the classes, which synchronous\n * static markup cannot wait for — then prepends the XHTML doctype react-email\n * uses. @react-email/render itself is avoided because its Workers build\n * statically imports prettier and html-to-text for options never used here.\n */\n\nconst DOCTYPE =\n '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">';\n\nexport function registryRenderer(\n emails: Readonly<Record<string, EmailTemplate>>,\n config?: EmailConfig\n): EmailRenderer {\n const index = indexTemplates('email', emails);\n return async (id, props) => {\n const template = lookupTemplate(index, 'email', id);\n const parsed = parseTemplateProps(template, props);\n const email = resolveEmail(template, config);\n const element = createElement(\n EmailProvider,\n { email },\n createElement(template.component as ComponentType<object>, parsed)\n );\n return { ...email, subject: template.subject, html: DOCTYPE + (await renderToHtml(element)) };\n };\n}\n\n/** Render to a string once every Suspense boundary has resolved; a rendering error rejects. */\nasync function renderToHtml(element: ReactElement): Promise<string> {\n let failure: unknown;\n const stream = await renderToReadableStream(element, {\n onError: (error) => {\n failure = error;\n },\n });\n await stream.allReady;\n const html = await new Response(stream).text();\n if (failure !== undefined) {\n throw failure instanceof Error ? failure : new Error('email render failed', { cause: failure });\n }\n // Streaming a document adds what static markup did not: an HTML5 doctype (the caller prepends\n // the XHTML one email clients expect) and React 19's image preload hints, which mean nothing in\n // an email. Both are dropped, as @react-email/render does.\n return html\n .replace(/^<!DOCTYPE html>/i, '')\n .replace(/<link rel=\"preload\" as=\"image\"[^>]*\\/>/g, '');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,UACJ;AAEF,SAAgB,iBACd,QACA,QACe;CACf,MAAM,QAAQ,eAAe,SAAS,MAAM;CAC5C,OAAO,OAAO,IAAI,UAAU;EAC1B,MAAM,WAAW,eAAe,OAAO,SAAS,EAAE;EAClD,MAAM,SAAS,mBAAmB,UAAU,KAAK;EACjD,MAAM,QAAQ,aAAa,UAAU,MAAM;EAC3C,MAAM,UAAU,cACd,eACA,EAAE,MAAM,GACR,cAAc,SAAS,WAAoC,MAAM,CACnE;EACA,OAAO;GAAE,GAAG;GAAO,SAAS,SAAS;GAAS,MAAM,UAAW,MAAM,aAAa,OAAO;EAAG;CAC9F;AACF;;AAGA,eAAe,aAAa,SAAwC;CAClE,IAAI;CACJ,MAAM,SAAS,MAAM,uBAAuB,SAAS,EACnD,UAAU,UAAU;EAClB,UAAU;CACZ,EACF,CAAC;CACD,MAAM,OAAO;CACb,MAAM,OAAO,MAAM,IAAI,SAAS,MAAM,CAAC,CAAC,KAAK;CAC7C,IAAI,YAAY,KAAA,GACd,MAAM,mBAAmB,QAAQ,UAAU,IAAI,MAAM,uBAAuB,EAAE,OAAO,QAAQ,CAAC;CAKhG,OAAO,KACJ,QAAQ,qBAAqB,EAAE,CAAC,CAChC,QAAQ,2CAA2C,EAAE;AAC1D"}
1
+ {"version":3,"file":"react-email.mjs","names":[],"sources":["../src/react-email.ts"],"sourcesContent":["import { type ComponentType, type ReactElement, createElement } from 'react';\nimport { renderToReadableStream } from 'react-dom/server';\nimport { type EmailConfig, resolveEmail } from './email';\nimport { EmailProvider } from './email-context';\nimport type { EmailRenderer } from './email-sender';\nimport {\n type EmailTemplate,\n indexTemplates,\n lookupTemplate,\n parseTemplateProps,\n} from './templates';\n\n/**\n * `@shware/workflow/react-email` — an EmailRenderer over the project's email\n * registry (`react-dom` is an optional peer dependency; import this subpath\n * only when you use it).\n *\n * The registry holds `emailTemplate({...})` definitions, looked up by their `id`. Props are\n * parsed against the template's schema before the component renders — a\n * failure throws TemplateValidationError and nothing renders — and the\n * component renders as an element inside an `EmailProvider` carrying the\n * template's resolved metadata (`resolveEmail` against the config's `email`\n * and the copy's message id, when the sender has one), so hooks and context\n * work and a layout's `useEmailContext()` reads the unsubscribe and\n * preferences links the email is sent with; the render returns that metadata\n * with the subject and HTML, for the sender. Rendering\n * streams and waits for every Suspense boundary (`allReady`) — react-email's\n * `<Tailwind>` suspends while it compiles the classes, which synchronous\n * static markup cannot wait for — then prepends the XHTML doctype react-email\n * uses. @react-email/render itself is avoided because its Workers build\n * statically imports prettier and html-to-text for options never used here.\n */\n\nconst DOCTYPE =\n '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">';\n\nexport function registryRenderer(\n emails: Readonly<Record<string, EmailTemplate>>,\n config?: EmailConfig\n): EmailRenderer {\n const index = indexTemplates('email', emails);\n return async (id, props, options) => {\n const template = lookupTemplate(index, 'email', id);\n const parsed = parseTemplateProps(template, props);\n const email = resolveEmail(template, config, options);\n const element = createElement(\n EmailProvider,\n { email },\n createElement(template.component as ComponentType<object>, parsed)\n );\n return { ...email, subject: template.subject, html: DOCTYPE + (await renderToHtml(element)) };\n };\n}\n\n/** Render to a string once every Suspense boundary has resolved; a rendering error rejects. */\nasync function renderToHtml(element: ReactElement): Promise<string> {\n let failure: unknown;\n const stream = await renderToReadableStream(element, {\n onError: (error) => {\n failure = error;\n },\n });\n await stream.allReady;\n const html = await new Response(stream).text();\n if (failure !== undefined) {\n throw failure instanceof Error ? failure : new Error('email render failed', { cause: failure });\n }\n // Streaming a document adds what static markup did not: an HTML5 doctype (the caller prepends\n // the XHTML one email clients expect) and React 19's image preload hints, which mean nothing in\n // an email. Both are dropped, as @react-email/render does.\n return html\n .replace(/^<!DOCTYPE html>/i, '')\n .replace(/<link rel=\"preload\" as=\"image\"[^>]*\\/>/g, '');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAM,UACJ;AAEF,SAAgB,iBACd,QACA,QACe;CACf,MAAM,QAAQ,eAAe,SAAS,MAAM;CAC5C,OAAO,OAAO,IAAI,OAAO,YAAY;EACnC,MAAM,WAAW,eAAe,OAAO,SAAS,EAAE;EAClD,MAAM,SAAS,mBAAmB,UAAU,KAAK;EACjD,MAAM,QAAQ,aAAa,UAAU,QAAQ,OAAO;EACpD,MAAM,UAAU,cACd,eACA,EAAE,MAAM,GACR,cAAc,SAAS,WAAoC,MAAM,CACnE;EACA,OAAO;GAAE,GAAG;GAAO,SAAS,SAAS;GAAS,MAAM,UAAW,MAAM,aAAa,OAAO;EAAG;CAC9F;AACF;;AAGA,eAAe,aAAa,SAAwC;CAClE,IAAI;CACJ,MAAM,SAAS,MAAM,uBAAuB,SAAS,EACnD,UAAU,UAAU;EAClB,UAAU;CACZ,EACF,CAAC;CACD,MAAM,OAAO;CACb,MAAM,OAAO,MAAM,IAAI,SAAS,MAAM,CAAC,CAAC,KAAK;CAC7C,IAAI,YAAY,KAAA,GACd,MAAM,mBAAmB,QAAQ,UAAU,IAAI,MAAM,uBAAuB,EAAE,OAAO,QAAQ,CAAC;CAKhG,OAAO,KACJ,QAAQ,qBAAqB,EAAE,CAAC,CAChC,QAAQ,2CAA2C,EAAE;AAC1D"}
@@ -7,7 +7,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
7
  * A copy is recorded before it goes out, so its id can travel with it: with a tracking origin,
8
8
  * an email's links become `<origin>/t/l/<message>/<position>` — `/t/u/...` for its unsubscribe
9
9
  * link, so what a click means is fixed when it is sent — and an open pixel `<origin>/t/o/<message>`
10
- * (served by the Worker, ./tracking.ts), and a push carries
10
+ * (served by the Worker, ./tracking.ts); the renderer gets the id too, for the email's
11
+ * preferences link (`email.preferencesUrl?m=<message>`), and a push carries
11
12
  * `message_id` in its payload for the app to report the tap (`JourneyClient.messageOpened`),
12
13
  * plus `delivered_url` / `opened_url` for a client that reports straight to the Worker.
13
14
  * The links are recorded when the sender commits the rewritten email, before it goes out.
@@ -32,6 +33,7 @@ function reportingObserver(reporting, origin) {
32
33
  if (message.channel === "email" && base !== void 0) {
33
34
  const urls = [];
34
35
  return {
36
+ messageId: id,
35
37
  link: (url, purpose) => {
36
38
  urls.push(url);
37
39
  return `${base}/t/${purpose === "unsubscribe" ? "u" : "l"}/${id}/${urls.length - 1}`;
@@ -1 +1 @@
1
- {"version":3,"file":"observer.cjs","names":[],"sources":["../../src/reporting/observer.ts"],"sourcesContent":["import type { JourneyObserver, OutboundMessage } from '../engine';\nimport type { JourneyReporting } from '../store';\n\n/**\n * The observer journeyWorker installs when the store keeps reporting: every node arrival, copy\n * and outcome recorded through `store.reporting`.\n *\n * A copy is recorded before it goes out, so its id can travel with it: with a tracking origin,\n * an email's links become `<origin>/t/l/<message>/<position>` — `/t/u/...` for its unsubscribe\n * link, so what a click means is fixed when it is sent — and an open pixel `<origin>/t/o/<message>`\n * (served by the Worker, ./tracking.ts), and a push carries\n * `message_id` in its payload for the app to report the tap (`JourneyClient.messageOpened`),\n * plus `delivered_url` / `opened_url` for a client that reports straight to the Worker.\n * The links are recorded when the sender commits the rewritten email, before it goes out.\n */\nexport function reportingObserver(\n reporting: JourneyReporting,\n origin: string | undefined\n): JourneyObserver {\n const base = origin?.replace(/\\/$/, '');\n\n return {\n started: (event) => reporting.instanceStarted(event),\n\n nodeReached: (event) => reporting.nodeReached(event),\n\n async messagePrepared(message) {\n const id = await reporting.recordMessage({\n idempotencyKey: message.idempotencyKey,\n workflow: message.workflow,\n instanceId: message.instanceId,\n nodeId: message.nodeId,\n template: message.template,\n channel: channelOf(message),\n userId: message.userId,\n topic:\n message.channel === 'email' || message.channel === 'push'\n ? (message.topic ?? null)\n : null,\n sentAt: Date.now(),\n });\n if (message.channel === 'email' && base !== undefined) {\n const urls: string[] = [];\n return {\n link: (url, purpose) => {\n urls.push(url);\n return `${base}/t/${purpose === 'unsubscribe' ? 'u' : 'l'}/${id}/${urls.length - 1}`;\n },\n pixel: `${base}/t/o/${id}`,\n unsubscribe: `${base}/t/u/${id}`,\n // Before the transport takes it, so no click can reach a link not yet recorded\n commit: () => reporting.recordLinks(id, urls),\n };\n }\n if (message.channel === 'push') {\n // The app reports the tap with `message_id`; a client that can reach the Worker on its\n // own (iOS's notification service extension, a browser's service worker) posts to these\n return {\n data: {\n message_id: id,\n ...(base === undefined\n ? {}\n : { delivered_url: `${base}/t/d/${id}`, opened_url: `${base}/t/p/${id}` }),\n },\n };\n }\n return undefined;\n },\n\n async messageSent(message, result) {\n await reporting.settleMessage(message.idempotencyKey, result, Date.now());\n },\n\n finished: (event) => reporting.instanceFinished(event),\n };\n}\n\n/** Where the copy lands — the Studio's metric channel: a push is reported per platform. */\nfunction channelOf(message: OutboundMessage): string {\n if (message.channel !== 'push') return message.channel;\n return `push_${message.device?.platform ?? 'unknown'}`;\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,SAAgB,kBACd,WACA,QACiB;CACjB,MAAM,OAAO,QAAQ,QAAQ,OAAO,EAAE;CAEtC,OAAO;EACL,UAAU,UAAU,UAAU,gBAAgB,KAAK;EAEnD,cAAc,UAAU,UAAU,YAAY,KAAK;EAEnD,MAAM,gBAAgB,SAAS;GAC7B,MAAM,KAAK,MAAM,UAAU,cAAc;IACvC,gBAAgB,QAAQ;IACxB,UAAU,QAAQ;IAClB,YAAY,QAAQ;IACpB,QAAQ,QAAQ;IAChB,UAAU,QAAQ;IAClB,SAAS,UAAU,OAAO;IAC1B,QAAQ,QAAQ;IAChB,OACE,QAAQ,YAAY,WAAW,QAAQ,YAAY,SAC9C,QAAQ,SAAS,OAClB;IACN,QAAQ,KAAK,IAAI;GACnB,CAAC;GACD,IAAI,QAAQ,YAAY,WAAW,SAAS,KAAA,GAAW;IACrD,MAAM,OAAiB,CAAC;IACxB,OAAO;KACL,OAAO,KAAK,YAAY;MACtB,KAAK,KAAK,GAAG;MACb,OAAO,GAAG,KAAK,KAAK,YAAY,gBAAgB,MAAM,IAAI,GAAG,GAAG,GAAG,KAAK,SAAS;KACnF;KACA,OAAO,GAAG,KAAK,OAAO;KACtB,aAAa,GAAG,KAAK,OAAO;KAE5B,cAAc,UAAU,YAAY,IAAI,IAAI;IAC9C;GACF;GACA,IAAI,QAAQ,YAAY,QAGtB,OAAO,EACL,MAAM;IACJ,YAAY;IACZ,GAAI,SAAS,KAAA,IACT,CAAC,IACD;KAAE,eAAe,GAAG,KAAK,OAAO;KAAM,YAAY,GAAG,KAAK,OAAO;IAAK;GAC5E,EACF;EAGJ;EAEA,MAAM,YAAY,SAAS,QAAQ;GACjC,MAAM,UAAU,cAAc,QAAQ,gBAAgB,QAAQ,KAAK,IAAI,CAAC;EAC1E;EAEA,WAAW,UAAU,UAAU,iBAAiB,KAAK;CACvD;AACF;;AAGA,SAAS,UAAU,SAAkC;CACnD,IAAI,QAAQ,YAAY,QAAQ,OAAO,QAAQ;CAC/C,OAAO,QAAQ,QAAQ,QAAQ,YAAY;AAC7C"}
1
+ {"version":3,"file":"observer.cjs","names":[],"sources":["../../src/reporting/observer.ts"],"sourcesContent":["import type { JourneyObserver, OutboundMessage } from '../engine';\nimport type { JourneyReporting } from '../store';\n\n/**\n * The observer journeyWorker installs when the store keeps reporting: every node arrival, copy\n * and outcome recorded through `store.reporting`.\n *\n * A copy is recorded before it goes out, so its id can travel with it: with a tracking origin,\n * an email's links become `<origin>/t/l/<message>/<position>` — `/t/u/...` for its unsubscribe\n * link, so what a click means is fixed when it is sent — and an open pixel `<origin>/t/o/<message>`\n * (served by the Worker, ./tracking.ts); the renderer gets the id too, for the email's\n * preferences link (`email.preferencesUrl?m=<message>`), and a push carries\n * `message_id` in its payload for the app to report the tap (`JourneyClient.messageOpened`),\n * plus `delivered_url` / `opened_url` for a client that reports straight to the Worker.\n * The links are recorded when the sender commits the rewritten email, before it goes out.\n */\nexport function reportingObserver(\n reporting: JourneyReporting,\n origin: string | undefined\n): JourneyObserver {\n const base = origin?.replace(/\\/$/, '');\n\n return {\n started: (event) => reporting.instanceStarted(event),\n\n nodeReached: (event) => reporting.nodeReached(event),\n\n async messagePrepared(message) {\n const id = await reporting.recordMessage({\n idempotencyKey: message.idempotencyKey,\n workflow: message.workflow,\n instanceId: message.instanceId,\n nodeId: message.nodeId,\n template: message.template,\n channel: channelOf(message),\n userId: message.userId,\n topic:\n message.channel === 'email' || message.channel === 'push'\n ? (message.topic ?? null)\n : null,\n sentAt: Date.now(),\n });\n if (message.channel === 'email' && base !== undefined) {\n const urls: string[] = [];\n return {\n messageId: id,\n link: (url, purpose) => {\n urls.push(url);\n return `${base}/t/${purpose === 'unsubscribe' ? 'u' : 'l'}/${id}/${urls.length - 1}`;\n },\n pixel: `${base}/t/o/${id}`,\n unsubscribe: `${base}/t/u/${id}`,\n // Before the transport takes it, so no click can reach a link not yet recorded\n commit: () => reporting.recordLinks(id, urls),\n };\n }\n if (message.channel === 'push') {\n // The app reports the tap with `message_id`; a client that can reach the Worker on its\n // own (iOS's notification service extension, a browser's service worker) posts to these\n return {\n data: {\n message_id: id,\n ...(base === undefined\n ? {}\n : { delivered_url: `${base}/t/d/${id}`, opened_url: `${base}/t/p/${id}` }),\n },\n };\n }\n return undefined;\n },\n\n async messageSent(message, result) {\n await reporting.settleMessage(message.idempotencyKey, result, Date.now());\n },\n\n finished: (event) => reporting.instanceFinished(event),\n };\n}\n\n/** Where the copy lands — the Studio's metric channel: a push is reported per platform. */\nfunction channelOf(message: OutboundMessage): string {\n if (message.channel !== 'push') return message.channel;\n return `push_${message.device?.platform ?? 'unknown'}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,kBACd,WACA,QACiB;CACjB,MAAM,OAAO,QAAQ,QAAQ,OAAO,EAAE;CAEtC,OAAO;EACL,UAAU,UAAU,UAAU,gBAAgB,KAAK;EAEnD,cAAc,UAAU,UAAU,YAAY,KAAK;EAEnD,MAAM,gBAAgB,SAAS;GAC7B,MAAM,KAAK,MAAM,UAAU,cAAc;IACvC,gBAAgB,QAAQ;IACxB,UAAU,QAAQ;IAClB,YAAY,QAAQ;IACpB,QAAQ,QAAQ;IAChB,UAAU,QAAQ;IAClB,SAAS,UAAU,OAAO;IAC1B,QAAQ,QAAQ;IAChB,OACE,QAAQ,YAAY,WAAW,QAAQ,YAAY,SAC9C,QAAQ,SAAS,OAClB;IACN,QAAQ,KAAK,IAAI;GACnB,CAAC;GACD,IAAI,QAAQ,YAAY,WAAW,SAAS,KAAA,GAAW;IACrD,MAAM,OAAiB,CAAC;IACxB,OAAO;KACL,WAAW;KACX,OAAO,KAAK,YAAY;MACtB,KAAK,KAAK,GAAG;MACb,OAAO,GAAG,KAAK,KAAK,YAAY,gBAAgB,MAAM,IAAI,GAAG,GAAG,GAAG,KAAK,SAAS;KACnF;KACA,OAAO,GAAG,KAAK,OAAO;KACtB,aAAa,GAAG,KAAK,OAAO;KAE5B,cAAc,UAAU,YAAY,IAAI,IAAI;IAC9C;GACF;GACA,IAAI,QAAQ,YAAY,QAGtB,OAAO,EACL,MAAM;IACJ,YAAY;IACZ,GAAI,SAAS,KAAA,IACT,CAAC,IACD;KAAE,eAAe,GAAG,KAAK,OAAO;KAAM,YAAY,GAAG,KAAK,OAAO;IAAK;GAC5E,EACF;EAGJ;EAEA,MAAM,YAAY,SAAS,QAAQ;GACjC,MAAM,UAAU,cAAc,QAAQ,gBAAgB,QAAQ,KAAK,IAAI,CAAC;EAC1E;EAEA,WAAW,UAAU,UAAU,iBAAiB,KAAK;CACvD;AACF;;AAGA,SAAS,UAAU,SAAkC;CACnD,IAAI,QAAQ,YAAY,QAAQ,OAAO,QAAQ;CAC/C,OAAO,QAAQ,QAAQ,QAAQ,YAAY;AAC7C"}
@@ -8,7 +8,8 @@ import { JourneyReporting } from "../store/index.cjs";
8
8
  * A copy is recorded before it goes out, so its id can travel with it: with a tracking origin,
9
9
  * an email's links become `<origin>/t/l/<message>/<position>` — `/t/u/...` for its unsubscribe
10
10
  * link, so what a click means is fixed when it is sent — and an open pixel `<origin>/t/o/<message>`
11
- * (served by the Worker, ./tracking.ts), and a push carries
11
+ * (served by the Worker, ./tracking.ts); the renderer gets the id too, for the email's
12
+ * preferences link (`email.preferencesUrl?m=<message>`), and a push carries
12
13
  * `message_id` in its payload for the app to report the tap (`JourneyClient.messageOpened`),
13
14
  * plus `delivered_url` / `opened_url` for a client that reports straight to the Worker.
14
15
  * The links are recorded when the sender commits the rewritten email, before it goes out.
@@ -1 +1 @@
1
- {"version":3,"file":"observer.d.cts","names":[],"sources":["../../src/reporting/observer.ts"],"mappings":";;;;;;;;;;;;;;;wBAegB,kBACd,WAAW,kBACX,6BACC"}
1
+ {"version":3,"file":"observer.d.cts","names":[],"sources":["../../src/reporting/observer.ts"],"mappings":";;;;;;;;;;;;;;;;wBAgBgB,kBACd,WAAW,kBACX,6BACC"}
@@ -8,7 +8,8 @@ import { JourneyReporting } from "../store/index.mjs";
8
8
  * A copy is recorded before it goes out, so its id can travel with it: with a tracking origin,
9
9
  * an email's links become `<origin>/t/l/<message>/<position>` — `/t/u/...` for its unsubscribe
10
10
  * link, so what a click means is fixed when it is sent — and an open pixel `<origin>/t/o/<message>`
11
- * (served by the Worker, ./tracking.ts), and a push carries
11
+ * (served by the Worker, ./tracking.ts); the renderer gets the id too, for the email's
12
+ * preferences link (`email.preferencesUrl?m=<message>`), and a push carries
12
13
  * `message_id` in its payload for the app to report the tap (`JourneyClient.messageOpened`),
13
14
  * plus `delivered_url` / `opened_url` for a client that reports straight to the Worker.
14
15
  * The links are recorded when the sender commits the rewritten email, before it goes out.
@@ -1 +1 @@
1
- {"version":3,"file":"observer.d.mts","names":[],"sources":["../../src/reporting/observer.ts"],"mappings":";;;;;;;;;;;;;;;wBAegB,kBACd,WAAW,kBACX,6BACC"}
1
+ {"version":3,"file":"observer.d.mts","names":[],"sources":["../../src/reporting/observer.ts"],"mappings":";;;;;;;;;;;;;;;;wBAgBgB,kBACd,WAAW,kBACX,6BACC"}
@@ -6,7 +6,8 @@
6
6
  * A copy is recorded before it goes out, so its id can travel with it: with a tracking origin,
7
7
  * an email's links become `<origin>/t/l/<message>/<position>` — `/t/u/...` for its unsubscribe
8
8
  * link, so what a click means is fixed when it is sent — and an open pixel `<origin>/t/o/<message>`
9
- * (served by the Worker, ./tracking.ts), and a push carries
9
+ * (served by the Worker, ./tracking.ts); the renderer gets the id too, for the email's
10
+ * preferences link (`email.preferencesUrl?m=<message>`), and a push carries
10
11
  * `message_id` in its payload for the app to report the tap (`JourneyClient.messageOpened`),
11
12
  * plus `delivered_url` / `opened_url` for a client that reports straight to the Worker.
12
13
  * The links are recorded when the sender commits the rewritten email, before it goes out.
@@ -31,6 +32,7 @@ function reportingObserver(reporting, origin) {
31
32
  if (message.channel === "email" && base !== void 0) {
32
33
  const urls = [];
33
34
  return {
35
+ messageId: id,
34
36
  link: (url, purpose) => {
35
37
  urls.push(url);
36
38
  return `${base}/t/${purpose === "unsubscribe" ? "u" : "l"}/${id}/${urls.length - 1}`;