delivery
The notification dispatch core: call ctx.notify(notificationType, { to, route, data, priority, idempotencyKey }) from any handler to fan out a notification across all registered channels (email, in-app, Slack, Discord, Teams). Inside a write handler the delivery runs after the write has committed (the call returns { kind: "deferred" }, a rolled-back write sends nothing); immediate: true delivers synchronously and returns { kind: "dispatched", deliveries }. It stores per-user channel preferences in the notification-preference entity, opt-outs for no-account recipient addresses in notification-address-opt-out (keyed by a blind-index hash, never the plaintext address), logs every attempt to store_delivery_attempts, and enforces idempotency and rate-limiting — add channel-email, channel-in-app or a chat channel on top to actually send anything. Unsubscribe/resubscribe links are served by createUnsubscribeRoutes({ secret }) mounted via the app’s extraRoutes at /api/delivery/unsubscribe and /api/delivery/resubscribe: GET /unsubscribe?token= renders a confirmation page (no write), POST /unsubscribe performs the opt-out (RFC 8058 one-click, token from the form body or query), POST /resubscribe undoes it (JSON {token} or form body only, never the query — reachable by a mail-client link prefetcher) — sign links with signUnsubscribeToken / signAddressUnsubscribeToken using the same secret. channel-email sets List-Unsubscribe / List-Unsubscribe-Post automatically when a message’s data.unsubscribeUrl points at the unsubscribe route. A notification declared with unsubscribe: true gets that link from delivery itself when the service has unsubscribeLinks (the runProdApp and runDevApp option unsubscribe: { secret } mounts the routes and wires it; base URL from auth.publicOrigin, auth.mail.baseUrl or APP_BASE_URL): user recipients get a user token, route recipients an address token (needs a blind-index key, otherwise no link); a data.unsubscribeUrl from the caller wins. unsubscribe.tenantOrigin: (ctx) => origin | null points the link at the tenant’s own host (subdomain or custom domain, must serve this app’s /api); null, a throw or a non-https value fall back to the app origin. The token carries the mail’s locale, so the confirmation and result pages render in the mail’s language. An app serving its own (e.g. legacy) unsubscribe links renders the same result page with renderUnsubscribeResultPage({ kind, locale }). To react to a no-account opt-out (e.g. remove the app’s own subscriber row), declare r.job({ name, trigger: { on: DELIVERY_ADDRESS_UNSUBSCRIBED_EVENT }, handler }) on a lane the app consumes: it runs after each committed opt-out, also an idempotent repeat, with unsubscribeAddressPayloadSchema (addressHash, notificationType, channel) as payload and the tenant in ctx.triggeredBy.tenantId; match the subscriber via hashUnsubscribeAddress(email). Declare unsubscribeUrl as an optional template variable if the mail body shows it. A job that sends an opt-in notification (e.g. a daily digest) reads the members who switched it on from the job-only query delivery:query:opted-in-user-ids ({ notificationType, channel } answers { userIds }).
Quick example
Section titled “Quick example”From recipes-delivery-notifications — the smallest working mount:
// Delivery Notifications Sample//// A support ticket is created and its assignee is notified via inApp, email// and push. The mail is a stored template: `r.notification` declares the// variables, the default text and the subject, the boot seed writes the text// into the template store, and a tenant can override it there.//// The feature code only declares WHAT to notify. HOW is handled by Delivery.
import { buildEntityTable, createEventStoreExecutor } from "@cosmicdrift/kumiko-framework/db";import { createEntity, createTextField, defineFeature, QnTypes, qn, templateVariable,} from "@cosmicdrift/kumiko-framework/engine";import { z } from "zod";
// --- Entity ---
export const ticketEntity = createEntity({ name: "ticket", table: "read_sample_delivery_tickets", fields: { title: createTextField({ personal: false, reason: "is_business_data", required: true, maxLength: 200, }), description: createTextField({ personal: false, reason: "is_business_data", maxLength: 2000 }), assigneeId: createTextField({ personal: "ref" }), priority: createTextField({ personal: false, reason: "is_business_data", required: true }), // "low" | "normal" | "critical" status: createTextField({ personal: false, reason: "is_business_data", required: true }), },});
export const ticketTable = buildEntityTable(ticketEntity);
function ticketExecutor() { return createEventStoreExecutor(ticketTable, ticketEntity, { entityName: "ticket" });}
// --- Feature ---
export const TICKET_ASSIGNED = qn("support", QnTypes.notify, "ticket-assigned");
export const supportFeature = defineFeature("support", (r) => { r.requires({ features: ["delivery"] });
r.entity(ticketEntity);
r.notification({ name: "ticket-assigned", variables: { ticketId: templateVariable.text({ required: true }), title: templateVariable.text({ required: true }), description: templateVariable.text({ required: true }), priority: templateVariable.text({ required: true }), url: templateVariable.link({ required: true }), }, template: { en: { body: '<h1>New ticket: <span data-variable="title"></span></h1><p><span data-variable="description"></span></p><p>Priority: <span data-variable="priority"></span></p><p><a data-button href="{{url}}">Open ticket</a></p>', }, }, meta: { en: { subject: "Support ticket #{{ticketId}} ({{priority}})" } }, // inApp and push build their own short text; email renders the stored // template with the notify data as variables. templates: { inApp: (data) => ({ title: `New ticket: ${data["title"]}`, body: (data["description"] as string) || "A ticket was assigned to you.", }), push: (data) => ({ title: "New ticket", body: `${data["title"]} (${data["priority"]})`, }), }, });
r.writeHandler({ name: "ticket:create", schema: z.object({ title: z.string().min(1), description: z.string().optional(), assigneeId: z.uuid().optional(), priority: z.enum(["low", "normal", "critical"]), status: z.string().default("open"), }), handler: async (event, ctx) => { const created = await ticketExecutor().create(event.payload, event.user, ctx.db); const assigneeId = event.payload.assigneeId; // No assignee, no notification. if (!created.isSuccess || assigneeId === undefined) return created; if (ctx.notify === undefined) { throw new Error("ticket:create needs ctx.notify, mount the delivery feature"); } const ticketId = created.data.id; await ctx.notify(TICKET_ASSIGNED, { to: assigneeId, // Known key per ticket: dedups a replayed handler and lets an admin screen ask // channel-in-app:query:read-state-by-keys whether the assignee has seen it. idempotencyKey: `ticket-assigned:${ticketId}`, data: { ticketId, title: event.payload.title, description: event.payload.description ?? "", priority: event.payload.priority, url: `https://app.example.com/support/tickets/${ticketId}`, }, }); return created; }, access: { roles: ["Admin", "Support"] }, });});📄 On GitHub: samples/recipes/delivery-notifications/src/feature.ts
Live preview
Section titled “Live preview”
How it fits
Section titled “How it fits”What this feature needs to run (Requires, top) and the write commands this feature provides (Provides, bottom).
flowchart TB
n_delivery["delivery"]
subgraph how_reqs["Requires"]
n_tenant["tenant"]
end
subgraph how_provides["Provides"]
n_cmd_delivery_write_resubscribe_address(["resubscribe-address"])
n_cmd_delivery_write_resubscribe_user(["resubscribe-user"])
n_cmd_delivery_write_set_preference(["set-preference"])
n_cmd_delivery_write_unsubscribe_address(["unsubscribe-address"])
n_cmd_delivery_write_unsubscribe_user(["unsubscribe-user"])
end
n_tenant --> n_delivery
n_delivery --> n_cmd_delivery_write_resubscribe_address
n_delivery --> n_cmd_delivery_write_resubscribe_user
n_delivery --> n_cmd_delivery_write_set_preference
n_delivery --> n_cmd_delivery_write_unsubscribe_address
n_delivery --> n_cmd_delivery_write_unsubscribe_user
Provides — write commands this feature registers (dispatch them through the command bus):
delivery:write:resubscribe-addressdelivery:write:resubscribe-userdelivery:write:set-preferencedelivery:write:unsubscribe-addressdelivery:write:unsubscribe-user
Getting started
Section titled “Getting started”Start with recipes-delivery-notifications for a step-by-step walkthrough with runnable code and integration tests.
Dependencies
Section titled “Dependencies”- Requires:
tenant - Activation: always on (not toggleable)