@adatechnology/notification-contracts 0.1.0-rc.1 → 0.1.0-rc.2
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/dist/index.cjs +61 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +36 -1
- package/dist/index.d.ts +36 -1
- package/dist/index.js +56 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -45,9 +45,14 @@ __export(index_exports, {
|
|
|
45
45
|
ThrottledError: () => ThrottledError,
|
|
46
46
|
createWhatsAppDriverFromChannel: () => createWhatsAppDriverFromChannel,
|
|
47
47
|
deliveryWebhookSchema: () => deliveryWebhookSchema,
|
|
48
|
+
deriveTitleFromBody: () => deriveTitleFromBody,
|
|
49
|
+
escapeTemplateHtml: () => escapeTemplateHtml,
|
|
50
|
+
extractTemplatePlaceholders: () => extractTemplatePlaceholders,
|
|
51
|
+
interpolateTemplate: () => interpolateTemplate,
|
|
48
52
|
listNotificationsQuerySchema: () => listNotificationsQuerySchema,
|
|
49
53
|
preferenceEntrySchema: () => preferenceEntrySchema,
|
|
50
54
|
registerDeviceSchema: () => registerDeviceSchema,
|
|
55
|
+
renderTemplate: () => renderTemplate,
|
|
51
56
|
sendNotificationSchema: () => sendNotificationSchema,
|
|
52
57
|
updatePreferencesSchema: () => updatePreferencesSchema,
|
|
53
58
|
upsertTemplateSchema: () => upsertTemplateSchema
|
|
@@ -414,6 +419,57 @@ function createWhatsAppDriverFromChannel(channel) {
|
|
|
414
419
|
};
|
|
415
420
|
}
|
|
416
421
|
__name(createWhatsAppDriverFromChannel, "createWhatsAppDriverFromChannel");
|
|
422
|
+
|
|
423
|
+
// src/templateRender.ts
|
|
424
|
+
var PLACEHOLDER_PATTERN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
|
|
425
|
+
var DEFAULT_TITLE_MAX_LENGTH = 120;
|
|
426
|
+
var HTML_ESCAPE_MAP = {
|
|
427
|
+
"&": "&",
|
|
428
|
+
"<": "<",
|
|
429
|
+
">": ">",
|
|
430
|
+
'"': """,
|
|
431
|
+
"'": "'"
|
|
432
|
+
};
|
|
433
|
+
function escapeTemplateHtml(text) {
|
|
434
|
+
return text.replace(/[&<>"']/g, (character) => HTML_ESCAPE_MAP[character] ?? character);
|
|
435
|
+
}
|
|
436
|
+
__name(escapeTemplateHtml, "escapeTemplateHtml");
|
|
437
|
+
function interpolateTemplate(template, payload) {
|
|
438
|
+
return template.replace(PLACEHOLDER_PATTERN, (_match, key) => {
|
|
439
|
+
const value = payload[key];
|
|
440
|
+
return value === void 0 || value === null ? "" : String(value);
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
__name(interpolateTemplate, "interpolateTemplate");
|
|
444
|
+
function deriveTitleFromBody(body) {
|
|
445
|
+
const firstLine = body.split("\n")[0] ?? "";
|
|
446
|
+
return firstLine.length > DEFAULT_TITLE_MAX_LENGTH ? `${firstLine.slice(0, DEFAULT_TITLE_MAX_LENGTH)}\u2026` : firstLine;
|
|
447
|
+
}
|
|
448
|
+
__name(deriveTitleFromBody, "deriveTitleFromBody");
|
|
449
|
+
function extractTemplatePlaceholders(template) {
|
|
450
|
+
const found = /* @__PURE__ */ new Set();
|
|
451
|
+
for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {
|
|
452
|
+
if (match[1]) found.add(match[1]);
|
|
453
|
+
}
|
|
454
|
+
return [
|
|
455
|
+
...found
|
|
456
|
+
];
|
|
457
|
+
}
|
|
458
|
+
__name(extractTemplatePlaceholders, "extractTemplatePlaceholders");
|
|
459
|
+
function renderTemplate(params) {
|
|
460
|
+
const body = interpolateTemplate(params.body, params.payload);
|
|
461
|
+
const title = params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body);
|
|
462
|
+
if (params.channel !== "email") return {
|
|
463
|
+
title,
|
|
464
|
+
body
|
|
465
|
+
};
|
|
466
|
+
return {
|
|
467
|
+
title,
|
|
468
|
+
body,
|
|
469
|
+
html: escapeTemplateHtml(body).replace(/\n/g, "<br>")
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
__name(renderTemplate, "renderTemplate");
|
|
417
473
|
// Annotate the CommonJS export names for ESM import in node:
|
|
418
474
|
0 && (module.exports = {
|
|
419
475
|
ChannelNotConfiguredError,
|
|
@@ -440,9 +496,14 @@ __name(createWhatsAppDriverFromChannel, "createWhatsAppDriverFromChannel");
|
|
|
440
496
|
ThrottledError,
|
|
441
497
|
createWhatsAppDriverFromChannel,
|
|
442
498
|
deliveryWebhookSchema,
|
|
499
|
+
deriveTitleFromBody,
|
|
500
|
+
escapeTemplateHtml,
|
|
501
|
+
extractTemplatePlaceholders,
|
|
502
|
+
interpolateTemplate,
|
|
443
503
|
listNotificationsQuerySchema,
|
|
444
504
|
preferenceEntrySchema,
|
|
445
505
|
registerDeviceSchema,
|
|
506
|
+
renderTemplate,
|
|
446
507
|
sendNotificationSchema,
|
|
447
508
|
updatePreferencesSchema,
|
|
448
509
|
upsertTemplateSchema
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/notification.types.ts","../src/schemas.ts","../src/events.ts","../src/errors.ts","../src/whatsappDriver.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport {\n NOTIFICATION_CHANNEL,\n INTRUSIVE_CHANNELS,\n NOTIFICATION_STATUS,\n DELIVERY_STATUS,\n DEVICE_PLATFORM,\n PUSH_DRIVER,\n EMAIL_DRIVER,\n SUPPRESSION_REASON,\n NOTIFICATION_CATEGORY_HINT,\n} from './notification.types'\nexport type {\n NotificationChannel,\n NotificationStatus,\n DeliveryStatus,\n DevicePlatform,\n PushDriver,\n EmailDriver,\n SuppressionReason,\n NotificationId,\n CompanyId,\n UserId,\n NotificationSummary,\n DeliverySummary,\n DeviceRegistration,\n NotificationPreference,\n NotificationTemplate,\n SendNotificationParams,\n SendNotificationResult,\n ListNotificationsParams,\n ListNotificationsResult,\n DeliveryReceipt,\n} from './notification.types'\n\nexport type {\n DeliveryAttemptResult,\n SendPushParams,\n SendEmailParams,\n SendWhatsAppParams,\n SendWhatsAppTemplateParams,\n SendSmsParams,\n PushDriverPort,\n EmailDriverPort,\n WhatsAppDriverPort,\n SmsDriverPort,\n ChannelDrivers,\n} from './channelDrivers'\n\nexport type {\n ResolvedRecipient,\n RecipientResolverPort,\n NotificationJob,\n QueuePort,\n RenderTemplateParams,\n RenderedTemplate,\n TemplateRendererPort,\n CachePort,\n RealtimeNotifierPort,\n RealtimeEvent,\n RealtimeSubscription,\n ClockPort,\n LogMeta,\n LoggerPort,\n MetricsPort,\n} from './providers'\n\nexport {\n sendNotificationSchema,\n registerDeviceSchema,\n preferenceEntrySchema,\n updatePreferencesSchema,\n upsertTemplateSchema,\n listNotificationsQuerySchema,\n deliveryWebhookSchema,\n} from './schemas'\nexport type {\n SendNotificationBody,\n RegisterDeviceBody,\n UpdatePreferencesBody,\n UpsertTemplateBody,\n ListNotificationsQuery,\n DeliveryWebhookBody,\n} from './schemas'\n\nexport { NOTIFICATION_EVENT } from './events'\nexport type {\n NotificationEvent,\n NotificationCreatedEvent,\n NotificationDispatchedEvent,\n NotificationReadEvent,\n DeliverySentEvent,\n DeliveryFailedEvent,\n DeliveryBouncedEvent,\n DeviceRegisteredEvent,\n DeviceInvalidatedEvent,\n PreferencesUpdatedEvent,\n NotificationHooks,\n} from './events'\n\nexport {\n NotificationError,\n NOTIFICATION_ERROR_CODES,\n TemplateNotFoundError,\n ChannelNotConfiguredError,\n RecipientUnresolvedError,\n SuppressedTargetError,\n NotificationNotFoundError,\n InvalidWebhookSignatureError,\n DuplicateWebhookDeliveryError,\n DeviceNotFoundError,\n ThrottledError,\n ConfigMissingError,\n} from './errors'\n\nexport { createWhatsAppDriverFromChannel } from './whatsappDriver'\nexport type { WhatsAppSendingChannel } from './whatsappDriver'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport const NOTIFICATION_CHANNEL = {\n INBOX: 'inbox',\n PUSH: 'push',\n EMAIL: 'email',\n WHATSAPP: 'whatsapp',\n SMS: 'sms',\n} as const\nexport type NotificationChannel = (typeof NOTIFICATION_CHANNEL)[keyof typeof NOTIFICATION_CHANNEL]\n\n/** Canais que interrompem o destinatário e por isso respeitam quiet hours (ver spec §10.4). */\nexport const INTRUSIVE_CHANNELS: readonly NotificationChannel[] = [\n NOTIFICATION_CHANNEL.PUSH,\n NOTIFICATION_CHANNEL.WHATSAPP,\n NOTIFICATION_CHANNEL.SMS,\n]\n\nexport const NOTIFICATION_STATUS = {\n PENDING: 'pending',\n SCHEDULED: 'scheduled',\n QUEUED: 'queued',\n DISPATCHED: 'dispatched',\n PARTIALLY_FAILED: 'partially_failed',\n FAILED: 'failed',\n} as const\nexport type NotificationStatus = (typeof NOTIFICATION_STATUS)[keyof typeof NOTIFICATION_STATUS]\n\nexport const DELIVERY_STATUS = {\n QUEUED: 'queued',\n SENT: 'sent',\n DELIVERED: 'delivered',\n FAILED: 'failed',\n BOUNCED: 'bounced',\n SKIPPED: 'skipped',\n} as const\nexport type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS]\n\nexport const DEVICE_PLATFORM = {\n IOS: 'ios',\n ANDROID: 'android',\n WEB: 'web',\n} as const\nexport type DevicePlatform = (typeof DEVICE_PLATFORM)[keyof typeof DEVICE_PLATFORM]\n\nexport const PUSH_DRIVER = {\n EXPO: 'expo',\n FCM: 'fcm',\n} as const\nexport type PushDriver = (typeof PUSH_DRIVER)[keyof typeof PUSH_DRIVER]\n\nexport const EMAIL_DRIVER = {\n SMTP: 'smtp',\n RESEND: 'resend',\n SES: 'ses',\n} as const\nexport type EmailDriver = (typeof EMAIL_DRIVER)[keyof typeof EMAIL_DRIVER]\n\nexport const SUPPRESSION_REASON = {\n BOUNCE: 'bounce',\n COMPLAINT: 'complaint',\n OPT_OUT: 'opt_out',\n} as const\nexport type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON]\n\n/**\n * Sugestão de nomenclatura, sem valor normativo (decisão Q2 da spec). `category` é `varchar`\n * livre porque é vocabulário de negócio do produto — fechá-la num enum aqui obrigaria uma major\n * do pacote a cada produto novo.\n */\nexport const NOTIFICATION_CATEGORY_HINT = {\n ORDER_STATUS: 'order_status',\n PAYMENT: 'payment',\n SECURITY: 'security',\n MARKETING: 'marketing',\n SYSTEM: 'system',\n} as const\n\nexport type NotificationId = string\nexport type CompanyId = string\nexport type UserId = string\n\nexport type NotificationSummary = {\n readonly id: NotificationId\n readonly category: string\n readonly templateKey: string\n readonly title: string\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n readonly status: NotificationStatus\n readonly scheduledFor?: string\n readonly readAt?: string\n readonly createdAt: string\n}\n\nexport type DeliverySummary = {\n readonly id: string\n readonly notificationId: NotificationId\n readonly channel: NotificationChannel\n readonly driver?: string\n /** Nunca o endereço em claro: `****1234`, `a***@dominio.com` (LGPD — ver spec §5). */\n readonly targetMasked?: string\n readonly status: DeliveryStatus\n readonly attempt: number\n readonly providerMessageId?: string\n readonly errorCode?: string\n readonly sentAt?: string\n readonly deliveredAt?: string\n readonly failedAt?: string\n}\n\nexport type DeviceRegistration = {\n readonly id: string\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n readonly lastSeenAt: string\n readonly disabledAt?: string\n readonly disabledReason?: string\n}\n\nexport type NotificationPreference = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\n /** `HH:mm` no timezone resolvido para o destinatário; ambos ausentes = sem janela de silêncio. */\n readonly quietHoursStart?: string\n readonly quietHoursEnd?: string\n readonly timezone?: string\n}\n\nexport type NotificationTemplate = {\n readonly id: string\n readonly key: string\n readonly channel: NotificationChannel\n readonly locale: string\n readonly version: number\n readonly subject?: string\n readonly body: string\n /**\n * Nome do template aprovado na Meta. Sem ele, o canal WhatsApp é pulado fora da janela de 24 h\n * em vez de estourar erro na cara do usuário (spec §10.7).\n */\n readonly whatsappTemplateName?: string\n readonly active: boolean\n}\n\nexport type SendNotificationParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n readonly payload?: Readonly<Record<string, unknown>>\n /** Sem canais explícitos, o fan-out resolve pelas preferências do destinatário. */\n readonly channels?: readonly NotificationChannel[]\n /** Chave de negócio da entrega. Repetição devolve a notificação existente, não uma nova. */\n readonly dedupeKey?: string\n readonly scheduledFor?: Date\n readonly locale?: string\n}\n\nexport type SendNotificationResult = {\n readonly notificationId: NotificationId\n /** `true` quando um `dedupeKey` já visto devolveu a notificação anterior — nada foi reenviado. */\n readonly deduplicated: boolean\n readonly deliveries: readonly DeliverySummary[]\n}\n\nexport type ListNotificationsParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsResult = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type DeliveryReceipt = {\n readonly providerMessageId: string\n readonly status: Extract<DeliveryStatus, 'delivered' | 'bounced' | 'failed'>\n readonly errorCode?: string\n readonly occurredAt: Date\n readonly suppressionReason?: SuppressionReason\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { z } from 'zod'\n\nimport { DEVICE_PLATFORM, NOTIFICATION_CHANNEL, PUSH_DRIVER, SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Schemas de fronteira. Regra que atravessa todos eles: **`companyId` nunca vem do corpo da\n * requisição** — é derivado do contexto autenticado (`database.md`, \"Consistência e\n * multiempresa\"). Aceitá-lo aqui seria entregar o isolamento multiempresa ao cliente.\n */\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/\nconst MAX_PER_PAGE = 100\n\nconst quietHoursShape = {\n quietHoursStart: z.string().regex(HHMM, 'Use HH:mm').optional(),\n quietHoursEnd: z.string().regex(HHMM, 'Use HH:mm').optional(),\n timezone: z.string().min(1).optional(),\n}\n\nexport const sendNotificationSchema = z.object({\n recipientUserId: z.string().uuid(),\n category: z.string().min(1).max(64),\n templateKey: z.string().min(1).max(128),\n payload: z.record(z.unknown()).optional(),\n channels: z.array(z.nativeEnum(NOTIFICATION_CHANNEL)).nonempty().optional(),\n dedupeKey: z.string().min(1).max(256).optional(),\n scheduledFor: z.coerce.date().optional(),\n locale: z.string().min(2).max(16).optional(),\n})\nexport type SendNotificationBody = z.infer<typeof sendNotificationSchema>\n\nexport const registerDeviceSchema = z.object({\n platform: z.nativeEnum(DEVICE_PLATFORM),\n driver: z.nativeEnum(PUSH_DRIVER),\n token: z.string().min(1).max(4096),\n appVersion: z.string().max(32).optional(),\n locale: z.string().min(2).max(16).optional(),\n timezone: z.string().min(1).max(64).optional(),\n})\nexport type RegisterDeviceBody = z.infer<typeof registerDeviceSchema>\n\nexport const preferenceEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n ...quietHoursShape,\n})\n\nexport const updatePreferencesSchema = z.object({\n preferences: z.array(preferenceEntrySchema).max(200),\n})\nexport type UpdatePreferencesBody = z.infer<typeof updatePreferencesSchema>\n\nexport const upsertTemplateSchema = z.object({\n key: z.string().min(1).max(128),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n locale: z.string().min(2).max(16),\n subject: z.string().max(256).optional(),\n body: z.string().min(1).max(8192),\n whatsappTemplateName: z.string().max(128).optional(),\n active: z.boolean().default(true),\n})\nexport type UpsertTemplateBody = z.infer<typeof upsertTemplateSchema>\n\n/** Query string chega sempre como texto — daí o `coerce` e o booleano por literal. */\nexport const listNotificationsQuerySchema = z.object({\n category: z.string().min(1).max(64).optional(),\n read: z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional(),\n cursor: z.string().max(512).optional(),\n perPage: z.coerce.number().int().min(1).max(MAX_PER_PAGE).default(20),\n})\nexport type ListNotificationsQuery = z.infer<typeof listNotificationsQuerySchema>\n\n/**\n * Forma normalizada do recibo de entrega, depois que o parser do driver traduziu o payload do\n * provedor. A verificação de assinatura acontece antes disto, sobre o `rawBody`.\n */\nexport const deliveryWebhookSchema = z.object({\n providerMessageId: z.string().min(1),\n status: z.enum(['delivered', 'bounced', 'failed']),\n errorCode: z.string().max(64).optional(),\n occurredAt: z.coerce.date(),\n suppressionReason: z.nativeEnum(SUPPRESSION_REASON).optional(),\n})\nexport type DeliveryWebhookBody = z.infer<typeof deliveryWebhookSchema>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type {\n CompanyId,\n DevicePlatform,\n NotificationChannel,\n NotificationId,\n NotificationStatus,\n PushDriver,\n SuppressionReason,\n UserId,\n} from './notification.types'\n\n/**\n * Eventos de domínio — os pontos de extensão do produto. É aqui que entra a regra de negócio que\n * o módulo não pode ter (ex.: bounce de e-mail marca o contato como inválido no CRM), sem\n * ninguém editar código do pacote (regra de módulos plugáveis, §3).\n */\nexport const NOTIFICATION_EVENT = {\n CREATED: 'notification.created',\n DISPATCHED: 'notification.dispatched',\n READ: 'notification.read',\n DELIVERY_SENT: 'delivery.sent',\n DELIVERY_FAILED: 'delivery.failed',\n DELIVERY_BOUNCED: 'delivery.bounced',\n DEVICE_REGISTERED: 'device.registered',\n DEVICE_INVALIDATED: 'device.invalidated',\n PREFERENCES_UPDATED: 'preferences.updated',\n} as const\nexport type NotificationEvent = (typeof NOTIFICATION_EVENT)[keyof typeof NOTIFICATION_EVENT]\n\ntype BaseEvent = {\n readonly companyId: CompanyId\n readonly occurredAt: Date\n}\n\nexport type NotificationCreatedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n /** Canais que sobreviveram ao fan-out; os pulados aparecem em `skippedChannels`. */\n readonly channels: readonly NotificationChannel[]\n readonly skippedChannels: readonly { readonly channel: NotificationChannel; readonly reason: string }[]\n}\n\nexport type NotificationDispatchedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly status: NotificationStatus\n}\n\nexport type NotificationReadEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n}\n\nexport type DeliverySentEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly providerMessageId?: string\n readonly attempt: number\n}\n\nexport type DeliveryFailedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly errorCode: string\n readonly attempt: number\n /** `false` quando o retry esgotou ou o erro é permanente — é o gancho para alerta do host. */\n readonly willRetry: boolean\n}\n\nexport type DeliveryBouncedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly reason: SuppressionReason\n}\n\nexport type DeviceRegisteredEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n}\n\nexport type DeviceInvalidatedEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly driver: PushDriver\n readonly errorCode: string\n}\n\nexport type PreferencesUpdatedEvent = BaseEvent & {\n readonly userId: UserId\n readonly categories: readonly string[]\n}\n\n/**\n * Hooks são `void`-tolerantes de propósito: falha de hook do produto não pode derrubar a entrega\n * da notificação. O módulo loga e segue — quem precisa de garantia transacional usa a fila.\n */\nexport type NotificationHooks = {\n onNotificationCreated?(event: NotificationCreatedEvent): Promise<void> | void\n onNotificationDispatched?(event: NotificationDispatchedEvent): Promise<void> | void\n onNotificationRead?(event: NotificationReadEvent): Promise<void> | void\n onDeliverySent?(event: DeliverySentEvent): Promise<void> | void\n onDeliveryFailed?(event: DeliveryFailedEvent): Promise<void> | void\n onDeliveryBounced?(event: DeliveryBouncedEvent): Promise<void> | void\n onDeviceRegistered?(event: DeviceRegisteredEvent): Promise<void> | void\n onDeviceInvalidated?(event: DeviceInvalidatedEvent): Promise<void> | void\n onPreferencesUpdated?(event: PreferencesUpdatedEvent): Promise<void> | void\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { NotificationChannel } from './notification.types'\n\n/**\n * Hierarquia autocontida: um pacote publicado não importa o `DomainError` do host. O host mapeia\n * estes erros no seu exception filter — e o próprio módulo já traz um, para o consumidor das rotas\n * não precisar escrever `try/catch` por endpoint.\n */\nexport class NotificationError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'NotificationError'\n }\n}\n\nexport const NOTIFICATION_ERROR_CODES = {\n TEMPLATE_NOT_FOUND: 'NOTIFICATION_TEMPLATE_NOT_FOUND',\n CHANNEL_NOT_CONFIGURED: 'NOTIFICATION_CHANNEL_NOT_CONFIGURED',\n RECIPIENT_UNRESOLVED: 'NOTIFICATION_RECIPIENT_UNRESOLVED',\n SUPPRESSED_TARGET: 'NOTIFICATION_SUPPRESSED_TARGET',\n NOT_FOUND: 'NOTIFICATION_NOT_FOUND',\n INVALID_WEBHOOK_SIGNATURE: 'NOTIFICATION_INVALID_WEBHOOK_SIGNATURE',\n DUPLICATE_WEBHOOK_DELIVERY: 'NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY',\n DEVICE_NOT_FOUND: 'NOTIFICATION_DEVICE_NOT_FOUND',\n THROTTLED: 'NOTIFICATION_THROTTLED',\n CONFIG_MISSING: 'NOTIFICATION_CONFIG_MISSING',\n} as const\n\nexport class TemplateNotFoundError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly channel: NotificationChannel,\n public readonly locale: string,\n ) {\n super(\n `Template não encontrado para a chave informada neste canal e locale.`,\n 404,\n NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND,\n { templateKey, channel, locale },\n )\n }\n}\n\n/** Canal ligado em `features` sem driver injetado — erro de composição, detectado no boot. */\nexport class ChannelNotConfiguredError extends NotificationError {\n constructor(public readonly channel: NotificationChannel) {\n super(\n `Canal habilitado sem driver injetado — injete o driver em providers.channels ou desligue a feature.`,\n 500,\n NOTIFICATION_ERROR_CODES.CHANNEL_NOT_CONFIGURED,\n { channel },\n )\n }\n}\n\n/**\n * `RecipientResolverPort` não devolveu endereço para o canal. Mensagem sem PII de propósito: o\n * `userId` é identificador opaco, o e-mail ou telefone jamais entra no erro (`security.md` §1).\n */\nexport class RecipientUnresolvedError extends NotificationError {\n constructor(\n public readonly userId: string,\n public readonly channel: NotificationChannel,\n ) {\n super(`Destinatário sem endereço utilizável para este canal.`, 422, NOTIFICATION_ERROR_CODES.RECIPIENT_UNRESOLVED, {\n userId,\n channel,\n })\n }\n}\n\nexport class SuppressedTargetError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly reason: string,\n ) {\n super(`Endereço suprimido para este canal — envio bloqueado.`, 409, NOTIFICATION_ERROR_CODES.SUPPRESSED_TARGET, {\n channel,\n reason,\n })\n }\n}\n\n/**\n * Também é a resposta para notificação de OUTRO usuário: devolver 404 em vez de 403 não revela a\n * existência do recurso a quem não pode vê-lo (BOLA/API1).\n */\nexport class NotificationNotFoundError extends NotificationError {\n constructor(public readonly notificationId: string) {\n super(`Notificação não encontrada.`, 404, NOTIFICATION_ERROR_CODES.NOT_FOUND, { notificationId })\n }\n}\n\nexport class InvalidWebhookSignatureError extends NotificationError {\n constructor() {\n super(`Assinatura do webhook inválida.`, 401, NOTIFICATION_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE)\n }\n}\n\n/** Recibo reenviado dentro da janela de replay (nonce já visto) — não é erro, é ruído esperado. */\nexport class DuplicateWebhookDeliveryError extends NotificationError {\n constructor(public readonly nonce: string) {\n super(`Entrega de webhook duplicada.`, 200, NOTIFICATION_ERROR_CODES.DUPLICATE_WEBHOOK_DELIVERY, { nonce })\n }\n}\n\nexport class DeviceNotFoundError extends NotificationError {\n constructor(public readonly deviceId: string) {\n super(`Dispositivo não encontrado.`, 404, NOTIFICATION_ERROR_CODES.DEVICE_NOT_FOUND, { deviceId })\n }\n}\n\nexport class ThrottledError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly retryAfterSeconds: number,\n ) {\n super(`Limite de envios para este destinatário atingido.`, 429, NOTIFICATION_ERROR_CODES.THROTTLED, {\n channel,\n retryAfterSeconds,\n })\n }\n}\n\n/**\n * Configuração obrigatória ausente (chave de HMAC, segredo de webhook) — falha no boot.\n *\n * Único erro do módulo cuja mensagem nomeia o campo: ele é lido por quem está subindo o serviço,\n * não devolvido a um cliente, e \"algo está faltando\" sem dizer o quê custa uma bisca no código.\n * O nome do campo é identificador de configuração, nunca valor — o segredo em si não aparece.\n */\nexport class ConfigMissingError extends NotificationError {\n constructor(public readonly field: string) {\n super(`Configuração obrigatória ausente: ${field}.`, 500, NOTIFICATION_ERROR_CODES.CONFIG_MISSING, { field })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { DeliveryAttemptResult, SendWhatsAppParams, WhatsAppDriverPort } from './channelDrivers'\nimport { SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Forma mínima que o `channel` do `meta-whatsapp-module` já satisfaz. Descrita aqui por\n * *estrutura*, e não importada do pacote de WhatsApp: é isso que mantém os dois trios\n * independentes — quem só usa inbox não carrega Meta, quem só usa WhatsApp não carrega\n * notificação, e a costura acontece no produto (regra de módulos plugáveis, §2).\n */\nexport type WhatsAppSendingChannel = {\n sendText(to: string, body: string): Promise<{ externalMessageId: string | null }>\n sendTemplate(params: {\n to: string\n templateName: string\n languageCode: string\n bodyParameters?: string[]\n }): Promise<{ externalMessageId: string | null }>\n}\n\n/**\n * Códigos da Graph API que o canal repassa. A lista é curta de propósito: cobre o que muda a\n * decisão do módulo (apagar destino × tentar de novo × desistir) e nada além disso.\n */\nconst INVALID_TARGET_CODES = new Set([131026, 131051])\nconst PERMANENT_CODES = new Set([131047, 131031, 368])\nconst RETRIABLE_CODES = new Set([613, 130429, 131056])\n\nfunction readNumericField(error: unknown, field: string): number | undefined {\n if (typeof error !== 'object' || error === null || !(field in error)) return undefined\n const value = (error as Record<string, unknown>)[field]\n return typeof value === 'number' ? value : undefined\n}\n\nfunction classifyError(error: unknown): DeliveryAttemptResult {\n const metaCode = readNumericField(error, 'code')\n if (metaCode !== undefined) {\n if (INVALID_TARGET_CODES.has(metaCode)) {\n return {\n outcome: 'invalid_target',\n errorCode: `meta_${metaCode}`,\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n }\n }\n if (PERMANENT_CODES.has(metaCode)) return { outcome: 'permanent', errorCode: `meta_${metaCode}` }\n if (RETRIABLE_CODES.has(metaCode)) return { outcome: 'retriable', errorCode: `meta_${metaCode}` }\n }\n\n const statusCode = readNumericField(error, 'statusCode') ?? readNumericField(error, 'status')\n if (statusCode === 429 || (statusCode !== undefined && statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: `http_${statusCode}` }\n }\n if (statusCode !== undefined && statusCode >= 400) {\n return { outcome: 'permanent', errorCode: `http_${statusCode}` }\n }\n\n // Sem código nenhum é quase sempre falha de rede/DNS, que passa numa segunda tentativa. O risco\n // do palpite é limitado: o retry é finito (`attempts`) e termina em `failed` de qualquer forma.\n return { outcome: 'retriable', errorCode: 'unknown' }\n}\n\nexport function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort {\n return {\n async send(params: SendWhatsAppParams): Promise<DeliveryAttemptResult> {\n try {\n const result = params.template\n ? await channel.sendTemplate({\n to: params.to,\n templateName: params.template.templateName,\n languageCode: params.template.languageCode,\n bodyParameters: params.template.bodyParameters ? [...params.template.bodyParameters] : undefined,\n })\n : await channel.sendText(params.to, params.body)\n\n return { outcome: 'sent', providerMessageId: result.externalMessageId ?? undefined }\n } catch (error) {\n return classifyError(error)\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;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;UACXC,cAAcL,OAAOE,SAASG;UAC9BC,cAAcN,OAAOE,SAASI;UAC9BC,gBAAgBP,OAAOE,SAASK,iBAAiB;eAAIP,OAAOE,SAASK;cAAkBrB;QACzF,CAAA,IACA,MAAMY,QAAQU,SAASR,OAAOI,IAAIJ,OAAOS,IAAI;AAEjD,eAAO;UAAElB,SAAS;UAAQmB,mBAAmBT,OAAOU,qBAAqBzB;QAAU;MACrF,SAASF,OAAO;AACd,eAAOI,cAAcJ,KAAAA;MACvB;IACF;EACF;AACF;AAnBgBa;","names":["NOTIFICATION_CHANNEL","INBOX","PUSH","EMAIL","WHATSAPP","SMS","INTRUSIVE_CHANNELS","NOTIFICATION_STATUS","PENDING","SCHEDULED","QUEUED","DISPATCHED","PARTIALLY_FAILED","FAILED","DELIVERY_STATUS","SENT","DELIVERED","BOUNCED","SKIPPED","DEVICE_PLATFORM","IOS","ANDROID","WEB","PUSH_DRIVER","EXPO","FCM","EMAIL_DRIVER","SMTP","RESEND","SES","SUPPRESSION_REASON","BOUNCE","COMPLAINT","OPT_OUT","NOTIFICATION_CATEGORY_HINT","ORDER_STATUS","PAYMENT","SECURITY","MARKETING","SYSTEM","HHMM","MAX_PER_PAGE","quietHoursShape","quietHoursStart","z","string","regex","optional","quietHoursEnd","timezone","min","sendNotificationSchema","object","recipientUserId","uuid","category","max","templateKey","payload","record","unknown","channels","array","nativeEnum","NOTIFICATION_CHANNEL","nonempty","dedupeKey","scheduledFor","coerce","date","locale","registerDeviceSchema","platform","DEVICE_PLATFORM","driver","PUSH_DRIVER","token","appVersion","preferenceEntrySchema","channel","enabled","boolean","updatePreferencesSchema","preferences","upsertTemplateSchema","key","subject","body","whatsappTemplateName","active","default","listNotificationsQuerySchema","read","enum","transform","value","cursor","perPage","number","int","deliveryWebhookSchema","providerMessageId","status","errorCode","occurredAt","suppressionReason","SUPPRESSION_REASON","NOTIFICATION_EVENT","CREATED","DISPATCHED","READ","DELIVERY_SENT","DELIVERY_FAILED","DELIVERY_BOUNCED","DEVICE_REGISTERED","DEVICE_INVALIDATED","PREFERENCES_UPDATED","NotificationError","Error","message","statusCode","code","details","name","NOTIFICATION_ERROR_CODES","TEMPLATE_NOT_FOUND","CHANNEL_NOT_CONFIGURED","RECIPIENT_UNRESOLVED","SUPPRESSED_TARGET","NOT_FOUND","INVALID_WEBHOOK_SIGNATURE","DUPLICATE_WEBHOOK_DELIVERY","DEVICE_NOT_FOUND","THROTTLED","CONFIG_MISSING","TemplateNotFoundError","templateKey","channel","locale","ChannelNotConfiguredError","RecipientUnresolvedError","userId","SuppressedTargetError","reason","NotificationNotFoundError","notificationId","InvalidWebhookSignatureError","DuplicateWebhookDeliveryError","nonce","DeviceNotFoundError","deviceId","ThrottledError","retryAfterSeconds","ConfigMissingError","field","INVALID_TARGET_CODES","Set","PERMANENT_CODES","RETRIABLE_CODES","readNumericField","error","field","undefined","value","classifyError","metaCode","has","outcome","errorCode","suppressionReason","SUPPRESSION_REASON","BOUNCE","statusCode","createWhatsAppDriverFromChannel","channel","send","params","result","template","sendTemplate","to","templateName","languageCode","bodyParameters","sendText","body","providerMessageId","externalMessageId"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/notification.types.ts","../src/schemas.ts","../src/events.ts","../src/errors.ts","../src/whatsappDriver.ts","../src/templateRender.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport {\n NOTIFICATION_CHANNEL,\n INTRUSIVE_CHANNELS,\n NOTIFICATION_STATUS,\n DELIVERY_STATUS,\n DEVICE_PLATFORM,\n PUSH_DRIVER,\n EMAIL_DRIVER,\n SUPPRESSION_REASON,\n NOTIFICATION_CATEGORY_HINT,\n} from './notification.types'\nexport type {\n NotificationChannel,\n NotificationStatus,\n DeliveryStatus,\n DevicePlatform,\n PushDriver,\n EmailDriver,\n SuppressionReason,\n NotificationId,\n CompanyId,\n UserId,\n NotificationSummary,\n DeliverySummary,\n DeviceRegistration,\n NotificationPreference,\n NotificationTemplate,\n SendNotificationParams,\n SendNotificationResult,\n ListNotificationsParams,\n ListNotificationsResult,\n DeliveryReceipt,\n} from './notification.types'\n\nexport type {\n DeliveryAttemptResult,\n SendPushParams,\n SendEmailParams,\n SendWhatsAppParams,\n SendWhatsAppTemplateParams,\n SendSmsParams,\n PushDriverPort,\n EmailDriverPort,\n WhatsAppDriverPort,\n SmsDriverPort,\n ChannelDrivers,\n} from './channelDrivers'\n\nexport type {\n ResolvedRecipient,\n RecipientResolverPort,\n NotificationJob,\n QueuePort,\n RenderTemplateParams,\n RenderedTemplate,\n TemplateRendererPort,\n CachePort,\n RealtimeNotifierPort,\n RealtimeEvent,\n RealtimeSubscription,\n ClockPort,\n LogMeta,\n LoggerPort,\n MetricsPort,\n} from './providers'\n\nexport {\n sendNotificationSchema,\n registerDeviceSchema,\n preferenceEntrySchema,\n updatePreferencesSchema,\n upsertTemplateSchema,\n listNotificationsQuerySchema,\n deliveryWebhookSchema,\n} from './schemas'\nexport type {\n SendNotificationBody,\n RegisterDeviceBody,\n UpdatePreferencesBody,\n UpsertTemplateBody,\n ListNotificationsQuery,\n DeliveryWebhookBody,\n} from './schemas'\n\nexport { NOTIFICATION_EVENT } from './events'\nexport type {\n NotificationEvent,\n NotificationCreatedEvent,\n NotificationDispatchedEvent,\n NotificationReadEvent,\n DeliverySentEvent,\n DeliveryFailedEvent,\n DeliveryBouncedEvent,\n DeviceRegisteredEvent,\n DeviceInvalidatedEvent,\n PreferencesUpdatedEvent,\n NotificationHooks,\n} from './events'\n\nexport {\n NotificationError,\n NOTIFICATION_ERROR_CODES,\n TemplateNotFoundError,\n ChannelNotConfiguredError,\n RecipientUnresolvedError,\n SuppressedTargetError,\n NotificationNotFoundError,\n InvalidWebhookSignatureError,\n DuplicateWebhookDeliveryError,\n DeviceNotFoundError,\n ThrottledError,\n ConfigMissingError,\n} from './errors'\n\nexport { createWhatsAppDriverFromChannel } from './whatsappDriver'\nexport type { WhatsAppSendingChannel } from './whatsappDriver'\n\nexport {\n deriveTitleFromBody,\n escapeTemplateHtml,\n extractTemplatePlaceholders,\n interpolateTemplate,\n renderTemplate,\n} from './templateRender'\nexport type { RenderedTemplatePreview } from './templateRender'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport const NOTIFICATION_CHANNEL = {\n INBOX: 'inbox',\n PUSH: 'push',\n EMAIL: 'email',\n WHATSAPP: 'whatsapp',\n SMS: 'sms',\n} as const\nexport type NotificationChannel = (typeof NOTIFICATION_CHANNEL)[keyof typeof NOTIFICATION_CHANNEL]\n\n/** Canais que interrompem o destinatário e por isso respeitam quiet hours (ver spec §10.4). */\nexport const INTRUSIVE_CHANNELS: readonly NotificationChannel[] = [\n NOTIFICATION_CHANNEL.PUSH,\n NOTIFICATION_CHANNEL.WHATSAPP,\n NOTIFICATION_CHANNEL.SMS,\n]\n\nexport const NOTIFICATION_STATUS = {\n PENDING: 'pending',\n SCHEDULED: 'scheduled',\n QUEUED: 'queued',\n DISPATCHED: 'dispatched',\n PARTIALLY_FAILED: 'partially_failed',\n FAILED: 'failed',\n} as const\nexport type NotificationStatus = (typeof NOTIFICATION_STATUS)[keyof typeof NOTIFICATION_STATUS]\n\nexport const DELIVERY_STATUS = {\n QUEUED: 'queued',\n SENT: 'sent',\n DELIVERED: 'delivered',\n FAILED: 'failed',\n BOUNCED: 'bounced',\n SKIPPED: 'skipped',\n} as const\nexport type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS]\n\nexport const DEVICE_PLATFORM = {\n IOS: 'ios',\n ANDROID: 'android',\n WEB: 'web',\n} as const\nexport type DevicePlatform = (typeof DEVICE_PLATFORM)[keyof typeof DEVICE_PLATFORM]\n\nexport const PUSH_DRIVER = {\n EXPO: 'expo',\n FCM: 'fcm',\n} as const\nexport type PushDriver = (typeof PUSH_DRIVER)[keyof typeof PUSH_DRIVER]\n\nexport const EMAIL_DRIVER = {\n SMTP: 'smtp',\n RESEND: 'resend',\n SES: 'ses',\n} as const\nexport type EmailDriver = (typeof EMAIL_DRIVER)[keyof typeof EMAIL_DRIVER]\n\nexport const SUPPRESSION_REASON = {\n BOUNCE: 'bounce',\n COMPLAINT: 'complaint',\n OPT_OUT: 'opt_out',\n} as const\nexport type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON]\n\n/**\n * Sugestão de nomenclatura, sem valor normativo (decisão Q2 da spec). `category` é `varchar`\n * livre porque é vocabulário de negócio do produto — fechá-la num enum aqui obrigaria uma major\n * do pacote a cada produto novo.\n */\nexport const NOTIFICATION_CATEGORY_HINT = {\n ORDER_STATUS: 'order_status',\n PAYMENT: 'payment',\n SECURITY: 'security',\n MARKETING: 'marketing',\n SYSTEM: 'system',\n} as const\n\nexport type NotificationId = string\nexport type CompanyId = string\nexport type UserId = string\n\nexport type NotificationSummary = {\n readonly id: NotificationId\n readonly category: string\n readonly templateKey: string\n readonly title: string\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n readonly status: NotificationStatus\n readonly scheduledFor?: string\n readonly readAt?: string\n readonly createdAt: string\n}\n\nexport type DeliverySummary = {\n readonly id: string\n readonly notificationId: NotificationId\n readonly channel: NotificationChannel\n readonly driver?: string\n /** Nunca o endereço em claro: `****1234`, `a***@dominio.com` (LGPD — ver spec §5). */\n readonly targetMasked?: string\n readonly status: DeliveryStatus\n readonly attempt: number\n readonly providerMessageId?: string\n readonly errorCode?: string\n readonly sentAt?: string\n readonly deliveredAt?: string\n readonly failedAt?: string\n}\n\nexport type DeviceRegistration = {\n readonly id: string\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n readonly lastSeenAt: string\n readonly disabledAt?: string\n readonly disabledReason?: string\n}\n\nexport type NotificationPreference = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\n /** `HH:mm` no timezone resolvido para o destinatário; ambos ausentes = sem janela de silêncio. */\n readonly quietHoursStart?: string\n readonly quietHoursEnd?: string\n readonly timezone?: string\n}\n\nexport type NotificationTemplate = {\n readonly id: string\n readonly key: string\n readonly channel: NotificationChannel\n readonly locale: string\n readonly version: number\n readonly subject?: string\n readonly body: string\n /**\n * Nome do template aprovado na Meta. Sem ele, o canal WhatsApp é pulado fora da janela de 24 h\n * em vez de estourar erro na cara do usuário (spec §10.7).\n */\n readonly whatsappTemplateName?: string\n readonly active: boolean\n}\n\nexport type SendNotificationParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n readonly payload?: Readonly<Record<string, unknown>>\n /** Sem canais explícitos, o fan-out resolve pelas preferências do destinatário. */\n readonly channels?: readonly NotificationChannel[]\n /** Chave de negócio da entrega. Repetição devolve a notificação existente, não uma nova. */\n readonly dedupeKey?: string\n readonly scheduledFor?: Date\n readonly locale?: string\n}\n\nexport type SendNotificationResult = {\n readonly notificationId: NotificationId\n /** `true` quando um `dedupeKey` já visto devolveu a notificação anterior — nada foi reenviado. */\n readonly deduplicated: boolean\n readonly deliveries: readonly DeliverySummary[]\n}\n\nexport type ListNotificationsParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsResult = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type DeliveryReceipt = {\n readonly providerMessageId: string\n readonly status: Extract<DeliveryStatus, 'delivered' | 'bounced' | 'failed'>\n readonly errorCode?: string\n readonly occurredAt: Date\n readonly suppressionReason?: SuppressionReason\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { z } from 'zod'\n\nimport { DEVICE_PLATFORM, NOTIFICATION_CHANNEL, PUSH_DRIVER, SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Schemas de fronteira. Regra que atravessa todos eles: **`companyId` nunca vem do corpo da\n * requisição** — é derivado do contexto autenticado (`database.md`, \"Consistência e\n * multiempresa\"). Aceitá-lo aqui seria entregar o isolamento multiempresa ao cliente.\n */\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/\nconst MAX_PER_PAGE = 100\n\nconst quietHoursShape = {\n quietHoursStart: z.string().regex(HHMM, 'Use HH:mm').optional(),\n quietHoursEnd: z.string().regex(HHMM, 'Use HH:mm').optional(),\n timezone: z.string().min(1).optional(),\n}\n\nexport const sendNotificationSchema = z.object({\n recipientUserId: z.string().uuid(),\n category: z.string().min(1).max(64),\n templateKey: z.string().min(1).max(128),\n payload: z.record(z.unknown()).optional(),\n channels: z.array(z.nativeEnum(NOTIFICATION_CHANNEL)).nonempty().optional(),\n dedupeKey: z.string().min(1).max(256).optional(),\n scheduledFor: z.coerce.date().optional(),\n locale: z.string().min(2).max(16).optional(),\n})\nexport type SendNotificationBody = z.infer<typeof sendNotificationSchema>\n\nexport const registerDeviceSchema = z.object({\n platform: z.nativeEnum(DEVICE_PLATFORM),\n driver: z.nativeEnum(PUSH_DRIVER),\n token: z.string().min(1).max(4096),\n appVersion: z.string().max(32).optional(),\n locale: z.string().min(2).max(16).optional(),\n timezone: z.string().min(1).max(64).optional(),\n})\nexport type RegisterDeviceBody = z.infer<typeof registerDeviceSchema>\n\nexport const preferenceEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n ...quietHoursShape,\n})\n\nexport const updatePreferencesSchema = z.object({\n preferences: z.array(preferenceEntrySchema).max(200),\n})\nexport type UpdatePreferencesBody = z.infer<typeof updatePreferencesSchema>\n\nexport const upsertTemplateSchema = z.object({\n key: z.string().min(1).max(128),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n locale: z.string().min(2).max(16),\n subject: z.string().max(256).optional(),\n body: z.string().min(1).max(8192),\n whatsappTemplateName: z.string().max(128).optional(),\n active: z.boolean().default(true),\n})\nexport type UpsertTemplateBody = z.infer<typeof upsertTemplateSchema>\n\n/** Query string chega sempre como texto — daí o `coerce` e o booleano por literal. */\nexport const listNotificationsQuerySchema = z.object({\n category: z.string().min(1).max(64).optional(),\n read: z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional(),\n cursor: z.string().max(512).optional(),\n perPage: z.coerce.number().int().min(1).max(MAX_PER_PAGE).default(20),\n})\nexport type ListNotificationsQuery = z.infer<typeof listNotificationsQuerySchema>\n\n/**\n * Forma normalizada do recibo de entrega, depois que o parser do driver traduziu o payload do\n * provedor. A verificação de assinatura acontece antes disto, sobre o `rawBody`.\n */\nexport const deliveryWebhookSchema = z.object({\n providerMessageId: z.string().min(1),\n status: z.enum(['delivered', 'bounced', 'failed']),\n errorCode: z.string().max(64).optional(),\n occurredAt: z.coerce.date(),\n suppressionReason: z.nativeEnum(SUPPRESSION_REASON).optional(),\n})\nexport type DeliveryWebhookBody = z.infer<typeof deliveryWebhookSchema>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type {\n CompanyId,\n DevicePlatform,\n NotificationChannel,\n NotificationId,\n NotificationStatus,\n PushDriver,\n SuppressionReason,\n UserId,\n} from './notification.types'\n\n/**\n * Eventos de domínio — os pontos de extensão do produto. É aqui que entra a regra de negócio que\n * o módulo não pode ter (ex.: bounce de e-mail marca o contato como inválido no CRM), sem\n * ninguém editar código do pacote (regra de módulos plugáveis, §3).\n */\nexport const NOTIFICATION_EVENT = {\n CREATED: 'notification.created',\n DISPATCHED: 'notification.dispatched',\n READ: 'notification.read',\n DELIVERY_SENT: 'delivery.sent',\n DELIVERY_FAILED: 'delivery.failed',\n DELIVERY_BOUNCED: 'delivery.bounced',\n DEVICE_REGISTERED: 'device.registered',\n DEVICE_INVALIDATED: 'device.invalidated',\n PREFERENCES_UPDATED: 'preferences.updated',\n} as const\nexport type NotificationEvent = (typeof NOTIFICATION_EVENT)[keyof typeof NOTIFICATION_EVENT]\n\ntype BaseEvent = {\n readonly companyId: CompanyId\n readonly occurredAt: Date\n}\n\nexport type NotificationCreatedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n /** Canais que sobreviveram ao fan-out; os pulados aparecem em `skippedChannels`. */\n readonly channels: readonly NotificationChannel[]\n readonly skippedChannels: readonly { readonly channel: NotificationChannel; readonly reason: string }[]\n}\n\nexport type NotificationDispatchedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly status: NotificationStatus\n}\n\nexport type NotificationReadEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n}\n\nexport type DeliverySentEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly providerMessageId?: string\n readonly attempt: number\n}\n\nexport type DeliveryFailedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly errorCode: string\n readonly attempt: number\n /** `false` quando o retry esgotou ou o erro é permanente — é o gancho para alerta do host. */\n readonly willRetry: boolean\n}\n\nexport type DeliveryBouncedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly reason: SuppressionReason\n}\n\nexport type DeviceRegisteredEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n}\n\nexport type DeviceInvalidatedEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly driver: PushDriver\n readonly errorCode: string\n}\n\nexport type PreferencesUpdatedEvent = BaseEvent & {\n readonly userId: UserId\n readonly categories: readonly string[]\n}\n\n/**\n * Hooks são `void`-tolerantes de propósito: falha de hook do produto não pode derrubar a entrega\n * da notificação. O módulo loga e segue — quem precisa de garantia transacional usa a fila.\n */\nexport type NotificationHooks = {\n onNotificationCreated?(event: NotificationCreatedEvent): Promise<void> | void\n onNotificationDispatched?(event: NotificationDispatchedEvent): Promise<void> | void\n onNotificationRead?(event: NotificationReadEvent): Promise<void> | void\n onDeliverySent?(event: DeliverySentEvent): Promise<void> | void\n onDeliveryFailed?(event: DeliveryFailedEvent): Promise<void> | void\n onDeliveryBounced?(event: DeliveryBouncedEvent): Promise<void> | void\n onDeviceRegistered?(event: DeviceRegisteredEvent): Promise<void> | void\n onDeviceInvalidated?(event: DeviceInvalidatedEvent): Promise<void> | void\n onPreferencesUpdated?(event: PreferencesUpdatedEvent): Promise<void> | void\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { NotificationChannel } from './notification.types'\n\n/**\n * Hierarquia autocontida: um pacote publicado não importa o `DomainError` do host. O host mapeia\n * estes erros no seu exception filter — e o próprio módulo já traz um, para o consumidor das rotas\n * não precisar escrever `try/catch` por endpoint.\n */\nexport class NotificationError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'NotificationError'\n }\n}\n\nexport const NOTIFICATION_ERROR_CODES = {\n TEMPLATE_NOT_FOUND: 'NOTIFICATION_TEMPLATE_NOT_FOUND',\n CHANNEL_NOT_CONFIGURED: 'NOTIFICATION_CHANNEL_NOT_CONFIGURED',\n RECIPIENT_UNRESOLVED: 'NOTIFICATION_RECIPIENT_UNRESOLVED',\n SUPPRESSED_TARGET: 'NOTIFICATION_SUPPRESSED_TARGET',\n NOT_FOUND: 'NOTIFICATION_NOT_FOUND',\n INVALID_WEBHOOK_SIGNATURE: 'NOTIFICATION_INVALID_WEBHOOK_SIGNATURE',\n DUPLICATE_WEBHOOK_DELIVERY: 'NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY',\n DEVICE_NOT_FOUND: 'NOTIFICATION_DEVICE_NOT_FOUND',\n THROTTLED: 'NOTIFICATION_THROTTLED',\n CONFIG_MISSING: 'NOTIFICATION_CONFIG_MISSING',\n} as const\n\nexport class TemplateNotFoundError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly channel: NotificationChannel,\n public readonly locale: string,\n ) {\n super(\n `Template não encontrado para a chave informada neste canal e locale.`,\n 404,\n NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND,\n { templateKey, channel, locale },\n )\n }\n}\n\n/** Canal ligado em `features` sem driver injetado — erro de composição, detectado no boot. */\nexport class ChannelNotConfiguredError extends NotificationError {\n constructor(public readonly channel: NotificationChannel) {\n super(\n `Canal habilitado sem driver injetado — injete o driver em providers.channels ou desligue a feature.`,\n 500,\n NOTIFICATION_ERROR_CODES.CHANNEL_NOT_CONFIGURED,\n { channel },\n )\n }\n}\n\n/**\n * `RecipientResolverPort` não devolveu endereço para o canal. Mensagem sem PII de propósito: o\n * `userId` é identificador opaco, o e-mail ou telefone jamais entra no erro (`security.md` §1).\n */\nexport class RecipientUnresolvedError extends NotificationError {\n constructor(\n public readonly userId: string,\n public readonly channel: NotificationChannel,\n ) {\n super(`Destinatário sem endereço utilizável para este canal.`, 422, NOTIFICATION_ERROR_CODES.RECIPIENT_UNRESOLVED, {\n userId,\n channel,\n })\n }\n}\n\nexport class SuppressedTargetError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly reason: string,\n ) {\n super(`Endereço suprimido para este canal — envio bloqueado.`, 409, NOTIFICATION_ERROR_CODES.SUPPRESSED_TARGET, {\n channel,\n reason,\n })\n }\n}\n\n/**\n * Também é a resposta para notificação de OUTRO usuário: devolver 404 em vez de 403 não revela a\n * existência do recurso a quem não pode vê-lo (BOLA/API1).\n */\nexport class NotificationNotFoundError extends NotificationError {\n constructor(public readonly notificationId: string) {\n super(`Notificação não encontrada.`, 404, NOTIFICATION_ERROR_CODES.NOT_FOUND, { notificationId })\n }\n}\n\nexport class InvalidWebhookSignatureError extends NotificationError {\n constructor() {\n super(`Assinatura do webhook inválida.`, 401, NOTIFICATION_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE)\n }\n}\n\n/** Recibo reenviado dentro da janela de replay (nonce já visto) — não é erro, é ruído esperado. */\nexport class DuplicateWebhookDeliveryError extends NotificationError {\n constructor(public readonly nonce: string) {\n super(`Entrega de webhook duplicada.`, 200, NOTIFICATION_ERROR_CODES.DUPLICATE_WEBHOOK_DELIVERY, { nonce })\n }\n}\n\nexport class DeviceNotFoundError extends NotificationError {\n constructor(public readonly deviceId: string) {\n super(`Dispositivo não encontrado.`, 404, NOTIFICATION_ERROR_CODES.DEVICE_NOT_FOUND, { deviceId })\n }\n}\n\nexport class ThrottledError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly retryAfterSeconds: number,\n ) {\n super(`Limite de envios para este destinatário atingido.`, 429, NOTIFICATION_ERROR_CODES.THROTTLED, {\n channel,\n retryAfterSeconds,\n })\n }\n}\n\n/**\n * Configuração obrigatória ausente (chave de HMAC, segredo de webhook) — falha no boot.\n *\n * Único erro do módulo cuja mensagem nomeia o campo: ele é lido por quem está subindo o serviço,\n * não devolvido a um cliente, e \"algo está faltando\" sem dizer o quê custa uma bisca no código.\n * O nome do campo é identificador de configuração, nunca valor — o segredo em si não aparece.\n */\nexport class ConfigMissingError extends NotificationError {\n constructor(public readonly field: string) {\n super(`Configuração obrigatória ausente: ${field}.`, 500, NOTIFICATION_ERROR_CODES.CONFIG_MISSING, { field })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { DeliveryAttemptResult, SendWhatsAppParams, WhatsAppDriverPort } from './channelDrivers'\nimport { SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Forma mínima que o `channel` do `meta-whatsapp-module` já satisfaz. Descrita aqui por\n * *estrutura*, e não importada do pacote de WhatsApp: é isso que mantém os dois trios\n * independentes — quem só usa inbox não carrega Meta, quem só usa WhatsApp não carrega\n * notificação, e a costura acontece no produto (regra de módulos plugáveis, §2).\n */\nexport type WhatsAppSendingChannel = {\n sendText(to: string, body: string): Promise<{ externalMessageId: string | null }>\n sendTemplate(params: {\n to: string\n templateName: string\n languageCode: string\n bodyParameters?: string[]\n }): Promise<{ externalMessageId: string | null }>\n}\n\n/**\n * Códigos da Graph API que o canal repassa. A lista é curta de propósito: cobre o que muda a\n * decisão do módulo (apagar destino × tentar de novo × desistir) e nada além disso.\n */\nconst INVALID_TARGET_CODES = new Set([131026, 131051])\nconst PERMANENT_CODES = new Set([131047, 131031, 368])\nconst RETRIABLE_CODES = new Set([613, 130429, 131056])\n\nfunction readNumericField(error: unknown, field: string): number | undefined {\n if (typeof error !== 'object' || error === null || !(field in error)) return undefined\n const value = (error as Record<string, unknown>)[field]\n return typeof value === 'number' ? value : undefined\n}\n\nfunction classifyError(error: unknown): DeliveryAttemptResult {\n const metaCode = readNumericField(error, 'code')\n if (metaCode !== undefined) {\n if (INVALID_TARGET_CODES.has(metaCode)) {\n return {\n outcome: 'invalid_target',\n errorCode: `meta_${metaCode}`,\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n }\n }\n if (PERMANENT_CODES.has(metaCode)) return { outcome: 'permanent', errorCode: `meta_${metaCode}` }\n if (RETRIABLE_CODES.has(metaCode)) return { outcome: 'retriable', errorCode: `meta_${metaCode}` }\n }\n\n const statusCode = readNumericField(error, 'statusCode') ?? readNumericField(error, 'status')\n if (statusCode === 429 || (statusCode !== undefined && statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: `http_${statusCode}` }\n }\n if (statusCode !== undefined && statusCode >= 400) {\n return { outcome: 'permanent', errorCode: `http_${statusCode}` }\n }\n\n // Sem código nenhum é quase sempre falha de rede/DNS, que passa numa segunda tentativa. O risco\n // do palpite é limitado: o retry é finito (`attempts`) e termina em `failed` de qualquer forma.\n return { outcome: 'retriable', errorCode: 'unknown' }\n}\n\nexport function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort {\n return {\n async send(params: SendWhatsAppParams): Promise<DeliveryAttemptResult> {\n try {\n const result = params.template\n ? await channel.sendTemplate({\n to: params.to,\n templateName: params.template.templateName,\n languageCode: params.template.languageCode,\n bodyParameters: params.template.bodyParameters ? [...params.template.bodyParameters] : undefined,\n })\n : await channel.sendText(params.to, params.body)\n\n return { outcome: 'sent', providerMessageId: result.externalMessageId ?? undefined }\n } catch (error) {\n return classifyError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * A renderização default de template, pura e sem dependência.\n *\n * Mora no contracts, e não no módulo, por um motivo específico: a tela de configuração precisa\n * mostrar um PREVIEW do que o cliente vai receber, e o módulo carrega Drizzle — o frontend não pode\n * importá-lo. Reimplementar a interpolação no host resolveria hoje e divergiria amanhã, e **preview\n * que mente é pior que preview nenhum**: alguém salva o template confiando no que viu.\n *\n * Com a função aqui, o `notification-module` renderiza para enviar e a UI renderiza para mostrar,\n * lendo o MESMO código. Divergência deixa de ser possível em vez de ser improvável.\n */\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g\nconst DEFAULT_TITLE_MAX_LENGTH = 120\n\nconst HTML_ESCAPE_MAP: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n}\n\nexport function escapeTemplateHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (character) => HTML_ESCAPE_MAP[character] ?? character)\n}\n\n/** `{{campo}}` → valor do payload. Campo ausente vira string vazia, nunca o literal `{{campo}}`. */\nexport function interpolateTemplate(template: string, payload: Readonly<Record<string, unknown>>): string {\n return template.replace(PLACEHOLDER_PATTERN, (_match, key: string) => {\n const value = payload[key]\n return value === undefined || value === null ? '' : String(value)\n })\n}\n\nexport function deriveTitleFromBody(body: string): string {\n const firstLine = body.split('\\n')[0] ?? ''\n return firstLine.length > DEFAULT_TITLE_MAX_LENGTH ? `${firstLine.slice(0, DEFAULT_TITLE_MAX_LENGTH)}…` : firstLine\n}\n\n/** Os nomes de campo que um template referencia — o que a tela de configuração precisa pedir. */\nexport function extractTemplatePlaceholders(template: string): readonly string[] {\n const found = new Set<string>()\n for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) found.add(match[1])\n }\n return [...found]\n}\n\nexport type RenderedTemplatePreview = {\n readonly title: string\n readonly body: string\n readonly html?: string\n}\n\n/**\n * Mesma saída que o envio produz. `channel` importa porque só e-mail ganha a versão HTML — mostrar\n * HTML no preview de WhatsApp faria a tela prometer formatação que o canal não tem.\n */\nexport function renderTemplate(params: {\n readonly channel: string\n readonly subject?: string | undefined\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n}): RenderedTemplatePreview {\n const body = interpolateTemplate(params.body, params.payload)\n const title = params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body)\n\n if (params.channel !== 'email') return { title, body }\n\n // Escapa o resultado já interpolado (texto do template e valores do payload juntos), depois troca\n // quebra de linha por <br> — quem quer HTML rico troca o renderer, em vez de descobrir por um bug\n // de escape.\n return { title, body, html: escapeTemplateHtml(body).replace(/\\n/g, '<br>') }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACIO,IAAMA,uBAAuB;EAClCC,OAAO;EACPC,MAAM;EACNC,OAAO;EACPC,UAAU;EACVC,KAAK;AACP;AAIO,IAAMC,qBAAqD;EAChEN,qBAAqBE;EACrBF,qBAAqBI;EACrBJ,qBAAqBK;;AAGhB,IAAME,sBAAsB;EACjCC,SAAS;EACTC,WAAW;EACXC,QAAQ;EACRC,YAAY;EACZC,kBAAkB;EAClBC,QAAQ;AACV;AAGO,IAAMC,kBAAkB;EAC7BJ,QAAQ;EACRK,MAAM;EACNC,WAAW;EACXH,QAAQ;EACRI,SAAS;EACTC,SAAS;AACX;AAGO,IAAMC,kBAAkB;EAC7BC,KAAK;EACLC,SAAS;EACTC,KAAK;AACP;AAGO,IAAMC,cAAc;EACzBC,MAAM;EACNC,KAAK;AACP;AAGO,IAAMC,eAAe;EAC1BC,MAAM;EACNC,QAAQ;EACRC,KAAK;AACP;AAGO,IAAMC,qBAAqB;EAChCC,QAAQ;EACRC,WAAW;EAC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AAOD,SAASH,QAAQL,qBAAqB,CAACU,QAAQC,QAAAA;AACpD,UAAMC,QAAQH,QAAQE,GAAAA;AACtB,WAAOC,UAAUC,UAAaD,UAAU,OAAO,KAAKE,OAAOF,KAAAA;EAC7D,CAAA;AACF;AALgBL;AAOT,SAASQ,oBAAoBC,MAAY;AAC9C,QAAMC,YAAYD,KAAKE,MAAM,IAAA,EAAM,CAAA,KAAM;AACzC,SAAOD,UAAUE,SAASlB,2BAA2B,GAAGgB,UAAUG,MAAM,GAAGnB,wBAAAA,CAAAA,WAA+BgB;AAC5G;AAHgBF;AAMT,SAASM,4BAA4Bb,UAAgB;AAC1D,QAAMc,QAAQ,oBAAIC,IAAAA;AAClB,aAAWC,SAAShB,SAASiB,SAASzB,mBAAAA,GAAsB;AAC1D,QAAIwB,MAAM,CAAA,EAAIF,OAAMI,IAAIF,MAAM,CAAA,CAAE;EAClC;AACA,SAAO;OAAIF;;AACb;AANgBD;AAkBT,SAASM,eAAeC,QAK9B;AACC,QAAMZ,OAAOT,oBAAoBqB,OAAOZ,MAAMY,OAAOnB,OAAO;AAC5D,QAAMoB,QAAQD,OAAOE,UAAUvB,oBAAoBqB,OAAOE,SAASF,OAAOnB,OAAO,IAAIM,oBAAoBC,IAAAA;AAEzG,MAAIY,OAAOG,YAAY,QAAS,QAAO;IAAEF;IAAOb;EAAK;AAKrD,SAAO;IAAEa;IAAOb;IAAMgB,MAAM7B,mBAAmBa,IAAAA,EAAMX,QAAQ,OAAO,MAAA;EAAQ;AAC9E;AAfgBsB;","names":["NOTIFICATION_CHANNEL","INBOX","PUSH","EMAIL","WHATSAPP","SMS","INTRUSIVE_CHANNELS","NOTIFICATION_STATUS","PENDING","SCHEDULED","QUEUED","DISPATCHED","PARTIALLY_FAILED","FAILED","DELIVERY_STATUS","SENT","DELIVERED","BOUNCED","SKIPPED","DEVICE_PLATFORM","IOS","ANDROID","WEB","PUSH_DRIVER","EXPO","FCM","EMAIL_DRIVER","SMTP","RESEND","SES","SUPPRESSION_REASON","BOUNCE","COMPLAINT","OPT_OUT","NOTIFICATION_CATEGORY_HINT","ORDER_STATUS","PAYMENT","SECURITY","MARKETING","SYSTEM","HHMM","MAX_PER_PAGE","quietHoursShape","quietHoursStart","z","string","regex","optional","quietHoursEnd","timezone","min","sendNotificationSchema","object","recipientUserId","uuid","category","max","templateKey","payload","record","unknown","channels","array","nativeEnum","NOTIFICATION_CHANNEL","nonempty","dedupeKey","scheduledFor","coerce","date","locale","registerDeviceSchema","platform","DEVICE_PLATFORM","driver","PUSH_DRIVER","token","appVersion","preferenceEntrySchema","channel","enabled","boolean","updatePreferencesSchema","preferences","upsertTemplateSchema","key","subject","body","whatsappTemplateName","active","default","listNotificationsQuerySchema","read","enum","transform","value","cursor","perPage","number","int","deliveryWebhookSchema","providerMessageId","status","errorCode","occurredAt","suppressionReason","SUPPRESSION_REASON","NOTIFICATION_EVENT","CREATED","DISPATCHED","READ","DELIVERY_SENT","DELIVERY_FAILED","DELIVERY_BOUNCED","DEVICE_REGISTERED","DEVICE_INVALIDATED","PREFERENCES_UPDATED","NotificationError","Error","message","statusCode","code","details","name","NOTIFICATION_ERROR_CODES","TEMPLATE_NOT_FOUND","CHANNEL_NOT_CONFIGURED","RECIPIENT_UNRESOLVED","SUPPRESSED_TARGET","NOT_FOUND","INVALID_WEBHOOK_SIGNATURE","DUPLICATE_WEBHOOK_DELIVERY","DEVICE_NOT_FOUND","THROTTLED","CONFIG_MISSING","TemplateNotFoundError","templateKey","channel","locale","ChannelNotConfiguredError","RecipientUnresolvedError","userId","SuppressedTargetError","reason","NotificationNotFoundError","notificationId","InvalidWebhookSignatureError","DuplicateWebhookDeliveryError","nonce","DeviceNotFoundError","deviceId","ThrottledError","retryAfterSeconds","ConfigMissingError","field","INVALID_TARGET_CODES","Set","PERMANENT_CODES","RETRIABLE_CODES","readNumericField","error","field","undefined","value","classifyError","metaCode","has","outcome","errorCode","suppressionReason","SUPPRESSION_REASON","BOUNCE","statusCode","createWhatsAppDriverFromChannel","channel","send","params","result","template","sendTemplate","to","templateName","languageCode","bodyParameters","sendText","body","providerMessageId","externalMessageId","PLACEHOLDER_PATTERN","DEFAULT_TITLE_MAX_LENGTH","HTML_ESCAPE_MAP","escapeTemplateHtml","text","replace","character","interpolateTemplate","template","payload","_match","key","value","undefined","String","deriveTitleFromBody","body","firstLine","split","length","slice","extractTemplatePlaceholders","found","Set","match","matchAll","add","renderTemplate","params","title","subject","channel","html"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -850,4 +850,39 @@ type WhatsAppSendingChannel = {
|
|
|
850
850
|
};
|
|
851
851
|
declare function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort;
|
|
852
852
|
|
|
853
|
-
|
|
853
|
+
/**
|
|
854
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
855
|
+
*
|
|
856
|
+
* A renderização default de template, pura e sem dependência.
|
|
857
|
+
*
|
|
858
|
+
* Mora no contracts, e não no módulo, por um motivo específico: a tela de configuração precisa
|
|
859
|
+
* mostrar um PREVIEW do que o cliente vai receber, e o módulo carrega Drizzle — o frontend não pode
|
|
860
|
+
* importá-lo. Reimplementar a interpolação no host resolveria hoje e divergiria amanhã, e **preview
|
|
861
|
+
* que mente é pior que preview nenhum**: alguém salva o template confiando no que viu.
|
|
862
|
+
*
|
|
863
|
+
* Com a função aqui, o `notification-module` renderiza para enviar e a UI renderiza para mostrar,
|
|
864
|
+
* lendo o MESMO código. Divergência deixa de ser possível em vez de ser improvável.
|
|
865
|
+
*/
|
|
866
|
+
declare function escapeTemplateHtml(text: string): string;
|
|
867
|
+
/** `{{campo}}` → valor do payload. Campo ausente vira string vazia, nunca o literal `{{campo}}`. */
|
|
868
|
+
declare function interpolateTemplate(template: string, payload: Readonly<Record<string, unknown>>): string;
|
|
869
|
+
declare function deriveTitleFromBody(body: string): string;
|
|
870
|
+
/** Os nomes de campo que um template referencia — o que a tela de configuração precisa pedir. */
|
|
871
|
+
declare function extractTemplatePlaceholders(template: string): readonly string[];
|
|
872
|
+
type RenderedTemplatePreview = {
|
|
873
|
+
readonly title: string;
|
|
874
|
+
readonly body: string;
|
|
875
|
+
readonly html?: string;
|
|
876
|
+
};
|
|
877
|
+
/**
|
|
878
|
+
* Mesma saída que o envio produz. `channel` importa porque só e-mail ganha a versão HTML — mostrar
|
|
879
|
+
* HTML no preview de WhatsApp faria a tela prometer formatação que o canal não tem.
|
|
880
|
+
*/
|
|
881
|
+
declare function renderTemplate(params: {
|
|
882
|
+
readonly channel: string;
|
|
883
|
+
readonly subject?: string | undefined;
|
|
884
|
+
readonly body: string;
|
|
885
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
886
|
+
}): RenderedTemplatePreview;
|
|
887
|
+
|
|
888
|
+
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 RenderedTemplatePreview, 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, deriveTitleFromBody, escapeTemplateHtml, extractTemplatePlaceholders, interpolateTemplate, listNotificationsQuerySchema, preferenceEntrySchema, registerDeviceSchema, renderTemplate, sendNotificationSchema, updatePreferencesSchema, upsertTemplateSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -850,4 +850,39 @@ type WhatsAppSendingChannel = {
|
|
|
850
850
|
};
|
|
851
851
|
declare function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort;
|
|
852
852
|
|
|
853
|
-
|
|
853
|
+
/**
|
|
854
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
855
|
+
*
|
|
856
|
+
* A renderização default de template, pura e sem dependência.
|
|
857
|
+
*
|
|
858
|
+
* Mora no contracts, e não no módulo, por um motivo específico: a tela de configuração precisa
|
|
859
|
+
* mostrar um PREVIEW do que o cliente vai receber, e o módulo carrega Drizzle — o frontend não pode
|
|
860
|
+
* importá-lo. Reimplementar a interpolação no host resolveria hoje e divergiria amanhã, e **preview
|
|
861
|
+
* que mente é pior que preview nenhum**: alguém salva o template confiando no que viu.
|
|
862
|
+
*
|
|
863
|
+
* Com a função aqui, o `notification-module` renderiza para enviar e a UI renderiza para mostrar,
|
|
864
|
+
* lendo o MESMO código. Divergência deixa de ser possível em vez de ser improvável.
|
|
865
|
+
*/
|
|
866
|
+
declare function escapeTemplateHtml(text: string): string;
|
|
867
|
+
/** `{{campo}}` → valor do payload. Campo ausente vira string vazia, nunca o literal `{{campo}}`. */
|
|
868
|
+
declare function interpolateTemplate(template: string, payload: Readonly<Record<string, unknown>>): string;
|
|
869
|
+
declare function deriveTitleFromBody(body: string): string;
|
|
870
|
+
/** Os nomes de campo que um template referencia — o que a tela de configuração precisa pedir. */
|
|
871
|
+
declare function extractTemplatePlaceholders(template: string): readonly string[];
|
|
872
|
+
type RenderedTemplatePreview = {
|
|
873
|
+
readonly title: string;
|
|
874
|
+
readonly body: string;
|
|
875
|
+
readonly html?: string;
|
|
876
|
+
};
|
|
877
|
+
/**
|
|
878
|
+
* Mesma saída que o envio produz. `channel` importa porque só e-mail ganha a versão HTML — mostrar
|
|
879
|
+
* HTML no preview de WhatsApp faria a tela prometer formatação que o canal não tem.
|
|
880
|
+
*/
|
|
881
|
+
declare function renderTemplate(params: {
|
|
882
|
+
readonly channel: string;
|
|
883
|
+
readonly subject?: string | undefined;
|
|
884
|
+
readonly body: string;
|
|
885
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
886
|
+
}): RenderedTemplatePreview;
|
|
887
|
+
|
|
888
|
+
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 RenderedTemplatePreview, 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, deriveTitleFromBody, escapeTemplateHtml, extractTemplatePlaceholders, interpolateTemplate, listNotificationsQuerySchema, preferenceEntrySchema, registerDeviceSchema, renderTemplate, sendNotificationSchema, updatePreferencesSchema, upsertTemplateSchema };
|
package/dist/index.js
CHANGED
|
@@ -361,6 +361,57 @@ function createWhatsAppDriverFromChannel(channel) {
|
|
|
361
361
|
};
|
|
362
362
|
}
|
|
363
363
|
__name(createWhatsAppDriverFromChannel, "createWhatsAppDriverFromChannel");
|
|
364
|
+
|
|
365
|
+
// src/templateRender.ts
|
|
366
|
+
var PLACEHOLDER_PATTERN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
|
|
367
|
+
var DEFAULT_TITLE_MAX_LENGTH = 120;
|
|
368
|
+
var HTML_ESCAPE_MAP = {
|
|
369
|
+
"&": "&",
|
|
370
|
+
"<": "<",
|
|
371
|
+
">": ">",
|
|
372
|
+
'"': """,
|
|
373
|
+
"'": "'"
|
|
374
|
+
};
|
|
375
|
+
function escapeTemplateHtml(text) {
|
|
376
|
+
return text.replace(/[&<>"']/g, (character) => HTML_ESCAPE_MAP[character] ?? character);
|
|
377
|
+
}
|
|
378
|
+
__name(escapeTemplateHtml, "escapeTemplateHtml");
|
|
379
|
+
function interpolateTemplate(template, payload) {
|
|
380
|
+
return template.replace(PLACEHOLDER_PATTERN, (_match, key) => {
|
|
381
|
+
const value = payload[key];
|
|
382
|
+
return value === void 0 || value === null ? "" : String(value);
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
__name(interpolateTemplate, "interpolateTemplate");
|
|
386
|
+
function deriveTitleFromBody(body) {
|
|
387
|
+
const firstLine = body.split("\n")[0] ?? "";
|
|
388
|
+
return firstLine.length > DEFAULT_TITLE_MAX_LENGTH ? `${firstLine.slice(0, DEFAULT_TITLE_MAX_LENGTH)}\u2026` : firstLine;
|
|
389
|
+
}
|
|
390
|
+
__name(deriveTitleFromBody, "deriveTitleFromBody");
|
|
391
|
+
function extractTemplatePlaceholders(template) {
|
|
392
|
+
const found = /* @__PURE__ */ new Set();
|
|
393
|
+
for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {
|
|
394
|
+
if (match[1]) found.add(match[1]);
|
|
395
|
+
}
|
|
396
|
+
return [
|
|
397
|
+
...found
|
|
398
|
+
];
|
|
399
|
+
}
|
|
400
|
+
__name(extractTemplatePlaceholders, "extractTemplatePlaceholders");
|
|
401
|
+
function renderTemplate(params) {
|
|
402
|
+
const body = interpolateTemplate(params.body, params.payload);
|
|
403
|
+
const title = params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body);
|
|
404
|
+
if (params.channel !== "email") return {
|
|
405
|
+
title,
|
|
406
|
+
body
|
|
407
|
+
};
|
|
408
|
+
return {
|
|
409
|
+
title,
|
|
410
|
+
body,
|
|
411
|
+
html: escapeTemplateHtml(body).replace(/\n/g, "<br>")
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
__name(renderTemplate, "renderTemplate");
|
|
364
415
|
export {
|
|
365
416
|
ChannelNotConfiguredError,
|
|
366
417
|
ConfigMissingError,
|
|
@@ -386,9 +437,14 @@ export {
|
|
|
386
437
|
ThrottledError,
|
|
387
438
|
createWhatsAppDriverFromChannel,
|
|
388
439
|
deliveryWebhookSchema,
|
|
440
|
+
deriveTitleFromBody,
|
|
441
|
+
escapeTemplateHtml,
|
|
442
|
+
extractTemplatePlaceholders,
|
|
443
|
+
interpolateTemplate,
|
|
389
444
|
listNotificationsQuerySchema,
|
|
390
445
|
preferenceEntrySchema,
|
|
391
446
|
registerDeviceSchema,
|
|
447
|
+
renderTemplate,
|
|
392
448
|
sendNotificationSchema,
|
|
393
449
|
updatePreferencesSchema,
|
|
394
450
|
upsertTemplateSchema
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/notification.types.ts","../src/schemas.ts","../src/events.ts","../src/errors.ts","../src/whatsappDriver.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport const NOTIFICATION_CHANNEL = {\n INBOX: 'inbox',\n PUSH: 'push',\n EMAIL: 'email',\n WHATSAPP: 'whatsapp',\n SMS: 'sms',\n} as const\nexport type NotificationChannel = (typeof NOTIFICATION_CHANNEL)[keyof typeof NOTIFICATION_CHANNEL]\n\n/** Canais que interrompem o destinatário e por isso respeitam quiet hours (ver spec §10.4). */\nexport const INTRUSIVE_CHANNELS: readonly NotificationChannel[] = [\n NOTIFICATION_CHANNEL.PUSH,\n NOTIFICATION_CHANNEL.WHATSAPP,\n NOTIFICATION_CHANNEL.SMS,\n]\n\nexport const NOTIFICATION_STATUS = {\n PENDING: 'pending',\n SCHEDULED: 'scheduled',\n QUEUED: 'queued',\n DISPATCHED: 'dispatched',\n PARTIALLY_FAILED: 'partially_failed',\n FAILED: 'failed',\n} as const\nexport type NotificationStatus = (typeof NOTIFICATION_STATUS)[keyof typeof NOTIFICATION_STATUS]\n\nexport const DELIVERY_STATUS = {\n QUEUED: 'queued',\n SENT: 'sent',\n DELIVERED: 'delivered',\n FAILED: 'failed',\n BOUNCED: 'bounced',\n SKIPPED: 'skipped',\n} as const\nexport type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS]\n\nexport const DEVICE_PLATFORM = {\n IOS: 'ios',\n ANDROID: 'android',\n WEB: 'web',\n} as const\nexport type DevicePlatform = (typeof DEVICE_PLATFORM)[keyof typeof DEVICE_PLATFORM]\n\nexport const PUSH_DRIVER = {\n EXPO: 'expo',\n FCM: 'fcm',\n} as const\nexport type PushDriver = (typeof PUSH_DRIVER)[keyof typeof PUSH_DRIVER]\n\nexport const EMAIL_DRIVER = {\n SMTP: 'smtp',\n RESEND: 'resend',\n SES: 'ses',\n} as const\nexport type EmailDriver = (typeof EMAIL_DRIVER)[keyof typeof EMAIL_DRIVER]\n\nexport const SUPPRESSION_REASON = {\n BOUNCE: 'bounce',\n COMPLAINT: 'complaint',\n OPT_OUT: 'opt_out',\n} as const\nexport type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON]\n\n/**\n * Sugestão de nomenclatura, sem valor normativo (decisão Q2 da spec). `category` é `varchar`\n * livre porque é vocabulário de negócio do produto — fechá-la num enum aqui obrigaria uma major\n * do pacote a cada produto novo.\n */\nexport const NOTIFICATION_CATEGORY_HINT = {\n ORDER_STATUS: 'order_status',\n PAYMENT: 'payment',\n SECURITY: 'security',\n MARKETING: 'marketing',\n SYSTEM: 'system',\n} as const\n\nexport type NotificationId = string\nexport type CompanyId = string\nexport type UserId = string\n\nexport type NotificationSummary = {\n readonly id: NotificationId\n readonly category: string\n readonly templateKey: string\n readonly title: string\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n readonly status: NotificationStatus\n readonly scheduledFor?: string\n readonly readAt?: string\n readonly createdAt: string\n}\n\nexport type DeliverySummary = {\n readonly id: string\n readonly notificationId: NotificationId\n readonly channel: NotificationChannel\n readonly driver?: string\n /** Nunca o endereço em claro: `****1234`, `a***@dominio.com` (LGPD — ver spec §5). */\n readonly targetMasked?: string\n readonly status: DeliveryStatus\n readonly attempt: number\n readonly providerMessageId?: string\n readonly errorCode?: string\n readonly sentAt?: string\n readonly deliveredAt?: string\n readonly failedAt?: string\n}\n\nexport type DeviceRegistration = {\n readonly id: string\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n readonly lastSeenAt: string\n readonly disabledAt?: string\n readonly disabledReason?: string\n}\n\nexport type NotificationPreference = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\n /** `HH:mm` no timezone resolvido para o destinatário; ambos ausentes = sem janela de silêncio. */\n readonly quietHoursStart?: string\n readonly quietHoursEnd?: string\n readonly timezone?: string\n}\n\nexport type NotificationTemplate = {\n readonly id: string\n readonly key: string\n readonly channel: NotificationChannel\n readonly locale: string\n readonly version: number\n readonly subject?: string\n readonly body: string\n /**\n * Nome do template aprovado na Meta. Sem ele, o canal WhatsApp é pulado fora da janela de 24 h\n * em vez de estourar erro na cara do usuário (spec §10.7).\n */\n readonly whatsappTemplateName?: string\n readonly active: boolean\n}\n\nexport type SendNotificationParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n readonly payload?: Readonly<Record<string, unknown>>\n /** Sem canais explícitos, o fan-out resolve pelas preferências do destinatário. */\n readonly channels?: readonly NotificationChannel[]\n /** Chave de negócio da entrega. Repetição devolve a notificação existente, não uma nova. */\n readonly dedupeKey?: string\n readonly scheduledFor?: Date\n readonly locale?: string\n}\n\nexport type SendNotificationResult = {\n readonly notificationId: NotificationId\n /** `true` quando um `dedupeKey` já visto devolveu a notificação anterior — nada foi reenviado. */\n readonly deduplicated: boolean\n readonly deliveries: readonly DeliverySummary[]\n}\n\nexport type ListNotificationsParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsResult = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type DeliveryReceipt = {\n readonly providerMessageId: string\n readonly status: Extract<DeliveryStatus, 'delivered' | 'bounced' | 'failed'>\n readonly errorCode?: string\n readonly occurredAt: Date\n readonly suppressionReason?: SuppressionReason\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { z } from 'zod'\n\nimport { DEVICE_PLATFORM, NOTIFICATION_CHANNEL, PUSH_DRIVER, SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Schemas de fronteira. Regra que atravessa todos eles: **`companyId` nunca vem do corpo da\n * requisição** — é derivado do contexto autenticado (`database.md`, \"Consistência e\n * multiempresa\"). Aceitá-lo aqui seria entregar o isolamento multiempresa ao cliente.\n */\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/\nconst MAX_PER_PAGE = 100\n\nconst quietHoursShape = {\n quietHoursStart: z.string().regex(HHMM, 'Use HH:mm').optional(),\n quietHoursEnd: z.string().regex(HHMM, 'Use HH:mm').optional(),\n timezone: z.string().min(1).optional(),\n}\n\nexport const sendNotificationSchema = z.object({\n recipientUserId: z.string().uuid(),\n category: z.string().min(1).max(64),\n templateKey: z.string().min(1).max(128),\n payload: z.record(z.unknown()).optional(),\n channels: z.array(z.nativeEnum(NOTIFICATION_CHANNEL)).nonempty().optional(),\n dedupeKey: z.string().min(1).max(256).optional(),\n scheduledFor: z.coerce.date().optional(),\n locale: z.string().min(2).max(16).optional(),\n})\nexport type SendNotificationBody = z.infer<typeof sendNotificationSchema>\n\nexport const registerDeviceSchema = z.object({\n platform: z.nativeEnum(DEVICE_PLATFORM),\n driver: z.nativeEnum(PUSH_DRIVER),\n token: z.string().min(1).max(4096),\n appVersion: z.string().max(32).optional(),\n locale: z.string().min(2).max(16).optional(),\n timezone: z.string().min(1).max(64).optional(),\n})\nexport type RegisterDeviceBody = z.infer<typeof registerDeviceSchema>\n\nexport const preferenceEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n ...quietHoursShape,\n})\n\nexport const updatePreferencesSchema = z.object({\n preferences: z.array(preferenceEntrySchema).max(200),\n})\nexport type UpdatePreferencesBody = z.infer<typeof updatePreferencesSchema>\n\nexport const upsertTemplateSchema = z.object({\n key: z.string().min(1).max(128),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n locale: z.string().min(2).max(16),\n subject: z.string().max(256).optional(),\n body: z.string().min(1).max(8192),\n whatsappTemplateName: z.string().max(128).optional(),\n active: z.boolean().default(true),\n})\nexport type UpsertTemplateBody = z.infer<typeof upsertTemplateSchema>\n\n/** Query string chega sempre como texto — daí o `coerce` e o booleano por literal. */\nexport const listNotificationsQuerySchema = z.object({\n category: z.string().min(1).max(64).optional(),\n read: z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional(),\n cursor: z.string().max(512).optional(),\n perPage: z.coerce.number().int().min(1).max(MAX_PER_PAGE).default(20),\n})\nexport type ListNotificationsQuery = z.infer<typeof listNotificationsQuerySchema>\n\n/**\n * Forma normalizada do recibo de entrega, depois que o parser do driver traduziu o payload do\n * provedor. A verificação de assinatura acontece antes disto, sobre o `rawBody`.\n */\nexport const deliveryWebhookSchema = z.object({\n providerMessageId: z.string().min(1),\n status: z.enum(['delivered', 'bounced', 'failed']),\n errorCode: z.string().max(64).optional(),\n occurredAt: z.coerce.date(),\n suppressionReason: z.nativeEnum(SUPPRESSION_REASON).optional(),\n})\nexport type DeliveryWebhookBody = z.infer<typeof deliveryWebhookSchema>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type {\n CompanyId,\n DevicePlatform,\n NotificationChannel,\n NotificationId,\n NotificationStatus,\n PushDriver,\n SuppressionReason,\n UserId,\n} from './notification.types'\n\n/**\n * Eventos de domínio — os pontos de extensão do produto. É aqui que entra a regra de negócio que\n * o módulo não pode ter (ex.: bounce de e-mail marca o contato como inválido no CRM), sem\n * ninguém editar código do pacote (regra de módulos plugáveis, §3).\n */\nexport const NOTIFICATION_EVENT = {\n CREATED: 'notification.created',\n DISPATCHED: 'notification.dispatched',\n READ: 'notification.read',\n DELIVERY_SENT: 'delivery.sent',\n DELIVERY_FAILED: 'delivery.failed',\n DELIVERY_BOUNCED: 'delivery.bounced',\n DEVICE_REGISTERED: 'device.registered',\n DEVICE_INVALIDATED: 'device.invalidated',\n PREFERENCES_UPDATED: 'preferences.updated',\n} as const\nexport type NotificationEvent = (typeof NOTIFICATION_EVENT)[keyof typeof NOTIFICATION_EVENT]\n\ntype BaseEvent = {\n readonly companyId: CompanyId\n readonly occurredAt: Date\n}\n\nexport type NotificationCreatedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n /** Canais que sobreviveram ao fan-out; os pulados aparecem em `skippedChannels`. */\n readonly channels: readonly NotificationChannel[]\n readonly skippedChannels: readonly { readonly channel: NotificationChannel; readonly reason: string }[]\n}\n\nexport type NotificationDispatchedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly status: NotificationStatus\n}\n\nexport type NotificationReadEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n}\n\nexport type DeliverySentEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly providerMessageId?: string\n readonly attempt: number\n}\n\nexport type DeliveryFailedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly errorCode: string\n readonly attempt: number\n /** `false` quando o retry esgotou ou o erro é permanente — é o gancho para alerta do host. */\n readonly willRetry: boolean\n}\n\nexport type DeliveryBouncedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly reason: SuppressionReason\n}\n\nexport type DeviceRegisteredEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n}\n\nexport type DeviceInvalidatedEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly driver: PushDriver\n readonly errorCode: string\n}\n\nexport type PreferencesUpdatedEvent = BaseEvent & {\n readonly userId: UserId\n readonly categories: readonly string[]\n}\n\n/**\n * Hooks são `void`-tolerantes de propósito: falha de hook do produto não pode derrubar a entrega\n * da notificação. O módulo loga e segue — quem precisa de garantia transacional usa a fila.\n */\nexport type NotificationHooks = {\n onNotificationCreated?(event: NotificationCreatedEvent): Promise<void> | void\n onNotificationDispatched?(event: NotificationDispatchedEvent): Promise<void> | void\n onNotificationRead?(event: NotificationReadEvent): Promise<void> | void\n onDeliverySent?(event: DeliverySentEvent): Promise<void> | void\n onDeliveryFailed?(event: DeliveryFailedEvent): Promise<void> | void\n onDeliveryBounced?(event: DeliveryBouncedEvent): Promise<void> | void\n onDeviceRegistered?(event: DeviceRegisteredEvent): Promise<void> | void\n onDeviceInvalidated?(event: DeviceInvalidatedEvent): Promise<void> | void\n onPreferencesUpdated?(event: PreferencesUpdatedEvent): Promise<void> | void\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { NotificationChannel } from './notification.types'\n\n/**\n * Hierarquia autocontida: um pacote publicado não importa o `DomainError` do host. O host mapeia\n * estes erros no seu exception filter — e o próprio módulo já traz um, para o consumidor das rotas\n * não precisar escrever `try/catch` por endpoint.\n */\nexport class NotificationError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'NotificationError'\n }\n}\n\nexport const NOTIFICATION_ERROR_CODES = {\n TEMPLATE_NOT_FOUND: 'NOTIFICATION_TEMPLATE_NOT_FOUND',\n CHANNEL_NOT_CONFIGURED: 'NOTIFICATION_CHANNEL_NOT_CONFIGURED',\n RECIPIENT_UNRESOLVED: 'NOTIFICATION_RECIPIENT_UNRESOLVED',\n SUPPRESSED_TARGET: 'NOTIFICATION_SUPPRESSED_TARGET',\n NOT_FOUND: 'NOTIFICATION_NOT_FOUND',\n INVALID_WEBHOOK_SIGNATURE: 'NOTIFICATION_INVALID_WEBHOOK_SIGNATURE',\n DUPLICATE_WEBHOOK_DELIVERY: 'NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY',\n DEVICE_NOT_FOUND: 'NOTIFICATION_DEVICE_NOT_FOUND',\n THROTTLED: 'NOTIFICATION_THROTTLED',\n CONFIG_MISSING: 'NOTIFICATION_CONFIG_MISSING',\n} as const\n\nexport class TemplateNotFoundError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly channel: NotificationChannel,\n public readonly locale: string,\n ) {\n super(\n `Template não encontrado para a chave informada neste canal e locale.`,\n 404,\n NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND,\n { templateKey, channel, locale },\n )\n }\n}\n\n/** Canal ligado em `features` sem driver injetado — erro de composição, detectado no boot. */\nexport class ChannelNotConfiguredError extends NotificationError {\n constructor(public readonly channel: NotificationChannel) {\n super(\n `Canal habilitado sem driver injetado — injete o driver em providers.channels ou desligue a feature.`,\n 500,\n NOTIFICATION_ERROR_CODES.CHANNEL_NOT_CONFIGURED,\n { channel },\n )\n }\n}\n\n/**\n * `RecipientResolverPort` não devolveu endereço para o canal. Mensagem sem PII de propósito: o\n * `userId` é identificador opaco, o e-mail ou telefone jamais entra no erro (`security.md` §1).\n */\nexport class RecipientUnresolvedError extends NotificationError {\n constructor(\n public readonly userId: string,\n public readonly channel: NotificationChannel,\n ) {\n super(`Destinatário sem endereço utilizável para este canal.`, 422, NOTIFICATION_ERROR_CODES.RECIPIENT_UNRESOLVED, {\n userId,\n channel,\n })\n }\n}\n\nexport class SuppressedTargetError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly reason: string,\n ) {\n super(`Endereço suprimido para este canal — envio bloqueado.`, 409, NOTIFICATION_ERROR_CODES.SUPPRESSED_TARGET, {\n channel,\n reason,\n })\n }\n}\n\n/**\n * Também é a resposta para notificação de OUTRO usuário: devolver 404 em vez de 403 não revela a\n * existência do recurso a quem não pode vê-lo (BOLA/API1).\n */\nexport class NotificationNotFoundError extends NotificationError {\n constructor(public readonly notificationId: string) {\n super(`Notificação não encontrada.`, 404, NOTIFICATION_ERROR_CODES.NOT_FOUND, { notificationId })\n }\n}\n\nexport class InvalidWebhookSignatureError extends NotificationError {\n constructor() {\n super(`Assinatura do webhook inválida.`, 401, NOTIFICATION_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE)\n }\n}\n\n/** Recibo reenviado dentro da janela de replay (nonce já visto) — não é erro, é ruído esperado. */\nexport class DuplicateWebhookDeliveryError extends NotificationError {\n constructor(public readonly nonce: string) {\n super(`Entrega de webhook duplicada.`, 200, NOTIFICATION_ERROR_CODES.DUPLICATE_WEBHOOK_DELIVERY, { nonce })\n }\n}\n\nexport class DeviceNotFoundError extends NotificationError {\n constructor(public readonly deviceId: string) {\n super(`Dispositivo não encontrado.`, 404, NOTIFICATION_ERROR_CODES.DEVICE_NOT_FOUND, { deviceId })\n }\n}\n\nexport class ThrottledError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly retryAfterSeconds: number,\n ) {\n super(`Limite de envios para este destinatário atingido.`, 429, NOTIFICATION_ERROR_CODES.THROTTLED, {\n channel,\n retryAfterSeconds,\n })\n }\n}\n\n/**\n * Configuração obrigatória ausente (chave de HMAC, segredo de webhook) — falha no boot.\n *\n * Único erro do módulo cuja mensagem nomeia o campo: ele é lido por quem está subindo o serviço,\n * não devolvido a um cliente, e \"algo está faltando\" sem dizer o quê custa uma bisca no código.\n * O nome do campo é identificador de configuração, nunca valor — o segredo em si não aparece.\n */\nexport class ConfigMissingError extends NotificationError {\n constructor(public readonly field: string) {\n super(`Configuração obrigatória ausente: ${field}.`, 500, NOTIFICATION_ERROR_CODES.CONFIG_MISSING, { field })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { DeliveryAttemptResult, SendWhatsAppParams, WhatsAppDriverPort } from './channelDrivers'\nimport { SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Forma mínima que o `channel` do `meta-whatsapp-module` já satisfaz. Descrita aqui por\n * *estrutura*, e não importada do pacote de WhatsApp: é isso que mantém os dois trios\n * independentes — quem só usa inbox não carrega Meta, quem só usa WhatsApp não carrega\n * notificação, e a costura acontece no produto (regra de módulos plugáveis, §2).\n */\nexport type WhatsAppSendingChannel = {\n sendText(to: string, body: string): Promise<{ externalMessageId: string | null }>\n sendTemplate(params: {\n to: string\n templateName: string\n languageCode: string\n bodyParameters?: string[]\n }): Promise<{ externalMessageId: string | null }>\n}\n\n/**\n * Códigos da Graph API que o canal repassa. A lista é curta de propósito: cobre o que muda a\n * decisão do módulo (apagar destino × tentar de novo × desistir) e nada além disso.\n */\nconst INVALID_TARGET_CODES = new Set([131026, 131051])\nconst PERMANENT_CODES = new Set([131047, 131031, 368])\nconst RETRIABLE_CODES = new Set([613, 130429, 131056])\n\nfunction readNumericField(error: unknown, field: string): number | undefined {\n if (typeof error !== 'object' || error === null || !(field in error)) return undefined\n const value = (error as Record<string, unknown>)[field]\n return typeof value === 'number' ? value : undefined\n}\n\nfunction classifyError(error: unknown): DeliveryAttemptResult {\n const metaCode = readNumericField(error, 'code')\n if (metaCode !== undefined) {\n if (INVALID_TARGET_CODES.has(metaCode)) {\n return {\n outcome: 'invalid_target',\n errorCode: `meta_${metaCode}`,\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n }\n }\n if (PERMANENT_CODES.has(metaCode)) return { outcome: 'permanent', errorCode: `meta_${metaCode}` }\n if (RETRIABLE_CODES.has(metaCode)) return { outcome: 'retriable', errorCode: `meta_${metaCode}` }\n }\n\n const statusCode = readNumericField(error, 'statusCode') ?? readNumericField(error, 'status')\n if (statusCode === 429 || (statusCode !== undefined && statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: `http_${statusCode}` }\n }\n if (statusCode !== undefined && statusCode >= 400) {\n return { outcome: 'permanent', errorCode: `http_${statusCode}` }\n }\n\n // Sem código nenhum é quase sempre falha de rede/DNS, que passa numa segunda tentativa. O risco\n // do palpite é limitado: o retry é finito (`attempts`) e termina em `failed` de qualquer forma.\n return { outcome: 'retriable', errorCode: 'unknown' }\n}\n\nexport function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort {\n return {\n async send(params: SendWhatsAppParams): Promise<DeliveryAttemptResult> {\n try {\n const result = params.template\n ? await channel.sendTemplate({\n to: params.to,\n templateName: params.template.templateName,\n languageCode: params.template.languageCode,\n bodyParameters: params.template.bodyParameters ? [...params.template.bodyParameters] : undefined,\n })\n : await channel.sendText(params.to, params.body)\n\n return { outcome: 'sent', providerMessageId: result.externalMessageId ?? undefined }\n } catch (error) {\n return classifyError(error)\n }\n },\n }\n}\n"],"mappings":";;;;AAIO,IAAMA,uBAAuB;EAClCC,OAAO;EACPC,MAAM;EACNC,OAAO;EACPC,UAAU;EACVC,KAAK;AACP;AAIO,IAAMC,qBAAqD;EAChEN,qBAAqBE;EACrBF,qBAAqBI;EACrBJ,qBAAqBK;;AAGhB,IAAME,sBAAsB;EACjCC,SAAS;EACTC,WAAW;EACXC,QAAQ;EACRC,YAAY;EACZC,kBAAkB;EAClBC,QAAQ;AACV;AAGO,IAAMC,kBAAkB;EAC7BJ,QAAQ;EACRK,MAAM;EACNC,WAAW;EACXH,QAAQ;EACRI,SAAS;EACTC,SAAS;AACX;AAGO,IAAMC,kBAAkB;EAC7BC,KAAK;EACLC,SAAS;EACTC,KAAK;AACP;AAGO,IAAMC,cAAc;EACzBC,MAAM;EACNC,KAAK;AACP;AAGO,IAAMC,eAAe;EAC1BC,MAAM;EACNC,QAAQ;EACRC,KAAK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E,SAAS;MAAaC,WAAW,QAAQH,QAAAA;IAAW;AAChG,QAAIP,gBAAgBQ,IAAID,QAAAA,EAAW,QAAO;MAAEE,SAAS;MAAaC,WAAW,QAAQH,QAAAA;IAAW;EAClG;AAEA,QAAMO,aAAab,iBAAiBC,OAAO,YAAA,KAAiBD,iBAAiBC,OAAO,QAAA;AACpF,MAAIY,eAAe,OAAQA,eAAeV,UAAaU,cAAc,KAAM;AACzE,WAAO;MAAEL,SAAS;MAAaC,WAAW,QAAQI,UAAAA;IAAa;EACjE;AACA,MAAIA,eAAeV,UAAaU,cAAc,KAAK;AACjD,WAAO;MAAEL,SAAS;MAAaC,WAAW,QAAQI,UAAAA;IAAa;EACjE;AAIA,SAAO;IAAEL,SAAS;IAAaC,WAAW;EAAU;AACtD;AAzBSJ;AA2BF,SAASS,gCAAgCC,SAA+B;AAC7E,SAAO;IACL,MAAMC,KAAKC,QAA0B;AACnC,UAAI;AACF,cAAMC,SAASD,OAAOE,WAClB,MAAMJ,QAAQK,aAAa;UACzBC,IAAIJ,OAAOI;UACXC,cAAcL,OAAOE,SAASG;UAC9BC,cAAcN,OAAOE,SAASI;UAC9BC,gBAAgBP,OAAOE,SAASK,iBAAiB;eAAIP,OAAOE,SAASK;cAAkBrB;QACzF,CAAA,IACA,MAAMY,QAAQU,SAASR,OAAOI,IAAIJ,OAAOS,IAAI;AAEjD,eAAO;UAAElB,SAAS;UAAQmB,mBAAmBT,OAAOU,qBAAqBzB;QAAU;MACrF,SAASF,OAAO;AACd,eAAOI,cAAcJ,KAAAA;MACvB;IACF;EACF;AACF;AAnBgBa;","names":["NOTIFICATION_CHANNEL","INBOX","PUSH","EMAIL","WHATSAPP","SMS","INTRUSIVE_CHANNELS","NOTIFICATION_STATUS","PENDING","SCHEDULED","QUEUED","DISPATCHED","PARTIALLY_FAILED","FAILED","DELIVERY_STATUS","SENT","DELIVERED","BOUNCED","SKIPPED","DEVICE_PLATFORM","IOS","ANDROID","WEB","PUSH_DRIVER","EXPO","FCM","EMAIL_DRIVER","SMTP","RESEND","SES","SUPPRESSION_REASON","BOUNCE","COMPLAINT","OPT_OUT","NOTIFICATION_CATEGORY_HINT","ORDER_STATUS","PAYMENT","SECURITY","MARKETING","SYSTEM","z","HHMM","MAX_PER_PAGE","quietHoursShape","quietHoursStart","z","string","regex","optional","quietHoursEnd","timezone","min","sendNotificationSchema","object","recipientUserId","uuid","category","max","templateKey","payload","record","unknown","channels","array","nativeEnum","NOTIFICATION_CHANNEL","nonempty","dedupeKey","scheduledFor","coerce","date","locale","registerDeviceSchema","platform","DEVICE_PLATFORM","driver","PUSH_DRIVER","token","appVersion","preferenceEntrySchema","channel","enabled","boolean","updatePreferencesSchema","preferences","upsertTemplateSchema","key","subject","body","whatsappTemplateName","active","default","listNotificationsQuerySchema","read","enum","transform","value","cursor","perPage","number","int","deliveryWebhookSchema","providerMessageId","status","errorCode","occurredAt","suppressionReason","SUPPRESSION_REASON","NOTIFICATION_EVENT","CREATED","DISPATCHED","READ","DELIVERY_SENT","DELIVERY_FAILED","DELIVERY_BOUNCED","DEVICE_REGISTERED","DEVICE_INVALIDATED","PREFERENCES_UPDATED","NotificationError","Error","message","statusCode","code","details","name","NOTIFICATION_ERROR_CODES","TEMPLATE_NOT_FOUND","CHANNEL_NOT_CONFIGURED","RECIPIENT_UNRESOLVED","SUPPRESSED_TARGET","NOT_FOUND","INVALID_WEBHOOK_SIGNATURE","DUPLICATE_WEBHOOK_DELIVERY","DEVICE_NOT_FOUND","THROTTLED","CONFIG_MISSING","TemplateNotFoundError","templateKey","channel","locale","ChannelNotConfiguredError","RecipientUnresolvedError","userId","SuppressedTargetError","reason","NotificationNotFoundError","notificationId","InvalidWebhookSignatureError","DuplicateWebhookDeliveryError","nonce","DeviceNotFoundError","deviceId","ThrottledError","retryAfterSeconds","ConfigMissingError","field","INVALID_TARGET_CODES","Set","PERMANENT_CODES","RETRIABLE_CODES","readNumericField","error","field","undefined","value","classifyError","metaCode","has","outcome","errorCode","suppressionReason","SUPPRESSION_REASON","BOUNCE","statusCode","createWhatsAppDriverFromChannel","channel","send","params","result","template","sendTemplate","to","templateName","languageCode","bodyParameters","sendText","body","providerMessageId","externalMessageId"]}
|
|
1
|
+
{"version":3,"sources":["../src/notification.types.ts","../src/schemas.ts","../src/events.ts","../src/errors.ts","../src/whatsappDriver.ts","../src/templateRender.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport const NOTIFICATION_CHANNEL = {\n INBOX: 'inbox',\n PUSH: 'push',\n EMAIL: 'email',\n WHATSAPP: 'whatsapp',\n SMS: 'sms',\n} as const\nexport type NotificationChannel = (typeof NOTIFICATION_CHANNEL)[keyof typeof NOTIFICATION_CHANNEL]\n\n/** Canais que interrompem o destinatário e por isso respeitam quiet hours (ver spec §10.4). */\nexport const INTRUSIVE_CHANNELS: readonly NotificationChannel[] = [\n NOTIFICATION_CHANNEL.PUSH,\n NOTIFICATION_CHANNEL.WHATSAPP,\n NOTIFICATION_CHANNEL.SMS,\n]\n\nexport const NOTIFICATION_STATUS = {\n PENDING: 'pending',\n SCHEDULED: 'scheduled',\n QUEUED: 'queued',\n DISPATCHED: 'dispatched',\n PARTIALLY_FAILED: 'partially_failed',\n FAILED: 'failed',\n} as const\nexport type NotificationStatus = (typeof NOTIFICATION_STATUS)[keyof typeof NOTIFICATION_STATUS]\n\nexport const DELIVERY_STATUS = {\n QUEUED: 'queued',\n SENT: 'sent',\n DELIVERED: 'delivered',\n FAILED: 'failed',\n BOUNCED: 'bounced',\n SKIPPED: 'skipped',\n} as const\nexport type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS]\n\nexport const DEVICE_PLATFORM = {\n IOS: 'ios',\n ANDROID: 'android',\n WEB: 'web',\n} as const\nexport type DevicePlatform = (typeof DEVICE_PLATFORM)[keyof typeof DEVICE_PLATFORM]\n\nexport const PUSH_DRIVER = {\n EXPO: 'expo',\n FCM: 'fcm',\n} as const\nexport type PushDriver = (typeof PUSH_DRIVER)[keyof typeof PUSH_DRIVER]\n\nexport const EMAIL_DRIVER = {\n SMTP: 'smtp',\n RESEND: 'resend',\n SES: 'ses',\n} as const\nexport type EmailDriver = (typeof EMAIL_DRIVER)[keyof typeof EMAIL_DRIVER]\n\nexport const SUPPRESSION_REASON = {\n BOUNCE: 'bounce',\n COMPLAINT: 'complaint',\n OPT_OUT: 'opt_out',\n} as const\nexport type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON]\n\n/**\n * Sugestão de nomenclatura, sem valor normativo (decisão Q2 da spec). `category` é `varchar`\n * livre porque é vocabulário de negócio do produto — fechá-la num enum aqui obrigaria uma major\n * do pacote a cada produto novo.\n */\nexport const NOTIFICATION_CATEGORY_HINT = {\n ORDER_STATUS: 'order_status',\n PAYMENT: 'payment',\n SECURITY: 'security',\n MARKETING: 'marketing',\n SYSTEM: 'system',\n} as const\n\nexport type NotificationId = string\nexport type CompanyId = string\nexport type UserId = string\n\nexport type NotificationSummary = {\n readonly id: NotificationId\n readonly category: string\n readonly templateKey: string\n readonly title: string\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n readonly status: NotificationStatus\n readonly scheduledFor?: string\n readonly readAt?: string\n readonly createdAt: string\n}\n\nexport type DeliverySummary = {\n readonly id: string\n readonly notificationId: NotificationId\n readonly channel: NotificationChannel\n readonly driver?: string\n /** Nunca o endereço em claro: `****1234`, `a***@dominio.com` (LGPD — ver spec §5). */\n readonly targetMasked?: string\n readonly status: DeliveryStatus\n readonly attempt: number\n readonly providerMessageId?: string\n readonly errorCode?: string\n readonly sentAt?: string\n readonly deliveredAt?: string\n readonly failedAt?: string\n}\n\nexport type DeviceRegistration = {\n readonly id: string\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n readonly lastSeenAt: string\n readonly disabledAt?: string\n readonly disabledReason?: string\n}\n\nexport type NotificationPreference = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\n /** `HH:mm` no timezone resolvido para o destinatário; ambos ausentes = sem janela de silêncio. */\n readonly quietHoursStart?: string\n readonly quietHoursEnd?: string\n readonly timezone?: string\n}\n\nexport type NotificationTemplate = {\n readonly id: string\n readonly key: string\n readonly channel: NotificationChannel\n readonly locale: string\n readonly version: number\n readonly subject?: string\n readonly body: string\n /**\n * Nome do template aprovado na Meta. Sem ele, o canal WhatsApp é pulado fora da janela de 24 h\n * em vez de estourar erro na cara do usuário (spec §10.7).\n */\n readonly whatsappTemplateName?: string\n readonly active: boolean\n}\n\nexport type SendNotificationParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n readonly payload?: Readonly<Record<string, unknown>>\n /** Sem canais explícitos, o fan-out resolve pelas preferências do destinatário. */\n readonly channels?: readonly NotificationChannel[]\n /** Chave de negócio da entrega. Repetição devolve a notificação existente, não uma nova. */\n readonly dedupeKey?: string\n readonly scheduledFor?: Date\n readonly locale?: string\n}\n\nexport type SendNotificationResult = {\n readonly notificationId: NotificationId\n /** `true` quando um `dedupeKey` já visto devolveu a notificação anterior — nada foi reenviado. */\n readonly deduplicated: boolean\n readonly deliveries: readonly DeliverySummary[]\n}\n\nexport type ListNotificationsParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsResult = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type DeliveryReceipt = {\n readonly providerMessageId: string\n readonly status: Extract<DeliveryStatus, 'delivered' | 'bounced' | 'failed'>\n readonly errorCode?: string\n readonly occurredAt: Date\n readonly suppressionReason?: SuppressionReason\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { z } from 'zod'\n\nimport { DEVICE_PLATFORM, NOTIFICATION_CHANNEL, PUSH_DRIVER, SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Schemas de fronteira. Regra que atravessa todos eles: **`companyId` nunca vem do corpo da\n * requisição** — é derivado do contexto autenticado (`database.md`, \"Consistência e\n * multiempresa\"). Aceitá-lo aqui seria entregar o isolamento multiempresa ao cliente.\n */\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/\nconst MAX_PER_PAGE = 100\n\nconst quietHoursShape = {\n quietHoursStart: z.string().regex(HHMM, 'Use HH:mm').optional(),\n quietHoursEnd: z.string().regex(HHMM, 'Use HH:mm').optional(),\n timezone: z.string().min(1).optional(),\n}\n\nexport const sendNotificationSchema = z.object({\n recipientUserId: z.string().uuid(),\n category: z.string().min(1).max(64),\n templateKey: z.string().min(1).max(128),\n payload: z.record(z.unknown()).optional(),\n channels: z.array(z.nativeEnum(NOTIFICATION_CHANNEL)).nonempty().optional(),\n dedupeKey: z.string().min(1).max(256).optional(),\n scheduledFor: z.coerce.date().optional(),\n locale: z.string().min(2).max(16).optional(),\n})\nexport type SendNotificationBody = z.infer<typeof sendNotificationSchema>\n\nexport const registerDeviceSchema = z.object({\n platform: z.nativeEnum(DEVICE_PLATFORM),\n driver: z.nativeEnum(PUSH_DRIVER),\n token: z.string().min(1).max(4096),\n appVersion: z.string().max(32).optional(),\n locale: z.string().min(2).max(16).optional(),\n timezone: z.string().min(1).max(64).optional(),\n})\nexport type RegisterDeviceBody = z.infer<typeof registerDeviceSchema>\n\nexport const preferenceEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n ...quietHoursShape,\n})\n\nexport const updatePreferencesSchema = z.object({\n preferences: z.array(preferenceEntrySchema).max(200),\n})\nexport type UpdatePreferencesBody = z.infer<typeof updatePreferencesSchema>\n\nexport const upsertTemplateSchema = z.object({\n key: z.string().min(1).max(128),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n locale: z.string().min(2).max(16),\n subject: z.string().max(256).optional(),\n body: z.string().min(1).max(8192),\n whatsappTemplateName: z.string().max(128).optional(),\n active: z.boolean().default(true),\n})\nexport type UpsertTemplateBody = z.infer<typeof upsertTemplateSchema>\n\n/** Query string chega sempre como texto — daí o `coerce` e o booleano por literal. */\nexport const listNotificationsQuerySchema = z.object({\n category: z.string().min(1).max(64).optional(),\n read: z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional(),\n cursor: z.string().max(512).optional(),\n perPage: z.coerce.number().int().min(1).max(MAX_PER_PAGE).default(20),\n})\nexport type ListNotificationsQuery = z.infer<typeof listNotificationsQuerySchema>\n\n/**\n * Forma normalizada do recibo de entrega, depois que o parser do driver traduziu o payload do\n * provedor. A verificação de assinatura acontece antes disto, sobre o `rawBody`.\n */\nexport const deliveryWebhookSchema = z.object({\n providerMessageId: z.string().min(1),\n status: z.enum(['delivered', 'bounced', 'failed']),\n errorCode: z.string().max(64).optional(),\n occurredAt: z.coerce.date(),\n suppressionReason: z.nativeEnum(SUPPRESSION_REASON).optional(),\n})\nexport type DeliveryWebhookBody = z.infer<typeof deliveryWebhookSchema>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type {\n CompanyId,\n DevicePlatform,\n NotificationChannel,\n NotificationId,\n NotificationStatus,\n PushDriver,\n SuppressionReason,\n UserId,\n} from './notification.types'\n\n/**\n * Eventos de domínio — os pontos de extensão do produto. É aqui que entra a regra de negócio que\n * o módulo não pode ter (ex.: bounce de e-mail marca o contato como inválido no CRM), sem\n * ninguém editar código do pacote (regra de módulos plugáveis, §3).\n */\nexport const NOTIFICATION_EVENT = {\n CREATED: 'notification.created',\n DISPATCHED: 'notification.dispatched',\n READ: 'notification.read',\n DELIVERY_SENT: 'delivery.sent',\n DELIVERY_FAILED: 'delivery.failed',\n DELIVERY_BOUNCED: 'delivery.bounced',\n DEVICE_REGISTERED: 'device.registered',\n DEVICE_INVALIDATED: 'device.invalidated',\n PREFERENCES_UPDATED: 'preferences.updated',\n} as const\nexport type NotificationEvent = (typeof NOTIFICATION_EVENT)[keyof typeof NOTIFICATION_EVENT]\n\ntype BaseEvent = {\n readonly companyId: CompanyId\n readonly occurredAt: Date\n}\n\nexport type NotificationCreatedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n /** Canais que sobreviveram ao fan-out; os pulados aparecem em `skippedChannels`. */\n readonly channels: readonly NotificationChannel[]\n readonly skippedChannels: readonly { readonly channel: NotificationChannel; readonly reason: string }[]\n}\n\nexport type NotificationDispatchedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly status: NotificationStatus\n}\n\nexport type NotificationReadEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n}\n\nexport type DeliverySentEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly providerMessageId?: string\n readonly attempt: number\n}\n\nexport type DeliveryFailedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly errorCode: string\n readonly attempt: number\n /** `false` quando o retry esgotou ou o erro é permanente — é o gancho para alerta do host. */\n readonly willRetry: boolean\n}\n\nexport type DeliveryBouncedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly reason: SuppressionReason\n}\n\nexport type DeviceRegisteredEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n}\n\nexport type DeviceInvalidatedEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly driver: PushDriver\n readonly errorCode: string\n}\n\nexport type PreferencesUpdatedEvent = BaseEvent & {\n readonly userId: UserId\n readonly categories: readonly string[]\n}\n\n/**\n * Hooks são `void`-tolerantes de propósito: falha de hook do produto não pode derrubar a entrega\n * da notificação. O módulo loga e segue — quem precisa de garantia transacional usa a fila.\n */\nexport type NotificationHooks = {\n onNotificationCreated?(event: NotificationCreatedEvent): Promise<void> | void\n onNotificationDispatched?(event: NotificationDispatchedEvent): Promise<void> | void\n onNotificationRead?(event: NotificationReadEvent): Promise<void> | void\n onDeliverySent?(event: DeliverySentEvent): Promise<void> | void\n onDeliveryFailed?(event: DeliveryFailedEvent): Promise<void> | void\n onDeliveryBounced?(event: DeliveryBouncedEvent): Promise<void> | void\n onDeviceRegistered?(event: DeviceRegisteredEvent): Promise<void> | void\n onDeviceInvalidated?(event: DeviceInvalidatedEvent): Promise<void> | void\n onPreferencesUpdated?(event: PreferencesUpdatedEvent): Promise<void> | void\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { NotificationChannel } from './notification.types'\n\n/**\n * Hierarquia autocontida: um pacote publicado não importa o `DomainError` do host. O host mapeia\n * estes erros no seu exception filter — e o próprio módulo já traz um, para o consumidor das rotas\n * não precisar escrever `try/catch` por endpoint.\n */\nexport class NotificationError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'NotificationError'\n }\n}\n\nexport const NOTIFICATION_ERROR_CODES = {\n TEMPLATE_NOT_FOUND: 'NOTIFICATION_TEMPLATE_NOT_FOUND',\n CHANNEL_NOT_CONFIGURED: 'NOTIFICATION_CHANNEL_NOT_CONFIGURED',\n RECIPIENT_UNRESOLVED: 'NOTIFICATION_RECIPIENT_UNRESOLVED',\n SUPPRESSED_TARGET: 'NOTIFICATION_SUPPRESSED_TARGET',\n NOT_FOUND: 'NOTIFICATION_NOT_FOUND',\n INVALID_WEBHOOK_SIGNATURE: 'NOTIFICATION_INVALID_WEBHOOK_SIGNATURE',\n DUPLICATE_WEBHOOK_DELIVERY: 'NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY',\n DEVICE_NOT_FOUND: 'NOTIFICATION_DEVICE_NOT_FOUND',\n THROTTLED: 'NOTIFICATION_THROTTLED',\n CONFIG_MISSING: 'NOTIFICATION_CONFIG_MISSING',\n} as const\n\nexport class TemplateNotFoundError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly channel: NotificationChannel,\n public readonly locale: string,\n ) {\n super(\n `Template não encontrado para a chave informada neste canal e locale.`,\n 404,\n NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND,\n { templateKey, channel, locale },\n )\n }\n}\n\n/** Canal ligado em `features` sem driver injetado — erro de composição, detectado no boot. */\nexport class ChannelNotConfiguredError extends NotificationError {\n constructor(public readonly channel: NotificationChannel) {\n super(\n `Canal habilitado sem driver injetado — injete o driver em providers.channels ou desligue a feature.`,\n 500,\n NOTIFICATION_ERROR_CODES.CHANNEL_NOT_CONFIGURED,\n { channel },\n )\n }\n}\n\n/**\n * `RecipientResolverPort` não devolveu endereço para o canal. Mensagem sem PII de propósito: o\n * `userId` é identificador opaco, o e-mail ou telefone jamais entra no erro (`security.md` §1).\n */\nexport class RecipientUnresolvedError extends NotificationError {\n constructor(\n public readonly userId: string,\n public readonly channel: NotificationChannel,\n ) {\n super(`Destinatário sem endereço utilizável para este canal.`, 422, NOTIFICATION_ERROR_CODES.RECIPIENT_UNRESOLVED, {\n userId,\n channel,\n })\n }\n}\n\nexport class SuppressedTargetError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly reason: string,\n ) {\n super(`Endereço suprimido para este canal — envio bloqueado.`, 409, NOTIFICATION_ERROR_CODES.SUPPRESSED_TARGET, {\n channel,\n reason,\n })\n }\n}\n\n/**\n * Também é a resposta para notificação de OUTRO usuário: devolver 404 em vez de 403 não revela a\n * existência do recurso a quem não pode vê-lo (BOLA/API1).\n */\nexport class NotificationNotFoundError extends NotificationError {\n constructor(public readonly notificationId: string) {\n super(`Notificação não encontrada.`, 404, NOTIFICATION_ERROR_CODES.NOT_FOUND, { notificationId })\n }\n}\n\nexport class InvalidWebhookSignatureError extends NotificationError {\n constructor() {\n super(`Assinatura do webhook inválida.`, 401, NOTIFICATION_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE)\n }\n}\n\n/** Recibo reenviado dentro da janela de replay (nonce já visto) — não é erro, é ruído esperado. */\nexport class DuplicateWebhookDeliveryError extends NotificationError {\n constructor(public readonly nonce: string) {\n super(`Entrega de webhook duplicada.`, 200, NOTIFICATION_ERROR_CODES.DUPLICATE_WEBHOOK_DELIVERY, { nonce })\n }\n}\n\nexport class DeviceNotFoundError extends NotificationError {\n constructor(public readonly deviceId: string) {\n super(`Dispositivo não encontrado.`, 404, NOTIFICATION_ERROR_CODES.DEVICE_NOT_FOUND, { deviceId })\n }\n}\n\nexport class ThrottledError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly retryAfterSeconds: number,\n ) {\n super(`Limite de envios para este destinatário atingido.`, 429, NOTIFICATION_ERROR_CODES.THROTTLED, {\n channel,\n retryAfterSeconds,\n })\n }\n}\n\n/**\n * Configuração obrigatória ausente (chave de HMAC, segredo de webhook) — falha no boot.\n *\n * Único erro do módulo cuja mensagem nomeia o campo: ele é lido por quem está subindo o serviço,\n * não devolvido a um cliente, e \"algo está faltando\" sem dizer o quê custa uma bisca no código.\n * O nome do campo é identificador de configuração, nunca valor — o segredo em si não aparece.\n */\nexport class ConfigMissingError extends NotificationError {\n constructor(public readonly field: string) {\n super(`Configuração obrigatória ausente: ${field}.`, 500, NOTIFICATION_ERROR_CODES.CONFIG_MISSING, { field })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { DeliveryAttemptResult, SendWhatsAppParams, WhatsAppDriverPort } from './channelDrivers'\nimport { SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Forma mínima que o `channel` do `meta-whatsapp-module` já satisfaz. Descrita aqui por\n * *estrutura*, e não importada do pacote de WhatsApp: é isso que mantém os dois trios\n * independentes — quem só usa inbox não carrega Meta, quem só usa WhatsApp não carrega\n * notificação, e a costura acontece no produto (regra de módulos plugáveis, §2).\n */\nexport type WhatsAppSendingChannel = {\n sendText(to: string, body: string): Promise<{ externalMessageId: string | null }>\n sendTemplate(params: {\n to: string\n templateName: string\n languageCode: string\n bodyParameters?: string[]\n }): Promise<{ externalMessageId: string | null }>\n}\n\n/**\n * Códigos da Graph API que o canal repassa. A lista é curta de propósito: cobre o que muda a\n * decisão do módulo (apagar destino × tentar de novo × desistir) e nada além disso.\n */\nconst INVALID_TARGET_CODES = new Set([131026, 131051])\nconst PERMANENT_CODES = new Set([131047, 131031, 368])\nconst RETRIABLE_CODES = new Set([613, 130429, 131056])\n\nfunction readNumericField(error: unknown, field: string): number | undefined {\n if (typeof error !== 'object' || error === null || !(field in error)) return undefined\n const value = (error as Record<string, unknown>)[field]\n return typeof value === 'number' ? value : undefined\n}\n\nfunction classifyError(error: unknown): DeliveryAttemptResult {\n const metaCode = readNumericField(error, 'code')\n if (metaCode !== undefined) {\n if (INVALID_TARGET_CODES.has(metaCode)) {\n return {\n outcome: 'invalid_target',\n errorCode: `meta_${metaCode}`,\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n }\n }\n if (PERMANENT_CODES.has(metaCode)) return { outcome: 'permanent', errorCode: `meta_${metaCode}` }\n if (RETRIABLE_CODES.has(metaCode)) return { outcome: 'retriable', errorCode: `meta_${metaCode}` }\n }\n\n const statusCode = readNumericField(error, 'statusCode') ?? readNumericField(error, 'status')\n if (statusCode === 429 || (statusCode !== undefined && statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: `http_${statusCode}` }\n }\n if (statusCode !== undefined && statusCode >= 400) {\n return { outcome: 'permanent', errorCode: `http_${statusCode}` }\n }\n\n // Sem código nenhum é quase sempre falha de rede/DNS, que passa numa segunda tentativa. O risco\n // do palpite é limitado: o retry é finito (`attempts`) e termina em `failed` de qualquer forma.\n return { outcome: 'retriable', errorCode: 'unknown' }\n}\n\nexport function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort {\n return {\n async send(params: SendWhatsAppParams): Promise<DeliveryAttemptResult> {\n try {\n const result = params.template\n ? await channel.sendTemplate({\n to: params.to,\n templateName: params.template.templateName,\n languageCode: params.template.languageCode,\n bodyParameters: params.template.bodyParameters ? [...params.template.bodyParameters] : undefined,\n })\n : await channel.sendText(params.to, params.body)\n\n return { outcome: 'sent', providerMessageId: result.externalMessageId ?? undefined }\n } catch (error) {\n return classifyError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * A renderização default de template, pura e sem dependência.\n *\n * Mora no contracts, e não no módulo, por um motivo específico: a tela de configuração precisa\n * mostrar um PREVIEW do que o cliente vai receber, e o módulo carrega Drizzle — o frontend não pode\n * importá-lo. Reimplementar a interpolação no host resolveria hoje e divergiria amanhã, e **preview\n * que mente é pior que preview nenhum**: alguém salva o template confiando no que viu.\n *\n * Com a função aqui, o `notification-module` renderiza para enviar e a UI renderiza para mostrar,\n * lendo o MESMO código. Divergência deixa de ser possível em vez de ser improvável.\n */\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g\nconst DEFAULT_TITLE_MAX_LENGTH = 120\n\nconst HTML_ESCAPE_MAP: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n}\n\nexport function escapeTemplateHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (character) => HTML_ESCAPE_MAP[character] ?? character)\n}\n\n/** `{{campo}}` → valor do payload. Campo ausente vira string vazia, nunca o literal `{{campo}}`. */\nexport function interpolateTemplate(template: string, payload: Readonly<Record<string, unknown>>): string {\n return template.replace(PLACEHOLDER_PATTERN, (_match, key: string) => {\n const value = payload[key]\n return value === undefined || value === null ? '' : String(value)\n })\n}\n\nexport function deriveTitleFromBody(body: string): string {\n const firstLine = body.split('\\n')[0] ?? ''\n return firstLine.length > DEFAULT_TITLE_MAX_LENGTH ? `${firstLine.slice(0, DEFAULT_TITLE_MAX_LENGTH)}…` : firstLine\n}\n\n/** Os nomes de campo que um template referencia — o que a tela de configuração precisa pedir. */\nexport function extractTemplatePlaceholders(template: string): readonly string[] {\n const found = new Set<string>()\n for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) found.add(match[1])\n }\n return [...found]\n}\n\nexport type RenderedTemplatePreview = {\n readonly title: string\n readonly body: string\n readonly html?: string\n}\n\n/**\n * Mesma saída que o envio produz. `channel` importa porque só e-mail ganha a versão HTML — mostrar\n * HTML no preview de WhatsApp faria a tela prometer formatação que o canal não tem.\n */\nexport function renderTemplate(params: {\n readonly channel: string\n readonly subject?: string | undefined\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n}): RenderedTemplatePreview {\n const body = interpolateTemplate(params.body, params.payload)\n const title = params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body)\n\n if (params.channel !== 'email') return { title, body }\n\n // Escapa o resultado já interpolado (texto do template e valores do payload juntos), depois troca\n // quebra de linha por <br> — quem quer HTML rico troca o renderer, em vez de descobrir por um bug\n // de escape.\n return { title, body, html: escapeTemplateHtml(body).replace(/\\n/g, '<br>') }\n}\n"],"mappings":";;;;AAIO,IAAMA,uBAAuB;EAClCC,OAAO;EACPC,MAAM;EACNC,OAAO;EACPC,UAAU;EACVC,KAAK;AACP;AAIO,IAAMC,qBAAqD;EAChEN,qBAAqBE;EACrBF,qBAAqBI;EACrBJ,qBAAqBK;;AAGhB,IAAME,sBAAsB;EACjCC,SAAS;EACTC,WAAW;EACXC,QAAQ;EACRC,YAAY;EACZC,kBAAkB;EAClBC,QAAQ;AACV;AAGO,IAAMC,kBAAkB;EAC7BJ,QAAQ;EACRK,MAAM;EACNC,WAAW;EACXH,QAAQ;EACRI,SAAS;EACTC,SAAS;AACX;AAGO,IAAMC,kBAAkB;EAC7BC,KAAK;EACLC,SAAS;EACTC,KAAK;AACP;AAGO,IAAMC,cAAc;EACzBC,MAAM;EACNC,KAAK;AACP;AAGO,IAAMC,eAAe;EAC1BC,MAAM;EACNC,QAAQ;EACRC,KAAK;AACP;AAGO,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H;AAKT,SAASI,oBAAoBC,UAAkBC,SAA0C;AAC9F,SAAOD,SAASH,QAAQL,qBAAqB,CAACU,QAAQC,QAAAA;AACpD,UAAMC,QAAQH,QAAQE,GAAAA;AACtB,WAAOC,UAAUC,UAAaD,UAAU,OAAO,KAAKE,OAAOF,KAAAA;EAC7D,CAAA;AACF;AALgBL;AAOT,SAASQ,oBAAoBC,MAAY;AAC9C,QAAMC,YAAYD,KAAKE,MAAM,IAAA,EAAM,CAAA,KAAM;AACzC,SAAOD,UAAUE,SAASlB,2BAA2B,GAAGgB,UAAUG,MAAM,GAAGnB,wBAAAA,CAAAA,WAA+BgB;AAC5G;AAHgBF;AAMT,SAASM,4BAA4Bb,UAAgB;AAC1D,QAAMc,QAAQ,oBAAIC,IAAAA;AAClB,aAAWC,SAAShB,SAASiB,SAASzB,mBAAAA,GAAsB;AAC1D,QAAIwB,MAAM,CAAA,EAAIF,OAAMI,IAAIF,MAAM,CAAA,CAAE;EAClC;AACA,SAAO;OAAIF;;AACb;AANgBD;AAkBT,SAASM,eAAeC,QAK9B;AACC,QAAMZ,OAAOT,oBAAoBqB,OAAOZ,MAAMY,OAAOnB,OAAO;AAC5D,QAAMoB,QAAQD,OAAOE,UAAUvB,oBAAoBqB,OAAOE,SAASF,OAAOnB,OAAO,IAAIM,oBAAoBC,IAAAA;AAEzG,MAAIY,OAAOG,YAAY,QAAS,QAAO;IAAEF;IAAOb;EAAK;AAKrD,SAAO;IAAEa;IAAOb;IAAMgB,MAAM7B,mBAAmBa,IAAAA,EAAMX,QAAQ,OAAO,MAAA;EAAQ;AAC9E;AAfgBsB;","names":["NOTIFICATION_CHANNEL","INBOX","PUSH","EMAIL","WHATSAPP","SMS","INTRUSIVE_CHANNELS","NOTIFICATION_STATUS","PENDING","SCHEDULED","QUEUED","DISPATCHED","PARTIALLY_FAILED","FAILED","DELIVERY_STATUS","SENT","DELIVERED","BOUNCED","SKIPPED","DEVICE_PLATFORM","IOS","ANDROID","WEB","PUSH_DRIVER","EXPO","FCM","EMAIL_DRIVER","SMTP","RESEND","SES","SUPPRESSION_REASON","BOUNCE","COMPLAINT","OPT_OUT","NOTIFICATION_CATEGORY_HINT","ORDER_STATUS","PAYMENT","SECURITY","MARKETING","SYSTEM","z","HHMM","MAX_PER_PAGE","quietHoursShape","quietHoursStart","z","string","regex","optional","quietHoursEnd","timezone","min","sendNotificationSchema","object","recipientUserId","uuid","category","max","templateKey","payload","record","unknown","channels","array","nativeEnum","NOTIFICATION_CHANNEL","nonempty","dedupeKey","scheduledFor","coerce","date","locale","registerDeviceSchema","platform","DEVICE_PLATFORM","driver","PUSH_DRIVER","token","appVersion","preferenceEntrySchema","channel","enabled","boolean","updatePreferencesSchema","preferences","upsertTemplateSchema","key","subject","body","whatsappTemplateName","active","default","listNotificationsQuerySchema","read","enum","transform","value","cursor","perPage","number","int","deliveryWebhookSchema","providerMessageId","status","errorCode","occurredAt","suppressionReason","SUPPRESSION_REASON","NOTIFICATION_EVENT","CREATED","DISPATCHED","READ","DELIVERY_SENT","DELIVERY_FAILED","DELIVERY_BOUNCED","DEVICE_REGISTERED","DEVICE_INVALIDATED","PREFERENCES_UPDATED","NotificationError","Error","message","statusCode","code","details","name","NOTIFICATION_ERROR_CODES","TEMPLATE_NOT_FOUND","CHANNEL_NOT_CONFIGURED","RECIPIENT_UNRESOLVED","SUPPRESSED_TARGET","NOT_FOUND","INVALID_WEBHOOK_SIGNATURE","DUPLICATE_WEBHOOK_DELIVERY","DEVICE_NOT_FOUND","THROTTLED","CONFIG_MISSING","TemplateNotFoundError","templateKey","channel","locale","ChannelNotConfiguredError","RecipientUnresolvedError","userId","SuppressedTargetError","reason","NotificationNotFoundError","notificationId","InvalidWebhookSignatureError","DuplicateWebhookDeliveryError","nonce","DeviceNotFoundError","deviceId","ThrottledError","retryAfterSeconds","ConfigMissingError","field","INVALID_TARGET_CODES","Set","PERMANENT_CODES","RETRIABLE_CODES","readNumericField","error","field","undefined","value","classifyError","metaCode","has","outcome","errorCode","suppressionReason","SUPPRESSION_REASON","BOUNCE","statusCode","createWhatsAppDriverFromChannel","channel","send","params","result","template","sendTemplate","to","templateName","languageCode","bodyParameters","sendText","body","providerMessageId","externalMessageId","PLACEHOLDER_PATTERN","DEFAULT_TITLE_MAX_LENGTH","HTML_ESCAPE_MAP","escapeTemplateHtml","text","replace","character","interpolateTemplate","template","payload","_match","key","value","undefined","String","deriveTitleFromBody","body","firstLine","split","length","slice","extractTemplatePlaceholders","found","Set","match","matchAll","add","renderTemplate","params","title","subject","channel","html"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adatechnology/notification-contracts",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.2",
|
|
4
4
|
"description": "Shared types, zod schemas, and port interfaces for the notification trio (contracts only — no runtime behavior)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|