@adatechnology/notification-contracts 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,853 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Copyright (c) 2026 Ada Technology. MIT License.
5
+ */
6
+ declare const NOTIFICATION_CHANNEL: {
7
+ readonly INBOX: "inbox";
8
+ readonly PUSH: "push";
9
+ readonly EMAIL: "email";
10
+ readonly WHATSAPP: "whatsapp";
11
+ readonly SMS: "sms";
12
+ };
13
+ type NotificationChannel = (typeof NOTIFICATION_CHANNEL)[keyof typeof NOTIFICATION_CHANNEL];
14
+ /** Canais que interrompem o destinatário e por isso respeitam quiet hours (ver spec §10.4). */
15
+ declare const INTRUSIVE_CHANNELS: readonly NotificationChannel[];
16
+ declare const NOTIFICATION_STATUS: {
17
+ readonly PENDING: "pending";
18
+ readonly SCHEDULED: "scheduled";
19
+ readonly QUEUED: "queued";
20
+ readonly DISPATCHED: "dispatched";
21
+ readonly PARTIALLY_FAILED: "partially_failed";
22
+ readonly FAILED: "failed";
23
+ };
24
+ type NotificationStatus = (typeof NOTIFICATION_STATUS)[keyof typeof NOTIFICATION_STATUS];
25
+ declare const DELIVERY_STATUS: {
26
+ readonly QUEUED: "queued";
27
+ readonly SENT: "sent";
28
+ readonly DELIVERED: "delivered";
29
+ readonly FAILED: "failed";
30
+ readonly BOUNCED: "bounced";
31
+ readonly SKIPPED: "skipped";
32
+ };
33
+ type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS];
34
+ declare const DEVICE_PLATFORM: {
35
+ readonly IOS: "ios";
36
+ readonly ANDROID: "android";
37
+ readonly WEB: "web";
38
+ };
39
+ type DevicePlatform = (typeof DEVICE_PLATFORM)[keyof typeof DEVICE_PLATFORM];
40
+ declare const PUSH_DRIVER: {
41
+ readonly EXPO: "expo";
42
+ readonly FCM: "fcm";
43
+ };
44
+ type PushDriver = (typeof PUSH_DRIVER)[keyof typeof PUSH_DRIVER];
45
+ declare const EMAIL_DRIVER: {
46
+ readonly SMTP: "smtp";
47
+ readonly RESEND: "resend";
48
+ readonly SES: "ses";
49
+ };
50
+ type EmailDriver = (typeof EMAIL_DRIVER)[keyof typeof EMAIL_DRIVER];
51
+ declare const SUPPRESSION_REASON: {
52
+ readonly BOUNCE: "bounce";
53
+ readonly COMPLAINT: "complaint";
54
+ readonly OPT_OUT: "opt_out";
55
+ };
56
+ type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON];
57
+ /**
58
+ * Sugestão de nomenclatura, sem valor normativo (decisão Q2 da spec). `category` é `varchar`
59
+ * livre porque é vocabulário de negócio do produto — fechá-la num enum aqui obrigaria uma major
60
+ * do pacote a cada produto novo.
61
+ */
62
+ declare const NOTIFICATION_CATEGORY_HINT: {
63
+ readonly ORDER_STATUS: "order_status";
64
+ readonly PAYMENT: "payment";
65
+ readonly SECURITY: "security";
66
+ readonly MARKETING: "marketing";
67
+ readonly SYSTEM: "system";
68
+ };
69
+ type NotificationId = string;
70
+ type CompanyId = string;
71
+ type UserId = string;
72
+ type NotificationSummary = {
73
+ readonly id: NotificationId;
74
+ readonly category: string;
75
+ readonly templateKey: string;
76
+ readonly title: string;
77
+ readonly body: string;
78
+ readonly payload: Readonly<Record<string, unknown>>;
79
+ readonly status: NotificationStatus;
80
+ readonly scheduledFor?: string;
81
+ readonly readAt?: string;
82
+ readonly createdAt: string;
83
+ };
84
+ type DeliverySummary = {
85
+ readonly id: string;
86
+ readonly notificationId: NotificationId;
87
+ readonly channel: NotificationChannel;
88
+ readonly driver?: string;
89
+ /** Nunca o endereço em claro: `****1234`, `a***@dominio.com` (LGPD — ver spec §5). */
90
+ readonly targetMasked?: string;
91
+ readonly status: DeliveryStatus;
92
+ readonly attempt: number;
93
+ readonly providerMessageId?: string;
94
+ readonly errorCode?: string;
95
+ readonly sentAt?: string;
96
+ readonly deliveredAt?: string;
97
+ readonly failedAt?: string;
98
+ };
99
+ type DeviceRegistration = {
100
+ readonly id: string;
101
+ readonly platform: DevicePlatform;
102
+ readonly driver: PushDriver;
103
+ readonly appVersion?: string;
104
+ readonly locale?: string;
105
+ readonly timezone?: string;
106
+ readonly lastSeenAt: string;
107
+ readonly disabledAt?: string;
108
+ readonly disabledReason?: string;
109
+ };
110
+ type NotificationPreference = {
111
+ readonly category: string;
112
+ readonly channel: NotificationChannel;
113
+ readonly enabled: boolean;
114
+ /** `HH:mm` no timezone resolvido para o destinatário; ambos ausentes = sem janela de silêncio. */
115
+ readonly quietHoursStart?: string;
116
+ readonly quietHoursEnd?: string;
117
+ readonly timezone?: string;
118
+ };
119
+ type NotificationTemplate = {
120
+ readonly id: string;
121
+ readonly key: string;
122
+ readonly channel: NotificationChannel;
123
+ readonly locale: string;
124
+ readonly version: number;
125
+ readonly subject?: string;
126
+ readonly body: string;
127
+ /**
128
+ * Nome do template aprovado na Meta. Sem ele, o canal WhatsApp é pulado fora da janela de 24 h
129
+ * em vez de estourar erro na cara do usuário (spec §10.7).
130
+ */
131
+ readonly whatsappTemplateName?: string;
132
+ readonly active: boolean;
133
+ };
134
+ type SendNotificationParams = {
135
+ readonly companyId: CompanyId;
136
+ readonly recipientUserId: UserId;
137
+ readonly category: string;
138
+ readonly templateKey: string;
139
+ readonly payload?: Readonly<Record<string, unknown>>;
140
+ /** Sem canais explícitos, o fan-out resolve pelas preferências do destinatário. */
141
+ readonly channels?: readonly NotificationChannel[];
142
+ /** Chave de negócio da entrega. Repetição devolve a notificação existente, não uma nova. */
143
+ readonly dedupeKey?: string;
144
+ readonly scheduledFor?: Date;
145
+ readonly locale?: string;
146
+ };
147
+ type SendNotificationResult = {
148
+ readonly notificationId: NotificationId;
149
+ /** `true` quando um `dedupeKey` já visto devolveu a notificação anterior — nada foi reenviado. */
150
+ readonly deduplicated: boolean;
151
+ readonly deliveries: readonly DeliverySummary[];
152
+ };
153
+ type ListNotificationsParams = {
154
+ readonly companyId: CompanyId;
155
+ readonly recipientUserId: UserId;
156
+ readonly category?: string;
157
+ readonly read?: boolean;
158
+ readonly cursor?: string;
159
+ readonly perPage?: number;
160
+ };
161
+ type ListNotificationsResult = {
162
+ readonly data: readonly NotificationSummary[];
163
+ readonly nextCursor?: string;
164
+ readonly unreadCount: number;
165
+ };
166
+ type DeliveryReceipt = {
167
+ readonly providerMessageId: string;
168
+ readonly status: Extract<DeliveryStatus, 'delivered' | 'bounced' | 'failed'>;
169
+ readonly errorCode?: string;
170
+ readonly occurredAt: Date;
171
+ readonly suppressionReason?: SuppressionReason;
172
+ };
173
+
174
+ /**
175
+ * Copyright (c) 2026 Ada Technology. MIT License.
176
+ */
177
+
178
+ /**
179
+ * Resultado de UMA tentativa de entrega, classificado **pelo driver** — nunca pelo módulo.
180
+ *
181
+ * Só o driver sabe que `DeviceNotRegistered` (Expo) e `registration-token-not-registered` (FCM)
182
+ * significam "apaga o token", e que 429/5xx significa "tenta de novo". Deixar essa leitura no
183
+ * módulo o obrigaria a conhecer o vocabulário de erro de cada provedor — e foi assim que, no
184
+ * modelo antigo, token morto ficava vivo para sempre e erro permanente entrava em retry infinito.
185
+ *
186
+ * O módulo age sobre o discriminante:
187
+ * - `sent` grava `providerMessageId`;
188
+ * - `invalid_target` desativa o device ou cria supressão, **sem** retry;
189
+ * - `retriable` reagenda com backoff exponencial + jitter até esgotar `attempts`;
190
+ * - `permanent` finaliza como `failed` na primeira tentativa.
191
+ */
192
+ type DeliveryAttemptResult = {
193
+ readonly outcome: 'sent';
194
+ readonly providerMessageId?: string;
195
+ } | {
196
+ readonly outcome: 'invalid_target';
197
+ readonly errorCode: string;
198
+ readonly suppressionReason?: SuppressionReason;
199
+ } | {
200
+ readonly outcome: 'retriable';
201
+ readonly errorCode: string;
202
+ readonly retryAfterSeconds?: number;
203
+ } | {
204
+ readonly outcome: 'permanent';
205
+ readonly errorCode: string;
206
+ };
207
+ type SendPushParams = {
208
+ readonly token: string;
209
+ readonly platform: DevicePlatform;
210
+ readonly title: string;
211
+ readonly body: string;
212
+ /**
213
+ * Só identificadores opacos (`notificationId`, `orderId`) — o payload viaja pelos servidores
214
+ * da Apple, Google e Expo, então nada de PII aqui (`security.md` §1).
215
+ */
216
+ readonly data?: Readonly<Record<string, string>>;
217
+ readonly badge?: number;
218
+ };
219
+ type SendEmailParams = {
220
+ readonly to: string;
221
+ readonly subject: string;
222
+ readonly html: string;
223
+ readonly text: string;
224
+ readonly replyTo?: string;
225
+ /** Correlaciona o recibo assíncrono (bounce/complaint) com a `delivery` que o originou. */
226
+ readonly idempotencyKey?: string;
227
+ };
228
+ type SendWhatsAppTemplateParams = {
229
+ readonly templateName: string;
230
+ readonly languageCode: string;
231
+ readonly bodyParameters?: readonly string[];
232
+ };
233
+ type SendWhatsAppParams = {
234
+ readonly to: string;
235
+ readonly body: string;
236
+ /**
237
+ * Presente = envio por template aprovado, único caminho válido fora da janela de 24 h.
238
+ * Ausente = mensagem livre, que a Meta só aceita dentro da janela.
239
+ */
240
+ readonly template?: SendWhatsAppTemplateParams;
241
+ };
242
+ type SendSmsParams = {
243
+ readonly to: string;
244
+ readonly body: string;
245
+ };
246
+ interface PushDriverPort {
247
+ readonly driver: PushDriver;
248
+ send(params: SendPushParams): Promise<DeliveryAttemptResult>;
249
+ }
250
+ interface EmailDriverPort {
251
+ readonly driver: string;
252
+ send(params: SendEmailParams): Promise<DeliveryAttemptResult>;
253
+ }
254
+ /**
255
+ * Satisfeita pelo `channel` do `meta-whatsapp-module` via `createWhatsAppDriverFromChannel()`.
256
+ * O contracts descreve a *forma* e não importa nada da Meta: é o que mantém os dois trios
257
+ * independentes, com a costura acontecendo no produto (regra de módulos plugáveis, §2).
258
+ */
259
+ interface WhatsAppDriverPort {
260
+ send(params: SendWhatsAppParams): Promise<DeliveryAttemptResult>;
261
+ }
262
+ /**
263
+ * Declarada sem driver publicado, de propósito: não há consumidor de SMS no ecossistema hoje, e
264
+ * extrair antes do 1º uso real é abstração prematura. Canal `sms` ligado sem driver injetado
265
+ * falha **no boot**, não na primeira notificação.
266
+ */
267
+ interface SmsDriverPort {
268
+ send(params: SendSmsParams): Promise<DeliveryAttemptResult>;
269
+ }
270
+ type ChannelDrivers = {
271
+ readonly push?: PushDriverPort;
272
+ readonly email?: EmailDriverPort;
273
+ readonly whatsapp?: WhatsAppDriverPort;
274
+ readonly sms?: SmsDriverPort;
275
+ };
276
+
277
+ /**
278
+ * Copyright (c) 2026 Ada Technology. MIT License.
279
+ */
280
+
281
+ type ResolvedRecipient = {
282
+ readonly email?: string;
283
+ readonly phone?: string;
284
+ readonly locale?: string;
285
+ readonly timezone?: string;
286
+ readonly displayName?: string;
287
+ };
288
+ /**
289
+ * Resolve o endereço do destinatário **no instante do envio**, a partir da tabela de usuários do
290
+ * produto — que o módulo não conhece e nunca lê.
291
+ *
292
+ * É o que permite ao módulo jamais persistir e-mail ou telefone em claro: `deliveries` guarda só
293
+ * `targetMasked`, supressão guarda HMAC, e o job na fila carrega apenas `notificationId`. Sem esta
294
+ * porta, a única alternativa seria copiar PII para dentro do schema do pacote.
295
+ */
296
+ interface RecipientResolverPort {
297
+ resolve(params: {
298
+ readonly userId: UserId;
299
+ readonly companyId: CompanyId;
300
+ }): Promise<ResolvedRecipient | undefined>;
301
+ }
302
+ type NotificationJob = {
303
+ /** Só a referência: conteúdo e endereço ficam no banco, nunca na fila (`worker.md`). */
304
+ readonly notificationId: NotificationId;
305
+ /**
306
+ * A entrega específica, não só a notificação — push fan-out cria uma `delivery` por device
307
+ * ativo, todas para o mesmo `(notificationId, channel)`; sem este id o worker não saberia qual
308
+ * delas aquele job representa.
309
+ */
310
+ readonly deliveryId: string;
311
+ readonly companyId: CompanyId;
312
+ readonly channel: NotificationChannel;
313
+ readonly attempt: number;
314
+ };
315
+ /**
316
+ * Adaptadores prontos em `@adatechnology/notification-module/queue/bullmq` e `/queue/amqp` —
317
+ * o módulo não abre conexão própria nem escolhe broker pelo host.
318
+ */
319
+ interface QueuePort {
320
+ enqueue(params: {
321
+ readonly job: NotificationJob;
322
+ readonly delaySeconds?: number;
323
+ }): Promise<void>;
324
+ consume(handler: (job: NotificationJob) => Promise<void>): Promise<void>;
325
+ close(): Promise<void>;
326
+ }
327
+ type RenderTemplateParams = {
328
+ readonly body: string;
329
+ readonly subject?: string;
330
+ readonly channel: NotificationChannel;
331
+ readonly payload: Readonly<Record<string, unknown>>;
332
+ readonly locale: string;
333
+ };
334
+ type RenderedTemplate = {
335
+ readonly title: string;
336
+ readonly body: string;
337
+ readonly html?: string;
338
+ };
339
+ /** Default do pacote interpola `{{campo}}` e escapa por canal; Handlebars/MJML é override do host. */
340
+ interface TemplateRendererPort {
341
+ render(params: RenderTemplateParams): Promise<RenderedTemplate> | RenderedTemplate;
342
+ }
343
+ /**
344
+ * Sem cache injetado, throttle por destinatário e nonce de webhook ficam **desligados** — e o
345
+ * módulo diz isso no boot em vez de fingir proteção. Cachear é decisão do host, que é quem sabe
346
+ * se o Redis dele é compartilhado entre instâncias.
347
+ */
348
+ interface CachePort {
349
+ get(key: string): Promise<string | undefined>;
350
+ set(params: {
351
+ readonly key: string;
352
+ readonly value: string;
353
+ readonly ttlSeconds: number;
354
+ }): Promise<void>;
355
+ increment(params: {
356
+ readonly key: string;
357
+ readonly ttlSeconds: number;
358
+ }): Promise<number>;
359
+ delete(key: string): Promise<void>;
360
+ }
361
+ type RealtimeEvent = {
362
+ readonly event: string;
363
+ readonly data: Readonly<Record<string, unknown>>;
364
+ };
365
+ type RealtimeSubscription = {
366
+ close(): void;
367
+ };
368
+ /** Alimenta o badge em tempo real; o SSE do próprio módulo é um consumidor desta porta. */
369
+ interface RealtimeNotifierPort {
370
+ publish(params: {
371
+ readonly companyId: CompanyId;
372
+ readonly userId: UserId;
373
+ readonly event: string;
374
+ readonly data: Readonly<Record<string, unknown>>;
375
+ }): Promise<void>;
376
+ /**
377
+ * Opcional, e a consequência de omiti-la é concreta: sem `subscribe`, o SSE do módulo cai no
378
+ * notificador em processo, que só entrega a eventos originados na **mesma instância**. Com duas
379
+ * réplicas atrás de um balanceador, o usuário conectado na réplica A não recebe o evento que
380
+ * nasceu na B — o badge fica parado até o próximo refetch.
381
+ *
382
+ * O host que roda mais de uma instância implementa esta porta sobre o pub/sub dele (Redis,
383
+ * NATS, Postgres LISTEN/NOTIFY). Opcional porque exigi-la obrigaria quem roda instância única a
384
+ * subir um broker que não precisa.
385
+ */
386
+ subscribe?(params: {
387
+ readonly companyId: CompanyId;
388
+ readonly userId: UserId;
389
+ readonly onEvent: (event: RealtimeEvent) => void;
390
+ }): Promise<RealtimeSubscription>;
391
+ }
392
+ /** Injetável para tornar determinístico o que depende de horário: quiet hours, agendamento, TTL. */
393
+ interface ClockPort {
394
+ now(): Date;
395
+ }
396
+ type LogMeta = Readonly<Record<string, unknown>>;
397
+ interface LoggerPort {
398
+ debug(message: string, meta?: LogMeta): void;
399
+ info(message: string, meta?: LogMeta): void;
400
+ warn(message: string, meta?: LogMeta): void;
401
+ error(message: string, meta?: LogMeta): void;
402
+ }
403
+ interface MetricsPort {
404
+ increment(params: {
405
+ readonly metric: string;
406
+ readonly labels?: Readonly<Record<string, string>>;
407
+ }): void;
408
+ observe(params: {
409
+ readonly metric: string;
410
+ readonly value: number;
411
+ readonly labels?: Readonly<Record<string, string>>;
412
+ }): void;
413
+ }
414
+
415
+ /**
416
+ * Copyright (c) 2026 Ada Technology. MIT License.
417
+ */
418
+
419
+ declare const sendNotificationSchema: z.ZodObject<{
420
+ recipientUserId: z.ZodString;
421
+ category: z.ZodString;
422
+ templateKey: z.ZodString;
423
+ payload: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
424
+ channels: z.ZodOptional<z.ZodArray<z.ZodNativeEnum<{
425
+ readonly INBOX: "inbox";
426
+ readonly PUSH: "push";
427
+ readonly EMAIL: "email";
428
+ readonly WHATSAPP: "whatsapp";
429
+ readonly SMS: "sms";
430
+ }>, "atleastone">>;
431
+ dedupeKey: z.ZodOptional<z.ZodString>;
432
+ scheduledFor: z.ZodOptional<z.ZodDate>;
433
+ locale: z.ZodOptional<z.ZodString>;
434
+ }, "strip", z.ZodTypeAny, {
435
+ recipientUserId: string;
436
+ category: string;
437
+ templateKey: string;
438
+ payload?: Record<string, unknown> | undefined;
439
+ channels?: ["inbox" | "push" | "email" | "whatsapp" | "sms", ...("inbox" | "push" | "email" | "whatsapp" | "sms")[]] | undefined;
440
+ dedupeKey?: string | undefined;
441
+ scheduledFor?: Date | undefined;
442
+ locale?: string | undefined;
443
+ }, {
444
+ recipientUserId: string;
445
+ category: string;
446
+ templateKey: string;
447
+ payload?: Record<string, unknown> | undefined;
448
+ channels?: ["inbox" | "push" | "email" | "whatsapp" | "sms", ...("inbox" | "push" | "email" | "whatsapp" | "sms")[]] | undefined;
449
+ dedupeKey?: string | undefined;
450
+ scheduledFor?: Date | undefined;
451
+ locale?: string | undefined;
452
+ }>;
453
+ type SendNotificationBody = z.infer<typeof sendNotificationSchema>;
454
+ declare const registerDeviceSchema: z.ZodObject<{
455
+ platform: z.ZodNativeEnum<{
456
+ readonly IOS: "ios";
457
+ readonly ANDROID: "android";
458
+ readonly WEB: "web";
459
+ }>;
460
+ driver: z.ZodNativeEnum<{
461
+ readonly EXPO: "expo";
462
+ readonly FCM: "fcm";
463
+ }>;
464
+ token: z.ZodString;
465
+ appVersion: z.ZodOptional<z.ZodString>;
466
+ locale: z.ZodOptional<z.ZodString>;
467
+ timezone: z.ZodOptional<z.ZodString>;
468
+ }, "strip", z.ZodTypeAny, {
469
+ platform: "ios" | "android" | "web";
470
+ driver: "expo" | "fcm";
471
+ token: string;
472
+ locale?: string | undefined;
473
+ appVersion?: string | undefined;
474
+ timezone?: string | undefined;
475
+ }, {
476
+ platform: "ios" | "android" | "web";
477
+ driver: "expo" | "fcm";
478
+ token: string;
479
+ locale?: string | undefined;
480
+ appVersion?: string | undefined;
481
+ timezone?: string | undefined;
482
+ }>;
483
+ type RegisterDeviceBody = z.infer<typeof registerDeviceSchema>;
484
+ declare const preferenceEntrySchema: z.ZodObject<{
485
+ quietHoursStart: z.ZodOptional<z.ZodString>;
486
+ quietHoursEnd: z.ZodOptional<z.ZodString>;
487
+ timezone: z.ZodOptional<z.ZodString>;
488
+ category: z.ZodString;
489
+ channel: z.ZodNativeEnum<{
490
+ readonly INBOX: "inbox";
491
+ readonly PUSH: "push";
492
+ readonly EMAIL: "email";
493
+ readonly WHATSAPP: "whatsapp";
494
+ readonly SMS: "sms";
495
+ }>;
496
+ enabled: z.ZodBoolean;
497
+ }, "strip", z.ZodTypeAny, {
498
+ category: string;
499
+ channel: "inbox" | "push" | "email" | "whatsapp" | "sms";
500
+ enabled: boolean;
501
+ timezone?: string | undefined;
502
+ quietHoursStart?: string | undefined;
503
+ quietHoursEnd?: string | undefined;
504
+ }, {
505
+ category: string;
506
+ channel: "inbox" | "push" | "email" | "whatsapp" | "sms";
507
+ enabled: boolean;
508
+ timezone?: string | undefined;
509
+ quietHoursStart?: string | undefined;
510
+ quietHoursEnd?: string | undefined;
511
+ }>;
512
+ declare const updatePreferencesSchema: z.ZodObject<{
513
+ preferences: z.ZodArray<z.ZodObject<{
514
+ quietHoursStart: z.ZodOptional<z.ZodString>;
515
+ quietHoursEnd: z.ZodOptional<z.ZodString>;
516
+ timezone: z.ZodOptional<z.ZodString>;
517
+ category: z.ZodString;
518
+ channel: z.ZodNativeEnum<{
519
+ readonly INBOX: "inbox";
520
+ readonly PUSH: "push";
521
+ readonly EMAIL: "email";
522
+ readonly WHATSAPP: "whatsapp";
523
+ readonly SMS: "sms";
524
+ }>;
525
+ enabled: z.ZodBoolean;
526
+ }, "strip", z.ZodTypeAny, {
527
+ category: string;
528
+ channel: "inbox" | "push" | "email" | "whatsapp" | "sms";
529
+ enabled: boolean;
530
+ timezone?: string | undefined;
531
+ quietHoursStart?: string | undefined;
532
+ quietHoursEnd?: string | undefined;
533
+ }, {
534
+ category: string;
535
+ channel: "inbox" | "push" | "email" | "whatsapp" | "sms";
536
+ enabled: boolean;
537
+ timezone?: string | undefined;
538
+ quietHoursStart?: string | undefined;
539
+ quietHoursEnd?: string | undefined;
540
+ }>, "many">;
541
+ }, "strip", z.ZodTypeAny, {
542
+ preferences: {
543
+ category: string;
544
+ channel: "inbox" | "push" | "email" | "whatsapp" | "sms";
545
+ enabled: boolean;
546
+ timezone?: string | undefined;
547
+ quietHoursStart?: string | undefined;
548
+ quietHoursEnd?: string | undefined;
549
+ }[];
550
+ }, {
551
+ preferences: {
552
+ category: string;
553
+ channel: "inbox" | "push" | "email" | "whatsapp" | "sms";
554
+ enabled: boolean;
555
+ timezone?: string | undefined;
556
+ quietHoursStart?: string | undefined;
557
+ quietHoursEnd?: string | undefined;
558
+ }[];
559
+ }>;
560
+ type UpdatePreferencesBody = z.infer<typeof updatePreferencesSchema>;
561
+ declare const upsertTemplateSchema: z.ZodObject<{
562
+ key: z.ZodString;
563
+ channel: z.ZodNativeEnum<{
564
+ readonly INBOX: "inbox";
565
+ readonly PUSH: "push";
566
+ readonly EMAIL: "email";
567
+ readonly WHATSAPP: "whatsapp";
568
+ readonly SMS: "sms";
569
+ }>;
570
+ locale: z.ZodString;
571
+ subject: z.ZodOptional<z.ZodString>;
572
+ body: z.ZodString;
573
+ whatsappTemplateName: z.ZodOptional<z.ZodString>;
574
+ active: z.ZodDefault<z.ZodBoolean>;
575
+ }, "strip", z.ZodTypeAny, {
576
+ locale: string;
577
+ channel: "inbox" | "push" | "email" | "whatsapp" | "sms";
578
+ key: string;
579
+ body: string;
580
+ active: boolean;
581
+ subject?: string | undefined;
582
+ whatsappTemplateName?: string | undefined;
583
+ }, {
584
+ locale: string;
585
+ channel: "inbox" | "push" | "email" | "whatsapp" | "sms";
586
+ key: string;
587
+ body: string;
588
+ subject?: string | undefined;
589
+ whatsappTemplateName?: string | undefined;
590
+ active?: boolean | undefined;
591
+ }>;
592
+ type UpsertTemplateBody = z.infer<typeof upsertTemplateSchema>;
593
+ /** Query string chega sempre como texto — daí o `coerce` e o booleano por literal. */
594
+ declare const listNotificationsQuerySchema: z.ZodObject<{
595
+ category: z.ZodOptional<z.ZodString>;
596
+ read: z.ZodOptional<z.ZodEffects<z.ZodEnum<["true", "false"]>, boolean, "true" | "false">>;
597
+ cursor: z.ZodOptional<z.ZodString>;
598
+ perPage: z.ZodDefault<z.ZodNumber>;
599
+ }, "strip", z.ZodTypeAny, {
600
+ perPage: number;
601
+ category?: string | undefined;
602
+ read?: boolean | undefined;
603
+ cursor?: string | undefined;
604
+ }, {
605
+ category?: string | undefined;
606
+ read?: "true" | "false" | undefined;
607
+ cursor?: string | undefined;
608
+ perPage?: number | undefined;
609
+ }>;
610
+ type ListNotificationsQuery = z.infer<typeof listNotificationsQuerySchema>;
611
+ /**
612
+ * Forma normalizada do recibo de entrega, depois que o parser do driver traduziu o payload do
613
+ * provedor. A verificação de assinatura acontece antes disto, sobre o `rawBody`.
614
+ */
615
+ declare const deliveryWebhookSchema: z.ZodObject<{
616
+ providerMessageId: z.ZodString;
617
+ status: z.ZodEnum<["delivered", "bounced", "failed"]>;
618
+ errorCode: z.ZodOptional<z.ZodString>;
619
+ occurredAt: z.ZodDate;
620
+ suppressionReason: z.ZodOptional<z.ZodNativeEnum<{
621
+ readonly BOUNCE: "bounce";
622
+ readonly COMPLAINT: "complaint";
623
+ readonly OPT_OUT: "opt_out";
624
+ }>>;
625
+ }, "strip", z.ZodTypeAny, {
626
+ status: "failed" | "delivered" | "bounced";
627
+ providerMessageId: string;
628
+ occurredAt: Date;
629
+ errorCode?: string | undefined;
630
+ suppressionReason?: "bounce" | "complaint" | "opt_out" | undefined;
631
+ }, {
632
+ status: "failed" | "delivered" | "bounced";
633
+ providerMessageId: string;
634
+ occurredAt: Date;
635
+ errorCode?: string | undefined;
636
+ suppressionReason?: "bounce" | "complaint" | "opt_out" | undefined;
637
+ }>;
638
+ type DeliveryWebhookBody = z.infer<typeof deliveryWebhookSchema>;
639
+
640
+ /**
641
+ * Copyright (c) 2026 Ada Technology. MIT License.
642
+ */
643
+
644
+ /**
645
+ * Eventos de domínio — os pontos de extensão do produto. É aqui que entra a regra de negócio que
646
+ * o módulo não pode ter (ex.: bounce de e-mail marca o contato como inválido no CRM), sem
647
+ * ninguém editar código do pacote (regra de módulos plugáveis, §3).
648
+ */
649
+ declare const NOTIFICATION_EVENT: {
650
+ readonly CREATED: "notification.created";
651
+ readonly DISPATCHED: "notification.dispatched";
652
+ readonly READ: "notification.read";
653
+ readonly DELIVERY_SENT: "delivery.sent";
654
+ readonly DELIVERY_FAILED: "delivery.failed";
655
+ readonly DELIVERY_BOUNCED: "delivery.bounced";
656
+ readonly DEVICE_REGISTERED: "device.registered";
657
+ readonly DEVICE_INVALIDATED: "device.invalidated";
658
+ readonly PREFERENCES_UPDATED: "preferences.updated";
659
+ };
660
+ type NotificationEvent = (typeof NOTIFICATION_EVENT)[keyof typeof NOTIFICATION_EVENT];
661
+ type BaseEvent = {
662
+ readonly companyId: CompanyId;
663
+ readonly occurredAt: Date;
664
+ };
665
+ type NotificationCreatedEvent = BaseEvent & {
666
+ readonly notificationId: NotificationId;
667
+ readonly recipientUserId: UserId;
668
+ readonly category: string;
669
+ readonly templateKey: string;
670
+ /** Canais que sobreviveram ao fan-out; os pulados aparecem em `skippedChannels`. */
671
+ readonly channels: readonly NotificationChannel[];
672
+ readonly skippedChannels: readonly {
673
+ readonly channel: NotificationChannel;
674
+ readonly reason: string;
675
+ }[];
676
+ };
677
+ type NotificationDispatchedEvent = BaseEvent & {
678
+ readonly notificationId: NotificationId;
679
+ readonly status: NotificationStatus;
680
+ };
681
+ type NotificationReadEvent = BaseEvent & {
682
+ readonly notificationId: NotificationId;
683
+ readonly recipientUserId: UserId;
684
+ };
685
+ type DeliverySentEvent = BaseEvent & {
686
+ readonly notificationId: NotificationId;
687
+ readonly deliveryId: string;
688
+ readonly channel: NotificationChannel;
689
+ readonly providerMessageId?: string;
690
+ readonly attempt: number;
691
+ };
692
+ type DeliveryFailedEvent = BaseEvent & {
693
+ readonly notificationId: NotificationId;
694
+ readonly deliveryId: string;
695
+ readonly channel: NotificationChannel;
696
+ readonly errorCode: string;
697
+ readonly attempt: number;
698
+ /** `false` quando o retry esgotou ou o erro é permanente — é o gancho para alerta do host. */
699
+ readonly willRetry: boolean;
700
+ };
701
+ type DeliveryBouncedEvent = BaseEvent & {
702
+ readonly notificationId: NotificationId;
703
+ readonly deliveryId: string;
704
+ readonly channel: NotificationChannel;
705
+ readonly reason: SuppressionReason;
706
+ };
707
+ type DeviceRegisteredEvent = BaseEvent & {
708
+ readonly deviceId: string;
709
+ readonly userId: UserId;
710
+ readonly platform: DevicePlatform;
711
+ readonly driver: PushDriver;
712
+ };
713
+ type DeviceInvalidatedEvent = BaseEvent & {
714
+ readonly deviceId: string;
715
+ readonly userId: UserId;
716
+ readonly driver: PushDriver;
717
+ readonly errorCode: string;
718
+ };
719
+ type PreferencesUpdatedEvent = BaseEvent & {
720
+ readonly userId: UserId;
721
+ readonly categories: readonly string[];
722
+ };
723
+ /**
724
+ * Hooks são `void`-tolerantes de propósito: falha de hook do produto não pode derrubar a entrega
725
+ * da notificação. O módulo loga e segue — quem precisa de garantia transacional usa a fila.
726
+ */
727
+ type NotificationHooks = {
728
+ onNotificationCreated?(event: NotificationCreatedEvent): Promise<void> | void;
729
+ onNotificationDispatched?(event: NotificationDispatchedEvent): Promise<void> | void;
730
+ onNotificationRead?(event: NotificationReadEvent): Promise<void> | void;
731
+ onDeliverySent?(event: DeliverySentEvent): Promise<void> | void;
732
+ onDeliveryFailed?(event: DeliveryFailedEvent): Promise<void> | void;
733
+ onDeliveryBounced?(event: DeliveryBouncedEvent): Promise<void> | void;
734
+ onDeviceRegistered?(event: DeviceRegisteredEvent): Promise<void> | void;
735
+ onDeviceInvalidated?(event: DeviceInvalidatedEvent): Promise<void> | void;
736
+ onPreferencesUpdated?(event: PreferencesUpdatedEvent): Promise<void> | void;
737
+ };
738
+
739
+ /**
740
+ * Copyright (c) 2026 Ada Technology. MIT License.
741
+ */
742
+
743
+ /**
744
+ * Hierarquia autocontida: um pacote publicado não importa o `DomainError` do host. O host mapeia
745
+ * estes erros no seu exception filter — e o próprio módulo já traz um, para o consumidor das rotas
746
+ * não precisar escrever `try/catch` por endpoint.
747
+ */
748
+ declare class NotificationError extends Error {
749
+ readonly statusCode: number;
750
+ readonly code: string;
751
+ readonly details?: Record<string, unknown> | undefined;
752
+ constructor(message: string, statusCode: number, code: string, details?: Record<string, unknown> | undefined);
753
+ }
754
+ declare const NOTIFICATION_ERROR_CODES: {
755
+ readonly TEMPLATE_NOT_FOUND: "NOTIFICATION_TEMPLATE_NOT_FOUND";
756
+ readonly CHANNEL_NOT_CONFIGURED: "NOTIFICATION_CHANNEL_NOT_CONFIGURED";
757
+ readonly RECIPIENT_UNRESOLVED: "NOTIFICATION_RECIPIENT_UNRESOLVED";
758
+ readonly SUPPRESSED_TARGET: "NOTIFICATION_SUPPRESSED_TARGET";
759
+ readonly NOT_FOUND: "NOTIFICATION_NOT_FOUND";
760
+ readonly INVALID_WEBHOOK_SIGNATURE: "NOTIFICATION_INVALID_WEBHOOK_SIGNATURE";
761
+ readonly DUPLICATE_WEBHOOK_DELIVERY: "NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY";
762
+ readonly DEVICE_NOT_FOUND: "NOTIFICATION_DEVICE_NOT_FOUND";
763
+ readonly THROTTLED: "NOTIFICATION_THROTTLED";
764
+ readonly CONFIG_MISSING: "NOTIFICATION_CONFIG_MISSING";
765
+ };
766
+ declare class TemplateNotFoundError extends NotificationError {
767
+ readonly templateKey: string;
768
+ readonly channel: NotificationChannel;
769
+ readonly locale: string;
770
+ constructor(templateKey: string, channel: NotificationChannel, locale: string);
771
+ }
772
+ /** Canal ligado em `features` sem driver injetado — erro de composição, detectado no boot. */
773
+ declare class ChannelNotConfiguredError extends NotificationError {
774
+ readonly channel: NotificationChannel;
775
+ constructor(channel: NotificationChannel);
776
+ }
777
+ /**
778
+ * `RecipientResolverPort` não devolveu endereço para o canal. Mensagem sem PII de propósito: o
779
+ * `userId` é identificador opaco, o e-mail ou telefone jamais entra no erro (`security.md` §1).
780
+ */
781
+ declare class RecipientUnresolvedError extends NotificationError {
782
+ readonly userId: string;
783
+ readonly channel: NotificationChannel;
784
+ constructor(userId: string, channel: NotificationChannel);
785
+ }
786
+ declare class SuppressedTargetError extends NotificationError {
787
+ readonly channel: NotificationChannel;
788
+ readonly reason: string;
789
+ constructor(channel: NotificationChannel, reason: string);
790
+ }
791
+ /**
792
+ * Também é a resposta para notificação de OUTRO usuário: devolver 404 em vez de 403 não revela a
793
+ * existência do recurso a quem não pode vê-lo (BOLA/API1).
794
+ */
795
+ declare class NotificationNotFoundError extends NotificationError {
796
+ readonly notificationId: string;
797
+ constructor(notificationId: string);
798
+ }
799
+ declare class InvalidWebhookSignatureError extends NotificationError {
800
+ constructor();
801
+ }
802
+ /** Recibo reenviado dentro da janela de replay (nonce já visto) — não é erro, é ruído esperado. */
803
+ declare class DuplicateWebhookDeliveryError extends NotificationError {
804
+ readonly nonce: string;
805
+ constructor(nonce: string);
806
+ }
807
+ declare class DeviceNotFoundError extends NotificationError {
808
+ readonly deviceId: string;
809
+ constructor(deviceId: string);
810
+ }
811
+ declare class ThrottledError extends NotificationError {
812
+ readonly channel: NotificationChannel;
813
+ readonly retryAfterSeconds: number;
814
+ constructor(channel: NotificationChannel, retryAfterSeconds: number);
815
+ }
816
+ /**
817
+ * Configuração obrigatória ausente (chave de HMAC, segredo de webhook) — falha no boot.
818
+ *
819
+ * Único erro do módulo cuja mensagem nomeia o campo: ele é lido por quem está subindo o serviço,
820
+ * não devolvido a um cliente, e "algo está faltando" sem dizer o quê custa uma bisca no código.
821
+ * O nome do campo é identificador de configuração, nunca valor — o segredo em si não aparece.
822
+ */
823
+ declare class ConfigMissingError extends NotificationError {
824
+ readonly field: string;
825
+ constructor(field: string);
826
+ }
827
+
828
+ /**
829
+ * Copyright (c) 2026 Ada Technology. MIT License.
830
+ */
831
+
832
+ /**
833
+ * Forma mínima que o `channel` do `meta-whatsapp-module` já satisfaz. Descrita aqui por
834
+ * *estrutura*, e não importada do pacote de WhatsApp: é isso que mantém os dois trios
835
+ * independentes — quem só usa inbox não carrega Meta, quem só usa WhatsApp não carrega
836
+ * notificação, e a costura acontece no produto (regra de módulos plugáveis, §2).
837
+ */
838
+ type WhatsAppSendingChannel = {
839
+ sendText(to: string, body: string): Promise<{
840
+ externalMessageId: string | null;
841
+ }>;
842
+ sendTemplate(params: {
843
+ to: string;
844
+ templateName: string;
845
+ languageCode: string;
846
+ bodyParameters?: string[];
847
+ }): Promise<{
848
+ externalMessageId: string | null;
849
+ }>;
850
+ };
851
+ declare function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort;
852
+
853
+ export { type CachePort, type ChannelDrivers, ChannelNotConfiguredError, type ClockPort, type CompanyId, ConfigMissingError, DELIVERY_STATUS, DEVICE_PLATFORM, type DeliveryAttemptResult, type DeliveryBouncedEvent, type DeliveryFailedEvent, type DeliveryReceipt, type DeliverySentEvent, type DeliveryStatus, type DeliverySummary, type DeliveryWebhookBody, type DeviceInvalidatedEvent, DeviceNotFoundError, type DevicePlatform, type DeviceRegisteredEvent, type DeviceRegistration, DuplicateWebhookDeliveryError, EMAIL_DRIVER, type EmailDriver, type EmailDriverPort, INTRUSIVE_CHANNELS, InvalidWebhookSignatureError, type ListNotificationsParams, type ListNotificationsQuery, type ListNotificationsResult, type LogMeta, type LoggerPort, type MetricsPort, NOTIFICATION_CATEGORY_HINT, NOTIFICATION_CHANNEL, NOTIFICATION_ERROR_CODES, NOTIFICATION_EVENT, NOTIFICATION_STATUS, type NotificationChannel, type NotificationCreatedEvent, type NotificationDispatchedEvent, NotificationError, type NotificationEvent, type NotificationHooks, type NotificationId, type NotificationJob, NotificationNotFoundError, type NotificationPreference, type NotificationReadEvent, type NotificationStatus, type NotificationSummary, type NotificationTemplate, PUSH_DRIVER, type PreferencesUpdatedEvent, type PushDriver, type PushDriverPort, type QueuePort, type RealtimeEvent, type RealtimeNotifierPort, type RealtimeSubscription, type RecipientResolverPort, RecipientUnresolvedError, type RegisterDeviceBody, type RenderTemplateParams, type RenderedTemplate, type ResolvedRecipient, SUPPRESSION_REASON, type SendEmailParams, type SendNotificationBody, type SendNotificationParams, type SendNotificationResult, type SendPushParams, type SendSmsParams, type SendWhatsAppParams, type SendWhatsAppTemplateParams, type SmsDriverPort, SuppressedTargetError, type SuppressionReason, TemplateNotFoundError, type TemplateRendererPort, ThrottledError, type UpdatePreferencesBody, type UpsertTemplateBody, type UserId, type WhatsAppDriverPort, type WhatsAppSendingChannel, createWhatsAppDriverFromChannel, deliveryWebhookSchema, listNotificationsQuerySchema, preferenceEntrySchema, registerDeviceSchema, sendNotificationSchema, updatePreferencesSchema, upsertTemplateSchema };