Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,197 @@
# OpenSpec Change: enterprise-notification-channel
- **Change ID**: enterprise-notification-channel
- **Package**: `@suaveplan/notification-channel`
- **Category**: universal
- **Target path**: `universal/messaging/notification-channel`
- **Status**: IN PROGRESS
- **Date**: 2026-04-24
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/notification-channel.md`
---
## Summary
Deliver `@suaveplan/notification-channel` on the genesis branch from scratch at enterprise quality. The package provides multi-channel notification routing: a `NotificationChannel` interface, concrete channel adapters (email, SMS, push/in-app, Slack webhook, Discord webhook, Telegram), a `NotificationRouter` that dispatches a notification through registered channels based on priority rules, template rendering per channel via `@suaveplan/email-templates` or `@suaveplan/templates`, preference-aware routing (per-recipient opt-in/opt-out per channel), delivery tracking integration, and a `NotificationService` orchestrator. The main-branch version sat at 95.61% coverage. Genesis adds structured errors, Zod schemas, OTel instrumentation, retry, and property-based tests.
---
## Current-state audit (genesis)
The package does not exist on genesis yet — this is a fresh build.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/error` (`workspace:^`) | `NotificationError`; `NOTIF.*` error codes |
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock`, `EventBusLike` |
| `@suaveplan/events` (`workspace:^`) | Notification lifecycle events |
| `@suaveplan/templates` (`workspace:^`) | Channel-specific template rendering |
| `@suaveplan/email-templates` (`workspace:^`) | Email-specific template rendering |
| `@suaveplan/retry` (`workspace:^`) | Retry on channel send failures |
| `@suaveplan/suppression` (`workspace:^`) | Email/SMS suppression list check |
| `zod` (`catalog:forms`) | Schema validation |
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters |
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check` (all `catalog:testing`).
---
## Public API surface
### Core types
```ts
type ChannelType = 'email' | 'sms' | 'push' | 'in-app' | 'slack' | 'discord' | 'telegram'
interface Notification {
id: string
recipient: NotificationRecipient
templateName: string
channels: ChannelType[]
context: Record<string, unknown>
priority: 'low' | 'normal' | 'high' | 'critical'
metadata: Record<string, unknown>
}
interface NotificationRecipient {
id: string
email?: string
phone?: string
pushToken?: string
slackUserId?: string
discordUserId?: string
telegramChatId?: string | number
preferences?: ChannelPreferences
}
type ChannelPreferences = Partial<Record<ChannelType, boolean>>
interface NotificationResult {
notificationId: string
channel: ChannelType
status: 'sent' | 'failed' | 'suppressed' | 'skipped'
error?: string
}
```
### `NotificationChannel` interface
```ts
interface NotificationChannel {
readonly type: ChannelType
send(recipient: NotificationRecipient, subject: string, body: string, options?: ChannelSendOptions): Promise<void>
isAvailableFor(recipient: NotificationRecipient): boolean
}
```
### `NotificationService`
```ts
class NotificationService {
constructor(options: NotificationServiceOptions)
register(channel: NotificationChannel): void
send(notification: Notification, options?: SendOptions): Promise<NotificationResult[]>
sendBatch(notifications: Notification[], options?: BatchOptions): AsyncGenerator<NotificationResult[]>
}
interface NotificationServiceOptions {
channels?: NotificationChannel[]
fallbackChain?: ChannelType[] // try channels in order until one succeeds
logger?: LoggerLike
bus?: EventBusLike
}
```
### Error codes
```ts
type NotificationErrorCode =
| 'NOTIF_NO_CHANNEL'
| 'NOTIF_ALL_FAILED'
| 'NOTIF_TEMPLATE_NOT_FOUND'
| 'NOTIF_RECIPIENT_INVALID'
| 'NOTIF_SUPPRESSED'
| 'NOTIF_SEND_FAILED'
| 'NOTIF_ABORTED'
```
---
## Genesis additions
1. **`NotificationError`** extends `SuaveplanError` with seven stable codes.
2. **Zod schemas** for `Notification`, `NotificationRecipient`, `ChannelPreferences`, `NotificationResult`, `NotificationServiceOptions`.
3. **Preference-aware routing** — before dispatch, checks `recipient.preferences[channel]`; `false` → `skipped` status.
4. **Suppression integration** — email and SMS channels call `@suaveplan/suppression` before dispatch; suppressed → `suppressed` status.
5. **Fallback chain** — if primary channel fails, try next channel in `fallbackChain` until one succeeds or all fail.
6. **OTel instrumentation** — counter `notification.send_total` with attributes `notification.channel`, `notification.status`; histogram `notification.send_duration_ms`.
7. **Property-based tests** — channel preference filter correctly skips opted-out channels for arbitrary preference maps.
---
## File layout
```text
universal/messaging/notification-channel/
package.json
tsconfig.json
vitest.config.ts
src/
index.ts
error-codes.ts
constants/
index.ts
types/
common.ts
common.md
core/
notification-service/
notification-service.ts
notification-service.md
notification-service.types.ts
notification-service.test.ts
index.ts
notification-router/
notification-router.ts
notification-router.md
notification-router.test.ts
index.ts
channels/
email-channel/
email-channel.ts
email-channel.md
email-channel.test.ts
index.ts
sms-channel/
sms-channel.ts
sms-channel.md
sms-channel.test.ts
index.ts
in-app-channel/
in-app-channel.ts
in-app-channel.md
in-app-channel.test.ts
index.ts
webhook-channel/
webhook-channel.ts
webhook-channel.md
webhook-channel.test.ts
index.ts
__benchmarks__/
notification-channel.bench.ts
tests/
integration.test.ts
property.test.ts
```
---
## Impact
**Downstream consumers**: any server-side notification dispatch service.
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/templates`, `@suaveplan/email-templates`, `@suaveplan/retry`, `@suaveplan/suppression`.

View File

@@ -0,0 +1,70 @@
# Tasks: enterprise-notification-channel
**Change ID**: enterprise-notification-channel
**Package**: `@suaveplan/notification-channel`
**Target path**: `universal/messaging/notification-channel`
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/templates`, `@suaveplan/email-templates`, `@suaveplan/retry`, `@suaveplan/suppression`
---
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Scaffold
- [ ] Create `universal/messaging/notification-channel/` with `src/`, `tests/`, `src/__benchmarks__/` and all feature subdirectories per the layout in `proposal.md`.
- [ ] Write `package.json` at version `0.1.0` with `"type": "module"`, `"sideEffects": false`, correct `exports` map, `dependencies`, and `devDependencies`.
- [ ] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
- [ ] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config`.
- [ ] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check` scripts.
---
## 2. Types + errors
- [ ] `src/types/common.ts` — `ChannelType`, `Notification`, `NotificationRecipient`, `ChannelPreferences`, `NotificationResult`, `NotificationChannel` (interface), `ChannelSendOptions`, `NotificationServiceOptions`, `SendOptions`, `BatchOptions`.
- [ ] `src/types/common.md` (≥200 words, both examples, API reference).
- [ ] `src/error-codes.ts` — `NotificationErrorCode` (7 codes), metadata, register, eager call.
- [ ] `src/types/schemas.ts` + `schemas.md` — Zod schemas.
---
## 3. Core modules
- [ ] **`src/core/notification-router/`** — `NotificationRouter`: given a `Notification` and registered channels, selects channels from `notification.channels` that are available for the recipient, not opted out (`ChannelPreferences`), and not suppressed. Returns `ChannelType[]` to dispatch. Tests: preference-filtered, suppressed email excluded, fallback chain triggered.
- [ ] **`src/channels/email-channel/`** — `EmailChannel implements NotificationChannel`: `type='email'`; `isAvailableFor` checks `recipient.email` is set; `send` renders via `@suaveplan/email-templates`, calls injected `emailSender`. Tests: happy path, missing email returns `isAvailableFor=false`, suppressed recipient skipped.
- [ ] **`src/channels/sms-channel/`** — `SmsChannel implements NotificationChannel`: `type='sms'`; `isAvailableFor` checks `recipient.phone` is set; `send` renders body via `@suaveplan/templates`, calls injected `smsSender`. Tests: happy path, missing phone not available.
- [ ] **`src/channels/in-app-channel/`** — `InAppChannel implements NotificationChannel`: stores notifications in memory (injectable store); `isAvailableFor` always true when `recipient.id` is set. Tests: send adds to store, list by recipient.
- [ ] **`src/channels/webhook-channel/`** — `WebhookChannel implements NotificationChannel`: `type` configurable; `send` POSTs JSON payload to configured webhook URL via injectable fetch with HMAC signature. Tests: POST called with correct JSON, signature header present.
- [ ] **`src/core/notification-service/`** — `NotificationService`: `register(channel)`, `send(notification, options)` — calls router to get channels, dispatches in parallel (or series for fallback chain), collects results. `sendBatch` yields results per notification. Tests: all channels succeed, one fails and fallback invoked, all failed → `NOTIF_ALL_FAILED`, `AbortSignal` cancel.
---
## 4. OTel instrumentation
- [ ] Counter `notification.send_total` with attributes `notification.channel`, `notification.status`; histogram `notification.send_duration_ms`.
---
## 5. Property-based tests (`tests/property.test.ts`)
- [ ] Preference filter: for arbitrary `ChannelPreferences` maps and channel lists, router only selects channels with `preference !== false`.
---
## 6. Benchmarks (`src/__benchmarks__/notification-channel.bench.ts`)
- [ ] `NotificationRouter.selectChannels` for 100 000 notifications with 4 registered channels.
---
## 7. Docs + verify
- [ ] One `.md` per implementation file (≥200 words, both examples, API reference). Root `README.md`.
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/notification-channel` — green.
- [ ] `bunx turbo test:coverage --filter=@suaveplan/notification-channel` — 100%.
- [ ] `bun scripts/publish.ts --package @suaveplan/notification-channel`.
- [ ] Archive: `openspec/archive/2026-04-24-enterprise-notification-channel/`.