@shware/workflow 2.0.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -2
- package/dist/apns-relay.cjs +4 -17
- package/dist/apns-relay.cjs.map +1 -1
- package/dist/apns-relay.mjs +4 -17
- package/dist/apns-relay.mjs.map +1 -1
- package/dist/aws/engine-step.cjs +104 -0
- package/dist/aws/engine-step.cjs.map +1 -0
- package/dist/aws/engine-step.d.cts +28 -0
- package/dist/aws/engine-step.d.cts.map +1 -0
- package/dist/aws/engine-step.d.mts +28 -0
- package/dist/aws/engine-step.d.mts.map +1 -0
- package/dist/aws/engine-step.mjs +102 -0
- package/dist/aws/engine-step.mjs.map +1 -0
- package/dist/aws/function-url.cjs +62 -0
- package/dist/aws/function-url.cjs.map +1 -0
- package/dist/aws/function-url.d.cts +38 -0
- package/dist/aws/function-url.d.cts.map +1 -0
- package/dist/aws/function-url.d.mts +38 -0
- package/dist/aws/function-url.d.mts.map +1 -0
- package/dist/aws/function-url.mjs +59 -0
- package/dist/aws/function-url.mjs.map +1 -0
- package/dist/aws/index.cjs +160 -0
- package/dist/aws/index.cjs.map +1 -0
- package/dist/aws/index.d.cts +68 -0
- package/dist/aws/index.d.cts.map +1 -0
- package/dist/aws/index.d.mts +68 -0
- package/dist/aws/index.d.mts.map +1 -0
- package/dist/aws/index.mjs +148 -0
- package/dist/aws/index.mjs.map +1 -0
- package/dist/aws/instances.cjs +196 -0
- package/dist/aws/instances.cjs.map +1 -0
- package/dist/aws/instances.d.cts +94 -0
- package/dist/aws/instances.d.cts.map +1 -0
- package/dist/aws/instances.d.mts +94 -0
- package/dist/aws/instances.d.mts.map +1 -0
- package/dist/aws/instances.mjs +192 -0
- package/dist/aws/instances.mjs.map +1 -0
- package/dist/aws/lambda-api.cjs +89 -0
- package/dist/aws/lambda-api.cjs.map +1 -0
- package/dist/aws/lambda-api.d.cts +43 -0
- package/dist/aws/lambda-api.d.cts.map +1 -0
- package/dist/aws/lambda-api.d.mts +43 -0
- package/dist/aws/lambda-api.d.mts.map +1 -0
- package/dist/aws/lambda-api.mjs +88 -0
- package/dist/aws/lambda-api.mjs.map +1 -0
- package/dist/client.d.cts +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/cloudflare/bindings.cjs +19 -0
- package/dist/cloudflare/bindings.cjs.map +1 -1
- package/dist/cloudflare/bindings.d.cts +39 -0
- package/dist/cloudflare/bindings.d.cts.map +1 -1
- package/dist/cloudflare/bindings.d.mts +39 -0
- package/dist/cloudflare/bindings.d.mts.map +1 -1
- package/dist/cloudflare/bindings.mjs +18 -1
- package/dist/cloudflare/bindings.mjs.map +1 -1
- package/dist/cloudflare/index.cjs +32 -28
- package/dist/cloudflare/index.d.cts +8 -6
- package/dist/cloudflare/index.d.mts +8 -6
- package/dist/cloudflare/index.mjs +12 -10
- package/dist/cloudflare/runner.cjs +27 -76
- package/dist/cloudflare/runner.cjs.map +1 -1
- package/dist/cloudflare/runner.d.cts +7 -2
- package/dist/cloudflare/runner.d.cts.map +1 -1
- package/dist/cloudflare/runner.d.mts +7 -2
- package/dist/cloudflare/runner.d.mts.map +1 -1
- package/dist/cloudflare/runner.mjs +26 -75
- package/dist/cloudflare/runner.mjs.map +1 -1
- package/dist/cloudflare/worker.cjs +22 -203
- package/dist/cloudflare/worker.cjs.map +1 -1
- package/dist/cloudflare/worker.d.cts +10 -56
- package/dist/cloudflare/worker.d.cts.map +1 -1
- package/dist/cloudflare/worker.d.mts +10 -56
- package/dist/cloudflare/worker.d.mts.map +1 -1
- package/dist/cloudflare/worker.mjs +20 -199
- package/dist/cloudflare/worker.mjs.map +1 -1
- package/dist/email-sender.cjs +62 -0
- package/dist/email-sender.cjs.map +1 -0
- package/dist/email-sender.d.cts +70 -0
- package/dist/email-sender.d.cts.map +1 -0
- package/dist/email-sender.d.mts +70 -0
- package/dist/email-sender.d.mts.map +1 -0
- package/dist/email-sender.mjs +60 -0
- package/dist/email-sender.mjs.map +1 -0
- package/dist/email.cjs +21 -0
- package/dist/email.cjs.map +1 -1
- package/dist/email.d.cts +6 -0
- package/dist/email.d.cts.map +1 -1
- package/dist/email.d.mts +6 -0
- package/dist/email.d.mts.map +1 -1
- package/dist/email.mjs +21 -1
- package/dist/email.mjs.map +1 -1
- package/dist/engine/index.cjs +1 -1
- package/dist/engine/index.mjs +1 -1
- package/dist/engine/interpreter.cjs +1 -1
- package/dist/engine/interpreter.cjs.map +1 -1
- package/dist/engine/interpreter.mjs +1 -1
- package/dist/engine/interpreter.mjs.map +1 -1
- package/dist/engine/ports.d.cts +6 -1
- package/dist/engine/ports.d.cts.map +1 -1
- package/dist/engine/ports.d.mts +6 -1
- package/dist/engine/ports.d.mts.map +1 -1
- package/dist/{cloudflare → host}/channels.cjs +13 -11
- package/dist/host/channels.cjs.map +1 -0
- package/dist/{cloudflare → host}/channels.d.cts +8 -3
- package/dist/host/channels.d.cts.map +1 -0
- package/dist/{cloudflare → host}/channels.d.mts +8 -3
- package/dist/host/channels.d.mts.map +1 -0
- package/dist/{cloudflare → host}/channels.mjs +9 -7
- package/dist/host/channels.mjs.map +1 -0
- package/dist/host/execute.cjs +81 -0
- package/dist/host/execute.cjs.map +1 -0
- package/dist/host/execute.d.cts +37 -0
- package/dist/host/execute.d.cts.map +1 -0
- package/dist/host/execute.d.mts +37 -0
- package/dist/host/execute.d.mts.map +1 -0
- package/dist/host/execute.mjs +80 -0
- package/dist/host/execute.mjs.map +1 -0
- package/dist/host/journey-host.cjs +214 -0
- package/dist/host/journey-host.cjs.map +1 -0
- package/dist/host/journey-host.d.cts +105 -0
- package/dist/host/journey-host.d.cts.map +1 -0
- package/dist/host/journey-host.d.mts +105 -0
- package/dist/host/journey-host.d.mts.map +1 -0
- package/dist/host/journey-host.mjs +210 -0
- package/dist/host/journey-host.mjs.map +1 -0
- package/dist/{cloudflare → host}/router.cjs +34 -13
- package/dist/host/router.cjs.map +1 -0
- package/dist/{cloudflare → host}/router.d.cts +2 -2
- package/dist/host/router.d.cts.map +1 -0
- package/dist/{cloudflare → host}/router.d.mts +2 -2
- package/dist/host/router.d.mts.map +1 -0
- package/dist/{cloudflare → host}/router.mjs +34 -13
- package/dist/host/router.mjs.map +1 -0
- package/dist/host/senders.cjs +63 -0
- package/dist/host/senders.cjs.map +1 -0
- package/dist/host/senders.d.cts +31 -0
- package/dist/host/senders.d.cts.map +1 -0
- package/dist/host/senders.d.mts +31 -0
- package/dist/host/senders.d.mts.map +1 -0
- package/dist/host/senders.mjs +59 -0
- package/dist/host/senders.mjs.map +1 -0
- package/dist/http2-client.cjs +90 -0
- package/dist/http2-client.cjs.map +1 -0
- package/dist/http2-client.d.cts +47 -0
- package/dist/http2-client.d.cts.map +1 -0
- package/dist/http2-client.d.mts +47 -0
- package/dist/http2-client.d.mts.map +1 -0
- package/dist/http2-client.mjs +88 -0
- package/dist/http2-client.mjs.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/react-email.cjs.map +1 -1
- package/dist/react-email.d.cts +1 -2
- package/dist/react-email.d.cts.map +1 -1
- package/dist/react-email.d.mts +1 -2
- package/dist/react-email.d.mts.map +1 -1
- package/dist/react-email.mjs.map +1 -1
- package/dist/store/d1.cjs +1 -0
- package/dist/store/d1.cjs.map +1 -1
- package/dist/store/d1.d.cts.map +1 -1
- package/dist/store/d1.d.mts.map +1 -1
- package/dist/store/d1.mjs +1 -0
- package/dist/store/d1.mjs.map +1 -1
- package/dist/store/index.cjs.map +1 -1
- package/dist/store/index.d.cts +74 -0
- package/dist/store/index.d.cts.map +1 -1
- package/dist/store/index.d.mts +74 -0
- package/dist/store/index.d.mts.map +1 -1
- package/dist/store/index.mjs.map +1 -1
- package/dist/store/postgres.cjs +177 -12
- package/dist/store/postgres.cjs.map +1 -1
- package/dist/store/postgres.d.cts +10 -1
- package/dist/store/postgres.d.cts.map +1 -1
- package/dist/store/postgres.d.mts +10 -1
- package/dist/store/postgres.d.mts.map +1 -1
- package/dist/store/postgres.mjs +177 -12
- package/dist/store/postgres.mjs.map +1 -1
- package/dist/store/tables.cjs +31 -2
- package/dist/store/tables.cjs.map +1 -1
- package/dist/store/tables.d.cts +1 -0
- package/dist/store/tables.d.cts.map +1 -1
- package/dist/store/tables.d.mts +1 -0
- package/dist/store/tables.d.mts.map +1 -1
- package/dist/store/tables.mjs +31 -2
- package/dist/store/tables.mjs.map +1 -1
- package/dist/transports/cloudflare-email.cjs +59 -0
- package/dist/transports/cloudflare-email.cjs.map +1 -0
- package/dist/transports/cloudflare-email.d.cts +38 -0
- package/dist/transports/cloudflare-email.d.cts.map +1 -0
- package/dist/transports/cloudflare-email.d.mts +38 -0
- package/dist/transports/cloudflare-email.d.mts.map +1 -0
- package/dist/transports/cloudflare-email.mjs +57 -0
- package/dist/transports/cloudflare-email.mjs.map +1 -0
- package/dist/transports/ses.cjs +91 -0
- package/dist/transports/ses.cjs.map +1 -0
- package/dist/transports/ses.d.cts +39 -0
- package/dist/transports/ses.d.cts.map +1 -0
- package/dist/transports/ses.d.mts +39 -0
- package/dist/transports/ses.d.mts.map +1 -0
- package/dist/transports/ses.mjs +89 -0
- package/dist/transports/ses.mjs.map +1 -0
- package/dist/transports/sigv4.cjs +83 -0
- package/dist/transports/sigv4.cjs.map +1 -0
- package/dist/transports/sigv4.d.cts +27 -0
- package/dist/transports/sigv4.d.cts.map +1 -0
- package/dist/transports/sigv4.d.mts +27 -0
- package/dist/transports/sigv4.d.mts.map +1 -0
- package/dist/transports/sigv4.mjs +82 -0
- package/dist/transports/sigv4.mjs.map +1 -0
- package/package.json +53 -1
- package/dist/cloudflare/channels.cjs.map +0 -1
- package/dist/cloudflare/channels.d.cts.map +0 -1
- package/dist/cloudflare/channels.d.mts.map +0 -1
- package/dist/cloudflare/channels.mjs.map +0 -1
- package/dist/cloudflare/router.cjs.map +0 -1
- package/dist/cloudflare/router.d.cts.map +0 -1
- package/dist/cloudflare/router.d.mts.map +0 -1
- package/dist/cloudflare/router.mjs.map +0 -1
- package/dist/cloudflare/senders.cjs +0 -121
- package/dist/cloudflare/senders.cjs.map +0 -1
- package/dist/cloudflare/senders.d.cts +0 -72
- package/dist/cloudflare/senders.d.cts.map +0 -1
- package/dist/cloudflare/senders.d.mts +0 -72
- package/dist/cloudflare/senders.d.mts.map +0 -1
- package/dist/cloudflare/senders.mjs +0 -115
- package/dist/cloudflare/senders.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs","names":["d1Store","WAKE_EVENT_TYPE","matchesWhere","JourneyFactSource","evaluateCondition","murmur3","PROFILE_UPDATED_EVENT","DEVICES_UPDATED_EVENT","semanticHash","BundleIR","SchemaMismatchError","checkEvent","recordPushOpen","z"],"sources":["../../src/cloudflare/router.ts"],"sourcesContent":["import * as z from 'zod/mini';\nimport { type Contract, type ContractResult, checkEvent } from '../contract';\nimport { murmur3 } from '../engine/bucket';\nimport {\n DEVICES_UPDATED_EVENT,\n PROFILE_UPDATED_EVENT,\n evaluateCondition,\n matchesWhere,\n} from '../engine/condition';\nimport { semanticHash } from '../hash';\nimport { BundleIR, type ConditionIR, type TriggerIR } from '../ir';\nimport { recordPushOpen } from '../reporting/tracking';\nimport { JourneyFactSource } from '../store/facts';\nimport {\n type BundleVersion,\n type JourneyStore,\n type ProfileProps,\n SchemaMismatchError,\n type SegmentTriggerRoute,\n} from '../store/index';\nimport {\n type JourneyEnv,\n type JourneyParams,\n WAKE_EVENT_TYPE,\n type WorkflowInstanceLike,\n} from './bindings';\nimport { d1Store } from './d1-env';\n\n/**\n * Ingest router. An incoming event does four things: it is stored, it wakes\n * waiting instances, it is matched against event triggers, and it re-evaluates\n * segment-trigger membership. Plus /deploy (persist a bundle) and /identify\n * (merge a profile — which wakes property-condition waits via\n * PROFILE_UPDATED_EVENT and re-evaluates segment triggers too).\n *\n * Storage goes through a JourneyStore; the `store` argument defaults to the\n * D1 + KV store built from the env's bindings, so a Worker that only has those\n * calls these functions exactly as before.\n */\n\nexport interface IngestInput {\n userId: string;\n event: string;\n payload?: Record<string, unknown>;\n ts?: number;\n /**\n * This occurrence's identity, and with it the idempotency of sending it.\n *\n * Only the sender can know whether two deliveries describe one occurrence or\n * two, so the engine does not decide: an id it has already stored makes the\n * second delivery a no-op. That matters because ingest is reachable from two\n * retrying callers — an HTTP client retrying a 500, and the interpreter's\n * send_event step being retried after it already committed its row — and a\n * second copy of an event silently changes every count- and window-based\n * condition that reads the log.\n *\n * Callers that retry should send an id they can reproduce. Omitting it gets\n * a fresh one, which records the event as its own occurrence.\n */\n id?: string;\n}\n\nexport interface IngestResult {\n /** The occurrence's identity: the caller's `id`, or the one minted for it. */\n id: string;\n /** False when that id was already in the log: nothing was written this time. */\n stored: boolean;\n woke: number;\n started: string[];\n}\n\nexport async function ingestEvent(\n env: JourneyEnv,\n input: IngestInput,\n store: JourneyStore = d1Store(env)\n): Promise<IngestResult> {\n if (input.event.startsWith('$')) {\n throw new Error(`event name '${input.event}' is reserved ('$' prefix is internal)`);\n }\n const ts = input.ts ?? Date.now();\n const payload = input.payload ?? {};\n // No id means the sender is not claiming this is a repeat of anything, which\n // a fresh one states truthfully — unlike a key derived from the contents,\n // which would silently collapse two identical events a second apart.\n const id = input.id ?? crypto.randomUUID();\n\n const stored = await store.insertEvent({\n id,\n userId: input.userId,\n event: input.event,\n ts,\n payload,\n });\n\n /*\n * The rest runs even for a duplicate. A retry arrives precisely because the\n * first attempt did not finish — it committed the row and then failed — so\n * returning early would strand the journeys the retry exists to start. Both\n * halves are independently idempotent: waking an instance that already moved\n * on is a no-op, and the entry ledger refuses a second entry.\n */\n const woke = await wakeSubscribers(env, store, input.userId, input.event);\n const started = await startTriggeredJourneys(env, store, { ...input, payload }, ts);\n started.push(...(await refreshSegmentTriggers(env, store, input.userId, ts)));\n return { id, stored, woke, started };\n}\n\nasync function wakeSubscribers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n event: string\n): Promise<number> {\n let woke = 0;\n for (const handle of await store.findWakeHandles(userId, event)) {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(handle);\n } catch {\n // Unknown instance (errored out without cleanup): drop the dangling subscription\n await store.unsubscribe(handle);\n continue;\n }\n try {\n await instance.sendEvent({ type: WAKE_EVENT_TYPE, payload: { event } });\n woke++;\n } catch {\n // Transient send failure (or an instance finishing right now): keep the\n // subscription — a later event retries it, and the wait's own timeout\n // bounds the damage. Deleting here would silence all future wake-ups.\n }\n }\n return woke;\n}\n\nasync function startTriggeredJourneys(\n env: JourneyEnv,\n store: JourneyStore,\n input: IngestInput & { payload: Record<string, unknown> },\n ts: number\n): Promise<string[]> {\n const started: string[] = [];\n for (const route of await store.findTriggers(input.event)) {\n // where: the payload gate — evaluated against the incoming event first\n if (route.where !== null && !matchesWhere(input.payload, route.where)) continue;\n\n // filter: the profile gate\n if (route.filter !== null) {\n const facts = new JourneyFactSource(store, input.userId);\n if (!(await evaluateCondition(route.filter, facts, ts))) continue;\n }\n\n const instanceId = await startJourney(\n env,\n store,\n route.workflow,\n route.hash,\n input.userId,\n ts,\n {\n event: input.event,\n payload: input.payload,\n }\n );\n if (instanceId !== null) started.push(instanceId);\n }\n return started;\n}\n\n/**\n * Segment-entry triggers, maintained lazily: on each ingest/identify for a\n * user, re-evaluate every trigger-routed segment for that user and act on the\n * membership transition (enter → start journeys, leave → drop membership so a\n * later re-entry is observable). Purely time-driven drift (an inactivity\n * segment turning true by clock alone) has no event to ride on: the scheduled\n * sweep catches it (`sweepSegments`).\n */\nexport async function refreshSegmentTriggers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n ts: number\n): Promise<string[]> {\n return refreshSegments(env, store, userId, ts, await store.listSegmentTriggers());\n}\n\n/**\n * Re-evaluate segments for one user — the routed ones only, or with `segments` every one named —\n * and act on each membership transition: entering records the membership and starts the\n * segment's routed workflows, leaving drops it. A segment trigger therefore starts journeys for\n * users who enter after it is deployed; a user already a member is not entered again.\n */\nasync function refreshSegments(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n ts: number,\n routes: readonly SegmentTriggerRoute[],\n segments: readonly string[] = [],\n // A sweep loads each definition once for all its users, not once per user\n definitions = new Map<string, ConditionIR | undefined>()\n): Promise<string[]> {\n const bySegment = new Map<string, { workflow: string; hash: string }[]>(\n segments.map((name) => [name, []])\n );\n for (const route of routes) {\n const list = bySegment.get(route.segment) ?? [];\n list.push({ workflow: route.workflow, hash: route.hash });\n bySegment.set(route.segment, list);\n }\n if (bySegment.size === 0) return [];\n\n const facts = new JourneyFactSource(store, userId);\n const started: string[] = [];\n const failures: unknown[] = [];\n for (const [segmentId, segmentRoutes] of bySegment) {\n if (!definitions.has(segmentId)) {\n definitions.set(segmentId, await store.getSegmentCondition(segmentId));\n }\n const definition = definitions.get(segmentId);\n if (definition === undefined) continue; // route without a definition: broken deploy, skip\n\n const matches = await evaluateCondition(definition, facts, ts);\n const member = await store.isSegmentMember(segmentId, userId);\n\n if (matches && !member) {\n // Entry transition: the membership and the starts it owes, recorded together\n await store.addSegmentMember(\n segmentId,\n userId,\n ts,\n segmentRoutes.map((route) => route.workflow)\n );\n } else if (!matches && member) {\n await store.removeSegmentMember(segmentId, userId);\n continue;\n }\n if (!matches) continue;\n\n // Every start the entry still owes — a fresh entry's, or one an earlier evaluation failed on.\n // Each is crossed off once its instance exists, so one workflow failing neither blocks the\n // others nor gets lost: the next evaluation (the sweep, the user's next event) retries it.\n const pending = new Set(await store.pendingSegmentStarts(segmentId, userId));\n for (const route of segmentRoutes) {\n if (!pending.has(route.workflow)) continue;\n try {\n const instanceId = await startJourney(env, store, route.workflow, route.hash, userId, ts, {\n event: '$segment_entry',\n payload: { segment: segmentId },\n });\n if (instanceId !== null) started.push(instanceId);\n await store.completeSegmentStart(segmentId, userId, route.workflow);\n } catch (error) {\n failures.push(error);\n }\n }\n }\n // Surface a failure to the caller (an ingest answers 500) once every start had its chance\n if (failures.length > 0) throw failures[0];\n return started;\n}\n\nexport interface SweepResult {\n users: number;\n /** Journeys the segments' entries started. */\n started: string[];\n /** Each deployed segment's size after the sweep (empty when the store keeps no reporting). */\n sizes: { segment: string; size: number }[];\n}\n\n/**\n * The scheduled sweep: every deployed segment evaluated for every known user — the evaluator a\n * journey's conditions run on, so a member is exactly who a journey would see in it. Membership\n * follows (joiners keep the time they joined, leavers are removed), segment triggers start the\n * journeys of whoever entered by the clock alone, and the store records each segment's size.\n * It walks users one by one: fine for thousands, a large audience wants SQL-side evaluation.\n */\nexport async function sweepSegments(\n env: JourneyEnv,\n store: JourneyStore,\n now = Date.now()\n): Promise<SweepResult> {\n // Erasures left unfinished (an instance would not stop) first: their users are not evaluated\n const erasing = new Set<string>();\n for (const userId of await store.pendingErasures()) {\n try {\n const { erased } = await eraseUser(env, userId, store);\n if (!erased) erasing.add(userId);\n } catch (error) {\n // Still pending: the next sweep tries again, and the rest of this one goes on\n erasing.add(userId);\n console.error(`[workflow] erasure of ${userId} failed`, error);\n }\n }\n const segments = (await store.listSegments()).map((segment) => segment.id);\n const routes = await store.listSegmentTriggers();\n const users = (await store.listUserIds()).filter((userId) => !erasing.has(userId));\n const started: string[] = [];\n const definitions = new Map<string, ConditionIR | undefined>();\n for (const userId of users) {\n try {\n started.push(\n ...(await refreshSegments(env, store, userId, now, routes, segments, definitions))\n );\n } catch (error) {\n // One user's failed start is kept for the next sweep; it must not stop everyone else's\n console.error(`[workflow] segment refresh for ${userId} failed`, error);\n }\n }\n const sizes = (await store.reporting?.snapshotSegments(now)) ?? [];\n return { users: users.length, started, sizes };\n}\n\n/**\n * Create one journey instance behind the entry ledger. Returns null when the\n * once-policy blocks the entry (the store's attempt is atomic, so concurrent\n * ingests cannot double-enter). A pair whose previous instance is recorded as\n * 'failed' is reclaimed rather than barred forever over one outage.\n */\nasync function startJourney(\n env: JourneyEnv,\n store: JourneyStore,\n workflow: string,\n hash: string,\n userId: string,\n ts: number,\n trigger: { event: string; payload: Record<string, unknown> }\n): Promise<string | null> {\n const instanceId = buildInstanceId(workflow, hash, userId, ts);\n const params: JourneyParams = { workflowId: workflow, contentHash: hash, userId, trigger };\n\n const outcome = await store.enterJourney({ workflow, userId, instanceId, hash, ts });\n if (outcome === null) return null; // already entered, and still alive\n\n try {\n await env.JOURNEY.create({ id: instanceId, params });\n } catch (error) {\n if (outcome === 'reclaimed') {\n // Put the corpse back rather than deleting it: the entry is still a\n // failure, and dropping the row would erase that from the ledger.\n await store.setEntryStatus(instanceId, 'failed');\n } else {\n // Roll the ledger back so a retried ingest can enter — otherwise the\n // once-policy would permanently record an entry that never ran.\n await store.removeEntry(instanceId);\n }\n throw error;\n }\n return instanceId;\n}\n\nconst utf8 = new TextEncoder();\n\n/**\n * Instance id: addressable (the router gets it directly to wake it), ≤100\n * chars, legal charset. The murmur3 fingerprint keeps ids distinct when the\n * sanitized/truncated userId alone would collide.\n */\nfunction buildInstanceId(workflow: string, hash: string, userId: string, ts: number): string {\n const uid = userId.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 24);\n const fingerprint = murmur3(utf8.encode(userId)).toString(36);\n return `${workflow.slice(0, 32)}-${hash.slice(0, 8)}-${uid}-${fingerprint}-${ts.toString(36)}`;\n}\n\n/* --------------------------------- identify --------------------------------- */\n\nexport interface IdentifyResult {\n ok: true;\n props: ProfileProps;\n woke: number;\n started: string[];\n}\n\n/**\n * Merge-patch profile properties (a null removes one), then wake property waits\n * and re-evaluate segment triggers. The merge is one statement in the store, so\n * two identifies landing together cannot lose each other's fields.\n */\nexport async function identifyUser(\n env: JourneyEnv,\n userId: string,\n props: ProfileProps,\n store: JourneyStore = d1Store(env)\n): Promise<IdentifyResult> {\n const ts = Date.now();\n const merged = await store.mergeProfile(userId, props);\n // Property-condition waits subscribe to this reserved event (see relevantEvents)\n const woke = await wakeSubscribers(env, store, userId, PROFILE_UPDATED_EVENT);\n // A profile change can move the user into (or out of) a trigger-routed segment\n const started = await refreshSegmentTriggers(env, store, userId, ts);\n return { ok: true, props: merged, woke, started };\n}\n\nexport interface DeviceRegistration {\n userId: string;\n token: string;\n platform: string;\n ts?: number;\n}\n\n/**\n * A push token registered for the user (or moved to them from another account: a token belongs\n * to one user at a time). Wakes the waits that read devices (`reachable('push')` inside\n * `waitUntil`), for the new owner and the previous one.\n */\nexport async function registerDevice(\n env: JourneyEnv,\n device: DeviceRegistration,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const previous = await store.removeDevice(device.token);\n await store.upsertDevice({ ...device, ts: device.ts ?? Date.now() });\n let woke = await wakeSubscribers(env, store, device.userId, DEVICES_UPDATED_EVENT);\n if (previous !== undefined && previous !== device.userId) {\n woke += await wakeSubscribers(env, store, previous, DEVICES_UPDATED_EVENT);\n }\n return { ok: true, woke };\n}\n\n/**\n * A deleted account: everything the engine keeps about the user is erased and the journeys still\n * running for them are terminated, so nothing more is sent. Idempotent.\n */\n/** Workflow instance states that will never run another step. */\nconst STOPPED_STATUSES = new Set(['complete', 'errored', 'terminated']);\n\n/**\n * Stop one instance for good; true once it is known not to run again. An instance the platform\n * no longer knows, or one already finished (terminate refuses those), counts as stopped. Any other\n * failure is not taken for \"already gone\": it answers false, and the erasure waits for a retry.\n */\nasync function stopInstance(env: JourneyEnv, instanceId: string): Promise<boolean> {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(instanceId);\n } catch (error) {\n if (/not[_ ]found/i.test(String(error))) return true;\n console.warn(`[workflow] looking up ${instanceId} to stop it failed`, error);\n return false;\n }\n if (instance.terminate === undefined) return false;\n try {\n await instance.terminate();\n return true;\n } catch (error) {\n const status = await instance.status?.().catch(() => undefined);\n if (status !== undefined && STOPPED_STATUSES.has(status.status)) return true;\n console.warn(`[workflow] terminating ${instanceId} failed`, error);\n return false;\n }\n}\n\n/**\n * Carry out a recorded erasure: stop every running instance of the user, and only once all have\n * stopped erase their data (the request with it). Stopping first means no step can write rows\n * back after the erase; erasing nothing until then keeps the entries that name the instances\n * still to stop, so a retry can finish the job.\n */\nasync function eraseUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore\n): Promise<{ erased: boolean; pending: string[] }> {\n const pending: string[] = [];\n for (const instanceId of await store.runningInstances(userId)) {\n if (!(await stopInstance(env, instanceId))) pending.push(instanceId);\n }\n if (pending.length > 0) return { erased: false, pending };\n await store.forgetUser(userId);\n return { erased: true, pending };\n}\n\n/**\n * Forget a user (a deleted account): the request is recorded first, then carried out. An\n * instance that will not stop leaves it pending — nothing erased yet — and the scheduled sweep\n * retries it; `erased: false` says so.\n */\nexport async function forgetUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore = d1Store(env),\n now = Date.now()\n): Promise<{ ok: true; erased: boolean; pending: string[] }> {\n await store.requestErasure(userId, now);\n return { ok: true, ...(await eraseUser(env, userId, store)) };\n}\n\n/**\n * The user signed out on the device: the token stays registered, bound to nobody, so the next\n * sign-in only has to bind it again. Wakes the former owner's device waits (`reachable('push')`\n * may no longer hold).\n */\nexport async function unbindDevice(\n env: JourneyEnv,\n token: string,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const owner = await store.unbindDevice(token);\n const woke =\n owner === undefined ? 0 : await wakeSubscribers(env, store, owner, DEVICES_UPDATED_EVENT);\n return { ok: true, woke };\n}\n\n/** A push token forgotten for good (the push service reports it gone); wakes its owner's device waits. */\nexport async function removeDevice(\n env: JourneyEnv,\n token: string,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const owner = await store.removeDevice(token);\n const woke =\n owner === undefined ? 0 : await wakeSubscribers(env, store, owner, DEVICES_UPDATED_EVENT);\n return { ok: true, woke };\n}\n\n/* ---------------------------------- deploy ---------------------------------- */\n\nexport interface DeployResult {\n workflows: string[];\n /**\n * Workflows whose trigger type has no runtime routing yet — they deploy (the\n * IR is stored and versioned) but will never start until the routing lands.\n * Currently: date (TODO — needs cron + Queues, instance creation is\n * rate-limited and a date trigger fans out to the whole audience at once)\n * and webhook (TODO — needs endpoint allocation).\n */\n unrouted: { workflow: string; trigger: TriggerIR['type'] }[];\n /**\n * 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 versioned deploy on a store that cannot tell which version is live (D1). */\nexport class UnversionedStoreError extends Error {\n override readonly name = 'UnversionedStoreError';\n constructor() {\n super('this store does not record which version is live: deploy with POST /bundle/deploy');\n }\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 = d1Store(env),\n version?: BundleVersion\n): Promise<DeployResult> {\n if (version !== undefined && store.replaceRoutesIfNewer === undefined) {\n throw new UnversionedStoreError();\n }\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)) ?? false;\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/* ----------------------------------- http ----------------------------------- */\n\n/**\n * Request bodies are untrusted JSON. They are read as unknown fields and\n * checked, never cast into the shape they are supposed to have: a cast only\n * silences the compiler, and what arrives here reaches SQL parameters.\n */\nasync function readBody(request: Request): Promise<Record<string, unknown>> {\n const body: unknown = await request.json();\n return isPlainObject(body) ? body : {};\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * How the ingest API applies a contract: 'enforce' refuses an invalid event or\n * patch with a 400 before anything is stored, woken or started; 'report' logs\n * the issues (event id, name, field paths — never the payload) and accepts it,\n * for checking real producers before turning enforcement on.\n */\nexport interface IngestValidation {\n contract?: Contract | undefined;\n mode?: 'enforce' | 'report' | undefined;\n}\n\nexport async function handleRequest(\n request: Request,\n env: JourneyEnv,\n store: JourneyStore = d1Store(env),\n validation: IngestValidation = {}\n): Promise<Response> {\n const url = new URL(request.url);\n const json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n const { contract } = validation;\n const enforce = validation.mode !== 'report';\n /** The contract's verdict: the value to use, or the response refusing the request. */\n const checked = <T>(\n result: ContractResult<T>,\n original: T,\n what: string\n ): { value: T } | { refused: Response } => {\n if (result.ok) return { value: result.data };\n const issues = result.issues.map((i) => `${i.path || '(root)'}: ${i.message}`);\n if (!enforce) {\n console.warn(`[workflow router] contract would refuse ${what}: ${issues.join('; ')}`);\n return { value: original };\n }\n return {\n refused: json({ error: `${what} refused by the contract`, issues: result.issues }, 400),\n };\n };\n\n if (request.method === 'GET' && url.pathname === '/health') {\n return json({ ok: true });\n }\n\n // Bearer auth on everything mutating. An unset token means an open dev\n // instance (see JourneyEnv.API_TOKEN) — production must configure it.\n if (env.API_TOKEN !== undefined) {\n if (request.headers.get('authorization') !== `Bearer ${env.API_TOKEN}`) {\n return json({ error: 'unauthorized' }, 401);\n }\n }\n\n try {\n if (request.method === 'POST' && url.pathname === '/events') {\n const { id, userId, event, payload, ts } = await readBody(request);\n if (!isNonEmptyString(userId) || !isNonEmptyString(event)) {\n return json({ error: 'userId and event required' }, 400);\n }\n if (event.startsWith('$')) {\n return json({ error: 'event names starting with $ are reserved' }, 400);\n }\n // An empty id is rejected rather than treated as absent: a caller that\n // sent one meant to identify the occurrence, and silently minting a\n // different one would turn their retry into a duplicate.\n if (id !== undefined && !isNonEmptyString(id)) {\n return json({ error: 'id must be a non-empty string' }, 400);\n }\n if (ts !== undefined && typeof ts !== 'number') {\n return json({ error: 'ts must be a number' }, 400);\n }\n if (payload !== undefined && !isPlainObject(payload)) {\n return json({ error: 'payload must be an object' }, 400);\n }\n let accepted = payload;\n if (contract !== undefined) {\n const verdict = checked(\n checkEvent(contract, event, payload ?? {}),\n accepted ?? {},\n `event '${event}'${typeof id === 'string' ? ` (${id})` : ''}`\n );\n if ('refused' in verdict) return verdict.refused;\n accepted = verdict.value;\n }\n return json(await ingestEvent(env, { id, userId, event, payload: accepted, ts }, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/identify') {\n const { userId, props } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isPlainObject(props)) return json({ error: 'props must be an object' }, 400);\n let patch = props as ProfileProps;\n if (contract !== undefined) {\n const verdict = checked(contract.parseProfilePatch(props), patch, 'identify');\n if ('refused' in verdict) return verdict.refused;\n patch = verdict.value as ProfileProps;\n }\n return json(await identifyUser(env, userId, patch, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices') {\n const { userId, token, platform, ts } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n if (platform !== 'ios' && platform !== 'android' && platform !== 'web') {\n return json({ error: \"platform must be 'ios', 'android' or 'web'\" }, 400);\n }\n if (ts !== undefined && typeof ts !== 'number')\n return json({ error: 'ts must be a number' }, 400);\n return json(\n await registerDevice(\n env,\n { userId, token, platform, ...(ts === undefined ? {} : { ts }) },\n store\n )\n );\n }\n\n if (request.method === 'POST' && url.pathname === '/messages/opened') {\n const { userId, messageId } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isNonEmptyString(messageId)) return json({ error: 'messageId required' }, 400);\n const recorded =\n store.reporting !== undefined && (await recordPushOpen(store.reporting, userId, messageId));\n return json({ ok: true, recorded });\n }\n\n if (request.method === 'POST' && url.pathname === '/users/forget') {\n const { userId } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n return json(await forgetUser(env, userId, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices/unbind') {\n const { token } = await readBody(request);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n return json(await unbindDevice(env, token, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices/remove') {\n const { token } = await readBody(request);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n return json(await removeDevice(env, token, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/deploy') {\n return json(await deployBundle(env, await request.json(), store));\n }\n\n return json({ error: 'not found' }, 404);\n } catch (error) {\n // Validation problems are the caller's to fix; anything else stays out of\n // the response body (internals are logged, not leaked).\n if (error instanceof z.core.$ZodError) {\n return json({ error: `invalid payload: ${error.message}` }, 400);\n }\n // The caller sent a self-inconsistent bundle: their problem to fix, so say what is wrong\n if (error instanceof BundleIntegrityError) {\n return json({ error: error.message }, 400);\n }\n // The operator's to fix (run the migrations), so the response says what is missing\n if (error instanceof SchemaMismatchError) {\n return json({ error: error.message, problems: error.problems }, 503);\n }\n console.error('[workflow router]', error);\n return json({ error: 'internal error' }, 500);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuEA,eAAsB,YACpB,KACA,OACA,QAAsBA,0BAAAA,QAAQ,GAAG,GACV;CACvB,IAAI,MAAM,MAAM,WAAW,GAAG,GAC5B,MAAM,IAAI,MAAM,eAAe,MAAM,MAAM,uCAAuC;CAEpF,MAAM,KAAK,MAAM,MAAM,KAAK,IAAI;CAChC,MAAM,UAAU,MAAM,WAAW,CAAC;CAIlC,MAAM,KAAK,MAAM,MAAM,OAAO,WAAW;CAEzC,MAAM,SAAS,MAAM,MAAM,YAAY;EACrC;EACA,QAAQ,MAAM;EACd,OAAO,MAAM;EACb;EACA;CACF,CAAC;CASD,MAAM,OAAO,MAAM,gBAAgB,KAAK,OAAO,MAAM,QAAQ,MAAM,KAAK;CACxE,MAAM,UAAU,MAAM,uBAAuB,KAAK,OAAO;EAAE,GAAG;EAAO;CAAQ,GAAG,EAAE;CAClF,QAAQ,KAAK,GAAI,MAAM,uBAAuB,KAAK,OAAO,MAAM,QAAQ,EAAE,CAAE;CAC5E,OAAO;EAAE;EAAI;EAAQ;EAAM;CAAQ;AACrC;AAEA,eAAe,gBACb,K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iBAgFc;EACf;;EAEA;;EAEA;IAAS;IAAiB;;;;;;;;;;wBAUN,cACpB,KAAK,YACL,OAAO,cACP,eACC,QAAQ;iBAqFM;EACf;EACA,OAAO;EACP;EACA;;;;;;;wBAQoB,aACpB,KAAK,YACL,gBACA,OAAO,cACP,QAAO,eACN,QAAQ;iBAUM;EACf;EACA;EACA;EACA;;;;;;;wBAQoB,eACpB,KAAK,YACL,QAAQ,oBACR,QAAO,eACN;EAAU;EAAU;;;;;;;wBAoED,WACpB,KAAK,YACL,gBACA,QAAO,cACP,eACC;EAAU;EAAU;EAAiB;;;;;;;wBAUlB,aACpB,KAAK,YACL,eACA,QAAO,eACN;EAAU;EAAU;;;wBAQD,aACpB,KAAK,YACL,eACA,QAAO,eACN;EAAU;EAAU;;iBASN;EACf;;;;;;;;EAQA;IAAY;IAAkB,SAAS;;;;;;EAKvC;;;qBAIW,8BAA8B;WACvB;EAClB;;;qBAMW,6BAA6B;EACxC,YAAY;;;;;;;;wBA8CQ,aACpB,KAAK,YACL,iBACA,QAAO,cACP,UAAU,gBACT,QAAQ;;;;;;;iBAqDM;EACf,WAAW;EACX;;wBAGoB,cACpB,SAAS,SACT,KAAK,YACL,QAAO,cACP,aAAY,mBACX,QAAQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router.d.mts","names":[],"sources":["../../src/cloudflare/router.ts"],"mappings":";;;;;;;;;;;;;;;;iBAwCiB;EACf;EACA;EACA,UAAU;EACV;;;;;;;;;;;;;;;EAeA;;iBAGe;;EAEf;;EAEA;EACA;EACA;;wBAGoB,YACpB,KAAK,YACL,OAAO,aACP,QAAO,eACN,QAAQ;;;;;;;;;wBAsGW,uBACpB,KAAK,YACL,OAAO,cACP,gBACA,aACC;iBAgFc;EACf;;EAEA;;EAEA;IAAS;IAAiB;;;;;;;;;;wBAUN,cACpB,KAAK,YACL,OAAO,cACP,eACC,QAAQ;iBAqFM;EACf;EACA,OAAO;EACP;EACA;;;;;;;wBAQoB,aACpB,KAAK,YACL,gBACA,OAAO,cACP,QAAO,eACN,QAAQ;iBAUM;EACf;EACA;EACA;EACA;;;;;;;wBAQoB,eACpB,KAAK,YACL,QAAQ,oBACR,QAAO,eACN;EAAU;EAAU;;;;;;;wBAoED,WACpB,KAAK,YACL,gBACA,QAAO,cACP,eACC;EAAU;EAAU;EAAiB;;;;;;;wBAUlB,aACpB,KAAK,YACL,eACA,QAAO,eACN;EAAU;EAAU;;;wBAQD,aACpB,KAAK,YACL,eACA,QAAO,eACN;EAAU;EAAU;;iBASN;EACf;;;;;;;;EAQA;IAAY;IAAkB,SAAS;;;;;;EAKvC;;;qBAIW,8BAA8B;WACvB;EAClB;;;qBAMW,6BAA6B;EACxC,YAAY;;;;;;;;wBA8CQ,aACpB,KAAK,YACL,iBACA,QAAO,cACP,UAAU,gBACT,QAAQ;;;;;;;iBAqDM;EACf,WAAW;EACX;;wBAGoB,cACpB,SAAS,SACT,KAAK,YACL,QAAO,cACP,aAAY,mBACX,QAAQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router.mjs","names":[],"sources":["../../src/cloudflare/router.ts"],"sourcesContent":["import * as z from 'zod/mini';\nimport { type Contract, type ContractResult, checkEvent } from '../contract';\nimport { murmur3 } from '../engine/bucket';\nimport {\n DEVICES_UPDATED_EVENT,\n PROFILE_UPDATED_EVENT,\n evaluateCondition,\n matchesWhere,\n} from '../engine/condition';\nimport { semanticHash } from '../hash';\nimport { BundleIR, type ConditionIR, type TriggerIR } from '../ir';\nimport { recordPushOpen } from '../reporting/tracking';\nimport { JourneyFactSource } from '../store/facts';\nimport {\n type BundleVersion,\n type JourneyStore,\n type ProfileProps,\n SchemaMismatchError,\n type SegmentTriggerRoute,\n} from '../store/index';\nimport {\n type JourneyEnv,\n type JourneyParams,\n WAKE_EVENT_TYPE,\n type WorkflowInstanceLike,\n} from './bindings';\nimport { d1Store } from './d1-env';\n\n/**\n * Ingest router. An incoming event does four things: it is stored, it wakes\n * waiting instances, it is matched against event triggers, and it re-evaluates\n * segment-trigger membership. Plus /deploy (persist a bundle) and /identify\n * (merge a profile — which wakes property-condition waits via\n * PROFILE_UPDATED_EVENT and re-evaluates segment triggers too).\n *\n * Storage goes through a JourneyStore; the `store` argument defaults to the\n * D1 + KV store built from the env's bindings, so a Worker that only has those\n * calls these functions exactly as before.\n */\n\nexport interface IngestInput {\n userId: string;\n event: string;\n payload?: Record<string, unknown>;\n ts?: number;\n /**\n * This occurrence's identity, and with it the idempotency of sending it.\n *\n * Only the sender can know whether two deliveries describe one occurrence or\n * two, so the engine does not decide: an id it has already stored makes the\n * second delivery a no-op. That matters because ingest is reachable from two\n * retrying callers — an HTTP client retrying a 500, and the interpreter's\n * send_event step being retried after it already committed its row — and a\n * second copy of an event silently changes every count- and window-based\n * condition that reads the log.\n *\n * Callers that retry should send an id they can reproduce. Omitting it gets\n * a fresh one, which records the event as its own occurrence.\n */\n id?: string;\n}\n\nexport interface IngestResult {\n /** The occurrence's identity: the caller's `id`, or the one minted for it. */\n id: string;\n /** False when that id was already in the log: nothing was written this time. */\n stored: boolean;\n woke: number;\n started: string[];\n}\n\nexport async function ingestEvent(\n env: JourneyEnv,\n input: IngestInput,\n store: JourneyStore = d1Store(env)\n): Promise<IngestResult> {\n if (input.event.startsWith('$')) {\n throw new Error(`event name '${input.event}' is reserved ('$' prefix is internal)`);\n }\n const ts = input.ts ?? Date.now();\n const payload = input.payload ?? {};\n // No id means the sender is not claiming this is a repeat of anything, which\n // a fresh one states truthfully — unlike a key derived from the contents,\n // which would silently collapse two identical events a second apart.\n const id = input.id ?? crypto.randomUUID();\n\n const stored = await store.insertEvent({\n id,\n userId: input.userId,\n event: input.event,\n ts,\n payload,\n });\n\n /*\n * The rest runs even for a duplicate. A retry arrives precisely because the\n * first attempt did not finish — it committed the row and then failed — so\n * returning early would strand the journeys the retry exists to start. Both\n * halves are independently idempotent: waking an instance that already moved\n * on is a no-op, and the entry ledger refuses a second entry.\n */\n const woke = await wakeSubscribers(env, store, input.userId, input.event);\n const started = await startTriggeredJourneys(env, store, { ...input, payload }, ts);\n started.push(...(await refreshSegmentTriggers(env, store, input.userId, ts)));\n return { id, stored, woke, started };\n}\n\nasync function wakeSubscribers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n event: string\n): Promise<number> {\n let woke = 0;\n for (const handle of await store.findWakeHandles(userId, event)) {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(handle);\n } catch {\n // Unknown instance (errored out without cleanup): drop the dangling subscription\n await store.unsubscribe(handle);\n continue;\n }\n try {\n await instance.sendEvent({ type: WAKE_EVENT_TYPE, payload: { event } });\n woke++;\n } catch {\n // Transient send failure (or an instance finishing right now): keep the\n // subscription — a later event retries it, and the wait's own timeout\n // bounds the damage. Deleting here would silence all future wake-ups.\n }\n }\n return woke;\n}\n\nasync function startTriggeredJourneys(\n env: JourneyEnv,\n store: JourneyStore,\n input: IngestInput & { payload: Record<string, unknown> },\n ts: number\n): Promise<string[]> {\n const started: string[] = [];\n for (const route of await store.findTriggers(input.event)) {\n // where: the payload gate — evaluated against the incoming event first\n if (route.where !== null && !matchesWhere(input.payload, route.where)) continue;\n\n // filter: the profile gate\n if (route.filter !== null) {\n const facts = new JourneyFactSource(store, input.userId);\n if (!(await evaluateCondition(route.filter, facts, ts))) continue;\n }\n\n const instanceId = await startJourney(\n env,\n store,\n route.workflow,\n route.hash,\n input.userId,\n ts,\n {\n event: input.event,\n payload: input.payload,\n }\n );\n if (instanceId !== null) started.push(instanceId);\n }\n return started;\n}\n\n/**\n * Segment-entry triggers, maintained lazily: on each ingest/identify for a\n * user, re-evaluate every trigger-routed segment for that user and act on the\n * membership transition (enter → start journeys, leave → drop membership so a\n * later re-entry is observable). Purely time-driven drift (an inactivity\n * segment turning true by clock alone) has no event to ride on: the scheduled\n * sweep catches it (`sweepSegments`).\n */\nexport async function refreshSegmentTriggers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n ts: number\n): Promise<string[]> {\n return refreshSegments(env, store, userId, ts, await store.listSegmentTriggers());\n}\n\n/**\n * Re-evaluate segments for one user — the routed ones only, or with `segments` every one named —\n * and act on each membership transition: entering records the membership and starts the\n * segment's routed workflows, leaving drops it. A segment trigger therefore starts journeys for\n * users who enter after it is deployed; a user already a member is not entered again.\n */\nasync function refreshSegments(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n ts: number,\n routes: readonly SegmentTriggerRoute[],\n segments: readonly string[] = [],\n // A sweep loads each definition once for all its users, not once per user\n definitions = new Map<string, ConditionIR | undefined>()\n): Promise<string[]> {\n const bySegment = new Map<string, { workflow: string; hash: string }[]>(\n segments.map((name) => [name, []])\n );\n for (const route of routes) {\n const list = bySegment.get(route.segment) ?? [];\n list.push({ workflow: route.workflow, hash: route.hash });\n bySegment.set(route.segment, list);\n }\n if (bySegment.size === 0) return [];\n\n const facts = new JourneyFactSource(store, userId);\n const started: string[] = [];\n const failures: unknown[] = [];\n for (const [segmentId, segmentRoutes] of bySegment) {\n if (!definitions.has(segmentId)) {\n definitions.set(segmentId, await store.getSegmentCondition(segmentId));\n }\n const definition = definitions.get(segmentId);\n if (definition === undefined) continue; // route without a definition: broken deploy, skip\n\n const matches = await evaluateCondition(definition, facts, ts);\n const member = await store.isSegmentMember(segmentId, userId);\n\n if (matches && !member) {\n // Entry transition: the membership and the starts it owes, recorded together\n await store.addSegmentMember(\n segmentId,\n userId,\n ts,\n segmentRoutes.map((route) => route.workflow)\n );\n } else if (!matches && member) {\n await store.removeSegmentMember(segmentId, userId);\n continue;\n }\n if (!matches) continue;\n\n // Every start the entry still owes — a fresh entry's, or one an earlier evaluation failed on.\n // Each is crossed off once its instance exists, so one workflow failing neither blocks the\n // others nor gets lost: the next evaluation (the sweep, the user's next event) retries it.\n const pending = new Set(await store.pendingSegmentStarts(segmentId, userId));\n for (const route of segmentRoutes) {\n if (!pending.has(route.workflow)) continue;\n try {\n const instanceId = await startJourney(env, store, route.workflow, route.hash, userId, ts, {\n event: '$segment_entry',\n payload: { segment: segmentId },\n });\n if (instanceId !== null) started.push(instanceId);\n await store.completeSegmentStart(segmentId, userId, route.workflow);\n } catch (error) {\n failures.push(error);\n }\n }\n }\n // Surface a failure to the caller (an ingest answers 500) once every start had its chance\n if (failures.length > 0) throw failures[0];\n return started;\n}\n\nexport interface SweepResult {\n users: number;\n /** Journeys the segments' entries started. */\n started: string[];\n /** Each deployed segment's size after the sweep (empty when the store keeps no reporting). */\n sizes: { segment: string; size: number }[];\n}\n\n/**\n * The scheduled sweep: every deployed segment evaluated for every known user — the evaluator a\n * journey's conditions run on, so a member is exactly who a journey would see in it. Membership\n * follows (joiners keep the time they joined, leavers are removed), segment triggers start the\n * journeys of whoever entered by the clock alone, and the store records each segment's size.\n * It walks users one by one: fine for thousands, a large audience wants SQL-side evaluation.\n */\nexport async function sweepSegments(\n env: JourneyEnv,\n store: JourneyStore,\n now = Date.now()\n): Promise<SweepResult> {\n // Erasures left unfinished (an instance would not stop) first: their users are not evaluated\n const erasing = new Set<string>();\n for (const userId of await store.pendingErasures()) {\n try {\n const { erased } = await eraseUser(env, userId, store);\n if (!erased) erasing.add(userId);\n } catch (error) {\n // Still pending: the next sweep tries again, and the rest of this one goes on\n erasing.add(userId);\n console.error(`[workflow] erasure of ${userId} failed`, error);\n }\n }\n const segments = (await store.listSegments()).map((segment) => segment.id);\n const routes = await store.listSegmentTriggers();\n const users = (await store.listUserIds()).filter((userId) => !erasing.has(userId));\n const started: string[] = [];\n const definitions = new Map<string, ConditionIR | undefined>();\n for (const userId of users) {\n try {\n started.push(\n ...(await refreshSegments(env, store, userId, now, routes, segments, definitions))\n );\n } catch (error) {\n // One user's failed start is kept for the next sweep; it must not stop everyone else's\n console.error(`[workflow] segment refresh for ${userId} failed`, error);\n }\n }\n const sizes = (await store.reporting?.snapshotSegments(now)) ?? [];\n return { users: users.length, started, sizes };\n}\n\n/**\n * Create one journey instance behind the entry ledger. Returns null when the\n * once-policy blocks the entry (the store's attempt is atomic, so concurrent\n * ingests cannot double-enter). A pair whose previous instance is recorded as\n * 'failed' is reclaimed rather than barred forever over one outage.\n */\nasync function startJourney(\n env: JourneyEnv,\n store: JourneyStore,\n workflow: string,\n hash: string,\n userId: string,\n ts: number,\n trigger: { event: string; payload: Record<string, unknown> }\n): Promise<string | null> {\n const instanceId = buildInstanceId(workflow, hash, userId, ts);\n const params: JourneyParams = { workflowId: workflow, contentHash: hash, userId, trigger };\n\n const outcome = await store.enterJourney({ workflow, userId, instanceId, hash, ts });\n if (outcome === null) return null; // already entered, and still alive\n\n try {\n await env.JOURNEY.create({ id: instanceId, params });\n } catch (error) {\n if (outcome === 'reclaimed') {\n // Put the corpse back rather than deleting it: the entry is still a\n // failure, and dropping the row would erase that from the ledger.\n await store.setEntryStatus(instanceId, 'failed');\n } else {\n // Roll the ledger back so a retried ingest can enter — otherwise the\n // once-policy would permanently record an entry that never ran.\n await store.removeEntry(instanceId);\n }\n throw error;\n }\n return instanceId;\n}\n\nconst utf8 = new TextEncoder();\n\n/**\n * Instance id: addressable (the router gets it directly to wake it), ≤100\n * chars, legal charset. The murmur3 fingerprint keeps ids distinct when the\n * sanitized/truncated userId alone would collide.\n */\nfunction buildInstanceId(workflow: string, hash: string, userId: string, ts: number): string {\n const uid = userId.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 24);\n const fingerprint = murmur3(utf8.encode(userId)).toString(36);\n return `${workflow.slice(0, 32)}-${hash.slice(0, 8)}-${uid}-${fingerprint}-${ts.toString(36)}`;\n}\n\n/* --------------------------------- identify --------------------------------- */\n\nexport interface IdentifyResult {\n ok: true;\n props: ProfileProps;\n woke: number;\n started: string[];\n}\n\n/**\n * Merge-patch profile properties (a null removes one), then wake property waits\n * and re-evaluate segment triggers. The merge is one statement in the store, so\n * two identifies landing together cannot lose each other's fields.\n */\nexport async function identifyUser(\n env: JourneyEnv,\n userId: string,\n props: ProfileProps,\n store: JourneyStore = d1Store(env)\n): Promise<IdentifyResult> {\n const ts = Date.now();\n const merged = await store.mergeProfile(userId, props);\n // Property-condition waits subscribe to this reserved event (see relevantEvents)\n const woke = await wakeSubscribers(env, store, userId, PROFILE_UPDATED_EVENT);\n // A profile change can move the user into (or out of) a trigger-routed segment\n const started = await refreshSegmentTriggers(env, store, userId, ts);\n return { ok: true, props: merged, woke, started };\n}\n\nexport interface DeviceRegistration {\n userId: string;\n token: string;\n platform: string;\n ts?: number;\n}\n\n/**\n * A push token registered for the user (or moved to them from another account: a token belongs\n * to one user at a time). Wakes the waits that read devices (`reachable('push')` inside\n * `waitUntil`), for the new owner and the previous one.\n */\nexport async function registerDevice(\n env: JourneyEnv,\n device: DeviceRegistration,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const previous = await store.removeDevice(device.token);\n await store.upsertDevice({ ...device, ts: device.ts ?? Date.now() });\n let woke = await wakeSubscribers(env, store, device.userId, DEVICES_UPDATED_EVENT);\n if (previous !== undefined && previous !== device.userId) {\n woke += await wakeSubscribers(env, store, previous, DEVICES_UPDATED_EVENT);\n }\n return { ok: true, woke };\n}\n\n/**\n * A deleted account: everything the engine keeps about the user is erased and the journeys still\n * running for them are terminated, so nothing more is sent. Idempotent.\n */\n/** Workflow instance states that will never run another step. */\nconst STOPPED_STATUSES = new Set(['complete', 'errored', 'terminated']);\n\n/**\n * Stop one instance for good; true once it is known not to run again. An instance the platform\n * no longer knows, or one already finished (terminate refuses those), counts as stopped. Any other\n * failure is not taken for \"already gone\": it answers false, and the erasure waits for a retry.\n */\nasync function stopInstance(env: JourneyEnv, instanceId: string): Promise<boolean> {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(instanceId);\n } catch (error) {\n if (/not[_ ]found/i.test(String(error))) return true;\n console.warn(`[workflow] looking up ${instanceId} to stop it failed`, error);\n return false;\n }\n if (instance.terminate === undefined) return false;\n try {\n await instance.terminate();\n return true;\n } catch (error) {\n const status = await instance.status?.().catch(() => undefined);\n if (status !== undefined && STOPPED_STATUSES.has(status.status)) return true;\n console.warn(`[workflow] terminating ${instanceId} failed`, error);\n return false;\n }\n}\n\n/**\n * Carry out a recorded erasure: stop every running instance of the user, and only once all have\n * stopped erase their data (the request with it). Stopping first means no step can write rows\n * back after the erase; erasing nothing until then keeps the entries that name the instances\n * still to stop, so a retry can finish the job.\n */\nasync function eraseUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore\n): Promise<{ erased: boolean; pending: string[] }> {\n const pending: string[] = [];\n for (const instanceId of await store.runningInstances(userId)) {\n if (!(await stopInstance(env, instanceId))) pending.push(instanceId);\n }\n if (pending.length > 0) return { erased: false, pending };\n await store.forgetUser(userId);\n return { erased: true, pending };\n}\n\n/**\n * Forget a user (a deleted account): the request is recorded first, then carried out. An\n * instance that will not stop leaves it pending — nothing erased yet — and the scheduled sweep\n * retries it; `erased: false` says so.\n */\nexport async function forgetUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore = d1Store(env),\n now = Date.now()\n): Promise<{ ok: true; erased: boolean; pending: string[] }> {\n await store.requestErasure(userId, now);\n return { ok: true, ...(await eraseUser(env, userId, store)) };\n}\n\n/**\n * The user signed out on the device: the token stays registered, bound to nobody, so the next\n * sign-in only has to bind it again. Wakes the former owner's device waits (`reachable('push')`\n * may no longer hold).\n */\nexport async function unbindDevice(\n env: JourneyEnv,\n token: string,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const owner = await store.unbindDevice(token);\n const woke =\n owner === undefined ? 0 : await wakeSubscribers(env, store, owner, DEVICES_UPDATED_EVENT);\n return { ok: true, woke };\n}\n\n/** A push token forgotten for good (the push service reports it gone); wakes its owner's device waits. */\nexport async function removeDevice(\n env: JourneyEnv,\n token: string,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const owner = await store.removeDevice(token);\n const woke =\n owner === undefined ? 0 : await wakeSubscribers(env, store, owner, DEVICES_UPDATED_EVENT);\n return { ok: true, woke };\n}\n\n/* ---------------------------------- deploy ---------------------------------- */\n\nexport interface DeployResult {\n workflows: string[];\n /**\n * Workflows whose trigger type has no runtime routing yet — they deploy (the\n * IR is stored and versioned) but will never start until the routing lands.\n * Currently: date (TODO — needs cron + Queues, instance creation is\n * rate-limited and a date trigger fans out to the whole audience at once)\n * and webhook (TODO — needs endpoint allocation).\n */\n unrouted: { workflow: string; trigger: TriggerIR['type'] }[];\n /**\n * 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 versioned deploy on a store that cannot tell which version is live (D1). */\nexport class UnversionedStoreError extends Error {\n override readonly name = 'UnversionedStoreError';\n constructor() {\n super('this store does not record which version is live: deploy with POST /bundle/deploy');\n }\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 = d1Store(env),\n version?: BundleVersion\n): Promise<DeployResult> {\n if (version !== undefined && store.replaceRoutesIfNewer === undefined) {\n throw new UnversionedStoreError();\n }\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)) ?? false;\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/* ----------------------------------- http ----------------------------------- */\n\n/**\n * Request bodies are untrusted JSON. They are read as unknown fields and\n * checked, never cast into the shape they are supposed to have: a cast only\n * silences the compiler, and what arrives here reaches SQL parameters.\n */\nasync function readBody(request: Request): Promise<Record<string, unknown>> {\n const body: unknown = await request.json();\n return isPlainObject(body) ? body : {};\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * How the ingest API applies a contract: 'enforce' refuses an invalid event or\n * patch with a 400 before anything is stored, woken or started; 'report' logs\n * the issues (event id, name, field paths — never the payload) and accepts it,\n * for checking real producers before turning enforcement on.\n */\nexport interface IngestValidation {\n contract?: Contract | undefined;\n mode?: 'enforce' | 'report' | undefined;\n}\n\nexport async function handleRequest(\n request: Request,\n env: JourneyEnv,\n store: JourneyStore = d1Store(env),\n validation: IngestValidation = {}\n): Promise<Response> {\n const url = new URL(request.url);\n const json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n const { contract } = validation;\n const enforce = validation.mode !== 'report';\n /** The contract's verdict: the value to use, or the response refusing the request. */\n const checked = <T>(\n result: ContractResult<T>,\n original: T,\n what: string\n ): { value: T } | { refused: Response } => {\n if (result.ok) return { value: result.data };\n const issues = result.issues.map((i) => `${i.path || '(root)'}: ${i.message}`);\n if (!enforce) {\n console.warn(`[workflow router] contract would refuse ${what}: ${issues.join('; ')}`);\n return { value: original };\n }\n return {\n refused: json({ error: `${what} refused by the contract`, issues: result.issues }, 400),\n };\n };\n\n if (request.method === 'GET' && url.pathname === '/health') {\n return json({ ok: true });\n }\n\n // Bearer auth on everything mutating. An unset token means an open dev\n // instance (see JourneyEnv.API_TOKEN) — production must configure it.\n if (env.API_TOKEN !== undefined) {\n if (request.headers.get('authorization') !== `Bearer ${env.API_TOKEN}`) {\n return json({ error: 'unauthorized' }, 401);\n }\n }\n\n try {\n if (request.method === 'POST' && url.pathname === '/events') {\n const { id, userId, event, payload, ts } = await readBody(request);\n if (!isNonEmptyString(userId) || !isNonEmptyString(event)) {\n return json({ error: 'userId and event required' }, 400);\n }\n if (event.startsWith('$')) {\n return json({ error: 'event names starting with $ are reserved' }, 400);\n }\n // An empty id is rejected rather than treated as absent: a caller that\n // sent one meant to identify the occurrence, and silently minting a\n // different one would turn their retry into a duplicate.\n if (id !== undefined && !isNonEmptyString(id)) {\n return json({ error: 'id must be a non-empty string' }, 400);\n }\n if (ts !== undefined && typeof ts !== 'number') {\n return json({ error: 'ts must be a number' }, 400);\n }\n if (payload !== undefined && !isPlainObject(payload)) {\n return json({ error: 'payload must be an object' }, 400);\n }\n let accepted = payload;\n if (contract !== undefined) {\n const verdict = checked(\n checkEvent(contract, event, payload ?? {}),\n accepted ?? {},\n `event '${event}'${typeof id === 'string' ? ` (${id})` : ''}`\n );\n if ('refused' in verdict) return verdict.refused;\n accepted = verdict.value;\n }\n return json(await ingestEvent(env, { id, userId, event, payload: accepted, ts }, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/identify') {\n const { userId, props } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isPlainObject(props)) return json({ error: 'props must be an object' }, 400);\n let patch = props as ProfileProps;\n if (contract !== undefined) {\n const verdict = checked(contract.parseProfilePatch(props), patch, 'identify');\n if ('refused' in verdict) return verdict.refused;\n patch = verdict.value as ProfileProps;\n }\n return json(await identifyUser(env, userId, patch, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices') {\n const { userId, token, platform, ts } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n if (platform !== 'ios' && platform !== 'android' && platform !== 'web') {\n return json({ error: \"platform must be 'ios', 'android' or 'web'\" }, 400);\n }\n if (ts !== undefined && typeof ts !== 'number')\n return json({ error: 'ts must be a number' }, 400);\n return json(\n await registerDevice(\n env,\n { userId, token, platform, ...(ts === undefined ? {} : { ts }) },\n store\n )\n );\n }\n\n if (request.method === 'POST' && url.pathname === '/messages/opened') {\n const { userId, messageId } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isNonEmptyString(messageId)) return json({ error: 'messageId required' }, 400);\n const recorded =\n store.reporting !== undefined && (await recordPushOpen(store.reporting, userId, messageId));\n return json({ ok: true, recorded });\n }\n\n if (request.method === 'POST' && url.pathname === '/users/forget') {\n const { userId } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n return json(await forgetUser(env, userId, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices/unbind') {\n const { token } = await readBody(request);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n return json(await unbindDevice(env, token, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices/remove') {\n const { token } = await readBody(request);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n return json(await removeDevice(env, token, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/deploy') {\n return json(await deployBundle(env, await request.json(), store));\n }\n\n return json({ error: 'not found' }, 404);\n } catch (error) {\n // Validation problems are the caller's to fix; anything else stays out of\n // the response body (internals are logged, not leaked).\n if (error instanceof z.core.$ZodError) {\n return json({ error: `invalid payload: ${error.message}` }, 400);\n }\n // The caller sent a self-inconsistent bundle: their problem to fix, so say what is wrong\n if (error instanceof BundleIntegrityError) {\n return json({ error: error.message }, 400);\n }\n // The operator's to fix (run the migrations), so the response says what is missing\n if (error instanceof SchemaMismatchError) {\n return json({ error: error.message, problems: error.problems }, 503);\n }\n console.error('[workflow router]', error);\n return json({ error: 'internal error' }, 500);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAuEA,eAAsB,YACpB,KACA,OACA,QAAsB,QAAQ,GAAG,GACV;CACvB,IAAI,MAAM,MAAM,WAAW,GAAG,GAC5B,MAAM,IAAI,MAAM,eAAe,MAAM,MAAM,uCAAuC;CAEpF,MAAM,KAAK,MAAM,MAAM,KAAK,IAAI;CAChC,MAAM,UAAU,MAAM,WAAW,CAAC;CAIlC,MAAM,KAAK,MAAM,MAAM,OAAO,WAAW;CAEzC,MAAM,SAAS,MAAM,MAAM,YAAY;EACrC;EACA,QAAQ,MAAM;EACd,OAAO,MAAM;EACb;EACA;CACF,CAAC;CASD,MAAM,OAAO,MAAM,gBAAgB,KAAK,OAAO,MAAM,QAAQ,MAAM,KAAK;CACxE,MAAM,UAAU,MAAM,uBAAuB,KAAK,OAAO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AG,GAAG;GAC1E,OAAO,KAAK,MAAM,aAAa,KAAK,OAAO,KAAK,CAAC;EACnD;EAEA,IAAI,QAAQ,WAAW,UAAU,IAAI,aAAa,mBAAmB;GACnE,MAAM,EAAE,UAAU,MAAM,SAAS,OAAO;GACxC,IAAI,CAAC,iBAAiB,KAAK,GAAG,OAAO,KAAK,EAAE,OAAO,iBAAiB,GAAG,GAAG;GAC1E,OAAO,KAAK,MAAM,aAAa,KAAK,OAAO,KAAK,CAAC;EACnD;EAEA,IAAI,QAAQ,WAAW,UAAU,IAAI,aAAa,WAChD,OAAO,KAAK,MAAM,aAAa,KAAK,MAAM,QAAQ,KAAK,GAAG,KAAK,CAAC;EAGlE,OAAO,KAAK,EAAE,OAAO,YAAY,GAAG,GAAG;CACzC,SAAS,OAAO;EAGd,IAAI,iBAAiB,EAAE,KAAK,WAC1B,OAAO,KAAK,EAAE,OAAO,oBAAoB,MAAM,UAAU,GAAG,GAAG;EAGjE,IAAI,iBAAiB,sBACnB,OAAO,KAAK,EAAE,OAAO,MAAM,QAAQ,GAAG,GAAG;EAG3C,IAAI,iBAAiB,qBACnB,OAAO,KAAK;GAAE,OAAO,MAAM;GAAS,UAAU,MAAM;EAAS,GAAG,GAAG;EAErE,QAAQ,MAAM,qBAAqB,KAAK;EACxC,OAAO,KAAK,EAAE,OAAO,iBAAiB,GAAG,GAAG;CAC9C;AACF"}
|
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_email = require("../email.cjs");
|
|
3
|
-
//#region src/cloudflare/senders.ts
|
|
4
|
-
/**
|
|
5
|
-
* Send straight through Cloudflare Email Service — a binding call, no outbound
|
|
6
|
-
* HTTP. Throwing hands retries to the CF step, and the message's
|
|
7
|
-
* idempotencyKey travels with the call so the binding can drop the duplicate a
|
|
8
|
-
* retry or replay produces.
|
|
9
|
-
*/
|
|
10
|
-
var CfEmailSender = class {
|
|
11
|
-
options;
|
|
12
|
-
constructor(options) {
|
|
13
|
-
this.options = options;
|
|
14
|
-
}
|
|
15
|
-
async send(message) {
|
|
16
|
-
if (message.channel !== "email") throw new Error(`CfEmailSender: unsupported channel '${message.channel}'`);
|
|
17
|
-
if (message.recipient === void 0) throw new Error(`CfEmailSender: no recipient for user '${message.userId}'`);
|
|
18
|
-
const { subject, html, from, replyTo, unsubscribeUrl } = await this.options.render(message.template, message.props);
|
|
19
|
-
const tracked = message.tracking === void 0 ? html : trackEmail(html, message.tracking, unsubscribeUrl);
|
|
20
|
-
await message.tracking?.commit?.();
|
|
21
|
-
await this.options.binding.send({
|
|
22
|
-
from,
|
|
23
|
-
to: message.recipient,
|
|
24
|
-
...replyTo === void 0 ? {} : { replyTo },
|
|
25
|
-
subject,
|
|
26
|
-
html: tracked,
|
|
27
|
-
idempotencyKey: message.idempotencyKey
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
const LINK = /(<a\b[^>]*?\shref\s*=\s*)(["'])(https?:\/\/[^"']+)\2/gi;
|
|
32
|
-
/**
|
|
33
|
-
* An email's tracking applied to its rendered HTML: every `http(s)` anchor routed through
|
|
34
|
-
* `link` (the original URL decoded from its attribute escaping, the tracking URL escaped back) —
|
|
35
|
-
* as the unsubscribe link when it is the one the email was rendered with, so what a click on it
|
|
36
|
-
* means is fixed when the email is sent — and the open pixel appended before `</body>`, or at the
|
|
37
|
-
* end when there is none.
|
|
38
|
-
*/
|
|
39
|
-
function trackEmail(html, tracking, unsubscribeUrl) {
|
|
40
|
-
const { link, pixel } = tracking;
|
|
41
|
-
let out = html;
|
|
42
|
-
if (link !== void 0) out = out.replace(LINK, (_, start, quote, attribute) => {
|
|
43
|
-
const url = unescapeAttribute(attribute);
|
|
44
|
-
const purpose = require_email.isUnsubscribeLink(url, unsubscribeUrl) ? "unsubscribe" : "link";
|
|
45
|
-
return `${start}${quote}${escapeAttribute(link(url, purpose))}${quote}`;
|
|
46
|
-
});
|
|
47
|
-
if (pixel !== void 0) {
|
|
48
|
-
const image = `<img src="${escapeAttribute(pixel)}" width="1" height="1" alt="" style="display:block;border:0;width:1px;height:1px" />`;
|
|
49
|
-
out = /<\/body>/i.test(out) ? out.replace(/<\/body>/i, `${image}</body>`) : `${out}${image}`;
|
|
50
|
-
}
|
|
51
|
-
return out;
|
|
52
|
-
}
|
|
53
|
-
function unescapeAttribute(value) {
|
|
54
|
-
return value.replaceAll("&", "&").replaceAll(""", "\"").replaceAll("'", "'");
|
|
55
|
-
}
|
|
56
|
-
function escapeAttribute(value) {
|
|
57
|
-
return value.replaceAll("&", "&").replaceAll("\"", """);
|
|
58
|
-
}
|
|
59
|
-
/** Development sender: structured logs, for eyeballing the pipeline. */
|
|
60
|
-
var LogMessageSender = class {
|
|
61
|
-
async send(message) {
|
|
62
|
-
const { tracking: _tracking, ...logged } = message;
|
|
63
|
-
console.log(`[send] ${JSON.stringify(logged)}`);
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
/**
|
|
67
|
-
* Webhook sender: POST to an external delivery service (a Resend/SES gateway,
|
|
68
|
-
* say). The idempotency key travels with it, so the receiver de-duplicates
|
|
69
|
-
* retries and replays on idempotencyKey.
|
|
70
|
-
*/
|
|
71
|
-
var WebhookMessageSender = class {
|
|
72
|
-
url;
|
|
73
|
-
constructor(url) {
|
|
74
|
-
this.url = url;
|
|
75
|
-
}
|
|
76
|
-
async send(message) {
|
|
77
|
-
const response = await fetch(this.url, {
|
|
78
|
-
method: "POST",
|
|
79
|
-
headers: {
|
|
80
|
-
"content-type": "application/json",
|
|
81
|
-
"idempotency-key": message.idempotencyKey
|
|
82
|
-
},
|
|
83
|
-
body: JSON.stringify(message)
|
|
84
|
-
});
|
|
85
|
-
if (!response.ok) throw new Error(`message webhook failed: ${response.status}`);
|
|
86
|
-
}
|
|
87
|
-
};
|
|
88
|
-
/**
|
|
89
|
-
* One sender per channel: the runner has a single outlet, this fans it out.
|
|
90
|
-
* A channel without a sender fails the send (a misconfiguration, not a retry).
|
|
91
|
-
*/
|
|
92
|
-
function routeByChannel(senders) {
|
|
93
|
-
return { async send(message) {
|
|
94
|
-
const sender = senders[message.channel];
|
|
95
|
-
if (sender === void 0) throw new Error(`no sender configured for channel '${message.channel}'`);
|
|
96
|
-
return sender.send(message);
|
|
97
|
-
} };
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* One push outlet per platform, chosen by the device each copy goes to (the
|
|
101
|
-
* engine sends one message per device, and the host's directory says which
|
|
102
|
-
* platform a token belongs to): `ios` straight to APNs, `android` through FCM,
|
|
103
|
-
* say. A platform with no sender fails the step rather than guessing.
|
|
104
|
-
*/
|
|
105
|
-
function routeByPlatform(senders) {
|
|
106
|
-
return { async send(message) {
|
|
107
|
-
const platform = message.device?.platform;
|
|
108
|
-
if (platform === void 0) throw new Error(`push for user '${message.userId}' carries no device`);
|
|
109
|
-
if (!Object.hasOwn(senders, platform)) throw new Error(`no push sender configured for platform '${platform}'`);
|
|
110
|
-
return senders[platform].send(message);
|
|
111
|
-
} };
|
|
112
|
-
}
|
|
113
|
-
//#endregion
|
|
114
|
-
exports.CfEmailSender = CfEmailSender;
|
|
115
|
-
exports.LogMessageSender = LogMessageSender;
|
|
116
|
-
exports.WebhookMessageSender = WebhookMessageSender;
|
|
117
|
-
exports.routeByChannel = routeByChannel;
|
|
118
|
-
exports.routeByPlatform = routeByPlatform;
|
|
119
|
-
exports.trackEmail = trackEmail;
|
|
120
|
-
|
|
121
|
-
//# sourceMappingURL=senders.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"senders.cjs","names":["isUnsubscribeLink"],"sources":["../../src/cloudflare/senders.ts"],"sourcesContent":["import { type ResolvedEmail, isUnsubscribeLink } from '../email';\nimport type { MessageSender, MessageTracking, OutboundMessage } from '../engine';\nimport type { ScalarIR } from '../ir';\nimport type { EmailBindingLike } from './bindings';\n\nexport type { EmailAddress } from '../email';\nexport type { EmailBindingLike } from './bindings';\n\n/** A rendered email: the template's resolved metadata (`resolveEmail`), its subject and its HTML. */\nexport interface RenderedEmail extends ResolvedEmail {\n subject: string;\n html: string;\n}\n\n/**\n * Template renderer, injected by the app — this package's core stays free of\n * any react-email dependency (`@shware/workflow/react-email` ships one over a\n * registry). The subject comes back final: it is sent exactly as written, from\n * the template's own sender, and the unsubscribe link is the one the HTML was\n * rendered with.\n */\nexport type EmailRenderer = (\n template: string,\n props: Record<string, ScalarIR | undefined>\n) => Promise<RenderedEmail>;\n\nexport interface CfEmailOptions {\n /** The Worker's `send_email` binding. */\n binding: EmailBindingLike;\n render: EmailRenderer;\n}\n\n/**\n * Send straight through Cloudflare Email Service — a binding call, no outbound\n * HTTP. Throwing hands retries to the CF step, and the message's\n * idempotencyKey travels with the call so the binding can drop the duplicate a\n * retry or replay produces.\n */\nexport class CfEmailSender implements MessageSender {\n constructor(private readonly options: CfEmailOptions) {}\n\n async send(message: OutboundMessage): Promise<void> {\n if (message.channel !== 'email') {\n throw new Error(`CfEmailSender: unsupported channel '${message.channel}'`);\n }\n if (message.recipient === undefined) {\n throw new Error(`CfEmailSender: no recipient for user '${message.userId}'`);\n }\n const { subject, html, from, replyTo, unsubscribeUrl } = await this.options.render(\n message.template,\n message.props\n );\n const tracked =\n message.tracking === undefined ? html : trackEmail(html, message.tracking, unsubscribeUrl);\n // The tracked links resolve before the email exists anywhere a scanner could follow them\n await message.tracking?.commit?.();\n await this.options.binding.send({\n from,\n to: message.recipient,\n ...(replyTo === undefined ? {} : { replyTo }),\n subject,\n html: tracked,\n idempotencyKey: message.idempotencyKey,\n });\n }\n}\n\nconst LINK = /(<a\\b[^>]*?\\shref\\s*=\\s*)([\"'])(https?:\\/\\/[^\"']+)\\2/gi;\n\n/**\n * An email's tracking applied to its rendered HTML: every `http(s)` anchor routed through\n * `link` (the original URL decoded from its attribute escaping, the tracking URL escaped back) —\n * as the unsubscribe link when it is the one the email was rendered with, so what a click on it\n * means is fixed when the email is sent — and the open pixel appended before `</body>`, or at the\n * end when there is none.\n */\nexport function trackEmail(\n html: string,\n tracking: MessageTracking,\n unsubscribeUrl?: string\n): string {\n const { link, pixel } = tracking;\n let out = html;\n if (link !== undefined) {\n out = out.replace(LINK, (_, start: string, quote: string, attribute: string) => {\n const url = unescapeAttribute(attribute);\n const purpose = isUnsubscribeLink(url, unsubscribeUrl) ? 'unsubscribe' : 'link';\n return `${start}${quote}${escapeAttribute(link(url, purpose))}${quote}`;\n });\n }\n if (pixel !== undefined) {\n const image = `<img src=\"${escapeAttribute(pixel)}\" width=\"1\" height=\"1\" alt=\"\" style=\"display:block;border:0;width:1px;height:1px\" />`;\n out = /<\\/body>/i.test(out) ? out.replace(/<\\/body>/i, `${image}</body>`) : `${out}${image}`;\n }\n return out;\n}\n\nfunction unescapeAttribute(value: string): string {\n return value.replaceAll('&', '&').replaceAll('"', '\"').replaceAll(''', \"'\");\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replaceAll('&', '&').replaceAll('\"', '"');\n}\n\n/** Development sender: structured logs, for eyeballing the pipeline. */\nexport class LogMessageSender implements MessageSender {\n async send(message: OutboundMessage): Promise<void> {\n const { tracking: _tracking, ...logged } = message;\n console.log(`[send] ${JSON.stringify(logged)}`);\n }\n}\n\n/**\n * Webhook sender: POST to an external delivery service (a Resend/SES gateway,\n * say). The idempotency key travels with it, so the receiver de-duplicates\n * retries and replays on idempotencyKey.\n */\nexport class WebhookMessageSender implements MessageSender {\n constructor(private readonly url: string) {}\n\n async send(message: OutboundMessage): Promise<void> {\n const response = await fetch(this.url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'idempotency-key': message.idempotencyKey,\n },\n body: JSON.stringify(message),\n });\n if (!response.ok) {\n throw new Error(`message webhook failed: ${response.status}`);\n }\n }\n}\n\n/**\n * One sender per channel: the runner has a single outlet, this fans it out.\n * A channel without a sender fails the send (a misconfiguration, not a retry).\n */\nexport function routeByChannel(\n senders: Partial<Record<OutboundMessage['channel'], MessageSender>>\n): MessageSender {\n return {\n async send(message) {\n const sender = senders[message.channel];\n if (sender === undefined) {\n throw new Error(`no sender configured for channel '${message.channel}'`);\n }\n return sender.send(message);\n },\n };\n}\n\n/**\n * One push outlet per platform, chosen by the device each copy goes to (the\n * engine sends one message per device, and the host's directory says which\n * platform a token belongs to): `ios` straight to APNs, `android` through FCM,\n * say. A platform with no sender fails the step rather than guessing.\n */\nexport function routeByPlatform(senders: Record<string, MessageSender>): MessageSender {\n return {\n async send(message) {\n const platform = message.device?.platform;\n if (platform === undefined) {\n throw new Error(`push for user '${message.userId}' carries no device`);\n }\n if (!Object.hasOwn(senders, platform)) {\n throw new Error(`no push sender configured for platform '${platform}'`);\n }\n return senders[platform].send(message);\n },\n };\n}\n"],"mappings":";;;;;;;;;AAsCA,IAAa,gBAAb,MAAoD;CACrB;CAA7B,YAAY,SAA0C;EAAzB,KAAA,UAAA;CAA0B;CAEvD,MAAM,KAAK,SAAyC;EAClD,IAAI,QAAQ,YAAY,SACtB,MAAM,IAAI,MAAM,uCAAuC,QAAQ,QAAQ,EAAE;EAE3E,IAAI,QAAQ,cAAc,KAAA,GACxB,MAAM,IAAI,MAAM,yCAAyC,QAAQ,OAAO,EAAE;EAE5E,MAAM,EAAE,SAAS,MAAM,MAAM,SAAS,mBAAmB,MAAM,KAAK,QAAQ,OAC1E,QAAQ,UACR,QAAQ,KACV;EACA,MAAM,UACJ,QAAQ,aAAa,KAAA,IAAY,OAAO,WAAW,MAAM,QAAQ,UAAU,cAAc;EAE3F,MAAM,QAAQ,UAAU,SAAS;EACjC,MAAM,KAAK,QAAQ,QAAQ,KAAK;GAC9B;GACA,IAAI,QAAQ;GACZ,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ;GAC3C;GACA,MAAM;GACN,gBAAgB,QAAQ;EAC1B,CAAC;CACH;AACF;AAEA,MAAM,OAAO;;;;;;;;AASb,SAAgB,WACd,MACA,UACA,gBACQ;CACR,MAAM,EAAE,MAAM,UAAU;CACxB,IAAI,MAAM;CACV,I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;EAClB,MAAM,SAAS,QAAQ,QAAQ;EAC/B,IAAI,WAAW,KAAA,GACb,MAAM,IAAI,MAAM,qCAAqC,QAAQ,QAAQ,EAAE;EAEzE,OAAO,OAAO,KAAK,OAAO;CAC5B,EACF;AACF;;;;;;;AAQA,SAAgB,gBAAgB,SAAuD;CACrF,OAAO,EACL,MAAM,KAAK,SAAS;EAClB,MAAM,WAAW,QAAQ,QAAQ;EACjC,IAAI,aAAa,KAAA,GACf,MAAM,IAAI,MAAM,kBAAkB,QAAQ,OAAO,oBAAoB;EAEvE,IAAI,CAAC,OAAO,OAAO,SAAS,QAAQ,GAClC,MAAM,IAAI,MAAM,2CAA2C,SAAS,EAAE;EAExE,OAAO,QAAQ,SAAS,CAAC,KAAK,OAAO;CACvC,EACF;AACF"}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { ScalarIR } from "../ir.cjs";
|
|
2
|
-
import { MessageSender, MessageTracking, OutboundMessage } from "../engine/ports.cjs";
|
|
3
|
-
import "../engine/index.cjs";
|
|
4
|
-
import { EmailAddress, ResolvedEmail } from "../email.cjs";
|
|
5
|
-
import { EmailBindingLike } from "./bindings.cjs";
|
|
6
|
-
//#region src/cloudflare/senders.d.ts
|
|
7
|
-
/** A rendered email: the template's resolved metadata (`resolveEmail`), its subject and its HTML. */
|
|
8
|
-
export interface RenderedEmail extends ResolvedEmail {
|
|
9
|
-
subject: string;
|
|
10
|
-
html: string;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Template renderer, injected by the app — this package's core stays free of
|
|
14
|
-
* any react-email dependency (`@shware/workflow/react-email` ships one over a
|
|
15
|
-
* registry). The subject comes back final: it is sent exactly as written, from
|
|
16
|
-
* the template's own sender, and the unsubscribe link is the one the HTML was
|
|
17
|
-
* rendered with.
|
|
18
|
-
*/
|
|
19
|
-
export type EmailRenderer = (template: string, props: Record<string, ScalarIR | undefined>) => Promise<RenderedEmail>;
|
|
20
|
-
export interface CfEmailOptions {
|
|
21
|
-
/** The Worker's `send_email` binding. */
|
|
22
|
-
binding: EmailBindingLike;
|
|
23
|
-
render: EmailRenderer;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Send straight through Cloudflare Email Service — a binding call, no outbound
|
|
27
|
-
* HTTP. Throwing hands retries to the CF step, and the message's
|
|
28
|
-
* idempotencyKey travels with the call so the binding can drop the duplicate a
|
|
29
|
-
* retry or replay produces.
|
|
30
|
-
*/
|
|
31
|
-
export declare class CfEmailSender implements MessageSender {
|
|
32
|
-
private readonly options;
|
|
33
|
-
constructor(options: CfEmailOptions);
|
|
34
|
-
send(message: OutboundMessage): Promise<void>;
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* An email's tracking applied to its rendered HTML: every `http(s)` anchor routed through
|
|
38
|
-
* `link` (the original URL decoded from its attribute escaping, the tracking URL escaped back) —
|
|
39
|
-
* as the unsubscribe link when it is the one the email was rendered with, so what a click on it
|
|
40
|
-
* means is fixed when the email is sent — and the open pixel appended before `</body>`, or at the
|
|
41
|
-
* end when there is none.
|
|
42
|
-
*/
|
|
43
|
-
export declare function trackEmail(html: string, tracking: MessageTracking, unsubscribeUrl?: string): string;
|
|
44
|
-
/** Development sender: structured logs, for eyeballing the pipeline. */
|
|
45
|
-
export declare class LogMessageSender implements MessageSender {
|
|
46
|
-
send(message: OutboundMessage): Promise<void>;
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Webhook sender: POST to an external delivery service (a Resend/SES gateway,
|
|
50
|
-
* say). The idempotency key travels with it, so the receiver de-duplicates
|
|
51
|
-
* retries and replays on idempotencyKey.
|
|
52
|
-
*/
|
|
53
|
-
export declare class WebhookMessageSender implements MessageSender {
|
|
54
|
-
private readonly url;
|
|
55
|
-
constructor(url: string);
|
|
56
|
-
send(message: OutboundMessage): Promise<void>;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* One sender per channel: the runner has a single outlet, this fans it out.
|
|
60
|
-
* A channel without a sender fails the send (a misconfiguration, not a retry).
|
|
61
|
-
*/
|
|
62
|
-
export declare function routeByChannel(senders: Partial<Record<OutboundMessage['channel'], MessageSender>>): MessageSender;
|
|
63
|
-
/**
|
|
64
|
-
* One push outlet per platform, chosen by the device each copy goes to (the
|
|
65
|
-
* engine sends one message per device, and the host's directory says which
|
|
66
|
-
* platform a token belongs to): `ios` straight to APNs, `android` through FCM,
|
|
67
|
-
* say. A platform with no sender fails the step rather than guessing.
|
|
68
|
-
*/
|
|
69
|
-
export declare function routeByPlatform(senders: Record<string, MessageSender>): MessageSender;
|
|
70
|
-
//#endregion
|
|
71
|
-
export type { EmailAddress, EmailBindingLike };
|
|
72
|
-
//# sourceMappingURL=senders.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"senders.d.cts","names":[],"sources":["../../src/cloudflare/senders.ts"],"mappings":";;;;;;;iBASiB,sBAAsB;EACrC;EACA;;;;;;;;;YAUU,iBACV,kBACA,OAAO,eAAe,0BACnB,QAAQ;iBAEI;;EAEf,SAAS;EACT,QAAQ;;;;;;;;qBASG,yBAAyB;mBACP;EAA7B,YAA6B,SAAS;EAEhC,KAAK,SAAS,kBAAkB;;;;;;;;;wBAmCxB,WACd,cACA,UAAU,iBACV;;qBA2BW,4BAA4B;EACjC,KAAK,SAAS,kBAAkB;;;;;;;qBAW3B,gCAAgC;mBACd;EAA7B,YAA6B;EAEvB,KAAK,SAAS,kBAAkB;;;;;;wBAmBxB,eACd,SAAS,QAAQ,OAAO,4BAA4B,kBACnD;;;;;;;wBAkBa,gBAAgB,SAAS,eAAe,iBAAiB"}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { ScalarIR } from "../ir.mjs";
|
|
2
|
-
import { MessageSender, MessageTracking, OutboundMessage } from "../engine/ports.mjs";
|
|
3
|
-
import "../engine/index.mjs";
|
|
4
|
-
import { EmailAddress, ResolvedEmail } from "../email.mjs";
|
|
5
|
-
import { EmailBindingLike } from "./bindings.mjs";
|
|
6
|
-
//#region src/cloudflare/senders.d.ts
|
|
7
|
-
/** A rendered email: the template's resolved metadata (`resolveEmail`), its subject and its HTML. */
|
|
8
|
-
export interface RenderedEmail extends ResolvedEmail {
|
|
9
|
-
subject: string;
|
|
10
|
-
html: string;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Template renderer, injected by the app — this package's core stays free of
|
|
14
|
-
* any react-email dependency (`@shware/workflow/react-email` ships one over a
|
|
15
|
-
* registry). The subject comes back final: it is sent exactly as written, from
|
|
16
|
-
* the template's own sender, and the unsubscribe link is the one the HTML was
|
|
17
|
-
* rendered with.
|
|
18
|
-
*/
|
|
19
|
-
export type EmailRenderer = (template: string, props: Record<string, ScalarIR | undefined>) => Promise<RenderedEmail>;
|
|
20
|
-
export interface CfEmailOptions {
|
|
21
|
-
/** The Worker's `send_email` binding. */
|
|
22
|
-
binding: EmailBindingLike;
|
|
23
|
-
render: EmailRenderer;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Send straight through Cloudflare Email Service — a binding call, no outbound
|
|
27
|
-
* HTTP. Throwing hands retries to the CF step, and the message's
|
|
28
|
-
* idempotencyKey travels with the call so the binding can drop the duplicate a
|
|
29
|
-
* retry or replay produces.
|
|
30
|
-
*/
|
|
31
|
-
export declare class CfEmailSender implements MessageSender {
|
|
32
|
-
private readonly options;
|
|
33
|
-
constructor(options: CfEmailOptions);
|
|
34
|
-
send(message: OutboundMessage): Promise<void>;
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* An email's tracking applied to its rendered HTML: every `http(s)` anchor routed through
|
|
38
|
-
* `link` (the original URL decoded from its attribute escaping, the tracking URL escaped back) —
|
|
39
|
-
* as the unsubscribe link when it is the one the email was rendered with, so what a click on it
|
|
40
|
-
* means is fixed when the email is sent — and the open pixel appended before `</body>`, or at the
|
|
41
|
-
* end when there is none.
|
|
42
|
-
*/
|
|
43
|
-
export declare function trackEmail(html: string, tracking: MessageTracking, unsubscribeUrl?: string): string;
|
|
44
|
-
/** Development sender: structured logs, for eyeballing the pipeline. */
|
|
45
|
-
export declare class LogMessageSender implements MessageSender {
|
|
46
|
-
send(message: OutboundMessage): Promise<void>;
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Webhook sender: POST to an external delivery service (a Resend/SES gateway,
|
|
50
|
-
* say). The idempotency key travels with it, so the receiver de-duplicates
|
|
51
|
-
* retries and replays on idempotencyKey.
|
|
52
|
-
*/
|
|
53
|
-
export declare class WebhookMessageSender implements MessageSender {
|
|
54
|
-
private readonly url;
|
|
55
|
-
constructor(url: string);
|
|
56
|
-
send(message: OutboundMessage): Promise<void>;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* One sender per channel: the runner has a single outlet, this fans it out.
|
|
60
|
-
* A channel without a sender fails the send (a misconfiguration, not a retry).
|
|
61
|
-
*/
|
|
62
|
-
export declare function routeByChannel(senders: Partial<Record<OutboundMessage['channel'], MessageSender>>): MessageSender;
|
|
63
|
-
/**
|
|
64
|
-
* One push outlet per platform, chosen by the device each copy goes to (the
|
|
65
|
-
* engine sends one message per device, and the host's directory says which
|
|
66
|
-
* platform a token belongs to): `ios` straight to APNs, `android` through FCM,
|
|
67
|
-
* say. A platform with no sender fails the step rather than guessing.
|
|
68
|
-
*/
|
|
69
|
-
export declare function routeByPlatform(senders: Record<string, MessageSender>): MessageSender;
|
|
70
|
-
//#endregion
|
|
71
|
-
export type { EmailAddress, EmailBindingLike };
|
|
72
|
-
//# sourceMappingURL=senders.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"senders.d.mts","names":[],"sources":["../../src/cloudflare/senders.ts"],"mappings":";;;;;;;iBASiB,sBAAsB;EACrC;EACA;;;;;;;;;YAUU,iBACV,kBACA,OAAO,eAAe,0BACnB,QAAQ;iBAEI;;EAEf,SAAS;EACT,QAAQ;;;;;;;;qBASG,yBAAyB;mBACP;EAA7B,YAA6B,SAAS;EAEhC,KAAK,SAAS,kBAAkB;;;;;;;;;wBAmCxB,WACd,cACA,UAAU,iBACV;;qBA2BW,4BAA4B;EACjC,KAAK,SAAS,kBAAkB;;;;;;;qBAW3B,gCAAgC;mBACd;EAA7B,YAA6B;EAEvB,KAAK,SAAS,kBAAkB;;;;;;wBAmBxB,eACd,SAAS,QAAQ,OAAO,4BAA4B,kBACnD;;;;;;;wBAkBa,gBAAgB,SAAS,eAAe,iBAAiB"}
|