@adatechnology/notification-contracts 0.1.0-rc.2 → 0.1.0-rc.3
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 +184 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +182 -1
- package/dist/index.d.ts +182 -1
- package/dist/index.js +175 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -93,6 +93,14 @@ var preferenceEntrySchema = z.object({
|
|
|
93
93
|
var updatePreferencesSchema = z.object({
|
|
94
94
|
preferences: z.array(preferenceEntrySchema).max(200)
|
|
95
95
|
});
|
|
96
|
+
var categoryPolicyEntrySchema = z.object({
|
|
97
|
+
category: z.string().min(1).max(64),
|
|
98
|
+
channel: z.nativeEnum(NOTIFICATION_CHANNEL),
|
|
99
|
+
enabled: z.boolean()
|
|
100
|
+
});
|
|
101
|
+
var updateCategoryPoliciesSchema = z.object({
|
|
102
|
+
policies: z.array(categoryPolicyEntrySchema).max(500)
|
|
103
|
+
});
|
|
96
104
|
var upsertTemplateSchema = z.object({
|
|
97
105
|
key: z.string().min(1).max(128),
|
|
98
106
|
channel: z.nativeEnum(NOTIFICATION_CHANNEL),
|
|
@@ -159,7 +167,38 @@ var NOTIFICATION_ERROR_CODES = {
|
|
|
159
167
|
DUPLICATE_WEBHOOK_DELIVERY: "NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY",
|
|
160
168
|
DEVICE_NOT_FOUND: "NOTIFICATION_DEVICE_NOT_FOUND",
|
|
161
169
|
THROTTLED: "NOTIFICATION_THROTTLED",
|
|
162
|
-
CONFIG_MISSING: "NOTIFICATION_CONFIG_MISSING"
|
|
170
|
+
CONFIG_MISSING: "NOTIFICATION_CONFIG_MISSING",
|
|
171
|
+
TEMPLATE_UNKNOWN_VARIABLE: "NOTIFICATION_TEMPLATE_UNKNOWN_VARIABLE"
|
|
172
|
+
};
|
|
173
|
+
var TemplateIdNotFoundError = class extends NotificationError {
|
|
174
|
+
static {
|
|
175
|
+
__name(this, "TemplateIdNotFoundError");
|
|
176
|
+
}
|
|
177
|
+
templateId;
|
|
178
|
+
constructor(templateId) {
|
|
179
|
+
super(`Template n\xE3o encontrado.`, 404, NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND, {
|
|
180
|
+
templateId
|
|
181
|
+
}), this.templateId = templateId;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
var UnknownTemplateVariablesError = class extends NotificationError {
|
|
185
|
+
static {
|
|
186
|
+
__name(this, "UnknownTemplateVariablesError");
|
|
187
|
+
}
|
|
188
|
+
templateKey;
|
|
189
|
+
fields;
|
|
190
|
+
constructor(templateKey, fields) {
|
|
191
|
+
super(`O template usa vari\xE1veis que n\xE3o existem no cat\xE1logo desta notifica\xE7\xE3o.`, 400, NOTIFICATION_ERROR_CODES.TEMPLATE_UNKNOWN_VARIABLE, {
|
|
192
|
+
templateKey,
|
|
193
|
+
fields: [
|
|
194
|
+
...fields
|
|
195
|
+
],
|
|
196
|
+
details: fields.map((field) => ({
|
|
197
|
+
field,
|
|
198
|
+
message: "vari\xE1vel desconhecida"
|
|
199
|
+
}))
|
|
200
|
+
}), this.templateKey = templateKey, this.fields = fields;
|
|
201
|
+
}
|
|
163
202
|
};
|
|
164
203
|
var TemplateNotFoundError = class extends NotificationError {
|
|
165
204
|
static {
|
|
@@ -362,6 +401,67 @@ function createWhatsAppDriverFromChannel(channel) {
|
|
|
362
401
|
}
|
|
363
402
|
__name(createWhatsAppDriverFromChannel, "createWhatsAppDriverFromChannel");
|
|
364
403
|
|
|
404
|
+
// src/previewViewport.ts
|
|
405
|
+
var PREVIEW_VIEWPORT = {
|
|
406
|
+
DESKTOP: "desktop",
|
|
407
|
+
MOBILE: "mobile"
|
|
408
|
+
};
|
|
409
|
+
var MOBILE = {
|
|
410
|
+
viewport: PREVIEW_VIEWPORT.MOBILE,
|
|
411
|
+
width: 375
|
|
412
|
+
};
|
|
413
|
+
var PREVIEW_VIEWPORT_BY_CHANNEL = {
|
|
414
|
+
[NOTIFICATION_CHANNEL.EMAIL]: [
|
|
415
|
+
{
|
|
416
|
+
viewport: PREVIEW_VIEWPORT.DESKTOP,
|
|
417
|
+
width: 600
|
|
418
|
+
},
|
|
419
|
+
MOBILE
|
|
420
|
+
],
|
|
421
|
+
[NOTIFICATION_CHANNEL.PUSH]: [
|
|
422
|
+
{
|
|
423
|
+
viewport: PREVIEW_VIEWPORT.DESKTOP,
|
|
424
|
+
width: 360
|
|
425
|
+
},
|
|
426
|
+
MOBILE
|
|
427
|
+
],
|
|
428
|
+
[NOTIFICATION_CHANNEL.WHATSAPP]: [
|
|
429
|
+
{
|
|
430
|
+
viewport: PREVIEW_VIEWPORT.DESKTOP,
|
|
431
|
+
width: 400
|
|
432
|
+
},
|
|
433
|
+
MOBILE
|
|
434
|
+
],
|
|
435
|
+
[NOTIFICATION_CHANNEL.INBOX]: [
|
|
436
|
+
{
|
|
437
|
+
viewport: PREVIEW_VIEWPORT.DESKTOP,
|
|
438
|
+
width: 480
|
|
439
|
+
},
|
|
440
|
+
MOBILE
|
|
441
|
+
],
|
|
442
|
+
[NOTIFICATION_CHANNEL.SMS]: [
|
|
443
|
+
MOBILE
|
|
444
|
+
]
|
|
445
|
+
};
|
|
446
|
+
var TEMPLATE_CONSTRAINTS_BY_CHANNEL = {
|
|
447
|
+
[NOTIFICATION_CHANNEL.EMAIL]: {
|
|
448
|
+
title: 78
|
|
449
|
+
},
|
|
450
|
+
[NOTIFICATION_CHANNEL.PUSH]: {
|
|
451
|
+
title: 65,
|
|
452
|
+
body: 240
|
|
453
|
+
},
|
|
454
|
+
[NOTIFICATION_CHANNEL.WHATSAPP]: {
|
|
455
|
+
body: 1024
|
|
456
|
+
},
|
|
457
|
+
[NOTIFICATION_CHANNEL.INBOX]: {
|
|
458
|
+
title: 120
|
|
459
|
+
},
|
|
460
|
+
[NOTIFICATION_CHANNEL.SMS]: {
|
|
461
|
+
body: 160
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
|
|
365
465
|
// src/templateRender.ts
|
|
366
466
|
var PLACEHOLDER_PATTERN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
|
|
367
467
|
var DEFAULT_TITLE_MAX_LENGTH = 120;
|
|
@@ -398,20 +498,83 @@ function extractTemplatePlaceholders(template) {
|
|
|
398
498
|
];
|
|
399
499
|
}
|
|
400
500
|
__name(extractTemplatePlaceholders, "extractTemplatePlaceholders");
|
|
501
|
+
function sanitizeTitle(title) {
|
|
502
|
+
return title.replace(/[\r\n]+/g, " ").trim();
|
|
503
|
+
}
|
|
504
|
+
__name(sanitizeTitle, "sanitizeTitle");
|
|
505
|
+
function checkConstraints(params) {
|
|
506
|
+
const limits = TEMPLATE_CONSTRAINTS_BY_CHANNEL[params.channel];
|
|
507
|
+
if (!limits) return [];
|
|
508
|
+
const checks = [];
|
|
509
|
+
const values = {
|
|
510
|
+
title: params.title,
|
|
511
|
+
body: params.body
|
|
512
|
+
};
|
|
513
|
+
for (const field of [
|
|
514
|
+
"title",
|
|
515
|
+
"body"
|
|
516
|
+
]) {
|
|
517
|
+
const limit = limits[field];
|
|
518
|
+
if (limit === void 0) continue;
|
|
519
|
+
const actual = values[field].length;
|
|
520
|
+
checks.push({
|
|
521
|
+
field,
|
|
522
|
+
limit,
|
|
523
|
+
actual,
|
|
524
|
+
exceeded: actual > limit
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
return checks;
|
|
528
|
+
}
|
|
529
|
+
__name(checkConstraints, "checkConstraints");
|
|
401
530
|
function renderTemplate(params) {
|
|
402
531
|
const body = interpolateTemplate(params.body, params.payload);
|
|
403
|
-
const title = params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body);
|
|
404
|
-
|
|
532
|
+
const title = sanitizeTitle(params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body));
|
|
533
|
+
const constraints = checkConstraints({
|
|
534
|
+
channel: params.channel,
|
|
405
535
|
title,
|
|
406
536
|
body
|
|
537
|
+
});
|
|
538
|
+
if (params.channel !== "email") return {
|
|
539
|
+
title,
|
|
540
|
+
body,
|
|
541
|
+
constraints
|
|
407
542
|
};
|
|
408
543
|
return {
|
|
409
544
|
title,
|
|
410
545
|
body,
|
|
546
|
+
constraints,
|
|
411
547
|
html: escapeTemplateHtml(body).replace(/\n/g, "<br>")
|
|
412
548
|
};
|
|
413
549
|
}
|
|
414
550
|
__name(renderTemplate, "renderTemplate");
|
|
551
|
+
|
|
552
|
+
// src/templateVariables.ts
|
|
553
|
+
function diffTemplateVariables(params) {
|
|
554
|
+
const used = extractTemplatePlaceholders(`${params.subject ?? ""}
|
|
555
|
+
${params.body}`);
|
|
556
|
+
if (!params.variables) return {
|
|
557
|
+
used,
|
|
558
|
+
unknown: [],
|
|
559
|
+
missingRequired: []
|
|
560
|
+
};
|
|
561
|
+
const declared = new Set(params.variables.map((variable) => variable.name));
|
|
562
|
+
const usedSet = new Set(used);
|
|
563
|
+
return {
|
|
564
|
+
used,
|
|
565
|
+
unknown: used.filter((name) => !declared.has(name)),
|
|
566
|
+
missingRequired: params.variables.filter((variable) => variable.required && !usedSet.has(variable.name)).map((variable) => variable.name)
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
__name(diffTemplateVariables, "diffTemplateVariables");
|
|
570
|
+
function buildPreviewPayload(variables) {
|
|
571
|
+
if (!variables) return {};
|
|
572
|
+
return Object.fromEntries(variables.map((variable) => [
|
|
573
|
+
variable.name,
|
|
574
|
+
variable.example
|
|
575
|
+
]));
|
|
576
|
+
}
|
|
577
|
+
__name(buildPreviewPayload, "buildPreviewPayload");
|
|
415
578
|
export {
|
|
416
579
|
ChannelNotConfiguredError,
|
|
417
580
|
ConfigMissingError,
|
|
@@ -429,15 +592,23 @@ export {
|
|
|
429
592
|
NOTIFICATION_STATUS,
|
|
430
593
|
NotificationError,
|
|
431
594
|
NotificationNotFoundError,
|
|
595
|
+
PREVIEW_VIEWPORT,
|
|
596
|
+
PREVIEW_VIEWPORT_BY_CHANNEL,
|
|
432
597
|
PUSH_DRIVER,
|
|
433
598
|
RecipientUnresolvedError,
|
|
434
599
|
SUPPRESSION_REASON,
|
|
435
600
|
SuppressedTargetError,
|
|
601
|
+
TEMPLATE_CONSTRAINTS_BY_CHANNEL,
|
|
602
|
+
TemplateIdNotFoundError,
|
|
436
603
|
TemplateNotFoundError,
|
|
437
604
|
ThrottledError,
|
|
605
|
+
UnknownTemplateVariablesError,
|
|
606
|
+
buildPreviewPayload,
|
|
607
|
+
categoryPolicyEntrySchema,
|
|
438
608
|
createWhatsAppDriverFromChannel,
|
|
439
609
|
deliveryWebhookSchema,
|
|
440
610
|
deriveTitleFromBody,
|
|
611
|
+
diffTemplateVariables,
|
|
441
612
|
escapeTemplateHtml,
|
|
442
613
|
extractTemplatePlaceholders,
|
|
443
614
|
interpolateTemplate,
|
|
@@ -446,6 +617,7 @@ export {
|
|
|
446
617
|
registerDeviceSchema,
|
|
447
618
|
renderTemplate,
|
|
448
619
|
sendNotificationSchema,
|
|
620
|
+
updateCategoryPoliciesSchema,
|
|
449
621
|
updatePreferencesSchema,
|
|
450
622
|
upsertTemplateSchema
|
|
451
623
|
};
|
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","../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,IAAMC,qBAAqB;EAChCC,QAAQ;EACRC,WAAW;EACXC,SAAS;AACX;AAQO,IAAMC,6BAA6B;EACxCC,cAAc;EACdC,SAAS;EACTC,UAAU;EACVC,WAAW;EACXC,QAAQ;AACV;;;AC1EA,SAASC,SAAS;AAUlB,IAAMC,OAAO;AACb,IAAMC,eAAe;AAErB,IAAMC,kBAAkB;EACtBC,iBAAiBC,EAAEC,OAAM,EAAGC,MAAMN,MAAM,WAAA,EAAaO,SAAQ;EAC7DC,eAAeJ,EAAEC,OAAM,EAAGC,MAAMN,MAAM,WAAA,EAAaO,SAAQ;EAC3DE,UAAUL,EAAEC,OAAM,EAAGK,IAAI,CAAA,EAAGH,SAAQ;AACtC;AAEO,IAAMI,yBAAyBP,EAAEQ,OAAO;EAC7CC,iBAAiBT,EAAEC,OAAM,EAAGS,KAAI;EAChCC,UAAUX,E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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"]}
|
|
1
|
+
{"version":3,"sources":["../src/notification.types.ts","../src/schemas.ts","../src/events.ts","../src/errors.ts","../src/whatsappDriver.ts","../src/previewViewport.ts","../src/templateRender.ts","../src/templateVariables.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\n/**\n * O teto de canais da empresa por categoria, acima da preferência do usuário. Linha ausente\n * significa permitido — fechar por omissão calaria toda categoria existente.\n */\nexport type NotificationCategoryPolicy = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\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 categoryPolicyEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n})\n\nexport const updateCategoryPoliciesSchema = z.object({\n policies: z.array(categoryPolicyEntrySchema).max(500),\n})\nexport type UpdateCategoryPoliciesBody = z.infer<typeof updateCategoryPoliciesSchema>\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 TEMPLATE_UNKNOWN_VARIABLE: 'NOTIFICATION_TEMPLATE_UNKNOWN_VARIABLE',\n} as const\n\n/** Busca por id, e não por identidade — o painel remove pela linha que listou. */\nexport class TemplateIdNotFoundError extends NotificationError {\n constructor(public readonly templateId: string) {\n super(`Template não encontrado.`, 404, NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND, { templateId })\n }\n}\n\n/**\n * O template referencia `{{campo}}` que o produto não promete enviar. Renderizaria vazio para\n * sempre, sem log e sem erro — daí ser recusa na gravação, e não aviso.\n *\n * `details.fields` traz TODAS as desconhecidas, não a primeira: corrigir uma por vez transforma o\n * salvamento em tentativa e erro (`apis.md`, Validação).\n */\nexport class UnknownTemplateVariablesError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly fields: readonly string[],\n ) {\n super(\n `O template usa variáveis que não existem no catálogo desta notificação.`,\n 400,\n NOTIFICATION_ERROR_CODES.TEMPLATE_UNKNOWN_VARIABLE,\n {\n templateKey,\n fields: [...fields],\n details: fields.map((field) => ({ field, message: 'variável desconhecida' })),\n },\n )\n }\n}\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 * Larguras e limites do preview, por canal.\n *\n * Moram aqui, e não no CSS da UI, porque o host que consome a camada headless precisa deles para\n * desenhar o próprio preview — e porque o limite de caracteres não é decoração de tela: ele é a\n * regra do canal, e o editor avisa com ela antes de salvar.\n */\n\nimport { NOTIFICATION_CHANNEL } from './notification.types'\nimport type { NotificationChannel } from './notification.types'\n\nexport const PREVIEW_VIEWPORT = {\n DESKTOP: 'desktop',\n MOBILE: 'mobile',\n} as const\nexport type PreviewViewport = (typeof PREVIEW_VIEWPORT)[keyof typeof PREVIEW_VIEWPORT]\n\nexport type PreviewViewportSpec = {\n readonly viewport: PreviewViewport\n readonly width: number\n}\n\nconst MOBILE: PreviewViewportSpec = { viewport: PREVIEW_VIEWPORT.MOBILE, width: 375 }\n\n/**\n * `email` em 600px é a largura clássica de corpo de e-mail; os demais aproximam o container em que\n * a mensagem aparece no desktop. `sms` não tem desktop — a mensagem é a mesma no aparelho e ponto.\n */\nexport const PREVIEW_VIEWPORT_BY_CHANNEL: Readonly<Record<NotificationChannel, readonly PreviewViewportSpec[]>> = {\n [NOTIFICATION_CHANNEL.EMAIL]: [{ viewport: PREVIEW_VIEWPORT.DESKTOP, width: 600 }, MOBILE],\n [NOTIFICATION_CHANNEL.PUSH]: [{ viewport: PREVIEW_VIEWPORT.DESKTOP, width: 360 }, MOBILE],\n [NOTIFICATION_CHANNEL.WHATSAPP]: [{ viewport: PREVIEW_VIEWPORT.DESKTOP, width: 400 }, MOBILE],\n [NOTIFICATION_CHANNEL.INBOX]: [{ viewport: PREVIEW_VIEWPORT.DESKTOP, width: 480 }, MOBILE],\n [NOTIFICATION_CHANNEL.SMS]: [MOBILE],\n}\n\nexport type TemplateConstraintField = 'title' | 'body'\n\nexport type TemplateConstraintLimits = {\n readonly title?: number\n readonly body?: number\n}\n\n/**\n * Onde o canal corta de verdade. `email.title` são os ~78 caracteres que a lista da caixa de\n * entrada mostra no celular; `push` segue o teto prático do Android; `sms` é o segmento de 160,\n * depois do qual a operadora cobra outra mensagem; `whatsapp.body` é o teto de corpo de template\n * da Meta. `inbox` acompanha o `deriveTitleFromBody`.\n */\nexport const TEMPLATE_CONSTRAINTS_BY_CHANNEL: Readonly<Record<NotificationChannel, TemplateConstraintLimits>> = {\n [NOTIFICATION_CHANNEL.EMAIL]: { title: 78 },\n [NOTIFICATION_CHANNEL.PUSH]: { title: 65, body: 240 },\n [NOTIFICATION_CHANNEL.WHATSAPP]: { body: 1024 },\n [NOTIFICATION_CHANNEL.INBOX]: { title: 120 },\n [NOTIFICATION_CHANNEL.SMS]: { body: 160 },\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\nimport { TEMPLATE_CONSTRAINTS_BY_CHANNEL } from './previewViewport'\nimport type { TemplateConstraintField } from './previewViewport'\nimport type { NotificationChannel } from './notification.types'\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 TemplateConstraintCheck = {\n readonly field: TemplateConstraintField\n readonly limit: number\n readonly actual: number\n readonly exceeded: boolean\n}\n\nexport type RenderedTemplatePreview = {\n readonly title: string\n readonly body: string\n readonly html?: string\n /**\n * O que o canal corta. Vazio quando o canal não declara limite. O editor usa isto para avisar\n * antes de salvar, e o preview para marcar onde o texto some — sem isso, dois quadros de\n * larguras diferentes só provariam que CSS quebra linha.\n */\n readonly constraints: readonly TemplateConstraintCheck[]\n}\n\n/**\n * `\\r` e `\\n` no assunto são o vetor clássico de injeção de header em e-mail. Os providers atuais\n * (Resend e SES são API JSON, nodemailer codifica) já barram, mas o assunto vem de painel agora:\n * a defesa fica onde o texto é produzido, não na esperança de que todo provider futuro trate.\n */\nfunction sanitizeTitle(title: string): string {\n return title.replace(/[\\r\\n]+/g, ' ').trim()\n}\n\nfunction checkConstraints(params: { channel: string; title: string; body: string }): TemplateConstraintCheck[] {\n const limits = TEMPLATE_CONSTRAINTS_BY_CHANNEL[params.channel as NotificationChannel]\n if (!limits) return []\n\n const checks: TemplateConstraintCheck[] = []\n const values: Record<TemplateConstraintField, string> = { title: params.title, body: params.body }\n for (const field of ['title', 'body'] as const) {\n const limit = limits[field]\n if (limit === undefined) continue\n const actual = values[field].length\n checks.push({ field, limit, actual, exceeded: actual > limit })\n }\n return checks\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 = sanitizeTitle(\n params.subject ? interpolateTemplate(params.subject, params.payload) : deriveTitleFromBody(body),\n )\n const constraints = checkConstraints({ channel: params.channel, title, body })\n\n if (params.channel !== 'email') return { title, body, constraints }\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, constraints, html: escapeTemplateHtml(body).replace(/\\n/g, '<br>') }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * O catálogo de variáveis de um template, e a diferença entre o que ele declara e o que o texto\n * usa.\n *\n * Existe porque `{{campo}}` desconhecido não falha: `interpolateTemplate` devolve string vazia, que\n * é o comportamento correto no envio — mensagem com buraco é melhor que mensagem com `{{campo}}`\n * cru. O preço é que um erro de digitação no painel some sem log e sem erro, e só aparece quando o\n * cliente recebe \"Olá , seu pedido\". Com um painel, isso deixa de ser raro.\n *\n * A função é pura e mora aqui, e não no módulo, pelo mesmo motivo do `renderTemplate`: a validação\n * do servidor e o aviso da tela precisam da MESMA regra, e o frontend não pode importar o módulo\n * (carrega Drizzle). Duas implementações divergiriam, e a tela passaria a aprovar o que a rota\n * recusa.\n */\n\nimport { extractTemplatePlaceholders } from './templateRender'\n\nexport type TemplateVariableDefinition = {\n readonly name: string\n /** Valor de exemplo — alimenta o preview. Só o produto sabe que `orderNumber` é \"QC-1042\". */\n readonly example: string\n /** `true` avisa quando o texto não usa a variável; nunca bloqueia (ver `diffTemplateVariables`). */\n readonly required: boolean\n /** Chave de i18n do rótulo na tela. Ausente, a tela mostra o próprio `name`. */\n readonly labelKey?: string\n}\n\n/** `templateKey` → variáveis que o produto promete enviar no payload daquela notificação. */\nexport type TemplateVariableCatalog = Readonly<Record<string, readonly TemplateVariableDefinition[]>>\n\nexport type TemplateVariableDiff = {\n /** Placeholders que o texto referencia, na ordem em que aparecem. */\n readonly used: readonly string[]\n /** Referenciados e não declarados — renderizariam vazio para sempre. */\n readonly unknown: readonly string[]\n /** Declarados como `required` e ausentes do texto. */\n readonly missingRequired: readonly string[]\n}\n\nexport type DiffTemplateVariablesParams = {\n readonly body: string\n readonly subject?: string | undefined\n /**\n * Ausente significa catálogo não declarado para esta `key`, e não catálogo vazio: nesse caso\n * nada é desconhecido. Fechar por omissão quebraria todo host que já usa o módulo sem catálogo.\n */\n readonly variables?: readonly TemplateVariableDefinition[] | undefined\n}\n\nexport function diffTemplateVariables(params: DiffTemplateVariablesParams): TemplateVariableDiff {\n const used = extractTemplatePlaceholders(`${params.subject ?? ''}\\n${params.body}`)\n\n if (!params.variables) return { used, unknown: [], missingRequired: [] }\n\n const declared = new Set(params.variables.map((variable) => variable.name))\n const usedSet = new Set(used)\n\n return {\n used,\n unknown: used.filter((name) => !declared.has(name)),\n missingRequired: params.variables\n .filter((variable) => variable.required && !usedSet.has(variable.name))\n .map((variable) => variable.name),\n }\n}\n\n/**\n * O payload de preview sai do próprio catálogo. Um mapa `key → exemplo` mantido em paralelo\n * divergiria do catálogo na primeira variável nova, e o preview voltaria a mentir.\n */\nexport function buildPreviewPayload(\n variables: readonly TemplateVariableDefinition[] | undefined,\n): Readonly<Record<string, string>> {\n if (!variables) return {}\n return Object.fromEntries(variables.map((variable) => [variable.name, variable.example]))\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;;AAahB,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,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AAUK,IAAI,CAACC,aAAaA,SAASC,IAAI,CAAA;AACzE,QAAMC,UAAU,IAAIJ,IAAIR,IAAAA;AAExB,SAAO;IACLA;IACAK,SAASL,KAAKa,OAAO,CAACF,SAAS,CAACJ,SAASO,IAAIH,IAAAA,CAAAA;IAC7CL,iBAAiBP,OAAOK,UACrBS,OAAO,CAACH,aAAaA,SAASK,YAAY,CAACH,QAAQE,IAAIJ,SAASC,IAAI,CAAA,EACpEF,IAAI,CAACC,aAAaA,SAASC,IAAI;EACpC;AACF;AAfgBb;AAqBT,SAASkB,oBACdZ,WAA4D;AAE5D,MAAI,CAACA,UAAW,QAAO,CAAC;AACxB,SAAOa,OAAOC,YAAYd,UAAUK,IAAI,CAACC,aAAa;IAACA,SAASC;IAAMD,SAASS;GAAQ,CAAA;AACzF;AALgBH;","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","categoryPolicyEntrySchema","updateCategoryPoliciesSchema","policies","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","TEMPLATE_UNKNOWN_VARIABLE","TemplateIdNotFoundError","templateId","UnknownTemplateVariablesError","templateKey","fields","map","field","TemplateNotFoundError","channel","locale","ChannelNotConfiguredError","RecipientUnresolvedError","userId","SuppressedTargetError","reason","NotificationNotFoundError","notificationId","InvalidWebhookSignatureError","DuplicateWebhookDeliveryError","nonce","DeviceNotFoundError","deviceId","ThrottledError","retryAfterSeconds","ConfigMissingError","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","PREVIEW_VIEWPORT","DESKTOP","MOBILE","viewport","width","PREVIEW_VIEWPORT_BY_CHANNEL","NOTIFICATION_CHANNEL","EMAIL","PUSH","WHATSAPP","INBOX","SMS","TEMPLATE_CONSTRAINTS_BY_CHANNEL","title","body","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","sanitizeTitle","title","trim","checkConstraints","params","limits","TEMPLATE_CONSTRAINTS_BY_CHANNEL","channel","checks","values","field","limit","actual","push","exceeded","renderTemplate","subject","constraints","html","diffTemplateVariables","params","used","extractTemplatePlaceholders","subject","body","variables","unknown","missingRequired","declared","Set","map","variable","name","usedSet","filter","has","required","buildPreviewPayload","Object","fromEntries","example"]}
|
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.3",
|
|
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": {
|