@12-apps/notifications 4.8.0 → 4.10.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/ADOPTING.md +173 -1
- package/README.md +138 -0
- package/dist/catalog-BOVZ2b-b.d.ts +132 -0
- package/dist/{chunk-M5XTROYM.js → chunk-5Y7QRORV.js} +8 -4
- package/dist/chunk-5Y7QRORV.js.map +1 -0
- package/dist/{chunk-BGI4BQ66.js → chunk-6W7INOYQ.js} +1 -1
- package/dist/chunk-6W7INOYQ.js.map +1 -0
- package/dist/chunk-EKUSNUBT.js +222 -0
- package/dist/chunk-EKUSNUBT.js.map +1 -0
- package/dist/chunk-FTFLU6KH.js +114 -0
- package/dist/chunk-FTFLU6KH.js.map +1 -0
- package/dist/chunk-JCVRQ42B.js +226 -0
- package/dist/chunk-JCVRQ42B.js.map +1 -0
- package/dist/chunk-RTURLH5U.js +33 -0
- package/dist/chunk-RTURLH5U.js.map +1 -0
- package/dist/{chunk-GGAZOLNN.js → chunk-SWOWHIFE.js} +2 -2
- package/dist/{chunk-7234ROOP.js → chunk-WVRODNXQ.js} +28 -6
- package/dist/chunk-WVRODNXQ.js.map +1 -0
- package/dist/chunk-ZFIYBNZ7.js +502 -0
- package/dist/chunk-ZFIYBNZ7.js.map +1 -0
- package/dist/{chunk-KU4FVOFA.js → chunk-ZIR3ILFH.js} +2 -2
- package/dist/{create-api-notifications-WaexrZnn.d.ts → create-api-notifications-CcPYrM3p.d.ts} +35 -4
- package/dist/{create-web-notifications-DrgqtU4Q.d.ts → create-web-notifications-_NVYmlvy.d.ts} +89 -4
- package/dist/email/index.d.ts +26 -0
- package/dist/email/index.js +20 -0
- package/dist/email/index.js.map +1 -0
- package/dist/email/locales.d.ts +43 -0
- package/dist/email/locales.js +29 -0
- package/dist/email/locales.js.map +1 -0
- package/dist/email/previews/hono.d.ts +46 -0
- package/dist/email/previews/hono.js +33 -0
- package/dist/email/previews/hono.js.map +1 -0
- package/dist/email/previews/index.d.ts +67 -0
- package/dist/email/previews/index.js +12 -0
- package/dist/email/previews/index.js.map +1 -0
- package/dist/email/previews/react/index.d.ts +43 -0
- package/dist/email/previews/react/index.js +58 -0
- package/dist/email/previews/react/index.js.map +1 -0
- package/dist/{generators-CH5m8Ucj.d.ts → generators-qAD4fNPq.d.ts} +1 -1
- package/dist/hono/index.d.ts +6 -5
- package/dist/hono/index.js +5 -3
- package/dist/hono/index.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +15 -5
- package/dist/{jobs-CcsSA0YR.d.ts → jobs--fex87-q.d.ts} +1 -1
- package/dist/live-DYxEFO49.d.ts +158 -0
- package/dist/manifest/index.d.ts +39 -1
- package/dist/manifest/index.js +9 -0
- package/dist/manifest/index.js.map +1 -1
- package/dist/manifest/server.d.ts +32 -7
- package/dist/manifest/server.js +16 -4
- package/dist/manifest/server.js.map +1 -1
- package/dist/manifest/web.d.ts +19 -4
- package/dist/manifest/web.js +9 -1
- package/dist/manifest/web.js.map +1 -1
- package/dist/{panel-UFXNO4AF.js → panel-T36JEMO3.js} +37 -13
- package/dist/panel-T36JEMO3.js.map +1 -0
- package/dist/{preferences-screen-V3ZBWP7A.js → preferences-screen-SXUIGECY.js} +2 -2
- package/dist/preview-screen-DYJRAnAY.d.ts +83 -0
- package/dist/react/index.d.ts +55 -6
- package/dist/react/index.js +16 -10
- package/dist/server/index.d.ts +8 -7
- package/dist/server/index.js +6 -4
- package/dist/template-Dlt5S54z.d.ts +196 -0
- package/dist/{types-CYJN1xCM.d.ts → types-BlqZkCWZ.d.ts} +11 -2
- package/dist/web-push/index.d.ts +2 -2
- package/dist/{web-push-iER5StBm.d.ts → web-push-Dnyaha2z.d.ts} +21 -1
- package/dist/{wire-CmRrB3_s.d.ts → wire-BG1kuoXX.d.ts} +1 -1
- package/package.json +22 -2
- package/src/email/chrome.en-US.ts +8 -0
- package/src/email/chrome.pt-BR.ts +21 -0
- package/src/email/index.ts +43 -0
- package/src/email/locales.ts +29 -0
- package/src/email/previews/catalog.ts +208 -0
- package/src/email/previews/hono.ts +69 -0
- package/src/email/previews/index.ts +26 -0
- package/src/email/previews/react/copy.en-US.ts +24 -0
- package/src/email/previews/react/copy.pt-BR.ts +24 -0
- package/src/email/previews/react/copy.ts +42 -0
- package/src/email/previews/react/index.tsx +14 -0
- package/src/email/previews/react/loadable.tsx +83 -0
- package/src/email/previews/react/message-list.tsx +133 -0
- package/src/email/previews/react/message-view.tsx +167 -0
- package/src/email/previews/react/preview-screen.tsx +342 -0
- package/src/email/previews/react/transport.ts +60 -0
- package/src/email/previews/routes.ts +111 -0
- package/src/email/template.ts +365 -0
- package/src/email/text.ts +59 -0
- package/src/email/theme.ts +77 -0
- package/src/index.ts +10 -0
- package/src/live.ts +179 -0
- package/src/manifest/index.ts +37 -0
- package/src/manifest/server.ts +23 -0
- package/src/manifest/web.ts +13 -0
- package/src/react/create-web-notifications.tsx +15 -1
- package/src/react/index.ts +29 -0
- package/src/react/live-card.tsx +279 -0
- package/src/react/live-config.ts +79 -0
- package/src/react/live-section.tsx +141 -0
- package/src/react/panel-lazy.tsx +3 -0
- package/src/react/panel.tsx +57 -10
- package/src/react/relative-time.ts +14 -2
- package/src/server/transports/email.ts +62 -0
- package/src/server/transports/web-push.ts +22 -0
- package/src/types.ts +10 -1
- package/dist/chunk-7234ROOP.js.map +0 -1
- package/dist/chunk-BGI4BQ66.js.map +0 -1
- package/dist/chunk-M5XTROYM.js.map +0 -1
- package/dist/chunk-O5BVUXPO.js +0 -22
- package/dist/chunk-O5BVUXPO.js.map +0 -1
- package/dist/panel-UFXNO4AF.js.map +0 -1
- /package/dist/{chunk-GGAZOLNN.js.map → chunk-SWOWHIFE.js.map} +0 -0
- /package/dist/{chunk-KU4FVOFA.js.map → chunk-ZIR3ILFH.js.map} +0 -0
- /package/dist/{preferences-screen-V3ZBWP7A.js.map → preferences-screen-SXUIGECY.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/react/relative-time.ts","../src/react/live-section.tsx","../src/react/live-card.tsx"],"sourcesContent":["import type { NotificationMessages } from '../messages';\n\n/**\n * \"há 5 min\"-style relative timestamp, falling back to an absolute date for\n * anything older than a week. Every word comes from the messages table, so a\n * host in another locale changes the copy and the locale together.\n *\n * `now` is a parameter rather than a read, and the live section is why. A\n * relative phrase is only true for the instant it was computed, so something\n * has to CAUSE the render that recomputes it — and the live entries' own data\n * cannot: a host backed by react-query gets the previous object back whenever a\n * poll is deep-equal (`structuralSharing`, on by default), which within one\n * stage it always is. The section therefore ticks a clock and hands it down.\n * Defaulted, so every existing caller reads the wall clock exactly as before.\n */\nexport function relativeTime(\n iso: string,\n messages: NotificationMessages,\n now: number = Date.now(),\n): string {\n const elapsedMs = now - new Date(iso).getTime();\n const minutes = Math.round(elapsedMs / 60_000);\n if (minutes < 1) return messages.justNow;\n if (minutes < 60) return messages.minutesAgo(minutes);\n const hours = Math.round(minutes / 60);\n if (hours < 24) return messages.hoursAgo(hours);\n const days = Math.round(hours / 24);\n if (days < 7) return messages.daysAgo(days);\n return new Date(iso).toLocaleDateString(messages.dateLocale);\n}\n","/**\n * The pinned block at the top of the panel: everything that is happening NOW,\n * above everything that has already happened.\n *\n * ## Why it is here and not a second surface\n *\n * The notification centre is where a person goes to find out what they missed.\n * Splitting \"happening\" into its own bell would make them check two places to\n * answer one question, and the half they would stop checking is the one that\n * only has something in it occasionally — which is this one. Above the list,\n * inside the same drawer, it is on the path they already walk.\n *\n * ## What it deliberately does NOT do\n *\n * - It does not touch `unread`. A live entry is not news; counting it would put\n * a number on the bell that no amount of reading can clear.\n * - It renders nothing at all when there is nothing live — no heading, no empty\n * state, no reserved space. A panel with one permanent empty section in it is\n * a panel that has taught its reader to skip the top.\n * - It does not fetch. `useActivities` is the host's, and `active` tells it\n * whether anyone is looking.\n */\nimport { useEffect, useId, useState, type JSX } from 'react';\n\nimport { Box } from '@12-apps/ui/mui/Box';\nimport { Text } from '@12-apps/ui/typography/Text';\n\nimport type { LiveActivity } from '../live';\nimport type { NotificationMessages } from '../messages';\n\nimport { LiveActivityCard } from './live-card';\nimport type { LiveActivitiesConfig } from './live-config';\n\n/**\n * How often the section re-reads the clock.\n *\n * Every minute, because the timestamps under the cards are in minutes and a\n * tick that cannot change what is on screen is a wasted render — which is why\n * it is gated on there being something to tick as well as on the panel being\n * open. An open panel with nothing live schedules nothing at all; the earlier\n * gate was `active` alone, and it re-rendered a section that renders `null`\n * once a minute for as long as somebody left the inbox open.\n */\nconst TICK_MS = 60_000;\n\n/**\n * The current minute, re-read on a timer while there is something to tick.\n *\n * The caller passes `active && there are activities` — see {@link TICK_MS} for\n * why both halves are in it.\n */\nfunction useMinuteTick(active: boolean): number {\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (!active) return;\n // Re-read once on becoming active too: a panel reopened after ten minutes\n // would otherwise show the minute it was closed at until the first tick.\n setNow(Date.now());\n const timer = setInterval(() => setNow(Date.now()), TICK_MS);\n return () => clearInterval(timer);\n }, [active]);\n return now;\n}\n\nexport interface LiveSectionProps {\n config: LiveActivitiesConfig;\n messages: NotificationMessages;\n /** Whether the panel is open — passed straight through to the host's hook. */\n active: boolean;\n /**\n * Follow a card's link.\n *\n * Optional, and the panel omits it for a host with no router: a card that\n * cannot go anywhere renders as text rather than as a named control that\n * does nothing.\n */\n onOpen?: (activity: LiveActivity) => void;\n}\n\n\n\nexport function LiveSection({\n config,\n messages,\n active,\n onOpen,\n}: LiveSectionProps): JSX.Element | null {\n // Unconditional, because it is a hook. `active` is how it is told nobody is\n // looking — the same arrangement `useSignal` has one seam over.\n const activities = config.useActivities({ active });\n const now = useMinuteTick(active && activities.length > 0);\n // Per MOUNT, not per module: `LiveSection` is exported, and a host with a\n // desktop and a mobile panel would otherwise emit one id twice and have both\n // regions resolve their label to whichever came first.\n const headingId = useId();\n\n if (activities.length === 0) return null;\n\n return (\n // A NAMED region. Without the label a screen-reader user meets a loose run\n // of controls ahead of the inbox with nothing saying what they are; the\n // panel's own title is the drawer's heading and cannot describe this block.\n <Box\n component=\"section\"\n aria-labelledby={headingId}\n data-testid=\"live-activities\"\n sx={{ pb: 1.5 }}\n >\n {/*\n A SPAN, not a heading. `aria-labelledby` names the region perfectly well\n from one, and an `<h2>` here would sit under the drawer's own `<h6>`\n title and ABOVE the inbox's `<h3>` empty state — an outline in which the\n inbox's states read as part of the live block, which is the opposite of\n what the two blocks are.\n */}\n <Text\n id={headingId}\n variant=\"caption\"\n size=\"xs\"\n color=\"secondary\"\n weight=\"semibold\"\n as=\"span\"\n >\n {config.messages.sectionTitle}\n </Text>\n <Box sx={{ pt: 0.75 }}>\n {activities.map((activity) => (\n <LiveActivityCard\n key={activity.id}\n activity={activity}\n messages={messages}\n live={config.messages}\n now={now}\n {...(onOpen ? { onOpen } : {})}\n {...(config.renderIcon ? { renderIcon: config.renderIcon } : {})}\n />\n ))}\n </Box>\n </Box>\n );\n}\n","/**\n * ONE pinned live entry: a mark, what is happening, its lane, and when it last\n * moved.\n *\n * Visually a WASH rather than a fill — a tinted card with a brand-tinted border\n * — for the reason the inbox's unread row uses the same treatment: this sits at\n * the top of a list of other people's news, and a saturated block there\n * out-shouts everything it is supposed to be introducing.\n *\n * ## The card is a DIV, and the button is inside it\n *\n * The obvious shape — one `<button>` wrapping the whole card — is not\n * available, because `Stepper` draws every stop as a real `<button>`\n * (`@12-apps/ui`'s `StepButton` is `styled(Button)`), and `clickable={false}`\n * only sets `pointer-events: none`. A button inside a button is invalid HTML:\n * the parser auto-closes the outer one at the first nested one, so any host\n * that server-renders the panel open hydrates against a tree the browser\n * rewrote, and every adopter's dev console carries a React error besides.\n *\n * `aria-hidden` and `inert` on the lane fix the tab stops and the accessible\n * name — they do NOT fix the nesting, and an earlier draft of this file claimed\n * they did. So the tap target is the TEXT block, and the lane and the timestamp\n * are its siblings: valid markup, and a target that still covers everything a\n * reader would aim at.\n */\nimport { useId, type JSX, type ReactNode } from 'react';\n\nimport { Stepper } from '@12-apps/ui/data-display/Stepper';\nimport { Box } from '@12-apps/ui/mui/Box';\nimport { alpha, type Theme } from '@12-apps/ui/mui/styles';\nimport { Text } from '@12-apps/ui/typography/Text';\n\nimport { liveActivityLane, type LiveActivity } from '../live';\nimport type { NotificationMessages } from '../messages';\n\nimport type { LiveActivitiesConfig, LiveActivityMessages } from './live-config';\nimport { relativeTime } from './relative-time';\n\nconst cardSx = {\n // `relative`, so the button below can stretch a hit area over the whole card\n // — see `targetSx`.\n position: 'relative',\n border: '1px solid',\n borderColor: (t: Theme) => alpha(t.palette.primary.main, 0.35),\n bgcolor: (t: Theme) => alpha(t.palette.primary.main, 0.06),\n borderRadius: 1.5,\n p: 1.25,\n mb: 1,\n} as const;\n\n/** The text block: the mark, the heading and the sentence under it. */\nconst targetSx = {\n display: 'flex',\n alignItems: 'center',\n gap: 1,\n width: '100%',\n textAlign: 'left',\n font: 'inherit',\n color: 'inherit',\n border: 'none',\n background: 'none',\n p: 0,\n} as const;\n\n/**\n * The button, stretched over the WHOLE card.\n *\n * Taking the lane out of the link fixed the markup and left the card looking\n * like one target while only its top half was one — the lane is the most\n * visually distinctive part of it, and aiming at the obvious thing did nothing.\n *\n * A stretched pseudo-element is the remedy that keeps the structure: the\n * `<button>` stays a sibling of the lane in the tree, so nothing nests, and its\n * `::after` covers the card. All three declarations are load-bearing — a\n * pseudo-element with no `content` generates no box at all, and an absolutely\n * positioned box with auto offsets is 0×0.\n *\n * ## What actually lets a click on the LANE reach it\n *\n * Not paint order. `@12-apps/ui` gives each `StepItem` `position: relative`, and\n * this overlay is positioned too — so the two sit in the SAME painting layer\n * (positioned, `z-index: auto`), where tree order decides, and the lane comes\n * after the button. Every stop, and its label, therefore sits over this\n * overlay. `clickable={false}` does not save it either: the package puts\n * `pointer-events: none` on the step CIRCLE and not on the label beside it.\n *\n * It is `inert` on {@link ActivityLane} that does it: an inert subtree is\n * skipped by hit-testing, so a click on a stop falls through to the overlay\n * underneath. That makes the attribute load-bearing for the TARGET as well as\n * for the tab order it was added for — remove it and the lane silently swallows\n * clicks again, which is why the two are pinned by one test.\n */\nconst stretchedSx = {\n ...targetSx,\n cursor: 'pointer',\n '&::after': { content: '\"\"', position: 'absolute', inset: 0 },\n} as const;\n\n/**\n * Make a four-stop lane fit the panel.\n *\n * The drawer is 400px on a desktop and the full viewport on a phone, so the\n * narrow case is ~320px of card minus its padding. `Stepper` renders its labels\n * at `body2` for every size but `sm` and reserves 24px of connector plus 8px of\n * margin on each side, which is more row than four short words have — measured\n * on a 320px viewport, the last stop hung off the edge and the DRAWER scrolled\n * sideways.\n *\n * Three overrides, each buying back a specific number of pixels: 11px labels, a\n * step column allowed to shrink below the package's 44px floor (so the row's\n * min-content width is the longest WORD rather than the longest phrase), and\n * thinner connectors. `overflow: hidden` is the backstop and not the mechanism\n * — a locale with longer words than any of this anticipates clips its own card\n * instead of making the panel scroll.\n */\nconst laneSx = {\n pt: 1.25,\n px: 0.5,\n overflow: 'hidden',\n '& .MuiTypography-root': { fontSize: 11, lineHeight: 1.25 },\n '& [data-testid^=\"stepper-step-content-\"]': { minWidth: 0 },\n '& [data-testid^=\"stepper-connector-\"]': { minWidth: 6, mx: 0.75 },\n} as const;\n\n/**\n * The lane, or nothing.\n *\n * `aria-hidden` AND `inert`, and each earns its place twice over. The stops are\n * real buttons, so leaving four focusable, named controls per entry in front of\n * an inbox would cost a keyboard user the list they opened the panel for —\n * that is what the pair was added for. `inert` then turns out to be what makes\n * the card's own hit area work as well, because an inert subtree is skipped by\n * hit-testing: see {@link stretchedSx}.\n *\n * Nothing is lost by hiding it — the stop the subject is at is already the\n * card's heading, and the row of dots restates it visually.\n */\nfunction ActivityLane({ activity }: { activity: LiveActivity }): JSX.Element | null {\n const lane = liveActivityLane(activity);\n if (lane === null) return null;\n return (\n <Box sx={laneSx} aria-hidden inert>\n <Stepper\n steps={lane.steps.map((step) => ({ id: step.id, label: step.label }))}\n activeId={lane.activeStepId}\n completed={new Set(lane.completed)}\n orientation=\"horizontal\"\n size=\"xs\"\n clickable={false}\n data-testid={`live-activity-steps-${activity.id}`}\n />\n </Box>\n );\n}\n\n/** The card's props. Not part of the package's surface — see `./index`. */\ninterface LiveActivityCardProps {\n activity: LiveActivity;\n messages: NotificationMessages;\n live: LiveActivityMessages;\n renderIcon?: LiveActivitiesConfig['renderIcon'];\n /** The clock this render reads, so the \"last moved\" line can be ticked. */\n now: number;\n /**\n * Follow the card's link.\n *\n * Absent — as it is for a host with no router — renders the text as text. A\n * named, focusable control that does nothing is worse than no control.\n */\n onOpen?: (activity: LiveActivity) => void;\n}\n\n/**\n * The mark on the left, when the host draws one.\n *\n * PRESENTATIONAL ONLY. It is rendered inside the card's `<button>` and inside\n * an `aria-hidden` wrapper, so a host returning anything focusable — an\n * icon-button, a link — puts a button inside a button (invalid HTML, and the\n * defect this card was restructured to remove) and hides a focusable node from\n * the accessibility tree. An icon, an emoji, an `<svg>`: yes. A control: no.\n */\nfunction ActivityIcon({ icon }: { icon: ReactNode }): JSX.Element | null {\n if (icon === undefined || icon === null) return null;\n return (\n <Box aria-hidden sx={{ display: 'flex', flex: '0 0 auto', color: 'primary.main' }}>\n {icon}\n </Box>\n );\n}\n\n/** The mark, the heading and the line under it. */\nfunction ActivityTarget({\n activity,\n renderIcon,\n bodyId,\n}: Pick<LiveActivityCardProps, 'activity' | 'renderIcon'> & {\n /** Ties the sentence to the button, so a label does not swallow it. */\n bodyId: string;\n}): JSX.Element {\n return (\n <>\n <ActivityIcon icon={renderIcon?.(activity)} />\n {/* A COLUMN, not a bare block: `Text` sets no `display`, so two adjacent\n spans in an ordinary div run together on one line with not even a\n space between them — which is how the heading and the sentence under\n it ended up as one word in an earlier draft. `row.tsx` gets this right\n the same way. */}\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.25, minWidth: 0 }}>\n {/*\n The live region is THIS LINE and nothing else. The card also carries a\n relative timestamp that moves every minute for as long as the subject\n lasts, and announcing that is a polite interruption per minute for\n news the reader did not ask to be read. What is worth interrupting for\n is the subject MOVING, which is what the heading says.\n */}\n <Text\n variant=\"body\"\n size=\"sm\"\n weight=\"semibold\"\n as=\"span\"\n aria-live=\"polite\"\n data-testid={`live-activity-title-${activity.id}`}\n >\n {activity.title}\n </Text>\n {activity.body === null ? null : (\n <Text id={bodyId} variant=\"caption\" size=\"xs\" color=\"secondary\" as=\"span\">\n {activity.body}\n </Text>\n )}\n </Box>\n </>\n );\n}\n\nexport function LiveActivityCard({\n activity,\n messages,\n live,\n renderIcon,\n now,\n onOpen,\n}: LiveActivityCardProps): JSX.Element {\n const followable = activity.link !== null && onOpen !== undefined;\n const bodyId = useId();\n const target = (\n <ActivityTarget\n activity={activity}\n bodyId={bodyId}\n {...(renderIcon ? { renderIcon } : {})}\n />\n );\n return (\n <Box data-testid={`live-activity-${activity.id}`} sx={cardSx}>\n {followable ? (\n <Box\n component=\"button\"\n type=\"button\"\n onClick={() => onOpen(activity)}\n // `aria-label` REPLACES the contents, so the sentence under the\n // heading — the detail that makes the heading actionable — would be\n // announced to nobody. `aria-describedby` puts it back.\n aria-label={live.openActivity(activity.title)}\n {...(activity.body === null ? {} : { 'aria-describedby': bodyId })}\n data-testid={`live-activity-open-${activity.id}`}\n sx={stretchedSx}\n >\n {target}\n </Box>\n ) : (\n <Box sx={targetSx}>{target}</Box>\n )}\n <ActivityLane activity={activity} />\n <Text variant=\"caption\" size=\"xs\" color=\"secondary\" as=\"span\" italic>\n {live.updated(relativeTime(activity.updatedAt, messages, now))}\n </Text>\n </Box>\n );\n}\n"],"mappings":";;;;;;;;AAeO,SAAS,aACd,KACA,UACA,MAAc,KAAK,IAAI,GACf;AACR,QAAM,YAAY,MAAM,IAAI,KAAK,GAAG,EAAE,QAAQ;AAC9C,QAAM,UAAU,KAAK,MAAM,YAAY,GAAM;AAC7C,MAAI,UAAU,EAAG,QAAO,SAAS;AACjC,MAAI,UAAU,GAAI,QAAO,SAAS,WAAW,OAAO;AACpD,QAAM,QAAQ,KAAK,MAAM,UAAU,EAAE;AACrC,MAAI,QAA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K;AAAA,EAClC,GAAG,CAAC,MAAM,CAAC;AACX,SAAO;AACT;AAXS;AA8BF,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAyC;AAGvC,QAAM,aAAa,OAAO,cAAc,EAAE,OAAO,CAAC;AAClD,QAAM,MAAM,cAAc,UAAU,WAAW,SAAS,CAAC;AAIzD,QAAM,YAAYC,OAAM;AAExB,MAAI,WAAW,WAAW,EAAG,QAAO;AAEpC;AAAA;AAAA;AAAA;AAAA,IAIE,gBAAAD;AAAA,MAACE;AAAA,MAAA;AAAA,QACC,WAAU;AAAA,QACV,mBAAiB;AAAA,QACjB,eAAY;AAAA,QACZ,IAAI,EAAE,IAAI,IAAI;AAAA,QASd;AAAA,0BAAAH;AAAA,YAACI;AAAA,YAAA;AAAA,cACC,IAAI;AAAA,cACJ,SAAQ;AAAA,cACR,MAAK;AAAA,cACL,OAAM;AAAA,cACN,QAAO;AAAA,cACP,IAAG;AAAA,cAEF,iBAAO,SAAS;AAAA;AAAA,UACnB;AAAA,UACA,gBAAAJ,KAACG,MAAA,EAAI,IAAI,EAAE,IAAI,KAAK,GACjB,qBAAW,IAAI,CAAC,aACf,gBAAAH;AAAA,YAAC;AAAA;AAAA,cAEC;AAAA,cACA;AAAA,cACA,MAAM,OAAO;AAAA,cACb;AAAA,cACC,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,cAC3B,GAAI,OAAO,aAAa,EAAE,YAAY,OAAO,WAAW,IAAI,CAAC;AAAA;AAAA,YANzD,SAAS;AAAA,UAOhB,CACD,GACH;AAAA;AAAA;AAAA,IACF;AAAA;AAEJ;AA3DgB;","names":["useId","Box","Text","jsx","jsxs","useId","Box","Text"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-7QVYU63E.js";
|
|
4
|
+
|
|
5
|
+
// src/live.ts
|
|
6
|
+
function liveActivityLane(activity) {
|
|
7
|
+
const activeStepId = activity.activeStepId;
|
|
8
|
+
if (activeStepId === null || activity.steps.length === 0) return null;
|
|
9
|
+
const reached = activity.steps.findIndex((step) => step.id === activeStepId);
|
|
10
|
+
if (reached < 0) return null;
|
|
11
|
+
return {
|
|
12
|
+
steps: activity.steps,
|
|
13
|
+
activeStepId,
|
|
14
|
+
completed: new Set(activity.steps.slice(0, reached).map((step) => step.id))
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
__name(liveActivityLane, "liveActivityLane");
|
|
18
|
+
var LIVE_SUBJECT_KEY = "liveSubject";
|
|
19
|
+
var LIVE_PUSH_TAG_PREFIX = "live:";
|
|
20
|
+
function livePushTag(data) {
|
|
21
|
+
const subject = data?.[LIVE_SUBJECT_KEY];
|
|
22
|
+
if (typeof subject !== "string" || subject === "") return null;
|
|
23
|
+
return `${LIVE_PUSH_TAG_PREFIX}${subject}`;
|
|
24
|
+
}
|
|
25
|
+
__name(livePushTag, "livePushTag");
|
|
26
|
+
|
|
27
|
+
export {
|
|
28
|
+
liveActivityLane,
|
|
29
|
+
LIVE_SUBJECT_KEY,
|
|
30
|
+
LIVE_PUSH_TAG_PREFIX,
|
|
31
|
+
livePushTag
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=chunk-RTURLH5U.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/live.ts"],"sourcesContent":["/**\n * LIVE ACTIVITIES — the notification centre's second kind of entry.\n *\n * An inbox notification is an EVENT: it happened, it is stamped, it is read or\n * unread, and it is still there tomorrow saying the same thing. A live activity\n * is ONGOING STATE: it is pinned above the list, it has no read/unread, nobody\n * deletes it, it updates itself, and it is GONE the moment the thing it tracks\n * finishes.\n *\n * The distinction is not cosmetic. A row that says \"your order is on its way\",\n * read an hour later, is a claim about the past presented as news — and the\n * more reliable the inbox is, the more of those a person accumulates. Somewhere\n * in that list is the one question they actually have, which is *where is it\n * now*. A live activity answers that question and then removes itself, which is\n * the property no amount of better event copy can buy.\n *\n * ## This file is domain-free, and that is the whole design\n *\n * Nothing here knows what is being tracked. A host publishes activities through\n * `LiveActivitiesConfig.useActivities` (see `./react/live-config`) and this\n * package owns the contract, the placement, the rendering and the OS-level\n * collapse. The package that raises an alert has never been this package's\n * business — see the `generators` seam — and the thing an alert is ABOUT is not\n * either.\n *\n * ## The lane\n *\n * `steps` + `activeStepId` describe a progress lane, because \"how far along is\n * this\" is the shape almost every ongoing subject has. Both are optional in\n * effect: an activity with no lane (`steps: []`, `activeStepId: null`) is a\n * perfectly good live entry — a heading, a sentence and a timestamp that keeps\n * moving.\n */\n\n/** One stop on a live activity's lane. */\nexport interface LiveActivityStep {\n /** Stable across updates — the id is what `activeStepId` names. */\n id: string;\n /** What the reader sees under the dot. The HOST's word, in the reader's language. */\n label: string;\n}\n\n/** One thing that is happening right now, as the notification centre shows it. */\nexport interface LiveActivity {\n /**\n * Stable for the whole life of the subject.\n *\n * The SAME id on every update, because it is the identity of the thing being\n * tracked and not of the message: the panel keys on it so a stage change\n * re-renders one card rather than swapping two, and it is what\n * {@link livePushTag} collapses an OS notification onto.\n *\n * **Unique among the activities live at one moment**, for the same reason:\n * it is the React key and the card's test id. Two activities sharing one\n * gives a duplicate-key warning and a card that silently shows the wrong\n * subject.\n */\n id: string;\n /**\n * Which host concern this belongs to, e.g. `order`, `delivery`, `import`.\n *\n * Free-form and never rendered — it exists so a host publishing from two\n * sources can tell its own activities apart in a test or a log without\n * parsing `id`.\n */\n kind: string;\n /** The heading — what is happening. */\n title: string;\n /** The line under it: the detail that makes the heading actionable, or none. */\n body: string | null;\n /** Where tapping the card goes, as a same-origin path. `null` renders no link. */\n link: string | null;\n /** The lane, in the order it is walked. Empty when this subject has no lane. */\n steps: readonly LiveActivityStep[];\n /**\n * The stop the subject is AT — one of `steps`, or `null` for a laneless entry.\n *\n * An id that names no step is neither, and it is handled rather than trusted:\n * see {@link liveActivityLane}.\n */\n activeStepId: string | null;\n /**\n * ISO-8601 — when the subject last MOVED, not when it was last polled.\n *\n * A timestamp that advances on every read would render \"just now\" forever,\n * which is the one thing a live entry must not say when nothing is happening.\n */\n updatedAt: string;\n}\n\n/** A live activity's lane, resolved for rendering. */\nexport interface LiveActivityLane {\n steps: readonly LiveActivityStep[];\n activeStepId: string;\n /** Every stop BEFORE the active one — never the active one itself. */\n completed: ReadonlySet<string>;\n}\n\n/**\n * The lane to draw, or `null` when this activity has none to draw.\n *\n * Three cases collapse to `null`, and the third is the one worth writing down:\n * no steps, no active step, and **an active step the lane does not contain**.\n * That last one is not a theoretical defect — it is what a host produces the\n * first time a subject reaches a stage the lane was filtered to exclude, and\n * the symptom is a row of dots with NONE of them lit, which reads as a process\n * that has stopped. A card with no lane still says what is happening and when\n * it last moved; a dead lane says the tracking is broken.\n *\n * `completed` deliberately stops short of the active stop: a completed step\n * draws a tick, and ticking the stop the subject is sitting in claims it has\n * already left.\n */\nexport function liveActivityLane(activity: LiveActivity): LiveActivityLane | null {\n const activeStepId = activity.activeStepId;\n if (activeStepId === null || activity.steps.length === 0) return null;\n const reached = activity.steps.findIndex((step) => step.id === activeStepId);\n if (reached < 0) return null;\n return {\n steps: activity.steps,\n activeStepId,\n completed: new Set(activity.steps.slice(0, reached).map((step) => step.id)),\n };\n}\n\n/**\n * The reserved `data` key that ties a NOTIFICATION to a live subject.\n *\n * A notification and a live activity are different objects with different\n * lifetimes, and this is the only thing that joins them: a generator whose\n * event is about something also tracked live puts the activity's id here, and\n * every channel that can collapse gets to.\n *\n * data: { [LIVE_SUBJECT_KEY]: `order:${orderId}` }\n *\n * A plain string on purpose. An object here would grow a second wire contract\n * inside a column this package stores verbatim.\n */\nexport const LIVE_SUBJECT_KEY = 'liveSubject';\n\n/**\n * Namespaces the tray tag, so a live tag does not collide with the ones a host\n * already uses.\n *\n * A convention rather than an enforcement — nothing stops a host emitting its\n * own `live:`-prefixed tags — but it means the two id spaces have to be made to\n * meet rather than meeting by accident.\n */\nexport const LIVE_PUSH_TAG_PREFIX = 'live:';\n\n/**\n * The OS notification tag for a push about a live subject, or `null` for an\n * ordinary event.\n *\n * ## What the tag buys, and why it is the PWA half of this feature\n *\n * A `tag` makes a new notification REPLACE the one already in the tray instead\n * of stacking under it, and — unless the sender asks otherwise — replace it\n * *silently*. So a subject that moves through four stages costs one tray entry\n * and one buzz, and the entry that remains is the CURRENT one. Without it a\n * phone accumulates one alert per stage, all of them still asserting a stage\n * the subject has since left; the freshest is at the top and the reader has to\n * work out that the three below it are history.\n *\n * That is as close as the web platform gets to an ongoing/live notification,\n * and it is the half that reaches a person who does not have the app open —\n * which is most of the time a live activity is live.\n *\n * The id is passed through unchanged: it is the host's, it is already unique\n * per subject, and a hash would make the tray impossible to reason about from a\n * log line.\n */\nexport function livePushTag(\n data: Readonly<Record<string, unknown>> | null | undefined,\n): string | null {\n const subject = data?.[LIVE_SUBJECT_KEY];\n if (typeof subject !== 'string' || subject === '') return null;\n return `${LIVE_PUSH_TAG_PREFIX}${subject}`;\n}\n"],"mappings":";;;;;AAiHO,SAAS,iBAAiB,UAAiD;AAChF,QAAM,eAAe,SAAS;AAC9B,MAAI,iBAAiB,QAAQ,SAAS,MAAM,WAAW,EAAG,QAAO;AACjE,QAAM,UAAU,SAAS,MAAM,UAAU,CAAC,SAAS,KAAK,OAAO,YAAY;AAC3E,MAAI,UAAU,EAAG,QAAO;AACxB,SAAO;AAAA,IACL,OAAO,SAAS;AAAA,IAChB;AAAA,IACA,WAAW,IAAI,IAAI,SAAS,MAAM,MAAM,GAAG,OAAO,EAAE,IAAI,CAAC,SAAS,KAAK,EAAE,CAAC;AAAA,EAC5E;AACF;AAVgB;AAyBT,IAAM,mBAAmB;AAUzB,IAAM,uBAAuB;AAwB7B,SAAS,YACd,MACe;AACf,QAAM,UAAU,OAAO,gBAAgB;AACvC,MAAI,OAAO,YAAY,YAAY,YAAY,GAAI,QAAO;AAC1D,SAAO,GAAG,oBAAoB,GAAG,OAAO;AAC1C;AANgB;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
NOTIFICATION_CHANNELS
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-6W7INOYQ.js";
|
|
4
4
|
import {
|
|
5
5
|
__name
|
|
6
6
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -131,4 +131,4 @@ export {
|
|
|
131
131
|
normalizePhoneE164,
|
|
132
132
|
inboxWire
|
|
133
133
|
};
|
|
134
|
-
//# sourceMappingURL=chunk-
|
|
134
|
+
//# sourceMappingURL=chunk-SWOWHIFE.js.map
|
|
@@ -7,14 +7,20 @@ import {
|
|
|
7
7
|
mergeChoices,
|
|
8
8
|
mergeStoredRow,
|
|
9
9
|
normalizePhoneE164
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-SWOWHIFE.js";
|
|
11
|
+
import {
|
|
12
|
+
messagesOf
|
|
13
|
+
} from "./chunk-M2TVBVH2.js";
|
|
14
|
+
import {
|
|
15
|
+
livePushTag
|
|
16
|
+
} from "./chunk-RTURLH5U.js";
|
|
11
17
|
import {
|
|
12
18
|
NOTIFICATION_CHANNELS,
|
|
13
19
|
taxonomyOf
|
|
14
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-6W7INOYQ.js";
|
|
15
21
|
import {
|
|
16
|
-
|
|
17
|
-
} from "./chunk-
|
|
22
|
+
renderEmail
|
|
23
|
+
} from "./chunk-EKUSNUBT.js";
|
|
18
24
|
import {
|
|
19
25
|
__name
|
|
20
26
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -278,6 +284,7 @@ var EMAIL_DRIVERS = {
|
|
|
278
284
|
function formatEmail(content, declaration) {
|
|
279
285
|
const href = absoluteLink(content.link, declaration.appUrl);
|
|
280
286
|
const label = declaration.linkLabel;
|
|
287
|
+
if (declaration.layout) return layoutEmail(content, declaration.layout, href, label);
|
|
281
288
|
return {
|
|
282
289
|
subject: content.title,
|
|
283
290
|
text: href ? `${content.body}
|
|
@@ -291,6 +298,20 @@ ${href}` : content.body,
|
|
|
291
298
|
};
|
|
292
299
|
}
|
|
293
300
|
__name(formatEmail, "formatEmail");
|
|
301
|
+
function layoutEmail(content, layout, href, label) {
|
|
302
|
+
const rendered = renderEmail({
|
|
303
|
+
subject: content.title,
|
|
304
|
+
heading: content.title,
|
|
305
|
+
paragraphs: [content.body],
|
|
306
|
+
action: href ? { label, href } : void 0,
|
|
307
|
+
chrome: layout.chrome,
|
|
308
|
+
brand: layout.brand,
|
|
309
|
+
locale: layout.locale,
|
|
310
|
+
theme: layout.theme
|
|
311
|
+
});
|
|
312
|
+
return { subject: rendered.subject, text: rendered.text, html: rendered.html };
|
|
313
|
+
}
|
|
314
|
+
__name(layoutEmail, "layoutEmail");
|
|
294
315
|
function emailTransport(declaration, extraDrivers = {}) {
|
|
295
316
|
const driver = resolveDriver("EMAIL", declaration, { ...EMAIL_DRIVERS, ...extraDrivers });
|
|
296
317
|
return {
|
|
@@ -401,7 +422,8 @@ function formatWebPush(content) {
|
|
|
401
422
|
title: content.title,
|
|
402
423
|
body: content.body,
|
|
403
424
|
link: content.link ?? null,
|
|
404
|
-
data: content.data ?? {}
|
|
425
|
+
data: content.data ?? {},
|
|
426
|
+
tag: livePushTag(content.data)
|
|
405
427
|
};
|
|
406
428
|
}
|
|
407
429
|
__name(formatWebPush, "formatWebPush");
|
|
@@ -1331,4 +1353,4 @@ export {
|
|
|
1331
1353
|
createTransportRegistry,
|
|
1332
1354
|
createApiNotifications
|
|
1333
1355
|
};
|
|
1334
|
-
//# sourceMappingURL=chunk-
|
|
1356
|
+
//# sourceMappingURL=chunk-WVRODNXQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/context.ts","../src/server/transports/drivers.ts","../src/server/transports/email.ts","../src/server/transports/sms.ts","../src/server/transports/web-push.ts","../src/server/transports/whatsapp.ts","../src/server/transports/registry.ts","../src/server/by-permission.ts","../src/server/dispatch.ts","../src/server/inbox.ts","../src/server/preferences.ts","../src/server/push-subscriptions.ts","../src/server/routes.ts","../src/server/router.ts","../src/server/create-api-notifications.ts"],"sourcesContent":["import type { NotificationWireMessages } from '../messages';\nimport { NOTIFICATION_CHANNELS, type NotificationChannel } from '../types';\n\n/**\n * What every route in this surface shares (12-15): the actor, the request, the\n * response envelope and the body parsing. Mirrors the entity-lifecycle /\n * report-builder shape — framework-neutral descriptors a forty-line adapter\n * mounts.\n */\n\n/**\n * What a host must resolve before a request reaches these handlers: WHO is\n * calling. That is the whole seam.\n *\n * There is no tenant here and no permission list, and both absences are the\n * design. Every endpoint in this surface is SELF-scoped — a user reads and\n * writes their own inbox and their own preferences — so the only authorization\n * question is \"who is signed in\", and the answer is applied by scoping every\n * query to `userId` rather than by a guard that could be forgotten. A\n * permission-gated ADMIN view of someone else's inbox would be a different\n * surface, and would need a different actor.\n */\nexport interface NotificationsActor {\n userId: string;\n}\n\n/** One request, already authenticated and routed by the host. */\nexport interface NotificationsRequest {\n actor: NotificationsActor;\n params: Record<string, string | undefined>;\n query: Record<string, string | undefined>;\n body?: unknown;\n /** Headers the surface reads (`user-agent`, for the device hint). */\n headers?: Record<string, string | undefined>;\n /**\n * The language to answer this caller in, as a language tag (`pt-BR`,\n * `en-US`) — the same field `@12-apps/wiring`'s `WireRequest` carries.\n *\n * Populated by the host's adapter, which is the only layer that can\n * negotiate one. Absent is meaningful and not an error: a host with one\n * audience never sets it, and this surface must then answer with the words\n * it was configured with rather than invent a language.\n */\n locale?: string;\n}\n\n/** What a handler answers with; the adapter maps it onto its response type. */\nexport interface NotificationsResponse {\n status: number;\n /** `undefined` means NO body at all (204) — not the same as `null`. */\n body: unknown;\n}\n\nexport interface NotificationsRoute {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n /**\n * Path relative to the host's account mount, in `:param` form. The SHAPE is\n * fixed because the packaged client builds these URLs.\n */\n path: string;\n handle(request: NotificationsRequest): Promise<NotificationsResponse>;\n}\n\n/** A user-safe API error carrying the HTTP status the wire promises. */\nexport class NotificationsApiError extends Error {\n readonly status: number;\n constructor(status: number, message: string) {\n super(message);\n this.name = 'NotificationsApiError';\n this.status = status;\n Object.setPrototypeOf(this, NotificationsApiError.prototype);\n }\n}\n\n/** Success is `{ data }`; a denial is `{ error }`, unwrapped. */\nexport const ok = (data: unknown, status = 200): NotificationsResponse => ({\n status,\n body: { data },\n});\n\nconst fail = (status: number, error: string): NotificationsResponse => ({\n status,\n body: { error },\n});\n\n/** Fold a thrown {@link NotificationsApiError} into a response; rethrow the rest. */\nexport function foldApiError(error: unknown): NotificationsResponse {\n if (error instanceof NotificationsApiError) return fail(error.status, error.message);\n throw error;\n}\n\n/** Wrap a handler so its thrown api errors become the wire's `{ error }`. */\nexport function guarded(\n handle: (request: NotificationsRequest) => Promise<NotificationsResponse>,\n): (request: NotificationsRequest) => Promise<NotificationsResponse> {\n return async (request) => {\n try {\n return await handle(request);\n } catch (error) {\n return foldApiError(error);\n }\n };\n}\n\n// ---------------------------------------------------------------------------\n// Body / query parsing — the request contract, in the package\n// ---------------------------------------------------------------------------\n\nfunction asRecord(body: unknown, messages: NotificationWireMessages): Record<string, unknown> {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n return body as Record<string, unknown>;\n}\n\n/** 1..100 non-empty string ids. */\nfunction parseIds(value: unknown, messages: NotificationWireMessages): string[] {\n if (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n return value.map((id) => {\n if (typeof id !== 'string' || id.length === 0) {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n return id;\n });\n}\n\n/**\n * Query strings arrive as strings; the store clamps, but a non-number is a\n * client bug and must not silently read as \"the default page\".\n */\nfunction parseLimit(raw: string | undefined, messages: NotificationWireMessages): number | undefined {\n if (raw === undefined || raw === '') return undefined;\n const limit = Number(raw);\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n return limit;\n}\n\nfunction parseFilter(\n raw: string | undefined,\n messages: NotificationWireMessages,\n): 'all' | 'unread' | undefined {\n if (raw === undefined) return undefined;\n if (raw !== 'all' && raw !== 'unread') {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n return raw;\n}\n\n/** `GET <mount>/notifications` — `filter`, `cursor`, `limit`. */\nexport function parseListQuery(\n query: Record<string, string | undefined>,\n messages: NotificationWireMessages,\n): { filter?: 'all' | 'unread'; cursor?: string; limit?: number } {\n const filter = parseFilter(query.filter, messages);\n const limit = parseLimit(query.limit, messages);\n return {\n ...(filter !== undefined ? { filter } : {}),\n ...(query.cursor ? { cursor: query.cursor } : {}),\n ...(limit !== undefined ? { limit } : {}),\n };\n}\n\n/** `POST <mount>/notifications/mark-read` — explicit ids, or `all: true`. */\nexport function parseMarkReadBody(\n body: unknown,\n messages: NotificationWireMessages,\n): { all: true } | { ids: string[] } {\n const record = asRecord(body, messages);\n const wantsAll = record.all === true;\n const hasIds = record.ids !== undefined;\n // Exactly one of the two. Both, or neither, is ambiguous in the one direction\n // that matters: \"mark everything read\" is not a thing to guess at.\n if (wantsAll === hasIds) {\n throw new NotificationsApiError(400, messages.markReadTargetRequired);\n }\n return wantsAll ? { all: true } : { ids: parseIds(record.ids, messages) };\n}\n\n/** `POST <mount>/notifications/delete` — 1..100 ids. */\nexport function parseDeleteBody(body: unknown, messages: NotificationWireMessages): string[] {\n return parseIds(asRecord(body, messages).ids, messages);\n}\n\n/**\n * `PUT <mount>/notification-preferences` — any subset of categories, each with\n * any subset of channel toggles. Categories left out stay untouched.\n */\nexport function parsePreferencesBody(\n body: unknown,\n messages: NotificationWireMessages,\n): Record<string, Partial<Record<NotificationChannel, boolean>>> {\n const record = asRecord(body, messages);\n const parsed: Record<string, Partial<Record<NotificationChannel, boolean>>> = {};\n for (const [category, value] of Object.entries(record)) {\n parsed[category] = parseToggles(value, messages);\n }\n return parsed;\n}\n\n/** One category's toggles, narrowed onto the closed channel set. */\nfunction parseToggles(\n value: unknown,\n messages: NotificationWireMessages,\n): Partial<Record<NotificationChannel, boolean>> {\n const toggles = asRecord(value, messages);\n const row: Partial<Record<NotificationChannel, boolean>> = {};\n for (const channel of NOTIFICATION_CHANNELS) {\n const flag = toggles[channel];\n if (flag === undefined) continue;\n if (typeof flag !== 'boolean') throw new NotificationsApiError(400, messages.invalidBody);\n row[channel] = flag;\n }\n return row;\n}\n\nconst MAX_ENDPOINT_CHARS = 2000;\nconst MAX_KEY_CHARS = 500;\n\nfunction parseEndpoint(value: unknown, messages: NotificationWireMessages): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_ENDPOINT_CHARS) {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n // A push endpoint is a URL the server will POST to, so an absolute http(s)\n // URL is a hard requirement rather than a formality.\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n return value;\n}\n\n/** `POST <mount>/push-subscriptions` — `PushSubscription.toJSON()`. */\nexport function parsePushSubscriptionBody(\n body: unknown,\n messages: NotificationWireMessages,\n): { endpoint: string; keys: { p256dh: string; auth: string } } {\n const record = asRecord(body, messages);\n const keys = asRecord(record.keys, messages);\n const key = (value: unknown): string => {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_KEY_CHARS) {\n throw new NotificationsApiError(400, messages.invalidBody);\n }\n return value;\n };\n return {\n endpoint: parseEndpoint(record.endpoint, messages),\n keys: { p256dh: key(keys.p256dh), auth: key(keys.auth) },\n };\n}\n\n/** `DELETE <mount>/push-subscriptions` — by endpoint. */\nexport function parsePushEndpointBody(body: unknown, messages: NotificationWireMessages): string {\n return parseEndpoint(asRecord(body, messages).endpoint, messages);\n}\n\n/**\n * `GET <mount>/push-subscriptions?endpoint=…` — the browser asking \"is the\n * subscription I am holding still MINE on the server?\".\n *\n * Optional: with no `endpoint` the route answers the key and the count as it\n * always has. Validated by the same rules as the write, so a junk value is a 400\n * rather than a lookup.\n */\nexport function parsePushEndpointQuery(\n query: Record<string, string | undefined>,\n messages: NotificationWireMessages,\n): string | undefined {\n if (query.endpoint === undefined || query.endpoint === '') return undefined;\n return parseEndpoint(query.endpoint, messages);\n}\n","/**\n * The DRIVER port — the reason a host adds a vendor with a config entry and no\n * code (12-15).\n *\n * the origin's transports each read `process.env` directly:\n * `NOTIFICATIONS_EMAIL_PROVIDER=resend` plus `RESEND_API_KEY`, and a second\n * vendor meant editing the package. That is exactly backwards for a published\n * package — it cannot know a host's variable names, and it must not be the\n * thing that decides whether a channel is on. So a channel is configured by\n * DECLARATION:\n *\n * transports: [\n * { channel: 'EMAIL', driver: 'resend', apiKey, from },\n * { channel: 'SMS', driver: 'log' },\n * ]\n *\n * A channel with no declaration reports `supports() === false` and the router\n * skips it: no delivery row, nothing fake-sent. A second vendor is one more\n * entry in the built-in driver table (or `drivers` on the config, for a host's\n * own), and the router, the registry and the other transports are untouched.\n */\n\nimport { normalizePhoneE164 } from '../../phone';\nimport type {\n NotificationContent,\n NotificationTransport,\n TransportRecipient,\n} from '../../types';\n\n/** Every HTTP call a built-in driver makes goes through this, so a test can. */\nexport type FetchImpl = (\n input: string,\n init?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n },\n) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;\n\n/** Shared by every declaration: which channel, which vendor. */\nexport interface DriverDeclarationBase {\n /** Vendor key: `resend` / `twilio` / `meta` / `log`, or a host's own. */\n driver: string;\n /**\n * The HTTP client the vendor call uses. Defaults to the global `fetch`.\n * Supplied by tests and by hosts that need a proxy or a retry policy.\n */\n fetchImpl?: FetchImpl;\n}\n\n/** A vendor rejection, carrying what the provider actually said. */\nexport class NotificationProviderError extends Error {\n readonly status: number;\n constructor(vendor: string, status: number, detail: string) {\n super(`${vendor} rejected the message (${status} ${detail}).`);\n this.name = 'NotificationProviderError';\n this.status = status;\n Object.setPrototypeOf(this, NotificationProviderError.prototype);\n }\n}\n\n/** `fetch` and throw {@link NotificationProviderError} on a non-2xx. */\nexport async function postOrThrow(\n vendor: string,\n fetchImpl: FetchImpl | undefined,\n url: string,\n init: { headers: Record<string, string>; body: string },\n): Promise<void> {\n const call = fetchImpl ?? (globalThis.fetch as unknown as FetchImpl);\n const response = await call(url, { method: 'POST', ...init });\n if (!response.ok) {\n throw new NotificationProviderError(vendor, response.status, await response.text());\n }\n}\n\n/**\n * Resolve one declaration against a driver table.\n *\n * Returning `null` — an unknown driver name — is a CONFIGURATION error, not a\n * runtime one, so the caller (the transport factory) throws with the names it\n * does know. A typo'd vendor that silently disabled a channel is the failure\n * mode this whole seam exists to remove.\n */\nexport function resolveDriver<TDeclaration extends DriverDeclarationBase, TDriver>(\n channel: string,\n declaration: TDeclaration,\n table: Record<string, (declaration: TDeclaration) => TDriver>,\n): TDriver {\n const factory = table[declaration.driver];\n if (!factory) {\n throw new Error(\n `@12-apps/notifications: unknown ${channel} driver \"${declaration.driver}\". ` +\n `Known drivers: ${Object.keys(table).sort().join(', ')}.`,\n );\n }\n return factory(declaration);\n}\n\n/**\n * Absolutize an in-app link for a channel that leaves the app.\n *\n * A relative path is useless in an inbox and a fabricated localhost link is\n * worse than none, so with no `appUrl` configured the link is simply dropped —\n * The origin's rule, kept.\n */\nexport function absoluteLink(link: string | undefined, appUrl: string | undefined): string | null {\n if (!link || !appUrl) return null;\n try {\n return new URL(link, appUrl).toString();\n } catch {\n return null;\n }\n}\n\n/**\n * The two PHONE channels' shared skeleton.\n *\n * SMS and WhatsApp differ in their vendor, their message shape and their\n * formatter — and in nothing else: both are unavailable for a recipient whose\n * number will not normalize, both normalize before the vendor ever sees the\n * destination, and both refuse rather than send when it cannot be. Stating that\n * rule twice is how the two drift, which is exactly what happened to the\n * transports' `supports()` gates before they funnelled through one helper.\n */\nexport function phoneChannel<TMessage>(\n channel: 'SMS' | 'WHATSAPP',\n options: {\n /** Country calling code for a bare local number. Required — see `phone.ts`. */\n defaultCountryCode: string;\n format: (content: NotificationContent) => TMessage;\n send: (toE164: string, message: TMessage) => Promise<void>;\n },\n): NotificationTransport<TMessage> {\n const toE164 = (recipient: TransportRecipient): string | null =>\n normalizePhoneE164(recipient.phone, {\n defaultCountryCode: options.defaultCountryCode,\n });\n return {\n channel,\n supports: (recipient) => toE164(recipient) !== null,\n format: options.format,\n async send(message, recipient) {\n const to = toE164(recipient);\n if (!to) throw new Error('Recipient has no usable phone number.');\n await options.send(to, message);\n },\n };\n}\n","import type {\n NotificationContent,\n NotificationLogger,\n NotificationTransport,\n TransportRecipient,\n} from '../../types';\n\nimport { renderEmail } from '../../email/template';\nimport type { EmailChromeCopy } from '../../email/template';\nimport type { EmailTheme } from '../../email/theme';\n\nimport {\n absoluteLink,\n postOrThrow,\n resolveDriver,\n type DriverDeclarationBase,\n} from './drivers';\n\n/**\n * EMAIL transport: formatter + sender behind the driver port.\n *\n * - `driver: 'resend'` — Resend's HTTP API (plain JSON POST, no SDK):\n * `apiKey` + `from`.\n * - `driver: 'log'` — dev/e2e driver: logs the message instead of sending\n * (explicit opt-in, never a silent default).\n * - no EMAIL declaration at all — `supports() === false`, router skips it.\n *\n * A different vendor (SES, an SMTP relay…) is one more entry in\n * {@link EMAIL_DRIVERS} — this transport, the router and the registry stay\n * untouched.\n */\n\n/** The channel message an email formatter produces. */\nexport interface EmailMessage {\n subject: string;\n text: string;\n html: string;\n}\n\n/** The vendor seam: deliver one already-formatted email. Throws on failure. */\nexport interface EmailDriver {\n send(to: string, message: EmailMessage): Promise<void>;\n}\n\nexport interface EmailDriverDeclaration extends DriverDeclarationBase {\n channel: 'EMAIL';\n /** Resend: the API key. */\n apiKey?: string;\n /** Resend: the verified `From` address. */\n from?: string;\n /** Where the CTA link points; without it a link is dropped. */\n appUrl?: string;\n /**\n * The CTA link's label. REQUIRED — this used to default to `'Ver detalhes'`,\n * so a host that declared EMAIL and nothing else mailed this product's\n * Portuguese to its own users, in their inbox, signed with the host's own\n * `from` address.\n */\n linkLabel: string;\n /**\n * Render through `../../email` — the ONE layout — instead of the three bare\n * `<p>` tags below.\n *\n * OPTIONAL, and its absence is the pre-layout behaviour verbatim. That is\n * deliberate rather than timid: `brand` and `chrome` are REQUIRED with no\n * default anywhere in the layout (a package that defaulted them would sign\n * another company's mail, in a language nobody chose), so a required field\n * here would break every host that already declares EMAIL — at runtime, on\n * the first send, which is the worst place to find out.\n *\n * So the seam is opt-in and the ad-hoc path is what remains for a host that\n * has not taken it. `layout.theme` may still be omitted; `../../email/theme`\n * argues why that one asymmetry is allowed.\n */\n layout?: {\n /** The product name in the header and the footer. */\n brand: string;\n /** The layout's own words. `@12-apps/notifications/email/locales` ships packs. */\n chrome: EmailChromeCopy;\n /** The recipient's language, for the document's `lang` attribute. */\n locale: string;\n /** Defaults to the layout's neutral palette. */\n theme?: EmailTheme;\n };\n logger?: NotificationLogger;\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"');\n}\n\nconst resendDriver = (declaration: EmailDriverDeclaration): EmailDriver => ({\n async send(to, message) {\n if (!declaration.apiKey || !declaration.from) {\n throw new Error('The resend email driver needs both `apiKey` and `from`.');\n }\n await postOrThrow('Resend', declaration.fetchImpl, 'https://api.resend.com/emails', {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${declaration.apiKey}`,\n },\n body: JSON.stringify({\n from: declaration.from,\n to: [to],\n subject: message.subject,\n text: message.text,\n html: message.html,\n }),\n });\n },\n});\n\nconst logEmailDriver = (declaration: EmailDriverDeclaration): EmailDriver => ({\n // Deliberately logs NO destination address — a recipient e-mail is PII and\n // must never reach logs; the subject alone is enough for local debugging.\n send(_to, message) {\n declaration.logger?.info(\n `[notifications:email] log driver suppressed a real send (subject=\"${message.subject}\")`,\n );\n return Promise.resolve();\n },\n});\n\n/** The built-in email vendors. A host adds one by extending this table. */\nexport const EMAIL_DRIVERS: Record<\n string,\n (declaration: EmailDriverDeclaration) => EmailDriver\n> = {\n resend: resendDriver,\n log: logEmailDriver,\n};\n\n/**\n * Agnostic content → subject/text/html. The link becomes a trailing CTA, only\n * when an app base URL is configured.\n *\n * Two renderings, and which one runs is the host's choice: with `layout`\n * declared this is the shared document (`../../email`), and without it the\n * three bare `<p>` tags that predate it. See `EmailDriverDeclaration.layout`\n * for why the new path could not simply replace the old one.\n */\nexport function formatEmail(\n content: NotificationContent,\n declaration: EmailDriverDeclaration,\n): EmailMessage {\n const href = absoluteLink(content.link, declaration.appUrl);\n const label = declaration.linkLabel;\n if (declaration.layout) return layoutEmail(content, declaration.layout, href, label);\n return {\n subject: content.title,\n text: href ? `${content.body}\\n\\n${href}` : content.body,\n html: [\n `<p><strong>${escapeHtml(content.title)}</strong></p>`,\n `<p>${escapeHtml(content.body)}</p>`,\n ...(href ? [`<p><a href=\"${escapeHtml(href)}\">${escapeHtml(label)}</a></p>`] : []),\n ].join('\\n'),\n };\n}\n\n/**\n * The same notification as a laid-out document.\n *\n * The layout escapes and builds the plain-text twin from the SAME object, which\n * is the pair of defects the branch above still carries by construction: its\n * text half is assembled separately, and its `href` reaches the anchor through\n * `escapeHtml` rather than through a scheme check.\n */\nfunction layoutEmail(\n content: NotificationContent,\n layout: NonNullable<EmailDriverDeclaration['layout']>,\n href: string | null,\n label: string,\n): EmailMessage {\n const rendered = renderEmail({\n subject: content.title,\n heading: content.title,\n paragraphs: [content.body],\n action: href ? { label, href } : undefined,\n chrome: layout.chrome,\n brand: layout.brand,\n locale: layout.locale,\n theme: layout.theme,\n });\n return { subject: rendered.subject, text: rendered.text, html: rendered.html };\n}\n\nexport function emailTransport(\n declaration: EmailDriverDeclaration,\n extraDrivers: Record<string, (d: EmailDriverDeclaration) => EmailDriver> = {},\n): NotificationTransport<EmailMessage> {\n const driver = resolveDriver('EMAIL', declaration, { ...EMAIL_DRIVERS, ...extraDrivers });\n return {\n channel: 'EMAIL',\n // Truthiness, not `!== null`: an EMPTY STRING is a very ordinary DB value\n // for a nullable column, and it used to pass this gate, earn a delivery row\n // and then fail forever against `send`'s own `!recipient.email` check.\n supports: (recipient: TransportRecipient) => Boolean(recipient.email),\n format: (content) => formatEmail(content, declaration),\n async send(message, recipient) {\n if (!recipient.email) throw new Error('Recipient has no email address.');\n await driver.send(recipient.email, message);\n },\n };\n}\n","import type {\n NotificationContent,\n NotificationLogger,\n NotificationTransport,\n} from '../../types';\n\nimport {\n absoluteLink,\n phoneChannel,\n postOrThrow,\n resolveDriver,\n type DriverDeclarationBase,\n} from './drivers';\n\n/**\n * SMS transport — Twilio behind the same driver port as email.\n *\n * - `driver: 'twilio'` — the Messages API (form-encoded POST with basic\n * auth, no SDK): `accountSid`, `authToken`, `from` (an E.164 sender or a\n * Messaging Service SID).\n * - `driver: 'log'` — dev driver: logs instead of sending.\n * - no SMS declaration — channel unavailable, router skips it.\n *\n * A recipient without a normalizable phone is unavailable on this channel\n * regardless of the driver (see `../../phone.ts` for the verification caveat).\n */\n\n/** The channel message the SMS formatter produces: one plain text body. */\nexport interface SmsMessage {\n body: string;\n}\n\nexport interface SmsDriver {\n send(toE164: string, message: SmsMessage): Promise<void>;\n}\n\nexport interface SmsDriverDeclaration extends DriverDeclarationBase {\n channel: 'SMS';\n accountSid?: string;\n authToken?: string;\n from?: string;\n appUrl?: string;\n /**\n * Country calling code for a bare local number, digits only (`'55'`, `'1'`).\n * REQUIRED: this package assumes no country, because the one it used to\n * assume turned a US number into a plausible Brazilian mobile and texted a\n * stranger the customer's order (see `../../phone.ts`).\n */\n defaultCountryCode: string;\n logger?: NotificationLogger;\n}\n\n/** SMS bodies are billed per 160-char segment — keep one message ≤ 3 segments. */\nconst MAX_SMS_CHARS = 480;\n\nconst twilioDriver = (declaration: SmsDriverDeclaration): SmsDriver => ({\n async send(toE164, message) {\n const sid = declaration.accountSid;\n if (!sid || !declaration.authToken || !declaration.from) {\n throw new Error('The twilio sms driver needs `accountSid`, `authToken` and `from`.');\n }\n const auth = Buffer.from(`${sid}:${declaration.authToken}`).toString('base64');\n await postOrThrow(\n 'Twilio',\n declaration.fetchImpl,\n `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(sid)}/Messages.json`,\n {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Basic ${auth}`,\n },\n body: new URLSearchParams({\n To: toE164,\n From: declaration.from,\n Body: message.body,\n }).toString(),\n },\n );\n },\n});\n\nconst logSmsDriver = (declaration: SmsDriverDeclaration): SmsDriver => ({\n // Deliberately logs NO destination — a phone number is PII and must never\n // reach logs; the message body alone is enough for local debugging.\n send(_toE164, message) {\n declaration.logger?.info(\n `[notifications:sms] log driver suppressed a real send (body=\"${message.body}\")`,\n );\n return Promise.resolve();\n },\n});\n\nexport const SMS_DRIVERS: Record<string, (declaration: SmsDriverDeclaration) => SmsDriver> = {\n twilio: twilioDriver,\n log: logSmsDriver,\n};\n\n/** Agnostic content → one plain SMS: \"title: body (link)\", length-capped. */\nexport function formatSms(\n content: NotificationContent,\n declaration: SmsDriverDeclaration,\n): SmsMessage {\n const parts = [`${content.title}: ${content.body}`];\n const href = absoluteLink(content.link, declaration.appUrl);\n if (href) parts.push(href);\n const body = parts.join(' ');\n return { body: body.length > MAX_SMS_CHARS ? `${body.slice(0, MAX_SMS_CHARS - 1)}…` : body };\n}\n\nexport function smsTransport(\n declaration: SmsDriverDeclaration,\n extraDrivers: Record<string, (d: SmsDriverDeclaration) => SmsDriver> = {},\n): NotificationTransport<SmsMessage> {\n const driver = resolveDriver('SMS', declaration, { ...SMS_DRIVERS, ...extraDrivers });\n return phoneChannel<SmsMessage>('SMS', {\n defaultCountryCode: declaration.defaultCountryCode,\n format: (content) => formatSms(content, declaration),\n send: (toE164, message) => driver.send(toE164, message),\n });\n}\n","import { livePushTag } from '../../live';\nimport type {\n NotificationContent,\n NotificationLogger,\n NotificationTransport,\n TransportRecipient,\n} from '../../types';\n\nimport { resolveDriver, type DriverDeclarationBase } from './drivers';\n\n/**\n * WEB_PUSH transport — browser alerts over the Web Push protocol.\n *\n * What is the PACKAGE's, and stays here: the payload the service worker\n * renders, the fan-out to every one of the user's browsers, the 404/410 PRUNE\n * that makes `push_subscriptions` self-heal, and the rule that a send succeeds\n * when at least one subscription accepted it and fails only when all errored.\n *\n * What is the VENDOR's, and crosses as a port: VAPID signing and RFC 8291\n * payload encryption. Those need the `web-push` package, a node-only\n * dependency this package must not force on a host that never enables the\n * channel — so `@12-apps/notifications/web-push` exports the sender behind its\n * own subpath and an optional peer, exactly as `./hono` does for the adapter.\n *\n * - `driver: 'vapid'` — `sender: vapidPushSender({ subject, publicKey,\n * privateKey })` from that subpath (or any other signer).\n * - `driver: 'log'` — dev driver: logs instead of sending.\n * - no WEB_PUSH declaration — channel unavailable, router skips it.\n */\n\n/** One browser subscription, as `PushManager.subscribe()` yields it. */\nexport interface WebPushSubscription {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n}\n\n/**\n * The vendor seam: sign + encrypt + POST one payload to one push service.\n *\n * MUST reject with an error carrying a numeric `statusCode` when the push\n * service answers one — that is how a gone subscription (404/410) is told\n * apart from a transient failure, and therefore what makes the prune correct\n * rather than destructive.\n */\nexport type WebPushSender = (\n subscription: WebPushSubscription,\n payload: string,\n) => Promise<void>;\n\n/** The channel message the Web Push formatter produces (the SW's payload). */\nexport interface WebPushMessage {\n title: string;\n body: string;\n link: string | null;\n data: Record<string, unknown>;\n /**\n * The OS tray tag, or `null` for an ordinary event.\n *\n * Present for a notification about a LIVE SUBJECT (see `../../live`), and\n * this is the whole of the live feature's reach onto a locked phone: a tag\n * makes the next push about the same subject REPLACE the one already in the\n * tray — silently — instead of stacking under it. Four stages then cost one\n * entry and one buzz, and the entry that remains is the current one.\n *\n * {@link formatWebPush} always sets it, `null` included, so on the WIRE the\n * key is always there and a service worker reads one shape. A worker that\n * ignores it keeps today's behaviour exactly, which is what makes this safe\n * to ship ahead of the workers.\n *\n * OPTIONAL in the type, and only in the type: a host that hand-writes its own\n * `NotificationTransport<WebPushMessage>` — a fixture, a second driver —\n * would otherwise stop compiling on a field it has no way to know about and\n * no reason to set.\n */\n tag?: string | null;\n}\n\nexport interface WebPushDriverDeclaration extends DriverDeclarationBase {\n channel: 'WEB_PUSH';\n /** Required by the `vapid` driver: the signer. */\n sender?: WebPushSender;\n /**\n * The VAPID PUBLIC key, served to the browser by\n * `GET <mount>/push-subscriptions` so the client can subscribe. Public by\n * definition — the private key never crosses into this declaration.\n */\n publicKey?: string;\n logger?: NotificationLogger;\n}\n\n/** The subscriptions the transport reads and prunes (db-backed by the mount). */\nexport interface WebPushSubscriptionSource {\n list(userId: string): Promise<{ id: string; endpoint: string; p256dh: string; auth: string }[]>;\n prune(id: string): Promise<void>;\n}\n\nconst vapidDriver = (declaration: WebPushDriverDeclaration): WebPushSender => {\n const sender = declaration.sender;\n if (!sender) {\n throw new Error(\n 'The vapid web-push driver needs a `sender` — import `vapidPushSender` from ' +\n '@12-apps/notifications/web-push.',\n );\n }\n return sender;\n};\n\nconst logWebPushDriver =\n (declaration: WebPushDriverDeclaration): WebPushSender =>\n (_subscription, payload) => {\n // No endpoint logged: a push endpoint is a bearer capability for that\n // browser, so it is a secret in exactly the way an e-mail address is PII.\n declaration.logger?.info(\n `[notifications:web-push] log driver suppressed a real send (${payload.length} bytes)`,\n );\n return Promise.resolve();\n };\n\nexport const WEB_PUSH_DRIVERS: Record<\n string,\n (declaration: WebPushDriverDeclaration) => WebPushSender\n> = {\n vapid: vapidDriver,\n log: logWebPushDriver,\n};\n\n/** Status codes that mean \"this subscription no longer exists — prune it\". */\nconst GONE_STATUSES = new Set([404, 410]);\n\nfunction statusCodeOf(error: unknown): number | null {\n if (error && typeof error === 'object' && 'statusCode' in error) {\n const code = (error as { statusCode: unknown }).statusCode;\n return typeof code === 'number' ? code : null;\n }\n return null;\n}\n\nexport function formatWebPush(content: NotificationContent): WebPushMessage {\n return {\n title: content.title,\n body: content.body,\n link: content.link ?? null,\n data: content.data ?? {},\n tag: livePushTag(content.data),\n };\n}\n\nexport function webPushTransport(\n declaration: WebPushDriverDeclaration,\n subscriptions: WebPushSubscriptionSource,\n extraDrivers: Record<string, (d: WebPushDriverDeclaration) => WebPushSender> = {},\n): NotificationTransport<WebPushMessage> {\n const send = resolveDriver('WEB_PUSH', declaration, {\n ...WEB_PUSH_DRIVERS,\n ...extraDrivers,\n });\n return {\n channel: 'WEB_PUSH',\n supports: (recipient: TransportRecipient) => recipient.pushSubscriptionCount > 0,\n format: formatWebPush,\n async send(message, recipient) {\n const rows = await subscriptions.list(recipient.userId);\n if (rows.length === 0) throw new Error('Recipient no longer has push subscriptions.');\n const payload = JSON.stringify(message);\n let delivered = 0;\n let lastError: unknown = null;\n for (const row of rows) {\n try {\n await send({ endpoint: row.endpoint, keys: { p256dh: row.p256dh, auth: row.auth } }, payload);\n delivered += 1;\n } catch (error) {\n const status = statusCodeOf(error);\n if (status !== null && GONE_STATUSES.has(status)) {\n // Expired/unsubscribed browser — prune so future sends skip it.\n await subscriptions.prune(row.id).catch(() => {\n /* already pruned by a concurrent send */\n });\n } else {\n lastError = error;\n }\n }\n }\n if (delivered === 0) {\n throw lastError instanceof Error\n ? lastError\n : new Error('No push subscription accepted the payload.');\n }\n },\n };\n}\n","import type {\n NotificationContent,\n NotificationLogger,\n NotificationTransport,\n} from '../../types';\n\nimport {\n absoluteLink,\n phoneChannel,\n postOrThrow,\n resolveDriver,\n type DriverDeclarationBase,\n} from './drivers';\n\n/**\n * WHATSAPP transport — Meta's WhatsApp Cloud API behind the driver port.\n *\n * - `driver: 'meta'` — the Cloud API (JSON POST with a bearer token, no\n * SDK): `accessToken` + `phoneNumberId`.\n * - `driver: 'log'` — dev driver: logs instead of sending.\n * - no WHATSAPP declaration — channel unavailable, router skips it.\n *\n * Template/session-window rule: WhatsApp only accepts FREE-FORM text inside a\n * 24h customer-service window; business-initiated messages outside it require\n * a pre-approved TEMPLATE. With `templateName` set the transport sends that\n * template with two body parameters — {{1}} = title, {{2}} = body (language\n * `templateLanguage`, default `pt_BR`). Without it the transport sends\n * free-form text, and a send outside the session window FAILS with the\n * provider's error recorded on the delivery row — the documented fallback\n * behaviour, visible instead of silent.\n *\n * The window cannot be TRACKED from here (only Meta knows when the customer\n * last wrote), so a host that declares WHATSAPP with no `templateName` and then\n * emits business-initiated notifications has every send rejected. That is\n * visible on the delivery rows, but only once they exist — so the mount warns\n * about the combination the moment the declaration is read, which is the one\n * moment a misconfiguration is cheap to notice.\n */\n\n/** The channel message the WhatsApp formatter produces. */\nexport interface WhatsAppMessage {\n /** Free-form text used inside the session window / without a template. */\n text: string;\n /** Template body parameters ({{1}} title, {{2}} body) when templated. */\n templateParameters: [title: string, body: string];\n}\n\nexport interface WhatsAppDriver {\n send(toE164: string, message: WhatsAppMessage): Promise<void>;\n}\n\nexport interface WhatsAppDriverDeclaration extends DriverDeclarationBase {\n channel: 'WHATSAPP';\n accessToken?: string;\n phoneNumberId?: string;\n templateName?: string;\n /**\n * The WhatsApp template's language code, e.g. `pt_BR`, `en_US`.\n *\n * REQUIRED: a template is registered with Meta under one language, and\n * sending it with the wrong code is rejected by the Graph API. This defaulted\n * to `pt_BR` — one market's answer — so a host that forgot it did not get a\n * sensible fallback, it got somebody else's template language and a delivery\n * failure it had no reason to expect.\n */\n templateLanguage: string;\n /** Graph API base, so a host can pin a version. */\n graphApiBase?: string;\n appUrl?: string;\n /**\n * Country calling code for a bare local number, digits only (`'55'`, `'1'`).\n * REQUIRED for the same reason SMS requires it — see `../../phone.ts`.\n */\n defaultCountryCode: string;\n logger?: NotificationLogger;\n}\n\nconst DEFAULT_GRAPH_API_BASE = 'https://graph.facebook.com/v20.0';\n\nfunction templatePayload(\n toDigits: string,\n message: WhatsAppMessage,\n declaration: WhatsAppDriverDeclaration,\n): object {\n return {\n messaging_product: 'whatsapp',\n to: toDigits,\n type: 'template',\n template: {\n name: declaration.templateName,\n language: { code: declaration.templateLanguage },\n components: [\n {\n type: 'body',\n parameters: message.templateParameters.map((text) => ({ type: 'text', text })),\n },\n ],\n },\n };\n}\n\nfunction textPayload(toDigits: string, message: WhatsAppMessage): object {\n return {\n messaging_product: 'whatsapp',\n to: toDigits,\n type: 'text',\n text: { body: message.text },\n };\n}\n\nconst metaDriver = (declaration: WhatsAppDriverDeclaration): WhatsAppDriver => ({\n async send(toE164, message) {\n if (!declaration.accessToken || !declaration.phoneNumberId) {\n throw new Error('The meta whatsapp driver needs `accessToken` and `phoneNumberId`.');\n }\n // The Cloud API addresses recipients by bare digits (no `+`).\n const toDigits = toE164.replace('+', '');\n const payload = declaration.templateName\n ? templatePayload(toDigits, message, declaration)\n : textPayload(toDigits, message);\n const base = declaration.graphApiBase ?? DEFAULT_GRAPH_API_BASE;\n await postOrThrow(\n 'WhatsApp Cloud API',\n declaration.fetchImpl,\n `${base}/${encodeURIComponent(declaration.phoneNumberId)}/messages`,\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${declaration.accessToken}`,\n },\n body: JSON.stringify(payload),\n },\n );\n },\n});\n\nconst logWhatsAppDriver = (declaration: WhatsAppDriverDeclaration): WhatsAppDriver => ({\n // Deliberately logs NO destination — a phone number is PII and must never\n // reach logs; the message text alone is enough for local debugging.\n send(_toE164, message) {\n declaration.logger?.info(\n `[notifications:whatsapp] log driver suppressed a real send (text=\"${message.text}\")`,\n );\n return Promise.resolve();\n },\n});\n\nexport const WHATSAPP_DRIVERS: Record<\n string,\n (declaration: WhatsAppDriverDeclaration) => WhatsAppDriver\n> = {\n meta: metaDriver,\n log: logWhatsAppDriver,\n};\n\n/** Agnostic content → WhatsApp text + template parameters. */\nexport function formatWhatsApp(\n content: NotificationContent,\n declaration: WhatsAppDriverDeclaration,\n): WhatsAppMessage {\n const lines = [`*${content.title}*`, '', content.body];\n const href = absoluteLink(content.link, declaration.appUrl);\n if (href) lines.push('', href);\n return { text: lines.join('\\n'), templateParameters: [content.title, content.body] };\n}\n\nexport function whatsAppTransport(\n declaration: WhatsAppDriverDeclaration,\n extraDrivers: Record<string, (d: WhatsAppDriverDeclaration) => WhatsAppDriver> = {},\n logger?: NotificationLogger,\n): NotificationTransport<WhatsAppMessage> {\n const driver = resolveDriver('WHATSAPP', declaration, {\n ...WHATSAPP_DRIVERS,\n ...extraDrivers,\n });\n if (!declaration.templateName) {\n // Not a throw: free-form IS correct for a host that only replies inside the\n // 24h window. It is a warning because the other reading — business-initiated\n // alerts with no template — is a channel that never delivers anything.\n logger?.error(\n '[notifications] WHATSAPP is declared with no `templateName`: only free-form ' +\n 'replies inside the 24h customer-service window will be accepted, and every ' +\n 'business-initiated send will be rejected by the Graph API.',\n );\n }\n return phoneChannel<WhatsAppMessage>('WHATSAPP', {\n defaultCountryCode: declaration.defaultCountryCode,\n format: (content) => formatWhatsApp(content, declaration),\n send: (toE164, message) => driver.send(toE164, message),\n });\n}\n","import type {\n NotificationChannel,\n NotificationLogger,\n NotificationTransport,\n} from '../../types';\n\nimport type { EmailDriver, EmailDriverDeclaration } from './email';\nimport { emailTransport } from './email';\nimport type { SmsDriver, SmsDriverDeclaration } from './sms';\nimport { smsTransport } from './sms';\nimport type { WebPushDriverDeclaration, WebPushSender, WebPushSubscriptionSource } from './web-push';\nimport { webPushTransport } from './web-push';\nimport type { WhatsAppDriver, WhatsAppDriverDeclaration } from './whatsapp';\nimport { whatsAppTransport } from './whatsapp';\n\n/**\n * The transport registry: the router dispatches through this, so adding a\n * channel = registering one adapter and the router, generators and existing\n * transports are untouched (open/closed).\n *\n * A mount declares its channels and gets a registry; nothing is process-wide.\n * The origin registered its four transports as an IMPORT SIDE EFFECT of the\n * package's root entry, which made \"which channels are on\" a property of the\n * module graph rather than of any configuration — importing the inbox helpers\n * in a unit test silently armed four transports.\n */\n\n/** One channel's declaration. The union is closed; the drivers are not. */\nexport type TransportDeclaration =\n | EmailDriverDeclaration\n | SmsDriverDeclaration\n | WhatsAppDriverDeclaration\n | WebPushDriverDeclaration;\n\n/** A host's own vendors, added per channel without touching the package. */\nexport interface ExtraDrivers {\n email?: Record<string, (declaration: EmailDriverDeclaration) => EmailDriver>;\n sms?: Record<string, (declaration: SmsDriverDeclaration) => SmsDriver>;\n whatsapp?: Record<string, (declaration: WhatsAppDriverDeclaration) => WhatsAppDriver>;\n webPush?: Record<string, (declaration: WebPushDriverDeclaration) => WebPushSender>;\n}\n\nexport interface TransportRegistry {\n /** The adapter for `channel`, or null when the host declared none. */\n get(channel: NotificationChannel): NotificationTransport<never> | null;\n /** Every declared adapter, in declaration order. */\n list(): NotificationTransport<never>[];\n /** Register (or replace, last-wins) an adapter built by the host itself. */\n register<TMessage>(transport: NotificationTransport<TMessage>): void;\n /** The VAPID public key, when the WEB_PUSH channel declared one. */\n webPushPublicKey(): string | null;\n}\n\nfunction build(\n declaration: TransportDeclaration,\n subscriptions: WebPushSubscriptionSource,\n extra: ExtraDrivers,\n logger?: NotificationLogger,\n): NotificationTransport<never> {\n switch (declaration.channel) {\n case 'EMAIL':\n return emailTransport(declaration, extra.email ?? {}) as NotificationTransport<never>;\n case 'SMS':\n return smsTransport(declaration, extra.sms ?? {}) as NotificationTransport<never>;\n case 'WHATSAPP':\n return whatsAppTransport(\n declaration,\n extra.whatsapp ?? {},\n logger,\n ) as NotificationTransport<never>;\n case 'WEB_PUSH':\n return webPushTransport(\n declaration,\n subscriptions,\n extra.webPush ?? {},\n ) as NotificationTransport<never>;\n }\n}\n\nexport function createTransportRegistry(\n declarations: readonly TransportDeclaration[],\n subscriptions: WebPushSubscriptionSource,\n extra: ExtraDrivers = {},\n /** The mount's logger, for a declaration that is legal but probably wrong. */\n logger?: NotificationLogger,\n): TransportRegistry {\n const transports = new Map<NotificationChannel, NotificationTransport<never>>();\n let publicKey: string | null = null;\n for (const declaration of declarations) {\n if (transports.has(declaration.channel)) {\n throw new Error(\n `@12-apps/notifications: the ${declaration.channel} channel is declared twice.`,\n );\n }\n if (declaration.channel === 'WEB_PUSH') publicKey = declaration.publicKey ?? null;\n transports.set(declaration.channel, build(declaration, subscriptions, extra, logger));\n }\n return {\n get: (channel) => transports.get(channel) ?? null,\n list: () => [...transports.values()],\n register(transport) {\n transports.set(transport.channel, transport as NotificationTransport<never>);\n },\n webPushPublicKey: () => publicKey,\n };\n}\n","import type { NotificationEvent, NotificationLogger } from '../types';\n\nimport type { NotificationRouter } from './router';\n\n/**\n * Permission-addressed notifications: \"tell whoever can act on this\", resolved\n * against the host's REAL authorization engine.\n *\n * Naming an audience by ROLE reads a coarse mirror column, so a tenant who\n * moved a capability onto a custom role — or granted it additively — gets a\n * notification list that disagrees with what the app actually authorizes. The\n * two answers drift silently, and the direction they drift in is \"the person\n * who can fix it never hears about it\".\n *\n * So this addresses by CAPABILITY: name the permissions the recipient must\n * hold, and the audience is derived from the same evaluation the guards use.\n *\n * ## What the package owns, and what the host answers\n *\n * The FOLD is the package's: the AND, the deduplication, the refusal of an\n * empty permission list, the per-recipient isolation, and the log line that\n * distinguishes \"nobody holds it\" from \"everybody's dispatch failed\". Those are\n * the parts that are the same in every host and that are easy to get subtly\n * wrong.\n *\n * The two QUERIES are the host's, through {@link NotificationAudienceDirectory}\n * — because an authorization engine is host machinery. In the extraction origin this\n * module could not live in a package at all: it needed `notify()` AND the RBAC\n * engine, and neither package could see the other. Inverting the dependency\n * (the host answers, the package asks) is what makes it portable.\n */\n\n/**\n * The host's authorization engine, as this fan-out needs it.\n *\n * `listCandidates` must be BOUNDED to people who actually hold a role at the\n * tenant. that host's implementation requires a role grant, which is what\n * keeps a store's storefront BUYERS — who all carry a default membership — out\n * of a loop that resolves permissions one user at a time.\n *\n * `getPermissions` must be scoped to `tenantId`. Unioning a user's grants\n * across tenants — the obvious way to \"simplify\" it — notifies someone about a\n * store whose money they have no authority over, and no `where` clause upstream\n * can save it because that user is already a candidate.\n */\nexport interface NotificationAudienceDirectory {\n listCandidates(tenantId: string): Promise<readonly string[]>;\n getPermissions(\n userId: string,\n tenantId: string,\n ): Promise<ReadonlySet<string> | readonly string[]>;\n}\n\n/**\n * One candidate that did not receive it, and why.\n *\n * `audience-error` is deliberately its own reason rather than folded into\n * `missing-permission`: \"this user does not hold the pair\" is a configuration\n * fact, while \"we could not find out whether they hold it\" is an outage, and\n * they need opposite responses. Collapsing them would report a database timeout\n * as a tenant that simply has nobody to tell.\n */\nexport interface PermissionNotificationSkip {\n userId: string;\n reason: 'missing-permission' | 'dispatch-failed' | 'audience-error';\n}\n\n/**\n * What one fan-out actually did. Returned rather than logged-and-forgotten so a\n * caller (and a test) can assert on the OUTCOME — who was reached and who was\n * not — without reaching into transport mocks to infer it.\n */\nexport interface PermissionNotificationResult {\n /** User ids whose notification committed, in candidate order. */\n notified: string[];\n /** Candidates that did not receive it, with the reason. */\n skipped: PermissionNotificationSkip[];\n}\n\n/** What {@link reportOutcome} needs to describe one fan-out. */\ninterface OutcomeReport {\n type: string;\n clientId: string;\n permissions: readonly string[];\n candidateCount: number;\n result: PermissionNotificationResult;\n}\n\n/**\n * Log what the fan-out amounted to, keyed on WHY nobody was reached rather\n * than on the fact that nobody was.\n *\n * The distinction is the whole point: \"this tenant has nobody holding the pair\"\n * is a configuration fact and belongs at info, while \"three people hold it and\n * every dispatch failed\" is an outage in which nobody was told about missing\n * money. Both leave `notified` empty, so keying on that alone would file the\n * second under the first and make a dead transport look like an unconfigured\n * store.\n */\nfunction reportOutcome(logger: NotificationLogger, report: OutcomeReport): void {\n const { type, clientId, permissions, candidateCount, result } = report;\n // Both non-configuration reasons count as \"not reached\": a candidate whose\n // authorization query threw is as un-notified as one whose dispatch threw.\n const failed = result.skipped.filter((skip) => skip.reason !== 'missing-permission').length;\n if (failed > 0) {\n logger.error(\n `[notifications] ${type}: ${failed} of ${failed + result.notified.length} matching ` +\n `recipient(s) at client ${clientId} could not be reached; ` +\n `${result.notified.length} delivered`,\n );\n return;\n }\n if (result.notified.length > 0) return;\n // Quiet, and deliberately at info: \"nobody at this tenant holds\n // `orders:refund` + `reports:financial:read`\" is worth being able to look up\n // when someone asks why they heard nothing, but it is not a fault.\n logger.info(\n `[notifications] ${type}: no recipient at client ${clientId} holds ` +\n `[${permissions.join(', ')}] (${candidateCount} candidate(s) evaluated)`,\n );\n}\n\nexport type NotifyByPermission = <TPayload>(\n clientId: string,\n permissions: readonly string[],\n event: Omit<NotificationEvent<TPayload>, 'recipient'>,\n) => Promise<PermissionNotificationResult>;\n\n/**\n * Send one notification to every user of `clientId` holding ALL of\n * `permissions` (AND, not OR).\n *\n * AND is the semantics that makes an addressed notification openable: pair the\n * permission that HANDLES the thing with the permission that gates the SURFACE\n * it links to, and every addressee is, by construction, someone the surface's\n * own guard will serve. OR would happily notify someone into a 403.\n *\n * Contract:\n * - `permissions` must be non-empty. An empty list is a PROGRAMMING ERROR and\n * throws: \"holds every permission in []\" is vacuously true for everyone, so\n * the quiet reading of an empty list is \"fan out to the entire tenant\" —\n * the one outcome a caller can never have meant. It is the only throw here.\n * - TENANT-SCOPED, unconditionally. Permissions are evaluated at `clientId`\n * and the inbox row is written with that same tenant.\n * - Recipients are DEDUPLICATED: candidates are a set, and holding the\n * permissions through two roles is one notification.\n * - Zero matching users is a NORMAL outcome — logged, never thrown.\n * - Recipients are ISOLATED, in BOTH host queries: the authorization lookup\n * and the dispatch each get their own try/catch, so neither a candidate the\n * engine cannot answer for nor a recipient `notify` throws on can cost the\n * others their notification — or cost the caller the outcome log.\n *\n * Cost: one `getPermissions` per candidate, run sequentially. That is only\n * affordable because the candidate set is bounded (see the directory docs).\n * Callers run this fire-and-forget, off whatever path produced the event.\n */\n/** What the two isolated per-candidate steps need. */\ninterface FanOutDeps {\n router: NotificationRouter;\n directory: NotificationAudienceDirectory;\n logger: NotificationLogger;\n}\n\n/**\n * One recipient's dispatch, isolated. Resolves `true` when the notification\n * committed and `false` when it did not — the failure is contained here so the\n * loop can carry on, which is the whole point of per-recipient isolation.\n *\n * The log names the USER ID and never an address: an e-mail in a log is PII.\n */\nasync function dispatchTo<TPayload>(\n deps: FanOutDeps,\n clientId: string,\n userId: string,\n event: Omit<NotificationEvent<TPayload>, 'recipient'>,\n): Promise<boolean> {\n try {\n await deps.router.notify<TPayload>({ ...event, recipient: { userId, clientId } });\n return true;\n } catch (error) {\n deps.logger.error(\n `[notifications] ${event.type} dispatch failed for user ${userId} at client ${clientId}:`,\n error,\n );\n return false;\n }\n}\n\n/**\n * One candidate's permissions, isolated. `null` means the host's engine could\n * not answer.\n *\n * This await used to sit bare in the loop while only `notify` was guarded, which\n * made the documented per-recipient isolation half true: an ordinary\n * connection-pool timeout on candidate #3 of 30 propagated out of\n * `notifyByPermission`, so #4..#30 were never evaluated, `reportOutcome` never\n * ran, and the only trace was a rejection in whatever `.catch` the\n * fire-and-forget caller happened to attach. For a short-payment alert that is\n * nobody being told that money is missing, with nothing in the log saying so.\n */\nasync function heldBy(\n deps: FanOutDeps,\n clientId: string,\n userId: string,\n): Promise<ReadonlySet<string> | null> {\n try {\n const granted = await deps.directory.getPermissions(userId, clientId);\n return granted instanceof Set ? granted : new Set(granted);\n } catch (error) {\n deps.logger.error(\n `[notifications] audience lookup failed for user ${userId} at client ${clientId}:`,\n error,\n );\n return null;\n }\n}\n\nexport function createNotifyByPermission(deps: FanOutDeps): NotifyByPermission {\n return async function notifyByPermission(clientId, permissions, event) {\n if (permissions.length === 0) {\n throw new Error(\n 'notifyByPermission(): `permissions` must be non-empty — ' +\n 'an empty list matches every user of the tenant.',\n );\n }\n const candidates = [...new Set(await deps.directory.listCandidates(clientId))];\n const result: PermissionNotificationResult = { notified: [], skipped: [] };\n\n for (const userId of candidates) {\n const held = await heldBy(deps, clientId, userId);\n if (!held) {\n result.skipped.push({ userId, reason: 'audience-error' });\n continue;\n }\n // THE AND. `held` folds every role the user has at this tenant, so this\n // one line is the whole authorization question — and a single-element\n // list needs no special case.\n if (!permissions.every((permission) => held.has(permission))) {\n result.skipped.push({ userId, reason: 'missing-permission' });\n continue;\n }\n if (await dispatchTo(deps, clientId, userId, event)) result.notified.push(userId);\n else result.skipped.push({ userId, reason: 'dispatch-failed' });\n }\n\n reportOutcome(deps.logger, {\n type: event.type,\n clientId,\n permissions,\n candidateCount: candidates.length,\n result,\n });\n return result;\n };\n}\n","import type {\n DeliveryStatus,\n NotificationChannel,\n NotificationContent,\n NotificationLogger,\n TransportRecipient,\n} from '../types';\n\nimport type {\n NotificationContactDirectory,\n NotificationDeliveryRow,\n NotificationsDb,\n NotificationsDbProvider,\n} from './db';\nimport type { PushSubscriptionStore } from './push-subscriptions';\nimport type { TransportRegistry } from './transports/registry';\n\n/**\n * Handing a delivery to its transport, and the retry sweep that re-hands the\n * ones that did not make it (12-15).\n *\n * ## Every send is CLAIMED first\n *\n * A dispatcher never sends a row it merely READ. It moves the row `QUEUED →\n * SENDING` with one conditional `updateMany` whose `where` carries the\n * precondition, and sends only when that statement reports `count === 1`:\n *\n * updateMany({ where: { id, status: 'QUEUED' }, data: { status: 'SENDING' } })\n *\n * The database decides the winner, in one statement, so two dispatchers racing\n * the same delivery produce exactly one provider call. The version this replaced\n * read the QUEUED rows, called `transport.send`, and only then wrote `SENT` —\n * with nothing marking the row taken in between, which is a read-validate-write\n * with a network round trip in the window. It needed no crash to double-send: a\n * sweep whose backlog outlived its own cron interval overlapped itself, and\n * every row the first run had not yet reached was sent twice. On SMS and\n * WhatsApp that is a second billed message to a real phone.\n *\n * A single-threaded fake cannot tell the two implementations apart, which is why\n * the concurrency contracts are pinned against real SQL in\n * `harness/backend/tests/notifications-pipeline.test.ts` as well as against the\n * in-memory seam.\n *\n * ## Nothing is retried forever\n *\n * Each claim increments `attempts` — at CLAIM time, so a dispatcher that dies\n * mid-send still spends one — and the `maxAttempts`-th failure writes `DEAD`\n * instead of `FAILED`. A `DEAD` row is terminal: no sweep selects it again.\n * Without a ceiling a permanently invalid destination is a billed provider call\n * on every sweep for the life of the row, and the sweep's working set only ever\n * grows.\n *\n * ## The sweep is bounded and cannot un-send\n *\n * It selects on `updatedAt` (never `createdAt`), takes at most `take` rows, and\n * re-queues each one with the same conditional-update shape — status pinned to\n * what was read, plus the staleness predicate. A row another dispatcher has\n * already moved fails that predicate, so a committed `SENT` can never be dragged\n * back to `QUEUED`.\n */\n\n/** Claims a delivery gets before it is DEAD. Overridable per mount. */\nexport const DEFAULT_MAX_DELIVERY_ATTEMPTS = 5;\n\n/** Rows one sweep may take. Bounds a run to well inside a cron interval. */\nexport const DEFAULT_SWEEP_TAKE = 200;\n\n/** Default staleness cutoff: a row that has not moved in five minutes. */\nexport const DEFAULT_SWEEP_CUTOFF_MS = 5 * 60_000;\n\n/**\n * The statuses a sweep may return to QUEUED, once stale.\n *\n * `SENDING` is in the list because that is what a dispatcher that died mid-send\n * leaves behind, and it is safe precisely because of the cutoff: a SENDING row\n * younger than the cutoff belongs to a dispatcher that is still working.\n * `SENT` and `DEAD` are absent, and that is the whole point of them.\n */\nconst RETRYABLE: DeliveryStatus[] = ['FAILED', 'QUEUED', 'SENDING'];\n\n/** What dispatch needs from the mount. */\nexport interface NotificationDispatchDeps {\n db: NotificationsDbProvider;\n transports: TransportRegistry;\n pushSubscriptions: PushSubscriptionStore;\n contacts: NotificationContactDirectory;\n logger: NotificationLogger;\n maxAttempts: number;\n}\n\n/** Load the recipient's destinations once, for every transport's gate. */\nexport async function loadRecipient(\n deps: NotificationDispatchDeps,\n userId: string,\n): Promise<TransportRecipient | null> {\n const contact = await deps.contacts.getContact(userId);\n if (!contact) return null;\n return {\n userId,\n email: contact.email,\n phone: contact.phone,\n // Carried through UNRESOLVED and only where the host supplied one: the\n // absent case has to stay distinguishable from a stated language, because\n // that is what lets a generator apply its own default in one place.\n ...(contact.locale === undefined ? {} : { locale: contact.locale }),\n pushSubscriptionCount: await deps.pushSubscriptions.count(userId),\n };\n}\n\n/** The stored inbox row, back as the agnostic content a formatter takes. */\nfunction contentOf(notification: {\n title: string;\n body: string;\n link: string | null;\n data: unknown;\n}): NotificationContent {\n return {\n title: notification.title,\n body: notification.body,\n ...(notification.link !== null ? { link: notification.link } : {}),\n data: (notification.data ?? {}) as Record<string, unknown>,\n };\n}\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/** Record the outcome of a claimed send — terminal once the ceiling is hit. */\nasync function settle(\n deps: NotificationDispatchDeps,\n client: NotificationsDb,\n delivery: NotificationDeliveryRow,\n error: unknown,\n): Promise<void> {\n // `attempts` was read BEFORE this claim incremented it, so `+ 1` is the\n // attempt that just failed.\n const spent = delivery.attempts + 1;\n const terminal = spent >= deps.maxAttempts;\n await client.notificationDelivery.update({\n where: { id: delivery.id },\n data: {\n status: terminal ? 'DEAD' : 'FAILED',\n error: terminal ? `${messageOf(error)} (gave up after ${spent} attempts)` : messageOf(error),\n },\n });\n}\n\n/**\n * Claim one delivery and, if we won it, send it.\n *\n * Resolves whether a provider call was made, which is what the sweep counts —\n * \"dispatched\" must mean sends attempted, not rows looked at.\n */\nasync function sendClaimed(\n deps: NotificationDispatchDeps,\n client: NotificationsDb,\n delivery: NotificationDeliveryRow,\n content: NotificationContent,\n recipient: TransportRecipient,\n): Promise<boolean> {\n const claimed = await client.notificationDelivery.updateMany({\n where: { id: delivery.id, status: 'QUEUED' },\n data: { status: 'SENDING', attempts: { increment: 1 } },\n });\n // Someone else moved it between our read and here. They own the send now.\n if (claimed.count !== 1) return false;\n\n const transport = deps.transports.get(delivery.channel as NotificationChannel);\n try {\n if (!transport) throw new Error(`No transport declared for ${delivery.channel}.`);\n await transport.send(transport.format(content) as never, recipient);\n await client.notificationDelivery.update({\n where: { id: delivery.id },\n data: { status: 'SENT', sentAt: new Date(), error: null },\n });\n } catch (error) {\n await settle(deps, client, delivery, error);\n }\n return true;\n}\n\n/**\n * The recipient no longer exists, so no channel will ever reach them.\n *\n * The rows are marked DEAD rather than left QUEUED: `getContact` returning null\n * is the host saying \"no such person\" (the same answer `notify` throws on), and\n * a QUEUED row for a deleted account is a row every sweep, forever, picks up and\n * cannot deliver.\n */\nasync function abandonUnreachable(\n deps: NotificationDispatchDeps,\n client: NotificationsDb,\n queued: readonly NotificationDeliveryRow[],\n userId: string,\n): Promise<void> {\n deps.logger.error(\n `[notifications] no contact for user ${userId}: ${queued.length} delivery row(s) marked DEAD`,\n );\n for (const delivery of queued) {\n await client.notificationDelivery.update({\n where: { id: delivery.id },\n data: { status: 'DEAD', error: 'The contact directory no longer knows this recipient.' },\n });\n }\n}\n\n/**\n * Send every still-QUEUED delivery of one notification, claiming each one first.\n *\n * Safe to call repeatedly and safe to call concurrently: SENT, SENDING and DEAD\n * rows are not selected, and of two callers that both read the same QUEUED row\n * only one wins the claim.\n */\nexport async function dispatchOne(\n deps: NotificationDispatchDeps,\n notificationId: string,\n): Promise<number> {\n const client = await deps.db();\n const notification = await client.notification.findUnique({ where: { id: notificationId } });\n if (!notification) return 0;\n const queued = await client.notificationDelivery.findMany({\n where: { notificationId, status: 'QUEUED' },\n });\n if (queued.length === 0) return 0;\n\n const recipient = await loadRecipient(deps, notification.userId);\n if (!recipient) {\n await abandonUnreachable(deps, client, queued, notification.userId);\n return 0;\n }\n\n const content = contentOf(notification);\n // Sequential on purpose: one recipient's channels (2–4 sends) gain little\n // from parallelism, and providers rate-limit per sender anyway.\n let sent = 0;\n for (const delivery of queued) {\n if (await sendClaimed(deps, client, delivery, content, recipient)) sent += 1;\n }\n return sent;\n}\n\n/**\n * Return one stale row to QUEUED, or report that somebody else got there first.\n *\n * The `where` is the guard, and every clause of it is load-bearing: `status`\n * pinned to the value we READ means a row that has since been SENT is not\n * dragged back (the unguarded version matched on `id` alone and reverted\n * committed sends, leaving a row claiming QUEUED with a `sent_at`), and\n * `updatedAt < cutoff` means a row a concurrent sweep already re-queued — whose\n * `updated_at` is now — is not re-queued a second time.\n */\nasync function requeue(\n client: NotificationsDb,\n row: NotificationDeliveryRow,\n cutoff: Date,\n): Promise<boolean> {\n const moved = await client.notificationDelivery.updateMany({\n where: { id: row.id, status: row.status as DeliveryStatus, updatedAt: { lt: cutoff } },\n data: { status: 'QUEUED' },\n });\n return moved.count === 1;\n}\n\n/**\n * Retry sweep for a cron/admin trigger: re-dispatch deliveries that have not\n * moved in `olderThanMs`.\n *\n * BOUNDED by `take`, deliberately. Unbounded, a 2 000-row outage backlog is a\n * single run that takes minutes of sequential provider round trips — outliving\n * its own cron interval, so the next tick starts while it is still working. The\n * claim makes that overlap harmless; the bound makes it rare.\n */\nexport async function drainPending(\n deps: NotificationDispatchDeps,\n olderThanMs: number,\n take: number,\n): Promise<{ dispatched: number }> {\n const client = await deps.db();\n const cutoff = new Date(Date.now() - olderThanMs);\n const stale = await client.notificationDelivery.findMany({\n where: { status: { in: RETRYABLE }, updatedAt: { lt: cutoff } },\n orderBy: { updatedAt: 'asc' },\n take,\n });\n\n const notificationIds = new Set<string>();\n for (const row of stale) {\n if (await requeue(client, row, cutoff)) notificationIds.add(row.notificationId);\n }\n\n let dispatched = 0;\n for (const id of notificationIds) {\n // Isolated per notification: an unreachable host seam on one of them must\n // not cost every later row in the batch its retry.\n try {\n dispatched += await dispatchOne(deps, id);\n } catch (error) {\n deps.logger.error(`[notifications] sweep failed to dispatch ${id}:`, error);\n }\n }\n return { dispatched };\n}\n","import { inboxWire, type ListNotificationsResult } from '../wire';\n\nimport type {\n NotificationDelegate,\n NotificationPageAfter,\n NotificationsDbProvider,\n NotificationWhere,\n} from './db';\n\n/**\n * Notification-centre inbox reads/writes. Every function is scoped to the\n * OWNER's `userId` — a caller can only ever see or touch their own rows (the\n * route layer supplies the authenticated user's id, never a client value).\n * Soft-deleted rows (`deletedAt` set) are excluded from every read and can\n * never be resurrected by mark-read.\n */\n\nexport interface ListNotificationsInput {\n /** `unread` narrows to unread rows; default lists all non-deleted. */\n filter?: 'all' | 'unread';\n /**\n * Cursor = the `id` of the last item of the previous page. Resolved to a\n * KEYSET position, so a row the user soft-deleted between the two requests —\n * routinely the bottom one, since that is the row with the delete button —\n * still anchors the next page instead of costing it a row. Owner-checked: an\n * id that is not the caller's names no position and answers an empty page.\n */\n cursor?: string;\n /** Page size (server-clamped 1..100, default 20). */\n limit?: number;\n}\n\nconst DEFAULT_PAGE = 20;\nconst MAX_PAGE = 100;\n\nexport interface NotificationInboxStore {\n list(userId: string, input?: ListNotificationsInput): Promise<ListNotificationsResult>;\n unreadCount(userId: string): Promise<number>;\n markRead(userId: string, ids: readonly string[]): Promise<number>;\n markAllRead(userId: string): Promise<number>;\n softDelete(userId: string, ids: readonly string[]): Promise<number>;\n}\n\n/**\n * Resolve a cursor into a keyset anchor, or refuse it.\n *\n * OWNERSHIP-CHECKED, which the positional cursor never was: `cursor` is a raw\n * client value, and while the `where` kept the ROWS the caller's own, the\n * anchor's position leaked the `created_at` of whatever row the id named.\n * `undefined` here means \"this cursor names no position in your list\" and the\n * caller answers an empty page — the anchor is not `deletedAt`-filtered, so the\n * only way to reach that is a foreign or invented id.\n */\nasync function resolveAnchor(\n notifications: NotificationDelegate,\n userId: string,\n cursor: string,\n): Promise<NotificationPageAfter | undefined> {\n const anchor = await notifications.findUnique({ where: { id: cursor } });\n if (!anchor || anchor.userId !== userId) return undefined;\n return { createdAt: anchor.createdAt, id: anchor.id };\n}\n\n/** The whole read filter for one page: owner, live, filter, page boundary. */\nfunction pageWhere(\n userId: string,\n filter: ListNotificationsInput['filter'],\n anchor: NotificationPageAfter | undefined,\n): NotificationWhere {\n return {\n userId,\n deletedAt: null,\n ...(filter === 'unread' ? { readAt: null } : {}),\n // `(createdAt, id) < (anchor.createdAt, anchor.id)`, as a portable `where`.\n ...(anchor\n ? {\n OR: [\n { createdAt: { lt: anchor.createdAt } },\n { createdAt: anchor.createdAt, id: { lt: anchor.id } },\n ] as NonNullable<NotificationWhere['OR']>,\n }\n : {}),\n };\n}\n\nexport function createInboxStore(db: NotificationsDbProvider): NotificationInboxStore {\n return {\n /** The owner's inbox, newest first, keyset-paginated, deleted excluded. */\n async list(userId, input = {}) {\n const client = await db();\n const limit = Math.min(Math.max(input.limit ?? DEFAULT_PAGE, 1), MAX_PAGE);\n const anchor = input.cursor\n ? await resolveAnchor(client.notification, userId, input.cursor)\n : undefined;\n if (input.cursor && !anchor) return { items: [], nextCursor: null };\n const rows = await client.notification.findMany({\n where: pageWhere(userId, input.filter, anchor),\n // `id` tie-breaks equal timestamps so pages never skip/repeat.\n orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],\n take: limit + 1,\n });\n const page = rows.slice(0, limit);\n return {\n items: page.map(inboxWire),\n nextCursor: rows.length > limit ? (page[page.length - 1]?.id ?? null) : null,\n };\n },\n\n /** Unread badge count (non-deleted, unread). */\n async unreadCount(userId) {\n const client = await db();\n return client.notification.count({ where: { userId, deletedAt: null, readAt: null } });\n },\n\n /**\n * Mark specific notifications read. Only the owner's own, still-unread,\n * non-deleted rows are touched — foreign or already-read ids are silently\n * ignored (idempotent). Returns how many rows flipped.\n */\n async markRead(userId, ids) {\n if (ids.length === 0) return 0;\n const client = await db();\n const result = await client.notification.updateMany({\n where: { id: { in: [...ids] }, userId, deletedAt: null, readAt: null },\n data: { readAt: new Date() },\n });\n return result.count;\n },\n\n /** Mark every unread notification of the owner read (\"mark all\"). */\n async markAllRead(userId) {\n const client = await db();\n const result = await client.notification.updateMany({\n where: { userId, deletedAt: null, readAt: null },\n data: { readAt: new Date() },\n });\n return result.count;\n },\n\n /**\n * Soft-delete notifications (single or bulk): stamps `deletedAt` so the\n * rows drop out of every list/count forever, while the delivery audit\n * trail under them survives. Owner-scoped and idempotent like mark-read.\n */\n async softDelete(userId, ids) {\n if (ids.length === 0) return 0;\n const client = await db();\n const result = await client.notification.updateMany({\n where: { id: { in: [...ids] }, userId, deletedAt: null },\n data: { deletedAt: new Date() },\n });\n return result.count;\n },\n };\n}\n","import {\n DEFAULT_CHANNEL_ROW,\n enabledChannelsOf,\n mergeChoices,\n mergeStoredRow,\n type ChannelMatrix,\n type ChannelRow,\n} from '../preferences-core';\nimport type {\n NotificationCategory,\n NotificationChannel,\n NotificationTaxonomy,\n} from '../types';\n\nimport type { NotificationsDbProvider } from './db';\n\n/**\n * Per-user channel preferences: which transport channels may carry each\n * notification category to a user. The inbox is NOT gated here — it is always\n * on.\n *\n * The POLICY (defaults, coercion, merge) lives in `../preferences-core.ts`;\n * this is the storage over it, and the split is what lets the react half render\n * the same defaults before the first read lands.\n */\n\nexport interface NotificationPreferenceStore {\n /** The user's full matrix, defaults merged in. */\n get(userId: string): Promise<ChannelMatrix>;\n /** Persist explicit choices for any subset of categories/toggles. */\n save(\n userId: string,\n input: Partial<Record<NotificationCategory, Partial<ChannelRow>>>,\n ): Promise<void>;\n /** The channels enabled for one (user, category) — the router's gate. */\n enabledChannels(\n userId: string,\n category: NotificationCategory,\n ): Promise<NotificationChannel[]>;\n}\n\nexport function createPreferenceStore(\n db: NotificationsDbProvider,\n taxonomy: NotificationTaxonomy,\n channelDefaults: Partial<ChannelRow> = {},\n): NotificationPreferenceStore {\n const defaultRow: ChannelRow = { ...DEFAULT_CHANNEL_ROW, ...channelDefaults };\n const known = new Set(taxonomy.categories);\n\n return {\n async get(userId) {\n const client = await db();\n const rows = await client.notificationPreference.findMany({ where: { userId } });\n const stored = new Map(rows.map((row) => [row.category, row.channels]));\n return Object.fromEntries(\n taxonomy.categories.map((category) => [\n category,\n // A category with no row, or a row missing a channel key, falls back\n // to the defaults — so a NEW channel ships without a data migration.\n mergeStoredRow(stored.get(category), defaultRow),\n ]),\n ) as ChannelMatrix;\n },\n\n /**\n * Only the categories present on `input` are written; within a category,\n * the toggles are merged over the user's CURRENT effective row (their\n * stored choices, or the defaults when none) — so a single-toggle save\n * (how the settings UI writes) never resets the category's other channels\n * back to their defaults.\n *\n * A category outside the taxonomy is IGNORED rather than stored: the DB\n * CHECK would reject it anyway, and a 500 from a stale client's extra key\n * would fail the whole save including the toggle the user did flip.\n */\n async save(userId, input) {\n const client = await db();\n for (const [category, choices] of Object.entries(input)) {\n if (!choices || !known.has(category)) continue;\n const existing = await client.notificationPreference.findUnique({\n where: { userId_category: { userId, category } },\n });\n const current = existing ? mergeStoredRow(existing.channels, defaultRow) : defaultRow;\n const channels = mergeChoices(current, choices);\n await client.notificationPreference.upsert({\n where: { userId_category: { userId, category } },\n create: { userId, category, channels },\n update: { channels },\n });\n }\n },\n\n async enabledChannels(userId, category) {\n const client = await db();\n const row = await client.notificationPreference.findUnique({\n where: { userId_category: { userId, category } },\n });\n return enabledChannelsOf(\n row ? mergeStoredRow(row.channels, defaultRow) : defaultRow,\n );\n },\n };\n}\n","import type { NotificationLogger } from '../types';\n\nimport type { NotificationsDbProvider } from './db';\nimport type { WebPushSubscriptionSource } from './transports/web-push';\n\n/**\n * Browser push subscription registry — the write side of the Web Push\n * destination. The client obtains a `PushSubscription` from\n * `PushManager.subscribe()` (using the VAPID public key) and posts it here;\n * unsubscribe removes it by endpoint. All owner-scoped.\n */\n\n/** What `PushSubscription.toJSON()` yields in the browser. */\nexport interface PushSubscriptionInput {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n /** Optional browser/device hint for a device list. */\n userAgent?: string;\n}\n\nexport interface PushSubscriptionStore extends WebPushSubscriptionSource {\n /**\n * Register (or refresh) one browser's subscription. Upserts on the globally\n * unique endpoint, so re-subscribing the same browser never duplicates — and\n * an endpoint recycled to a different signed-in user is re-owned by them.\n *\n * Re-owning is the right call and the alternative is worse: `PushManager`\n * returns the SAME endpoint for the same browser profile, so one row per\n * `(userId, endpoint)` would push user A's notifications to a browser now used\n * by B with B's own keys — which decrypt. Re-owning costs A their channel;\n * keeping both rows costs A their privacy. What re-owning must NOT do is\n * happen unrecorded, hence the warning.\n */\n save(userId: string, input: PushSubscriptionInput): Promise<void>;\n /** Remove one browser's subscription (owner-scoped; unknown = no-op). */\n remove(userId: string, endpoint: string): Promise<void>;\n /** How many devices the user has registered (settings UI hint). */\n count(userId: string): Promise<number>;\n /**\n * Whether THIS endpoint is currently registered to THIS user.\n *\n * The settings screen needs it because a browser's own subscription object is\n * not evidence that the server still has the row: a re-own or a 404/410 prune\n * removes the row while the browser keeps the subscription, and a screen that\n * reads only the browser then tells a user they are receiving alerts they will\n * never get again. `false` covers both \"no such row\" and \"somebody else's\n * row\", so an endpoint the caller does not own reveals nothing about who does.\n */\n isRegisteredTo(userId: string, endpoint: string): Promise<boolean>;\n}\n\nexport function createPushSubscriptionStore(\n db: NotificationsDbProvider,\n logger?: NotificationLogger,\n): PushSubscriptionStore {\n return {\n async save(userId, input) {\n const client = await db();\n const existing = await client.pushSubscription.findUnique({\n where: { endpoint: input.endpoint },\n });\n if (existing && existing.userId !== userId) {\n // No endpoint in the message: a push endpoint is a bearer capability for\n // that browser and must not reach logs. The two user ids are what makes\n // \"user X stopped getting web push on a shared machine\" answerable.\n logger?.error(\n `[notifications] push endpoint re-owned: user ${existing.userId} lost this ` +\n `browser's subscription to user ${userId}`,\n );\n }\n await client.pushSubscription.upsert({\n where: { endpoint: input.endpoint },\n create: {\n userId,\n endpoint: input.endpoint,\n p256dh: input.keys.p256dh,\n auth: input.keys.auth,\n userAgent: input.userAgent ?? null,\n },\n update: {\n userId,\n p256dh: input.keys.p256dh,\n auth: input.keys.auth,\n userAgent: input.userAgent ?? null,\n },\n });\n },\n\n async remove(userId, endpoint) {\n const client = await db();\n await client.pushSubscription.deleteMany({ where: { userId, endpoint } });\n },\n\n async count(userId) {\n const client = await db();\n return client.pushSubscription.count({ where: { userId } });\n },\n\n async isRegisteredTo(userId, endpoint) {\n const client = await db();\n const row = await client.pushSubscription.findUnique({ where: { endpoint } });\n return row?.userId === userId;\n },\n\n async list(userId) {\n const client = await db();\n const rows = await client.pushSubscription.findMany({ where: { userId } });\n return rows.map((row) => ({\n id: row.id,\n endpoint: row.endpoint,\n p256dh: row.p256dh,\n auth: row.auth,\n }));\n },\n\n async prune(id) {\n const client = await db();\n await client.pushSubscription.delete({ where: { id } });\n },\n };\n}\n","import {\n messagesOf,\n type NotificationsCopySource,\n type NotificationWireMessages,\n} from '../messages';\nimport { NOTIFICATION_CHANNELS, type NotificationChannel } from '../types';\n\nimport {\n guarded,\n ok,\n parseDeleteBody,\n parseListQuery,\n parseMarkReadBody,\n parsePreferencesBody,\n parsePushEndpointBody,\n parsePushEndpointQuery,\n parsePushSubscriptionBody,\n type NotificationsRoute,\n} from './context';\nimport type { NotificationContactDirectory } from './db';\nimport type { NotificationInboxStore } from './inbox';\nimport type { NotificationPreferenceStore } from './preferences';\nimport type { PushSubscriptionStore } from './push-subscriptions';\nimport type { TransportRegistry } from './transports/registry';\n\n/**\n * The endpoints, as framework-neutral descriptors (12-15).\n *\n * Nine routes, and the paths are the PACKAGE's: the shipped react client\n * builds these URLs, so a host that renamed one would be a host whose own bell\n * stopped working. The host names only where the whole block is mounted\n * (the origin mounts it at `/api/account`).\n *\n * Route ORDER is preserved by every adapter. Nothing here is shaped `/:id`, so\n * no sibling can capture a literal — but the order is still the contract,\n * because that is what a host mounting an `/:id` route of its own under the\n * same prefix has to reason about.\n */\n\ninterface NotificationRoutesDeps {\n inbox: NotificationInboxStore;\n preferences: NotificationPreferenceStore;\n pushSubscriptions: PushSubscriptionStore;\n transports: TransportRegistry;\n contacts: NotificationContactDirectory;\n categories: readonly string[];\n /**\n * The SOURCE, not a resolved pack — the route table is built once per\n * process and every handler below runs per request.\n */\n messages: NotificationsCopySource<NotificationWireMessages>;\n /** Told when a write actually changed something (for a realtime hint). */\n onInboxChanged?: (userId: string) => void;\n}\n\n/**\n * Whether each channel CAN reach this user right now — destination on file and\n * the channel declared — so the settings UI can disable dead toggles with a\n * hint (no phone → SMS/WhatsApp off).\n *\n * Web push is probed with a HYPOTHETICAL subscription: for the SETTINGS screen\n * the channel is \"available\" when the platform can send at all, because the\n * browser subscribe step happens right from that toggle. Requiring an existing\n * subscription here would deadlock the UX.\n */\nasync function channelAvailability(\n deps: NotificationRoutesDeps,\n userId: string,\n): Promise<Record<NotificationChannel, boolean>> {\n const contact = await deps.contacts.getContact(userId);\n const recipient = {\n userId,\n email: contact?.email ?? null,\n phone: contact?.phone ?? null,\n pushSubscriptionCount: 1,\n };\n return Object.fromEntries(\n NOTIFICATION_CHANNELS.map((channel) => [\n channel,\n deps.transports.get(channel)?.supports(recipient) ?? false,\n ]),\n ) as Record<NotificationChannel, boolean>;\n}\n\n/** The `{ preferences, availability, categories }` payload both prefs routes answer. */\nasync function preferencesPayload(\n deps: NotificationRoutesDeps,\n userId: string,\n): Promise<{\n preferences: Record<string, Record<string, boolean>>;\n availability: Record<NotificationChannel, boolean>;\n categories: string[];\n}> {\n const [preferences, availability] = await Promise.all([\n deps.preferences.get(userId),\n channelAvailability(deps, userId),\n ]);\n // `categories` travels with the matrix so the settings screen renders the\n // HOST's taxonomy without being told it twice (once in the api config, once\n // in the web config) — the two could then disagree.\n return { preferences, availability, categories: [...deps.categories] };\n}\n\nfunction inboxRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {\n return [\n {\n method: 'GET',\n path: '/notifications',\n handle: guarded(async ({ actor, query, locale }) =>\n ok(\n await deps.inbox.list(\n actor.userId,\n parseListQuery(query, messagesOf(deps, locale)),\n ),\n ),\n ),\n },\n {\n method: 'GET',\n path: '/notifications/unread-count',\n handle: guarded(async ({ actor }) =>\n // Polled by the SPAs, so it stays a single indexed COUNT.\n ok({ count: await deps.inbox.unreadCount(actor.userId) }),\n ),\n },\n {\n method: 'POST',\n path: '/notifications/mark-read',\n handle: guarded(async ({ actor, body, locale }) => {\n const target = parseMarkReadBody(body, messagesOf(deps, locale));\n const updated =\n 'all' in target\n ? await deps.inbox.markAllRead(actor.userId)\n : await deps.inbox.markRead(actor.userId, target.ids);\n // Only when something actually flipped. This endpoint is idempotent, so\n // a re-send of an already-read id reports `updated: 0` and has changed\n // nothing — hinting on that would wake every one of this user's devices\n // to re-read a badge that did not move.\n if (updated > 0) deps.onInboxChanged?.(actor.userId);\n return ok({ updated });\n }),\n },\n {\n method: 'POST',\n // POST, not DELETE, because the ids travel in a JSON body.\n path: '/notifications/delete',\n handle: guarded(async ({ actor, body, locale }) => {\n const deleted = await deps.inbox.softDelete(\n actor.userId,\n parseDeleteBody(body, messagesOf(deps, locale)),\n );\n // Same rule as mark-read. A delete can move the badge too — an UNREAD\n // row that is removed takes its place in the count with it.\n if (deleted > 0) deps.onInboxChanged?.(actor.userId);\n return ok({ deleted });\n }),\n },\n ];\n}\n\nfunction preferenceRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {\n return [\n {\n method: 'GET',\n path: '/notification-preferences',\n handle: guarded(async ({ actor }) => ok(await preferencesPayload(deps, actor.userId))),\n },\n {\n method: 'PUT',\n path: '/notification-preferences',\n handle: guarded(async ({ actor, body, locale }) => {\n // The dispatch pipeline reads these on every emit, so a save takes\n // effect immediately — no cache to invalidate.\n await deps.preferences.save(\n actor.userId,\n parsePreferencesBody(body, messagesOf(deps, locale)),\n );\n return ok(await preferencesPayload(deps, actor.userId));\n }),\n },\n ];\n}\n\nfunction pushRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {\n return [\n {\n method: 'GET',\n path: '/push-subscriptions',\n handle: guarded(async ({ actor, query, locale }) => {\n const endpoint = parsePushEndpointQuery(query, messagesOf(deps, locale));\n return ok({\n // null = web push is not configured on this deployment.\n vapidPublicKey: deps.transports.webPushPublicKey(),\n count: await deps.pushSubscriptions.count(actor.userId),\n // Only when asked. `registered` is what lets the settings screen stop\n // trusting the browser alone: a re-owned or pruned row answers false,\n // so the screen offers *Ativar* again instead of claiming all is well.\n ...(endpoint !== undefined\n ? { registered: await deps.pushSubscriptions.isRegisteredTo(actor.userId, endpoint) }\n : {}),\n });\n }),\n },\n {\n method: 'POST',\n path: '/push-subscriptions',\n handle: guarded(async ({ actor, body, headers, locale }) => {\n const input = parsePushSubscriptionBody(body, messagesOf(deps, locale));\n const userAgent = headers?.['user-agent'];\n await deps.pushSubscriptions.save(actor.userId, {\n ...input,\n ...(userAgent ? { userAgent } : {}),\n });\n return ok({ count: await deps.pushSubscriptions.count(actor.userId) });\n }),\n },\n {\n method: 'DELETE',\n // The endpoint is a long opaque URL, unusable as a path param.\n path: '/push-subscriptions',\n handle: guarded(async ({ actor, body, locale }) => {\n await deps.pushSubscriptions.remove(\n actor.userId,\n parsePushEndpointBody(body, messagesOf(deps, locale)),\n );\n return ok({ count: await deps.pushSubscriptions.count(actor.userId) });\n }),\n },\n ];\n}\n\nexport function notificationRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {\n return [...inboxRoutes(deps), ...preferenceRoutes(deps), ...pushRoutes(deps)];\n}\n","import { UnknownNotificationRecipientError } from '../errors';\nimport type { NotificationGeneratorRegistry } from '../generators';\nimport { DEFAULT_CHANNEL_ROW, enabledChannelsOf } from '../preferences-core';\nimport type { NotificationChannel, NotificationEvent, TransportRecipient } from '../types';\n\nimport {\n dispatchOne,\n drainPending,\n loadRecipient,\n DEFAULT_SWEEP_CUTOFF_MS,\n DEFAULT_SWEEP_TAKE,\n type NotificationDispatchDeps,\n} from './dispatch';\nimport type { NotificationPreferenceStore } from './preferences';\n\n/**\n * The channel router + the `notify` emit API — the single front door into the\n * pipeline. Any server-side caller (route handler, background worker, agent\n * tool) emits with one typed call and zero knowledge of channels, formatting,\n * or preferences:\n *\n * await notifications.notify({ type: 'order.paid', recipient: { userId }, payload });\n *\n * What one emit does:\n * 1. Resolves the registered generator for `type` → agnostic content.\n * 2. ALWAYS writes the inbox record (the always-on channel), atomically\n * with…\n * 3. …one QUEUED delivery per channel that is (a) enabled by the recipient's\n * preferences for the generator's category and (b) supported by its\n * transport for this recipient.\n * 4. Hands the deliveries to the transports ASYNCHRONOUSLY (fire-and-forget\n * by default) so emit sites never block on provider I/O.\n *\n * The TRANSACTION IS THIS PACKAGE'S OWN, and a host cannot enlist in it: step 2\n * opens `client.$transaction` itself, and a Prisma `TransactionClient` has no\n * `$transaction` to nest. So `notify` must be called AFTER the caller's own\n * transaction commits — called from inside one, it commits an inbox row and\n * dispatches an e-mail for a payment that then rolls back.\n *\n * Failure isolation: each delivery is sent in its own try/catch — one channel\n * failing marks only its row FAILED (error recorded) and never blocks the\n * inbox record or the other channels. Delivery is at-least-once: the unique\n * (notification, channel) row makes fan-out idempotent, and every send is\n * CLAIMED before it happens (`./dispatch.ts`), so the remaining re-send window\n * is the unavoidable one — a crash between the provider call and the SENT flip.\n * Transports are required to tolerate that.\n *\n * Queueing: in-process async dispatch by default, or a real queue when the\n * host passes `scheduleDispatch`. The QUEUED status + the drain sweep are what\n * make either safe — the delivery rows are the durable record, so a queue that\n * is unavailable (or absent) costs latency, never a notification.\n */\n\n/**\n * Which channels a TENANT may use, decided per emit — the host's plan gate.\n *\n * A `null`/absent clientId is a PLATFORM notification (password resets,\n * operator alerts) and is never policy-filtered. With no policy installed\n * every channel passes.\n */\nexport type NotificationChannelPolicy = (\n clientId: string,\n channels: readonly NotificationChannel[],\n) => Promise<NotificationChannel[]> | NotificationChannel[];\n\n/** How the host defers dispatch of one already-committed notification. */\nexport type NotificationDispatchScheduler = (notificationId: string) => Promise<void>;\n\n/** One committed inbox record, as the commit observer sees it. */\nexport interface CommittedNotification {\n notificationId: string;\n /** The owner — the only field a user-scoped fan-out needs. */\n userId: string;\n /** The tenant the row was stamped with, or null for a platform emit. */\n clientId: string | null;\n}\n\n/**\n * Told about each inbox record the moment it commits. Synchronous and\n * `void`-returning by contract: an observer may not make an emit site wait,\n * and may not fail one.\n *\n * It exists because the inbox record is written HERE, in the package, while the\n * thing that usually wants to know — a realtime bus — is a dependency this\n * package does not have and should not gain. Placing it at the funnel rather\n * than at the emit sites is the point: `notify` is the single front door, so\n * every sender is covered by construction, including ones written later.\n */\nexport type NotificationCommittedListener = (notification: CommittedNotification) => void;\n\n/** Options for `notify`. */\nexport interface NotifyOptions {\n /**\n * Await transport dispatch instead of fire-and-forget. For tests and\n * worker/cron contexts where the process may exit right after emitting.\n */\n sync?: boolean;\n}\n\n/** What `notify` resolves with (dispatch may still be in flight). */\nexport interface NotifyResult {\n notificationId: string;\n /** Channels a delivery row was enqueued for (preference ∩ transport gate). */\n channels: NotificationChannel[];\n}\n\ninterface NotificationRouterDeps extends NotificationDispatchDeps {\n generators: NotificationGeneratorRegistry;\n preferences: NotificationPreferenceStore;\n channelPolicy?: NotificationChannelPolicy;\n scheduleDispatch?: NotificationDispatchScheduler;\n onCommitted?: NotificationCommittedListener;\n}\n\nexport interface NotificationRouter {\n notify<TPayload>(\n event: NotificationEvent<TPayload>,\n options?: NotifyOptions,\n ): Promise<NotifyResult>;\n dispatchDeliveries(notificationId: string): Promise<void>;\n drainPending(olderThanMs?: number, take?: number): Promise<{ dispatched: number }>;\n}\n\n/**\n * The channels that survive a plan gate this package could not consult.\n *\n * A policy error degrades to the FREE defaults (`DEFAULT_CHANNEL_ROW`, i.e.\n * e-mail + web push) intersected with what the other gates allowed — not to\n * everything. Failing fully open was the original reading, and the rationale\n * given for it only ever argued for the free channels: the dunning e-mail this\n * system carries is how payment gets collected, so a transient entitlements\n * error must not silence it. That argument says nothing about SMS and WhatsApp,\n * which are billed per message and are exactly what the host's own gate was\n * about to refuse. So the free channels stay (an extra notification beats none)\n * and the paid ones do not (the host is not billed for a channel it did not\n * authorize).\n */\nfunction policyFallback(channels: NotificationChannel[]): NotificationChannel[] {\n const free = new Set(enabledChannelsOf(DEFAULT_CHANNEL_ROW));\n return channels.filter((channel) => free.has(channel));\n}\n\n/** Apply the host's policy, degrading to the free channels on an error. */\nasync function applyPolicy(\n deps: NotificationRouterDeps,\n clientId: string | null | undefined,\n channels: NotificationChannel[],\n): Promise<NotificationChannel[]> {\n if (!deps.channelPolicy || clientId === null || clientId === undefined) return channels;\n try {\n return await deps.channelPolicy(clientId, channels);\n } catch (error) {\n deps.logger.error(\n `[notifications] channelPolicy failed for client ${clientId}; ` +\n 'degrading to the free channels:',\n error,\n );\n return policyFallback(channels);\n }\n}\n\n/** Run the commit observer without ever letting it reach the caller. */\nfunction announce(deps: NotificationRouterDeps, notification: CommittedNotification): void {\n if (!deps.onCommitted) return;\n try {\n deps.onCommitted(notification);\n } catch (error) {\n // An observer is an accelerator, never a step. The row is committed; a\n // listener that throws must not turn a delivered notification into a 500.\n deps.logger.error(\n `[notifications] commit listener failed for ${notification.notificationId}:`,\n error,\n );\n }\n}\n\n/** The channels one emit will actually enqueue: preference ∩ transport ∩ plan. */\nasync function resolveChannels(\n deps: NotificationRouterDeps,\n event: NotificationEvent<unknown>,\n category: string,\n recipient: TransportRecipient,\n): Promise<NotificationChannel[]> {\n const enabled = await deps.preferences.enabledChannels(event.recipient.userId, category);\n const supported = enabled.filter((channel) => {\n const transport = deps.transports.get(channel);\n return transport !== null && transport.supports(recipient);\n });\n // The host's plan gate: a tenant-scoped emit keeps only the channels the\n // tenant's plan covers, so a revoked transport DEGRADES to the remaining ones\n // rather than dropping the notification silently.\n return applyPolicy(deps, event.recipient.clientId, supported);\n}\n\n/** Commit the inbox record and its delivery rows together, in one transaction. */\nasync function commit(\n deps: NotificationRouterDeps,\n event: NotificationEvent<unknown>,\n category: string,\n content: { title: string; body: string; link?: string; data?: Record<string, unknown> },\n channels: NotificationChannel[],\n): Promise<{ id: string; userId: string; clientId: string | null }> {\n const client = await deps.db();\n return client.$transaction(async (tx) => {\n const created = await tx.notification.create({\n data: {\n userId: event.recipient.userId,\n clientId: event.recipient.clientId ?? null,\n type: event.type,\n category,\n title: content.title,\n body: content.body,\n link: content.link ?? null,\n data: content.data ?? {},\n },\n });\n if (channels.length > 0) {\n await tx.notificationDelivery.createMany({\n data: channels.map((channel) => ({ notificationId: created.id, channel })),\n // Idempotence backstop: the unique (notification, channel) key.\n skipDuplicates: true,\n });\n }\n return created;\n });\n}\n\nexport function createNotificationRouter(deps: NotificationRouterDeps): NotificationRouter {\n return {\n dispatchDeliveries: async (notificationId) => {\n await dispatchOne(deps, notificationId);\n },\n drainPending: (olderThanMs = DEFAULT_SWEEP_CUTOFF_MS, take = DEFAULT_SWEEP_TAKE) =>\n drainPending(deps, olderThanMs, take),\n\n async notify(event, options = {}) {\n const generator = deps.generators.resolve(event.type);\n\n /*\n The recipient is loaded BEFORE the content is rendered, and the order is\n the whole of the fix.\n\n `notify` is already per-person — `event.recipient.userId` is one user,\n and a permission fan-out resolves its audience and calls this once each\n — so the reader was knowable here all along. Rendering first simply\n threw that away: the row was written in whatever language the generator\n had been bound to at boot, for everyone.\n\n Loading first also means a notification addressed to nobody now throws\n before any content is built, which is the cheaper order anyway.\n */\n const recipient = await loadRecipient(deps, event.recipient.userId);\n if (!recipient) throw new UnknownNotificationRecipientError(event.recipient.userId);\n\n // Forwarded exactly as the directory stated it, `undefined` included: the\n // generator owns the fallback, in one place a reader can find.\n const content = generator.generate(event.payload as never, { locale: recipient.locale });\n\n const channels = await resolveChannels(deps, event, generator.category, recipient);\n const notification = await commit(deps, event, generator.category, content, channels);\n\n // AFTER the transaction, never inside it: a subscriber woken by an event\n // published mid-transaction would re-read and not find the row it was told\n // about — the classic read-your-own-hint race.\n announce(deps, {\n notificationId: notification.id,\n userId: notification.userId,\n clientId: notification.clientId,\n });\n\n // `sync` always means \"send it here, now\" — a test or a worker about to\n // exit must not have its send handed to a queue it will never drain.\n if (options.sync) {\n await dispatchOne(deps, notification.id);\n return { notificationId: notification.id, channels };\n }\n\n void (\n deps.scheduleDispatch\n ? deps.scheduleDispatch(notification.id)\n : dispatchOne(deps, notification.id)\n ).catch((error: unknown) => {\n // Detached-path backstop only: per-delivery failures are already\n // recorded on their rows; this catches infrastructure errors.\n deps.logger.error(`[notifications] dispatch failed for ${notification.id}:`, error);\n });\n\n return { notificationId: notification.id, channels };\n },\n };\n}\n","import { createGeneratorRegistry, type NotificationGeneratorRegistry } from '../generators';\nimport type {\n NotificationsCopySource,\n NotificationWireMessages,\n} from '../messages';\nimport type { ChannelRow } from '../preferences-core';\nimport {\n taxonomyOf,\n type NotificationCategory,\n type NotificationGenerator,\n type NotificationLogger,\n} from '../types';\n\nimport {\n createNotifyByPermission,\n type NotificationAudienceDirectory,\n type NotifyByPermission,\n} from './by-permission';\nimport type { NotificationsRoute } from './context';\nimport type { NotificationContactDirectory, NotificationsDbProvider } from './db';\nimport { DEFAULT_MAX_DELIVERY_ATTEMPTS } from './dispatch';\nimport { createInboxStore, type NotificationInboxStore } from './inbox';\nimport { createPreferenceStore, type NotificationPreferenceStore } from './preferences';\nimport {\n createPushSubscriptionStore,\n type PushSubscriptionStore,\n} from './push-subscriptions';\nimport { notificationRoutes } from './routes';\nimport {\n createNotificationRouter,\n type NotificationChannelPolicy,\n type NotificationCommittedListener,\n type NotificationDispatchScheduler,\n type NotificationRouter,\n} from './router';\nimport {\n createTransportRegistry,\n type ExtraDrivers,\n type TransportDeclaration,\n type TransportRegistry,\n} from './transports/registry';\n\n/**\n * The one thing this package exposes to a BACKEND host (12-15).\n *\n * The pipeline used to be a private workspace package plus six hand-written\n * route files: each one resolving the session, calling a loose helper, and\n * shaping a response, with the transports reading their own credentials out of\n * `process.env` and registering themselves as an import side effect. Only \"who\n * is calling, where the rows live, how a channel reaches a person\" was ever the\n * host's business; the rest — the routing, the delivery rows, the retries, the\n * request contract, the envelope, the pt-BR copy — is this surface's.\n *\n * Routes are FRAMEWORK-NEUTRAL descriptors, not a Hono/Express router (the\n * report-builder doctrine). `@12-apps/notifications/hono` adapts them.\n *\n * What stays the HOST's, and is passed in rather than guessed at:\n *\n * - **Authentication** — the adapter's `resolveActor` hands over a user id.\n * Every endpoint is self-scoped, so that is the entire authorization seam.\n * - **Where the four owned tables live** — the structural `db` seam.\n * - **How to reach a person** — `contacts`, because a package cannot know the\n * shape of a host's identity table (nor whether its phones are verified).\n * - **Which vendors carry which channel** — `transports`, one declaration per\n * channel. An undeclared channel is off; a second vendor is a config entry.\n * - **Billing** — `channelPolicy`, the plan gate answered per emit.\n * - **Its authorization engine** — `audience`, for the permission fan-out.\n * - **Its domain events** — `generators`, registered from the outside.\n */\n\nexport interface NotificationsServerConfig {\n /** Prisma-shaped client for the four owned models, through the seam. */\n db: NotificationsDbProvider;\n /** How a transport reaches a person (the host's identity table). */\n contacts: NotificationContactDirectory;\n /** One declaration per channel the host wants on. Default: none, all off. */\n transports?: readonly TransportDeclaration[];\n /** The host's own vendor drivers, per channel. */\n drivers?: ExtraDrivers;\n /** The domain events this mount can emit. */\n generators?: readonly NotificationGenerator<never>[];\n /**\n * Preference categories — the granularity at which a user chooses channels.\n *\n * REQUIRED. This defaulted to one product's four (`orders`, `payments`,\n * `stock`, `system`), which is the host's vocabulary and not this library's:\n * a host that omitted it rendered four rows it never chose, with its own\n * categories absent, and nothing failed — `category` is a free string by\n * design, so there was no layer left to notice.\n */\n categories: readonly NotificationCategory[];\n /** Override which channels a never-touched category defaults to. */\n channelDefaults?: Partial<ChannelRow>;\n /** The tenant plan gate, answered per emit. */\n channelPolicy?: NotificationChannelPolicy;\n /** Hand dispatch to a real queue instead of the in-process detached send. */\n scheduleDispatch?: NotificationDispatchScheduler;\n /**\n * Claims one delivery gets before the sweep gives up on it and writes DEAD.\n * Default 5. There is no \"unlimited\": a permanently invalid destination would\n * be a billed provider call on every sweep for the life of the row.\n */\n maxDeliveryAttempts?: number;\n /** Told the moment an inbox record commits (a realtime bus, typically). */\n onCommitted?: NotificationCommittedListener;\n /** Told when a mark-read/delete actually changed something. */\n onInboxChanged?: (userId: string) => void;\n /** The host's authorization engine, for `notifyByPermission`. */\n audience?: NotificationAudienceDirectory;\n /**\n * Every user-facing sentence this surface can produce — REQUIRED host config.\n *\n * A pack, or a RESOLVER for a host whose callers do not share a language.\n * Passed to the routes UNRESOLVED: this factory runs once per process (and\n * at least one host memoises its call), so resolving here would answer every\n * later request in the language the process started with.\n */\n messages: NotificationsCopySource<NotificationWireMessages>;\n /** The host's logger. Defaults to the console. */\n logger?: NotificationLogger;\n}\n\nexport interface ApiNotifications {\n /** The whole generated surface, in mount order. */\n routes: NotificationsRoute[];\n /** The emit front door. */\n notify: NotificationRouter['notify'];\n /** Send every still-QUEUED delivery of one notification. */\n dispatchDeliveries: NotificationRouter['dispatchDeliveries'];\n /** The retry sweep, for a cron/admin trigger. */\n drainPending: NotificationRouter['drainPending'];\n /**\n * \"Tell whoever can act on this.\" Rejects when the host configured no\n * `audience` — loudly, because the alternative is a money alert nobody gets.\n */\n notifyByPermission: NotifyByPermission;\n /** The stores, for host surfaces that read the same tables. */\n inbox: NotificationInboxStore;\n preferences: NotificationPreferenceStore;\n pushSubscriptions: PushSubscriptionStore;\n /** Register a generator after the mount (a lazily-imported domain module). */\n registerGenerator: NotificationGeneratorRegistry['register'];\n /** The declared transports, for diagnostics and availability probes. */\n transports: TransportRegistry;\n /**\n * The copy source in force, so a host's own screens can reuse a sentence.\n *\n * The SOURCE rather than a resolved pack, for the same reason the routes get\n * one: a host screen serving two readers must be able to ask per reader.\n * Read it with `messagesOf({ messages }, locale)`.\n */\n messages: NotificationsCopySource<NotificationWireMessages>;\n}\n\n/** Drop the keys the host left unset, so an absent seam stays absent. */\nfunction present<T extends object>(entries: T): Partial<T> {\n return Object.fromEntries(\n Object.entries(entries).filter(([, value]) => value !== undefined),\n ) as Partial<T>;\n}\n\n/** Fallback logger — used until the host passes its own. */\nconst consoleLogger: NotificationLogger = {\n info: (message, ...meta) => console.info(message, ...meta),\n error: (message, ...meta) => console.error(message, ...meta),\n};\n\nexport function createApiNotifications(config: NotificationsServerConfig): ApiNotifications {\n /**\n * The SOURCE travels; nothing is resolved here.\n *\n * This factory runs once per process — and at least one host memoises its\n * call behind an `if (assembled) return assembled;` — so a `messagesOf(config)`\n * on this line would word every later request in the language the process\n * started with. The handlers resolve per request instead.\n */\n const messages = config.messages;\n const taxonomy = taxonomyOf(config);\n const logger = config.logger ?? consoleLogger;\n\n const generators = createGeneratorRegistry(config.generators ?? []);\n const inbox = createInboxStore(config.db);\n const preferences = createPreferenceStore(\n config.db,\n taxonomy,\n config.channelDefaults ?? {},\n );\n const pushSubscriptions = createPushSubscriptionStore(config.db, logger);\n const transports = createTransportRegistry(\n config.transports ?? [],\n pushSubscriptions,\n config.drivers ?? {},\n logger,\n );\n\n const router = createNotificationRouter({\n db: config.db,\n generators,\n transports,\n preferences,\n pushSubscriptions,\n contacts: config.contacts,\n logger,\n maxAttempts: config.maxDeliveryAttempts ?? DEFAULT_MAX_DELIVERY_ATTEMPTS,\n // `exactOptionalPropertyTypes` is on, so an absent host seam must be an\n // ABSENT key rather than an explicit `undefined`.\n ...present({\n channelPolicy: config.channelPolicy,\n scheduleDispatch: config.scheduleDispatch,\n onCommitted: config.onCommitted,\n }),\n });\n\n const audience = config.audience;\n const notifyByPermission: NotifyByPermission = audience\n ? createNotifyByPermission({ router, directory: audience, logger })\n : () =>\n Promise.reject(\n new Error(\n 'notifyByPermission() needs an `audience` directory — pass the host authorization ' +\n 'engine to createApiNotifications({ audience }).',\n ),\n );\n\n return {\n routes: notificationRoutes({\n inbox,\n preferences,\n pushSubscriptions,\n transports,\n contacts: config.contacts,\n categories: taxonomy.categories,\n messages,\n ...present({ onInboxChanged: config.onInboxChanged }),\n }),\n notify: router.notify,\n dispatchDeliveries: router.dispatchDeliveries,\n drainPending: router.drainPending,\n notifyByPermission,\n inbox,\n preferences,\n pushSubscriptions,\n registerGenerator: generators.register,\n transports,\n messages,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEO,IAAM,wBAAN,MAAM,+BAA8B,MAAM;AAAA,EAhEjD,OAgEiD;AAAA;AAAA;AAAA,EACtC;AAAA,EACT,YAAY,QAAgB,SAAiB;AAC3C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,WAAO,eAAe,MAAM,uBAAsB,SAAS;AAAA,EAC7D;AACF;AAGO,IAAM,KAAK,wBAAC,MAAe,SAAS,SAAgC;AAAA,EACzE;AAAA,EACA,MAAM,EAAE,KAAK;AACf,IAHkB;AAKlB,IAAM,OAAO,wBAAC,QAAgB,WAA0C;AAAA,EACtE;AAAA,EACA,MAAM,EAAE,MAAM;AAChB,IAHa;AAMN,SAAS,aAAa,OAAuC;AAClE,MAAI,iBAAiB,sBAAuB,QAAO,KAAK,MAAM,QAAQ,MAAM,OAAO;AACnF,QAAM;AACR;AAHgB;AAMT,SAAS,QACd,QACmE;AACnE,SAAO,OAAO,YAAY;AACxB,QAAI;AACF,aAAO,MAAM,OAAO,OAAO;AAAA,IAC7B,SAAS,OAAO;AACd,aAAO,aAAa,KAAK;AAAA,IAC3B;AAAA,EACF;AACF;AAVgB;AAgBhB,SAAS,SAAS,MAAe,UAA6D;AAC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