@adatechnology/notification-contracts 0.1.0-rc.3 → 0.1.0-rc.5
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 +59 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +77 -16
- package/dist/index.d.ts +77 -16
- package/dist/index.js +55 -25
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -27,6 +27,8 @@ __export(index_exports, {
|
|
|
27
27
|
DEVICE_PLATFORM: () => DEVICE_PLATFORM,
|
|
28
28
|
DeviceNotFoundError: () => DeviceNotFoundError,
|
|
29
29
|
DuplicateWebhookDeliveryError: () => DuplicateWebhookDeliveryError,
|
|
30
|
+
EMAIL_ATTACHMENT_MAX_BYTES: () => EMAIL_ATTACHMENT_MAX_BYTES,
|
|
31
|
+
EMAIL_ATTACHMENT_MAX_COUNT: () => EMAIL_ATTACHMENT_MAX_COUNT,
|
|
30
32
|
EMAIL_DRIVER: () => EMAIL_DRIVER,
|
|
31
33
|
INTRUSIVE_CHANNELS: () => INTRUSIVE_CHANNELS,
|
|
32
34
|
InvalidWebhookSignatureError: () => InvalidWebhookSignatureError,
|
|
@@ -44,12 +46,14 @@ __export(index_exports, {
|
|
|
44
46
|
SUPPRESSION_REASON: () => SUPPRESSION_REASON,
|
|
45
47
|
SuppressedTargetError: () => SuppressedTargetError,
|
|
46
48
|
TEMPLATE_CONSTRAINTS_BY_CHANNEL: () => TEMPLATE_CONSTRAINTS_BY_CHANNEL,
|
|
49
|
+
TEMPLATE_VARIABLE_KIND: () => TEMPLATE_VARIABLE_KIND,
|
|
47
50
|
TemplateIdNotFoundError: () => TemplateIdNotFoundError,
|
|
48
51
|
TemplateNotFoundError: () => TemplateNotFoundError,
|
|
49
52
|
ThrottledError: () => ThrottledError,
|
|
50
53
|
UnknownTemplateVariablesError: () => UnknownTemplateVariablesError,
|
|
51
54
|
buildPreviewPayload: () => buildPreviewPayload,
|
|
52
55
|
categoryPolicyEntrySchema: () => categoryPolicyEntrySchema,
|
|
56
|
+
checkEmailAttachment: () => checkEmailAttachment,
|
|
53
57
|
createWhatsAppDriverFromChannel: () => createWhatsAppDriverFromChannel,
|
|
54
58
|
deliveryWebhookSchema: () => deliveryWebhookSchema,
|
|
55
59
|
deriveTitleFromBody: () => deriveTitleFromBody,
|
|
@@ -124,6 +128,18 @@ var NOTIFICATION_CATEGORY_HINT = {
|
|
|
124
128
|
SYSTEM: "system"
|
|
125
129
|
};
|
|
126
130
|
|
|
131
|
+
// src/emailAttachment.ts
|
|
132
|
+
var EMAIL_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
|
|
133
|
+
var EMAIL_ATTACHMENT_MAX_COUNT = 10;
|
|
134
|
+
function checkEmailAttachment(attachment) {
|
|
135
|
+
if (!attachment.filename.trim()) return "ATTACHMENT_FILENAME_EMPTY";
|
|
136
|
+
if (/[/\\]|\.\./.test(attachment.filename)) return "ATTACHMENT_FILENAME_UNSAFE";
|
|
137
|
+
if (!attachment.contentType.trim()) return "ATTACHMENT_CONTENT_TYPE_EMPTY";
|
|
138
|
+
if (!attachment.url.startsWith("https://")) return "ATTACHMENT_URL_NOT_HTTPS";
|
|
139
|
+
return void 0;
|
|
140
|
+
}
|
|
141
|
+
__name(checkEmailAttachment, "checkEmailAttachment");
|
|
142
|
+
|
|
127
143
|
// src/schemas.ts
|
|
128
144
|
var import_zod = require("zod");
|
|
129
145
|
var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
@@ -470,44 +486,51 @@ __name(createWhatsAppDriverFromChannel, "createWhatsAppDriverFromChannel");
|
|
|
470
486
|
|
|
471
487
|
// src/previewViewport.ts
|
|
472
488
|
var PREVIEW_VIEWPORT = {
|
|
473
|
-
|
|
474
|
-
|
|
489
|
+
BROWSER: "browser",
|
|
490
|
+
IOS: "ios",
|
|
491
|
+
ANDROID: "android"
|
|
475
492
|
};
|
|
476
|
-
var
|
|
477
|
-
viewport: PREVIEW_VIEWPORT.
|
|
493
|
+
var IOS = {
|
|
494
|
+
viewport: PREVIEW_VIEWPORT.IOS,
|
|
478
495
|
width: 375
|
|
479
496
|
};
|
|
497
|
+
var ANDROID = {
|
|
498
|
+
viewport: PREVIEW_VIEWPORT.ANDROID,
|
|
499
|
+
width: 360
|
|
500
|
+
};
|
|
480
501
|
var PREVIEW_VIEWPORT_BY_CHANNEL = {
|
|
502
|
+
/** O unico canal lido no computador tambem — e o assunto corta diferente em cada lugar. */
|
|
481
503
|
[NOTIFICATION_CHANNEL.EMAIL]: [
|
|
482
504
|
{
|
|
483
|
-
viewport: PREVIEW_VIEWPORT.
|
|
505
|
+
viewport: PREVIEW_VIEWPORT.BROWSER,
|
|
484
506
|
width: 600
|
|
485
507
|
},
|
|
486
|
-
|
|
508
|
+
IOS,
|
|
509
|
+
ANDROID
|
|
487
510
|
],
|
|
511
|
+
/**
|
|
512
|
+
* Push, WhatsApp e SMS sao de aparelho. Um quadro largo ao lado sugeriria uma leitura em tela
|
|
513
|
+
* grande que nao existe — e o corte que importa (duas linhas no push, 160 caracteres no SMS)
|
|
514
|
+
* so acontece no celular.
|
|
515
|
+
*/
|
|
488
516
|
[NOTIFICATION_CHANNEL.PUSH]: [
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
width: 360
|
|
492
|
-
},
|
|
493
|
-
MOBILE
|
|
517
|
+
IOS,
|
|
518
|
+
ANDROID
|
|
494
519
|
],
|
|
495
520
|
[NOTIFICATION_CHANNEL.WHATSAPP]: [
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
width: 400
|
|
499
|
-
},
|
|
500
|
-
MOBILE
|
|
521
|
+
IOS,
|
|
522
|
+
ANDROID
|
|
501
523
|
],
|
|
524
|
+
[NOTIFICATION_CHANNEL.SMS]: [
|
|
525
|
+
IOS,
|
|
526
|
+
ANDROID
|
|
527
|
+
],
|
|
528
|
+
/** Inbox e a tela do proprio produto, que e de computador neste ecossistema. */
|
|
502
529
|
[NOTIFICATION_CHANNEL.INBOX]: [
|
|
503
530
|
{
|
|
504
|
-
viewport: PREVIEW_VIEWPORT.
|
|
531
|
+
viewport: PREVIEW_VIEWPORT.BROWSER,
|
|
505
532
|
width: 480
|
|
506
|
-
}
|
|
507
|
-
MOBILE
|
|
508
|
-
],
|
|
509
|
-
[NOTIFICATION_CHANNEL.SMS]: [
|
|
510
|
-
MOBILE
|
|
533
|
+
}
|
|
511
534
|
]
|
|
512
535
|
};
|
|
513
536
|
var TEMPLATE_CONSTRAINTS_BY_CHANNEL = {
|
|
@@ -617,26 +640,33 @@ function renderTemplate(params) {
|
|
|
617
640
|
__name(renderTemplate, "renderTemplate");
|
|
618
641
|
|
|
619
642
|
// src/templateVariables.ts
|
|
643
|
+
var TEMPLATE_VARIABLE_KIND = {
|
|
644
|
+
TEXT: "text",
|
|
645
|
+
ATTACHMENT: "attachment"
|
|
646
|
+
};
|
|
620
647
|
function diffTemplateVariables(params) {
|
|
621
648
|
const used = extractTemplatePlaceholders(`${params.subject ?? ""}
|
|
622
649
|
${params.body}`);
|
|
623
650
|
if (!params.variables) return {
|
|
624
651
|
used,
|
|
625
652
|
unknown: [],
|
|
626
|
-
missingRequired: []
|
|
653
|
+
missingRequired: [],
|
|
654
|
+
attachmentsInText: []
|
|
627
655
|
};
|
|
628
656
|
const declared = new Set(params.variables.map((variable) => variable.name));
|
|
629
657
|
const usedSet = new Set(used);
|
|
658
|
+
const attachments = new Set(params.variables.filter((variable) => variable.kind === TEMPLATE_VARIABLE_KIND.ATTACHMENT).map((variable) => variable.name));
|
|
630
659
|
return {
|
|
631
660
|
used,
|
|
632
661
|
unknown: used.filter((name) => !declared.has(name)),
|
|
633
|
-
missingRequired: params.variables.filter((variable) => variable.required && !usedSet.has(variable.name)).map((variable) => variable.name)
|
|
662
|
+
missingRequired: params.variables.filter((variable) => variable.required && variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT && !usedSet.has(variable.name)).map((variable) => variable.name),
|
|
663
|
+
attachmentsInText: used.filter((name) => attachments.has(name))
|
|
634
664
|
};
|
|
635
665
|
}
|
|
636
666
|
__name(diffTemplateVariables, "diffTemplateVariables");
|
|
637
667
|
function buildPreviewPayload(variables) {
|
|
638
668
|
if (!variables) return {};
|
|
639
|
-
return Object.fromEntries(variables.map((variable) => [
|
|
669
|
+
return Object.fromEntries(variables.filter((variable) => variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT).map((variable) => [
|
|
640
670
|
variable.name,
|
|
641
671
|
variable.example
|
|
642
672
|
]));
|
|
@@ -650,6 +680,8 @@ __name(buildPreviewPayload, "buildPreviewPayload");
|
|
|
650
680
|
DEVICE_PLATFORM,
|
|
651
681
|
DeviceNotFoundError,
|
|
652
682
|
DuplicateWebhookDeliveryError,
|
|
683
|
+
EMAIL_ATTACHMENT_MAX_BYTES,
|
|
684
|
+
EMAIL_ATTACHMENT_MAX_COUNT,
|
|
653
685
|
EMAIL_DRIVER,
|
|
654
686
|
INTRUSIVE_CHANNELS,
|
|
655
687
|
InvalidWebhookSignatureError,
|
|
@@ -667,12 +699,14 @@ __name(buildPreviewPayload, "buildPreviewPayload");
|
|
|
667
699
|
SUPPRESSION_REASON,
|
|
668
700
|
SuppressedTargetError,
|
|
669
701
|
TEMPLATE_CONSTRAINTS_BY_CHANNEL,
|
|
702
|
+
TEMPLATE_VARIABLE_KIND,
|
|
670
703
|
TemplateIdNotFoundError,
|
|
671
704
|
TemplateNotFoundError,
|
|
672
705
|
ThrottledError,
|
|
673
706
|
UnknownTemplateVariablesError,
|
|
674
707
|
buildPreviewPayload,
|
|
675
708
|
categoryPolicyEntrySchema,
|
|
709
|
+
checkEmailAttachment,
|
|
676
710
|
createWhatsAppDriverFromChannel,
|
|
677
711
|
deliveryWebhookSchema,
|
|
678
712
|
deriveTitleFromBody,
|
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","../src/previewViewport.ts","../src/templateRender.ts","../src/templateVariables.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 NotificationCategoryPolicy,\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 updateCategoryPoliciesSchema,\n categoryPolicyEntrySchema,\n upsertTemplateSchema,\n listNotificationsQuerySchema,\n deliveryWebhookSchema,\n} from './schemas'\nexport type {\n SendNotificationBody,\n RegisterDeviceBody,\n UpdatePreferencesBody,\n UpdateCategoryPoliciesBody,\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 UnknownTemplateVariablesError,\n TemplateIdNotFoundError,\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, TemplateConstraintCheck } from './templateRender'\n\nexport { buildPreviewPayload, diffTemplateVariables } from './templateVariables'\nexport type {\n DiffTemplateVariablesParams,\n TemplateVariableCatalog,\n TemplateVariableDefinition,\n TemplateVariableDiff,\n} from './templateVariables'\n\nexport { PREVIEW_VIEWPORT, PREVIEW_VIEWPORT_BY_CHANNEL, TEMPLATE_CONSTRAINTS_BY_CHANNEL } from './previewViewport'\nexport type {\n PreviewViewport,\n PreviewViewportSpec,\n TemplateConstraintField,\n TemplateConstraintLimits,\n} from './previewViewport'\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\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":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACIO,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,cAAc;EACzBC,MAAM;EAC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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","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"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/notification.types.ts","../src/emailAttachment.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 {\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 NotificationCategoryPolicy,\n SendNotificationParams,\n SendNotificationResult,\n ListNotificationsParams,\n ListNotificationsResult,\n DeliveryReceipt,\n} from './notification.types'\n\nexport { EMAIL_ATTACHMENT_MAX_BYTES, EMAIL_ATTACHMENT_MAX_COUNT, checkEmailAttachment } from './emailAttachment'\nexport type { EmailAttachment } from './emailAttachment'\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 updateCategoryPoliciesSchema,\n categoryPolicyEntrySchema,\n upsertTemplateSchema,\n listNotificationsQuerySchema,\n deliveryWebhookSchema,\n} from './schemas'\nexport type {\n SendNotificationBody,\n RegisterDeviceBody,\n UpdatePreferencesBody,\n UpdateCategoryPoliciesBody,\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 UnknownTemplateVariablesError,\n TemplateIdNotFoundError,\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, TemplateConstraintCheck } from './templateRender'\n\nexport { buildPreviewPayload, diffTemplateVariables, TEMPLATE_VARIABLE_KIND } from './templateVariables'\nexport type {\n DiffTemplateVariablesParams,\n TemplateVariableCatalog,\n TemplateVariableDefinition,\n TemplateVariableKind,\n TemplateVariableDiff,\n} from './templateVariables'\n\nexport { PREVIEW_VIEWPORT, PREVIEW_VIEWPORT_BY_CHANNEL, TEMPLATE_CONSTRAINTS_BY_CHANNEL } from './previewViewport'\nexport type {\n PreviewViewport,\n PreviewViewportSpec,\n TemplateConstraintField,\n TemplateConstraintLimits,\n} from './previewViewport'\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\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 * Anexo de e-mail — por REFERÊNCIA, nunca por conteúdo.\n *\n * O template é linha versionada no Postgres e o job é payload no Redis. Um PDF em qualquer um dos\n * dois é blob replicado a cada versão e a cada tentativa, e uma nota fiscal é dado pessoal — o\n * `security.md` §6 já manda o payload de fila carregar referência, e o §7 manda entregar arquivo por\n * URL assinada de vida curta. Anexo segue a mesma regra: o que trafega é onde o arquivo está.\n *\n * Quem baixa é o DRIVER, no momento do envio, e é ele que aplica o teto de tamanho. Baixar antes\n * (no módulo) seria carregar bytes na memória de um processo que pode nem chegar a enviar.\n */\n\n/**\n * 25MB é o teto prático: Gmail e Outlook recusam acima disso, e o SES conta o MIME inteiro já em\n * base64 — que infla ~33%. O driver reprova ANTES de montar a mensagem, senão o erro vem do\n * provedor como uma falha genérica de envio.\n */\nexport const EMAIL_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024\n\n/** Um e-mail com trinta anexos é engano de laço, não um caso de uso. */\nexport const EMAIL_ATTACHMENT_MAX_COUNT = 10\n\nexport type EmailAttachment = {\n /** O nome que o destinatário vê. Sem caminho: `../` num nome de anexo é travessia de diretório. */\n readonly filename: string\n /**\n * URL de onde o driver baixa no momento do envio. Assinada e de vida curta quando o arquivo for\n * privado — o driver não autentica, ele só faz `GET`.\n */\n readonly url: string\n /** Declarado pelo produto, e não adivinhado da extensão: extensão mente, e cliente de e-mail confia. */\n readonly contentType: string\n}\n\n/**\n * Recusa o que não pode virar anexo antes de qualquer rede.\n *\n * Devolve o motivo em vez de lançar: o chamador é um driver, e uma tentativa de entrega registra o\n * porquê da recusa na `delivery` — `throw` viraria erro genérico e o operador ficaria sem a causa.\n */\nexport function checkEmailAttachment(attachment: EmailAttachment): string | undefined {\n if (!attachment.filename.trim()) return 'ATTACHMENT_FILENAME_EMPTY'\n\n // Travessia de diretório: o nome vai para o cabeçalho MIME e, do outro lado, para o disco de quem\n // salva. `/`, `\\` e `..` não têm por que existir num nome de arquivo anexado.\n if (/[/\\\\]|\\.\\./.test(attachment.filename)) return 'ATTACHMENT_FILENAME_UNSAFE'\n\n if (!attachment.contentType.trim()) return 'ATTACHMENT_CONTENT_TYPE_EMPTY'\n\n // Só `https`: `file:`, `data:` e `http:` puxariam do disco do servidor, inflariam a mensagem ou\n // trafegariam um documento pessoal em claro.\n if (!attachment.url.startsWith('https://')) return 'ATTACHMENT_URL_NOT_HTTPS'\n\n return undefined\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\n/**\n * Dispositivo, e nao \"desktop/mobile\".\n *\n * iOS e Android nao sao o mesmo preview com outra largura: o cartao de push tem raio, tipografia e\n * numero de linhas diferentes em cada um, e a largura padrao tambem difere (375 contra 360). Quem\n * escreve a mensagem precisa ver os dois, porque o corte acontece em um antes do outro.\n */\nexport const PREVIEW_VIEWPORT = {\n BROWSER: 'browser',\n IOS: 'ios',\n ANDROID: 'android',\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 IOS: PreviewViewportSpec = { viewport: PREVIEW_VIEWPORT.IOS, width: 375 }\nconst ANDROID: PreviewViewportSpec = { viewport: PREVIEW_VIEWPORT.ANDROID, width: 360 }\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 /** O unico canal lido no computador tambem — e o assunto corta diferente em cada lugar. */\n [NOTIFICATION_CHANNEL.EMAIL]: [{ viewport: PREVIEW_VIEWPORT.BROWSER, width: 600 }, IOS, ANDROID],\n /**\n * Push, WhatsApp e SMS sao de aparelho. Um quadro largo ao lado sugeriria uma leitura em tela\n * grande que nao existe — e o corte que importa (duas linhas no push, 160 caracteres no SMS)\n * so acontece no celular.\n */\n [NOTIFICATION_CHANNEL.PUSH]: [IOS, ANDROID],\n [NOTIFICATION_CHANNEL.WHATSAPP]: [IOS, ANDROID],\n [NOTIFICATION_CHANNEL.SMS]: [IOS, ANDROID],\n /** Inbox e a tela do proprio produto, que e de computador neste ecossistema. */\n [NOTIFICATION_CHANNEL.INBOX]: [{ viewport: PREVIEW_VIEWPORT.BROWSER, width: 480 }],\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\n/**\n * `text` entra no corpo por interpolação; `attachment` NÃO — ele viaja ao lado da mensagem.\n *\n * A distinção existe porque as duas regras de validação são opostas: variável de texto declarada e\n * ausente do corpo é um aviso, e variável de anexo ausente do corpo é o normal. Sem o tipo, todo\n * anexo obrigatório apareceria eternamente como \"faltando no texto\".\n */\nexport const TEMPLATE_VARIABLE_KIND = {\n TEXT: 'text',\n ATTACHMENT: 'attachment',\n} as const\nexport type TemplateVariableKind = (typeof TEMPLATE_VARIABLE_KIND)[keyof typeof TEMPLATE_VARIABLE_KIND]\n\nexport type TemplateVariableDefinition = {\n readonly name: string\n /** Ausente é `text`: todo catálogo escrito antes disto continua valendo sem alteração. */\n readonly kind?: TemplateVariableKind\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. Só variáveis de texto entram aqui. */\n readonly missingRequired: readonly string[]\n /**\n * Anexos referenciados DENTRO do texto — quase sempre engano.\n *\n * `{{nota}}` no corpo de um anexo renderiza a URL crua no meio da frase, e não anexa nada. Se a\n * intenção era mandar o link, a variável devia ser de texto; se era anexar, ela não pertence ao\n * corpo. Aviso e não erro: link para o arquivo é uma escolha legítima, só não é esta.\n */\n readonly attachmentsInText: 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: [], attachmentsInText: [] }\n\n const declared = new Set(params.variables.map((variable) => variable.name))\n const usedSet = new Set(used)\n const attachments = new Set(\n params.variables\n .filter((variable) => variable.kind === TEMPLATE_VARIABLE_KIND.ATTACHMENT)\n .map((variable) => variable.name),\n )\n\n return {\n used,\n unknown: used.filter((name) => !declared.has(name)),\n missingRequired: params.variables\n .filter(\n (variable) =>\n variable.required && variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT && !usedSet.has(variable.name),\n )\n .map((variable) => variable.name),\n attachmentsInText: used.filter((name) => attachments.has(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\n // Anexo não é interpolado: incluí-lo aqui faria o preview desenhar a URL no meio do texto de um\n // corpo que nunca vai conter essa URL.\n return Object.fromEntries(\n variables\n .filter((variable) => variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT)\n .map((variable) => [variable.name, variable.example]),\n )\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;;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,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;;;ACrEO,IAAMC,6BAA6B,KAAK,OAAO;AAG/C,IAAMC,6BAA6B;AAoBn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AA;IAAIC,iBAAiB,CAAA;IAAIC,mBAAmB,CAAA;EAAG;AAE9F,QAAMC,WAAW,IAAIC,IAAIV,OAAOK,UAAUM,IAAI,CAACC,aAAaA,SAASC,IAAI,CAAA;AACzE,QAAMC,UAAU,IAAIJ,IAAIT,IAAAA;AACxB,QAAMc,cAAc,IAAIL,IACtBV,OAAOK,UACJW,OAAO,CAACJ,aAAaA,SAASK,SAASrB,uBAAuBE,UAAU,EACxEa,IAAI,CAACC,aAAaA,SAASC,IAAI,CAAA;AAGpC,SAAO;IACLZ;IACAK,SAASL,KAAKe,OAAO,CAACH,SAAS,CAACJ,SAASS,IAAIL,IAAAA,CAAAA;IAC7CN,iBAAiBP,OAAOK,UACrBW,OACC,CAACJ,aACCA,SAASO,YAAYP,SAASK,SAASrB,uBAAuBE,cAAc,CAACgB,QAAQI,IAAIN,SAASC,IAAI,CAAA,EAEzGF,IAAI,CAACC,aAAaA,SAASC,IAAI;IAClCL,mBAAmBP,KAAKe,OAAO,CAACH,SAASE,YAAYG,IAAIL,IAAAA,CAAAA;EAC3D;AACF;AAxBgBd;AA8BT,SAASqB,oBACdf,WAA4D;AAE5D,MAAI,CAACA,UAAW,QAAO,CAAC;AAIxB,SAAOgB,OAAOC,YACZjB,UACGW,OAAO,CAACJ,aAAaA,SAASK,SAASrB,uBAAuBE,UAAU,EACxEa,IAAI,CAACC,aAAa;IAACA,SAASC;IAAMD,SAASW;GAAQ,CAAA;AAE1D;AAZgBH;","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","EMAIL_ATTACHMENT_MAX_BYTES","EMAIL_ATTACHMENT_MAX_COUNT","checkEmailAttachment","attachment","filename","trim","test","contentType","url","startsWith","undefined","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","BROWSER","IOS","ANDROID","viewport","width","PREVIEW_VIEWPORT_BY_CHANNEL","NOTIFICATION_CHANNEL","EMAIL","PUSH","WHATSAPP","SMS","INBOX","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","TEMPLATE_VARIABLE_KIND","TEXT","ATTACHMENT","diffTemplateVariables","params","used","extractTemplatePlaceholders","subject","body","variables","unknown","missingRequired","attachmentsInText","declared","Set","map","variable","name","usedSet","attachments","filter","kind","has","required","buildPreviewPayload","Object","fromEntries","example"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -182,22 +182,48 @@ type DeliveryReceipt = {
|
|
|
182
182
|
|
|
183
183
|
/**
|
|
184
184
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
185
|
+
*
|
|
186
|
+
* Anexo de e-mail — por REFERÊNCIA, nunca por conteúdo.
|
|
187
|
+
*
|
|
188
|
+
* O template é linha versionada no Postgres e o job é payload no Redis. Um PDF em qualquer um dos
|
|
189
|
+
* dois é blob replicado a cada versão e a cada tentativa, e uma nota fiscal é dado pessoal — o
|
|
190
|
+
* `security.md` §6 já manda o payload de fila carregar referência, e o §7 manda entregar arquivo por
|
|
191
|
+
* URL assinada de vida curta. Anexo segue a mesma regra: o que trafega é onde o arquivo está.
|
|
192
|
+
*
|
|
193
|
+
* Quem baixa é o DRIVER, no momento do envio, e é ele que aplica o teto de tamanho. Baixar antes
|
|
194
|
+
* (no módulo) seria carregar bytes na memória de um processo que pode nem chegar a enviar.
|
|
185
195
|
*/
|
|
186
|
-
|
|
187
196
|
/**
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
197
|
+
* 25MB é o teto prático: Gmail e Outlook recusam acima disso, e o SES conta o MIME inteiro já em
|
|
198
|
+
* base64 — que infla ~33%. O driver reprova ANTES de montar a mensagem, senão o erro vem do
|
|
199
|
+
* provedor como uma falha genérica de envio.
|
|
200
|
+
*/
|
|
201
|
+
declare const EMAIL_ATTACHMENT_MAX_BYTES: number;
|
|
202
|
+
/** Um e-mail com trinta anexos é engano de laço, não um caso de uso. */
|
|
203
|
+
declare const EMAIL_ATTACHMENT_MAX_COUNT = 10;
|
|
204
|
+
type EmailAttachment = {
|
|
205
|
+
/** O nome que o destinatário vê. Sem caminho: `../` num nome de anexo é travessia de diretório. */
|
|
206
|
+
readonly filename: string;
|
|
207
|
+
/**
|
|
208
|
+
* URL de onde o driver baixa no momento do envio. Assinada e de vida curta quando o arquivo for
|
|
209
|
+
* privado — o driver não autentica, ele só faz `GET`.
|
|
210
|
+
*/
|
|
211
|
+
readonly url: string;
|
|
212
|
+
/** Declarado pelo produto, e não adivinhado da extensão: extensão mente, e cliente de e-mail confia. */
|
|
213
|
+
readonly contentType: string;
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* Recusa o que não pode virar anexo antes de qualquer rede.
|
|
194
217
|
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* - `invalid_target` desativa o device ou cria supressão, **sem** retry;
|
|
198
|
-
* - `retriable` reagenda com backoff exponencial + jitter até esgotar `attempts`;
|
|
199
|
-
* - `permanent` finaliza como `failed` na primeira tentativa.
|
|
218
|
+
* Devolve o motivo em vez de lançar: o chamador é um driver, e uma tentativa de entrega registra o
|
|
219
|
+
* porquê da recusa na `delivery` — `throw` viraria erro genérico e o operador ficaria sem a causa.
|
|
200
220
|
*/
|
|
221
|
+
declare function checkEmailAttachment(attachment: EmailAttachment): string | undefined;
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
225
|
+
*/
|
|
226
|
+
|
|
201
227
|
type DeliveryAttemptResult = {
|
|
202
228
|
readonly outcome: 'sent';
|
|
203
229
|
readonly providerMessageId?: string;
|
|
@@ -231,6 +257,11 @@ type SendEmailParams = {
|
|
|
231
257
|
readonly html: string;
|
|
232
258
|
readonly text: string;
|
|
233
259
|
readonly replyTo?: string;
|
|
260
|
+
/**
|
|
261
|
+
* Anexos por REFERÊNCIA: o driver baixa de `url` no momento do envio. Ver `emailAttachment.ts`
|
|
262
|
+
* para por que o conteúdo não trafega aqui.
|
|
263
|
+
*/
|
|
264
|
+
readonly attachments?: readonly EmailAttachment[];
|
|
234
265
|
/** Correlaciona o recibo assíncrono (bounce/complaint) com a `delivery` que o originou. */
|
|
235
266
|
readonly idempotencyKey?: string;
|
|
236
267
|
};
|
|
@@ -940,9 +971,17 @@ declare function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel
|
|
|
940
971
|
* regra do canal, e o editor avisa com ela antes de salvar.
|
|
941
972
|
*/
|
|
942
973
|
|
|
974
|
+
/**
|
|
975
|
+
* Dispositivo, e nao "desktop/mobile".
|
|
976
|
+
*
|
|
977
|
+
* iOS e Android nao sao o mesmo preview com outra largura: o cartao de push tem raio, tipografia e
|
|
978
|
+
* numero de linhas diferentes em cada um, e a largura padrao tambem difere (375 contra 360). Quem
|
|
979
|
+
* escreve a mensagem precisa ver os dois, porque o corte acontece em um antes do outro.
|
|
980
|
+
*/
|
|
943
981
|
declare const PREVIEW_VIEWPORT: {
|
|
944
|
-
readonly
|
|
945
|
-
readonly
|
|
982
|
+
readonly BROWSER: "browser";
|
|
983
|
+
readonly IOS: "ios";
|
|
984
|
+
readonly ANDROID: "android";
|
|
946
985
|
};
|
|
947
986
|
type PreviewViewport = (typeof PREVIEW_VIEWPORT)[keyof typeof PREVIEW_VIEWPORT];
|
|
948
987
|
type PreviewViewportSpec = {
|
|
@@ -1031,8 +1070,22 @@ declare function renderTemplate(params: {
|
|
|
1031
1070
|
* (carrega Drizzle). Duas implementações divergiriam, e a tela passaria a aprovar o que a rota
|
|
1032
1071
|
* recusa.
|
|
1033
1072
|
*/
|
|
1073
|
+
/**
|
|
1074
|
+
* `text` entra no corpo por interpolação; `attachment` NÃO — ele viaja ao lado da mensagem.
|
|
1075
|
+
*
|
|
1076
|
+
* A distinção existe porque as duas regras de validação são opostas: variável de texto declarada e
|
|
1077
|
+
* ausente do corpo é um aviso, e variável de anexo ausente do corpo é o normal. Sem o tipo, todo
|
|
1078
|
+
* anexo obrigatório apareceria eternamente como "faltando no texto".
|
|
1079
|
+
*/
|
|
1080
|
+
declare const TEMPLATE_VARIABLE_KIND: {
|
|
1081
|
+
readonly TEXT: "text";
|
|
1082
|
+
readonly ATTACHMENT: "attachment";
|
|
1083
|
+
};
|
|
1084
|
+
type TemplateVariableKind = (typeof TEMPLATE_VARIABLE_KIND)[keyof typeof TEMPLATE_VARIABLE_KIND];
|
|
1034
1085
|
type TemplateVariableDefinition = {
|
|
1035
1086
|
readonly name: string;
|
|
1087
|
+
/** Ausente é `text`: todo catálogo escrito antes disto continua valendo sem alteração. */
|
|
1088
|
+
readonly kind?: TemplateVariableKind;
|
|
1036
1089
|
/** Valor de exemplo — alimenta o preview. Só o produto sabe que `orderNumber` é "QC-1042". */
|
|
1037
1090
|
readonly example: string;
|
|
1038
1091
|
/** `true` avisa quando o texto não usa a variável; nunca bloqueia (ver `diffTemplateVariables`). */
|
|
@@ -1047,8 +1100,16 @@ type TemplateVariableDiff = {
|
|
|
1047
1100
|
readonly used: readonly string[];
|
|
1048
1101
|
/** Referenciados e não declarados — renderizariam vazio para sempre. */
|
|
1049
1102
|
readonly unknown: readonly string[];
|
|
1050
|
-
/** Declarados como `required` e ausentes do texto. */
|
|
1103
|
+
/** Declarados como `required` e ausentes do texto. Só variáveis de texto entram aqui. */
|
|
1051
1104
|
readonly missingRequired: readonly string[];
|
|
1105
|
+
/**
|
|
1106
|
+
* Anexos referenciados DENTRO do texto — quase sempre engano.
|
|
1107
|
+
*
|
|
1108
|
+
* `{{nota}}` no corpo de um anexo renderiza a URL crua no meio da frase, e não anexa nada. Se a
|
|
1109
|
+
* intenção era mandar o link, a variável devia ser de texto; se era anexar, ela não pertence ao
|
|
1110
|
+
* corpo. Aviso e não erro: link para o arquivo é uma escolha legítima, só não é esta.
|
|
1111
|
+
*/
|
|
1112
|
+
readonly attachmentsInText: readonly string[];
|
|
1052
1113
|
};
|
|
1053
1114
|
type DiffTemplateVariablesParams = {
|
|
1054
1115
|
readonly body: string;
|
|
@@ -1066,4 +1127,4 @@ declare function diffTemplateVariables(params: DiffTemplateVariablesParams): Tem
|
|
|
1066
1127
|
*/
|
|
1067
1128
|
declare function buildPreviewPayload(variables: readonly TemplateVariableDefinition[] | undefined): Readonly<Record<string, string>>;
|
|
1068
1129
|
|
|
1069
|
-
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, type DiffTemplateVariablesParams, 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 NotificationCategoryPolicy, 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, PREVIEW_VIEWPORT, PREVIEW_VIEWPORT_BY_CHANNEL, PUSH_DRIVER, type PreferencesUpdatedEvent, type PreviewViewport, type PreviewViewportSpec, 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, TEMPLATE_CONSTRAINTS_BY_CHANNEL, type TemplateConstraintCheck, type TemplateConstraintField, type TemplateConstraintLimits, TemplateIdNotFoundError, TemplateNotFoundError, type TemplateRendererPort, type TemplateVariableCatalog, type TemplateVariableDefinition, type TemplateVariableDiff, ThrottledError, UnknownTemplateVariablesError, type UpdateCategoryPoliciesBody, type UpdatePreferencesBody, type UpsertTemplateBody, type UserId, type WhatsAppDriverPort, type WhatsAppSendingChannel, buildPreviewPayload, categoryPolicyEntrySchema, createWhatsAppDriverFromChannel, deliveryWebhookSchema, deriveTitleFromBody, diffTemplateVariables, escapeTemplateHtml, extractTemplatePlaceholders, interpolateTemplate, listNotificationsQuerySchema, preferenceEntrySchema, registerDeviceSchema, renderTemplate, sendNotificationSchema, updateCategoryPoliciesSchema, updatePreferencesSchema, upsertTemplateSchema };
|
|
1130
|
+
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, type DiffTemplateVariablesParams, DuplicateWebhookDeliveryError, EMAIL_ATTACHMENT_MAX_BYTES, EMAIL_ATTACHMENT_MAX_COUNT, EMAIL_DRIVER, type EmailAttachment, 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 NotificationCategoryPolicy, 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, PREVIEW_VIEWPORT, PREVIEW_VIEWPORT_BY_CHANNEL, PUSH_DRIVER, type PreferencesUpdatedEvent, type PreviewViewport, type PreviewViewportSpec, 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, TEMPLATE_CONSTRAINTS_BY_CHANNEL, TEMPLATE_VARIABLE_KIND, type TemplateConstraintCheck, type TemplateConstraintField, type TemplateConstraintLimits, TemplateIdNotFoundError, TemplateNotFoundError, type TemplateRendererPort, type TemplateVariableCatalog, type TemplateVariableDefinition, type TemplateVariableDiff, type TemplateVariableKind, ThrottledError, UnknownTemplateVariablesError, type UpdateCategoryPoliciesBody, type UpdatePreferencesBody, type UpsertTemplateBody, type UserId, type WhatsAppDriverPort, type WhatsAppSendingChannel, buildPreviewPayload, categoryPolicyEntrySchema, checkEmailAttachment, createWhatsAppDriverFromChannel, deliveryWebhookSchema, deriveTitleFromBody, diffTemplateVariables, escapeTemplateHtml, extractTemplatePlaceholders, interpolateTemplate, listNotificationsQuerySchema, preferenceEntrySchema, registerDeviceSchema, renderTemplate, sendNotificationSchema, updateCategoryPoliciesSchema, updatePreferencesSchema, upsertTemplateSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -182,22 +182,48 @@ type DeliveryReceipt = {
|
|
|
182
182
|
|
|
183
183
|
/**
|
|
184
184
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
185
|
+
*
|
|
186
|
+
* Anexo de e-mail — por REFERÊNCIA, nunca por conteúdo.
|
|
187
|
+
*
|
|
188
|
+
* O template é linha versionada no Postgres e o job é payload no Redis. Um PDF em qualquer um dos
|
|
189
|
+
* dois é blob replicado a cada versão e a cada tentativa, e uma nota fiscal é dado pessoal — o
|
|
190
|
+
* `security.md` §6 já manda o payload de fila carregar referência, e o §7 manda entregar arquivo por
|
|
191
|
+
* URL assinada de vida curta. Anexo segue a mesma regra: o que trafega é onde o arquivo está.
|
|
192
|
+
*
|
|
193
|
+
* Quem baixa é o DRIVER, no momento do envio, e é ele que aplica o teto de tamanho. Baixar antes
|
|
194
|
+
* (no módulo) seria carregar bytes na memória de um processo que pode nem chegar a enviar.
|
|
185
195
|
*/
|
|
186
|
-
|
|
187
196
|
/**
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
197
|
+
* 25MB é o teto prático: Gmail e Outlook recusam acima disso, e o SES conta o MIME inteiro já em
|
|
198
|
+
* base64 — que infla ~33%. O driver reprova ANTES de montar a mensagem, senão o erro vem do
|
|
199
|
+
* provedor como uma falha genérica de envio.
|
|
200
|
+
*/
|
|
201
|
+
declare const EMAIL_ATTACHMENT_MAX_BYTES: number;
|
|
202
|
+
/** Um e-mail com trinta anexos é engano de laço, não um caso de uso. */
|
|
203
|
+
declare const EMAIL_ATTACHMENT_MAX_COUNT = 10;
|
|
204
|
+
type EmailAttachment = {
|
|
205
|
+
/** O nome que o destinatário vê. Sem caminho: `../` num nome de anexo é travessia de diretório. */
|
|
206
|
+
readonly filename: string;
|
|
207
|
+
/**
|
|
208
|
+
* URL de onde o driver baixa no momento do envio. Assinada e de vida curta quando o arquivo for
|
|
209
|
+
* privado — o driver não autentica, ele só faz `GET`.
|
|
210
|
+
*/
|
|
211
|
+
readonly url: string;
|
|
212
|
+
/** Declarado pelo produto, e não adivinhado da extensão: extensão mente, e cliente de e-mail confia. */
|
|
213
|
+
readonly contentType: string;
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* Recusa o que não pode virar anexo antes de qualquer rede.
|
|
194
217
|
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* - `invalid_target` desativa o device ou cria supressão, **sem** retry;
|
|
198
|
-
* - `retriable` reagenda com backoff exponencial + jitter até esgotar `attempts`;
|
|
199
|
-
* - `permanent` finaliza como `failed` na primeira tentativa.
|
|
218
|
+
* Devolve o motivo em vez de lançar: o chamador é um driver, e uma tentativa de entrega registra o
|
|
219
|
+
* porquê da recusa na `delivery` — `throw` viraria erro genérico e o operador ficaria sem a causa.
|
|
200
220
|
*/
|
|
221
|
+
declare function checkEmailAttachment(attachment: EmailAttachment): string | undefined;
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
225
|
+
*/
|
|
226
|
+
|
|
201
227
|
type DeliveryAttemptResult = {
|
|
202
228
|
readonly outcome: 'sent';
|
|
203
229
|
readonly providerMessageId?: string;
|
|
@@ -231,6 +257,11 @@ type SendEmailParams = {
|
|
|
231
257
|
readonly html: string;
|
|
232
258
|
readonly text: string;
|
|
233
259
|
readonly replyTo?: string;
|
|
260
|
+
/**
|
|
261
|
+
* Anexos por REFERÊNCIA: o driver baixa de `url` no momento do envio. Ver `emailAttachment.ts`
|
|
262
|
+
* para por que o conteúdo não trafega aqui.
|
|
263
|
+
*/
|
|
264
|
+
readonly attachments?: readonly EmailAttachment[];
|
|
234
265
|
/** Correlaciona o recibo assíncrono (bounce/complaint) com a `delivery` que o originou. */
|
|
235
266
|
readonly idempotencyKey?: string;
|
|
236
267
|
};
|
|
@@ -940,9 +971,17 @@ declare function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel
|
|
|
940
971
|
* regra do canal, e o editor avisa com ela antes de salvar.
|
|
941
972
|
*/
|
|
942
973
|
|
|
974
|
+
/**
|
|
975
|
+
* Dispositivo, e nao "desktop/mobile".
|
|
976
|
+
*
|
|
977
|
+
* iOS e Android nao sao o mesmo preview com outra largura: o cartao de push tem raio, tipografia e
|
|
978
|
+
* numero de linhas diferentes em cada um, e a largura padrao tambem difere (375 contra 360). Quem
|
|
979
|
+
* escreve a mensagem precisa ver os dois, porque o corte acontece em um antes do outro.
|
|
980
|
+
*/
|
|
943
981
|
declare const PREVIEW_VIEWPORT: {
|
|
944
|
-
readonly
|
|
945
|
-
readonly
|
|
982
|
+
readonly BROWSER: "browser";
|
|
983
|
+
readonly IOS: "ios";
|
|
984
|
+
readonly ANDROID: "android";
|
|
946
985
|
};
|
|
947
986
|
type PreviewViewport = (typeof PREVIEW_VIEWPORT)[keyof typeof PREVIEW_VIEWPORT];
|
|
948
987
|
type PreviewViewportSpec = {
|
|
@@ -1031,8 +1070,22 @@ declare function renderTemplate(params: {
|
|
|
1031
1070
|
* (carrega Drizzle). Duas implementações divergiriam, e a tela passaria a aprovar o que a rota
|
|
1032
1071
|
* recusa.
|
|
1033
1072
|
*/
|
|
1073
|
+
/**
|
|
1074
|
+
* `text` entra no corpo por interpolação; `attachment` NÃO — ele viaja ao lado da mensagem.
|
|
1075
|
+
*
|
|
1076
|
+
* A distinção existe porque as duas regras de validação são opostas: variável de texto declarada e
|
|
1077
|
+
* ausente do corpo é um aviso, e variável de anexo ausente do corpo é o normal. Sem o tipo, todo
|
|
1078
|
+
* anexo obrigatório apareceria eternamente como "faltando no texto".
|
|
1079
|
+
*/
|
|
1080
|
+
declare const TEMPLATE_VARIABLE_KIND: {
|
|
1081
|
+
readonly TEXT: "text";
|
|
1082
|
+
readonly ATTACHMENT: "attachment";
|
|
1083
|
+
};
|
|
1084
|
+
type TemplateVariableKind = (typeof TEMPLATE_VARIABLE_KIND)[keyof typeof TEMPLATE_VARIABLE_KIND];
|
|
1034
1085
|
type TemplateVariableDefinition = {
|
|
1035
1086
|
readonly name: string;
|
|
1087
|
+
/** Ausente é `text`: todo catálogo escrito antes disto continua valendo sem alteração. */
|
|
1088
|
+
readonly kind?: TemplateVariableKind;
|
|
1036
1089
|
/** Valor de exemplo — alimenta o preview. Só o produto sabe que `orderNumber` é "QC-1042". */
|
|
1037
1090
|
readonly example: string;
|
|
1038
1091
|
/** `true` avisa quando o texto não usa a variável; nunca bloqueia (ver `diffTemplateVariables`). */
|
|
@@ -1047,8 +1100,16 @@ type TemplateVariableDiff = {
|
|
|
1047
1100
|
readonly used: readonly string[];
|
|
1048
1101
|
/** Referenciados e não declarados — renderizariam vazio para sempre. */
|
|
1049
1102
|
readonly unknown: readonly string[];
|
|
1050
|
-
/** Declarados como `required` e ausentes do texto. */
|
|
1103
|
+
/** Declarados como `required` e ausentes do texto. Só variáveis de texto entram aqui. */
|
|
1051
1104
|
readonly missingRequired: readonly string[];
|
|
1105
|
+
/**
|
|
1106
|
+
* Anexos referenciados DENTRO do texto — quase sempre engano.
|
|
1107
|
+
*
|
|
1108
|
+
* `{{nota}}` no corpo de um anexo renderiza a URL crua no meio da frase, e não anexa nada. Se a
|
|
1109
|
+
* intenção era mandar o link, a variável devia ser de texto; se era anexar, ela não pertence ao
|
|
1110
|
+
* corpo. Aviso e não erro: link para o arquivo é uma escolha legítima, só não é esta.
|
|
1111
|
+
*/
|
|
1112
|
+
readonly attachmentsInText: readonly string[];
|
|
1052
1113
|
};
|
|
1053
1114
|
type DiffTemplateVariablesParams = {
|
|
1054
1115
|
readonly body: string;
|
|
@@ -1066,4 +1127,4 @@ declare function diffTemplateVariables(params: DiffTemplateVariablesParams): Tem
|
|
|
1066
1127
|
*/
|
|
1067
1128
|
declare function buildPreviewPayload(variables: readonly TemplateVariableDefinition[] | undefined): Readonly<Record<string, string>>;
|
|
1068
1129
|
|
|
1069
|
-
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, type DiffTemplateVariablesParams, 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 NotificationCategoryPolicy, 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, PREVIEW_VIEWPORT, PREVIEW_VIEWPORT_BY_CHANNEL, PUSH_DRIVER, type PreferencesUpdatedEvent, type PreviewViewport, type PreviewViewportSpec, 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, TEMPLATE_CONSTRAINTS_BY_CHANNEL, type TemplateConstraintCheck, type TemplateConstraintField, type TemplateConstraintLimits, TemplateIdNotFoundError, TemplateNotFoundError, type TemplateRendererPort, type TemplateVariableCatalog, type TemplateVariableDefinition, type TemplateVariableDiff, ThrottledError, UnknownTemplateVariablesError, type UpdateCategoryPoliciesBody, type UpdatePreferencesBody, type UpsertTemplateBody, type UserId, type WhatsAppDriverPort, type WhatsAppSendingChannel, buildPreviewPayload, categoryPolicyEntrySchema, createWhatsAppDriverFromChannel, deliveryWebhookSchema, deriveTitleFromBody, diffTemplateVariables, escapeTemplateHtml, extractTemplatePlaceholders, interpolateTemplate, listNotificationsQuerySchema, preferenceEntrySchema, registerDeviceSchema, renderTemplate, sendNotificationSchema, updateCategoryPoliciesSchema, updatePreferencesSchema, upsertTemplateSchema };
|
|
1130
|
+
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, type DiffTemplateVariablesParams, DuplicateWebhookDeliveryError, EMAIL_ATTACHMENT_MAX_BYTES, EMAIL_ATTACHMENT_MAX_COUNT, EMAIL_DRIVER, type EmailAttachment, 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 NotificationCategoryPolicy, 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, PREVIEW_VIEWPORT, PREVIEW_VIEWPORT_BY_CHANNEL, PUSH_DRIVER, type PreferencesUpdatedEvent, type PreviewViewport, type PreviewViewportSpec, 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, TEMPLATE_CONSTRAINTS_BY_CHANNEL, TEMPLATE_VARIABLE_KIND, type TemplateConstraintCheck, type TemplateConstraintField, type TemplateConstraintLimits, TemplateIdNotFoundError, TemplateNotFoundError, type TemplateRendererPort, type TemplateVariableCatalog, type TemplateVariableDefinition, type TemplateVariableDiff, type TemplateVariableKind, ThrottledError, UnknownTemplateVariablesError, type UpdateCategoryPoliciesBody, type UpdatePreferencesBody, type UpsertTemplateBody, type UserId, type WhatsAppDriverPort, type WhatsAppSendingChannel, buildPreviewPayload, categoryPolicyEntrySchema, checkEmailAttachment, createWhatsAppDriverFromChannel, deliveryWebhookSchema, deriveTitleFromBody, diffTemplateVariables, escapeTemplateHtml, extractTemplatePlaceholders, interpolateTemplate, listNotificationsQuerySchema, preferenceEntrySchema, registerDeviceSchema, renderTemplate, sendNotificationSchema, updateCategoryPoliciesSchema, updatePreferencesSchema, upsertTemplateSchema };
|
package/dist/index.js
CHANGED
|
@@ -57,6 +57,18 @@ var NOTIFICATION_CATEGORY_HINT = {
|
|
|
57
57
|
SYSTEM: "system"
|
|
58
58
|
};
|
|
59
59
|
|
|
60
|
+
// src/emailAttachment.ts
|
|
61
|
+
var EMAIL_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
|
|
62
|
+
var EMAIL_ATTACHMENT_MAX_COUNT = 10;
|
|
63
|
+
function checkEmailAttachment(attachment) {
|
|
64
|
+
if (!attachment.filename.trim()) return "ATTACHMENT_FILENAME_EMPTY";
|
|
65
|
+
if (/[/\\]|\.\./.test(attachment.filename)) return "ATTACHMENT_FILENAME_UNSAFE";
|
|
66
|
+
if (!attachment.contentType.trim()) return "ATTACHMENT_CONTENT_TYPE_EMPTY";
|
|
67
|
+
if (!attachment.url.startsWith("https://")) return "ATTACHMENT_URL_NOT_HTTPS";
|
|
68
|
+
return void 0;
|
|
69
|
+
}
|
|
70
|
+
__name(checkEmailAttachment, "checkEmailAttachment");
|
|
71
|
+
|
|
60
72
|
// src/schemas.ts
|
|
61
73
|
import { z } from "zod";
|
|
62
74
|
var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
@@ -403,44 +415,51 @@ __name(createWhatsAppDriverFromChannel, "createWhatsAppDriverFromChannel");
|
|
|
403
415
|
|
|
404
416
|
// src/previewViewport.ts
|
|
405
417
|
var PREVIEW_VIEWPORT = {
|
|
406
|
-
|
|
407
|
-
|
|
418
|
+
BROWSER: "browser",
|
|
419
|
+
IOS: "ios",
|
|
420
|
+
ANDROID: "android"
|
|
408
421
|
};
|
|
409
|
-
var
|
|
410
|
-
viewport: PREVIEW_VIEWPORT.
|
|
422
|
+
var IOS = {
|
|
423
|
+
viewport: PREVIEW_VIEWPORT.IOS,
|
|
411
424
|
width: 375
|
|
412
425
|
};
|
|
426
|
+
var ANDROID = {
|
|
427
|
+
viewport: PREVIEW_VIEWPORT.ANDROID,
|
|
428
|
+
width: 360
|
|
429
|
+
};
|
|
413
430
|
var PREVIEW_VIEWPORT_BY_CHANNEL = {
|
|
431
|
+
/** O unico canal lido no computador tambem — e o assunto corta diferente em cada lugar. */
|
|
414
432
|
[NOTIFICATION_CHANNEL.EMAIL]: [
|
|
415
433
|
{
|
|
416
|
-
viewport: PREVIEW_VIEWPORT.
|
|
434
|
+
viewport: PREVIEW_VIEWPORT.BROWSER,
|
|
417
435
|
width: 600
|
|
418
436
|
},
|
|
419
|
-
|
|
437
|
+
IOS,
|
|
438
|
+
ANDROID
|
|
420
439
|
],
|
|
440
|
+
/**
|
|
441
|
+
* Push, WhatsApp e SMS sao de aparelho. Um quadro largo ao lado sugeriria uma leitura em tela
|
|
442
|
+
* grande que nao existe — e o corte que importa (duas linhas no push, 160 caracteres no SMS)
|
|
443
|
+
* so acontece no celular.
|
|
444
|
+
*/
|
|
421
445
|
[NOTIFICATION_CHANNEL.PUSH]: [
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
width: 360
|
|
425
|
-
},
|
|
426
|
-
MOBILE
|
|
446
|
+
IOS,
|
|
447
|
+
ANDROID
|
|
427
448
|
],
|
|
428
449
|
[NOTIFICATION_CHANNEL.WHATSAPP]: [
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
width: 400
|
|
432
|
-
},
|
|
433
|
-
MOBILE
|
|
450
|
+
IOS,
|
|
451
|
+
ANDROID
|
|
434
452
|
],
|
|
453
|
+
[NOTIFICATION_CHANNEL.SMS]: [
|
|
454
|
+
IOS,
|
|
455
|
+
ANDROID
|
|
456
|
+
],
|
|
457
|
+
/** Inbox e a tela do proprio produto, que e de computador neste ecossistema. */
|
|
435
458
|
[NOTIFICATION_CHANNEL.INBOX]: [
|
|
436
459
|
{
|
|
437
|
-
viewport: PREVIEW_VIEWPORT.
|
|
460
|
+
viewport: PREVIEW_VIEWPORT.BROWSER,
|
|
438
461
|
width: 480
|
|
439
|
-
}
|
|
440
|
-
MOBILE
|
|
441
|
-
],
|
|
442
|
-
[NOTIFICATION_CHANNEL.SMS]: [
|
|
443
|
-
MOBILE
|
|
462
|
+
}
|
|
444
463
|
]
|
|
445
464
|
};
|
|
446
465
|
var TEMPLATE_CONSTRAINTS_BY_CHANNEL = {
|
|
@@ -550,26 +569,33 @@ function renderTemplate(params) {
|
|
|
550
569
|
__name(renderTemplate, "renderTemplate");
|
|
551
570
|
|
|
552
571
|
// src/templateVariables.ts
|
|
572
|
+
var TEMPLATE_VARIABLE_KIND = {
|
|
573
|
+
TEXT: "text",
|
|
574
|
+
ATTACHMENT: "attachment"
|
|
575
|
+
};
|
|
553
576
|
function diffTemplateVariables(params) {
|
|
554
577
|
const used = extractTemplatePlaceholders(`${params.subject ?? ""}
|
|
555
578
|
${params.body}`);
|
|
556
579
|
if (!params.variables) return {
|
|
557
580
|
used,
|
|
558
581
|
unknown: [],
|
|
559
|
-
missingRequired: []
|
|
582
|
+
missingRequired: [],
|
|
583
|
+
attachmentsInText: []
|
|
560
584
|
};
|
|
561
585
|
const declared = new Set(params.variables.map((variable) => variable.name));
|
|
562
586
|
const usedSet = new Set(used);
|
|
587
|
+
const attachments = new Set(params.variables.filter((variable) => variable.kind === TEMPLATE_VARIABLE_KIND.ATTACHMENT).map((variable) => variable.name));
|
|
563
588
|
return {
|
|
564
589
|
used,
|
|
565
590
|
unknown: used.filter((name) => !declared.has(name)),
|
|
566
|
-
missingRequired: params.variables.filter((variable) => variable.required && !usedSet.has(variable.name)).map((variable) => variable.name)
|
|
591
|
+
missingRequired: params.variables.filter((variable) => variable.required && variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT && !usedSet.has(variable.name)).map((variable) => variable.name),
|
|
592
|
+
attachmentsInText: used.filter((name) => attachments.has(name))
|
|
567
593
|
};
|
|
568
594
|
}
|
|
569
595
|
__name(diffTemplateVariables, "diffTemplateVariables");
|
|
570
596
|
function buildPreviewPayload(variables) {
|
|
571
597
|
if (!variables) return {};
|
|
572
|
-
return Object.fromEntries(variables.map((variable) => [
|
|
598
|
+
return Object.fromEntries(variables.filter((variable) => variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT).map((variable) => [
|
|
573
599
|
variable.name,
|
|
574
600
|
variable.example
|
|
575
601
|
]));
|
|
@@ -582,6 +608,8 @@ export {
|
|
|
582
608
|
DEVICE_PLATFORM,
|
|
583
609
|
DeviceNotFoundError,
|
|
584
610
|
DuplicateWebhookDeliveryError,
|
|
611
|
+
EMAIL_ATTACHMENT_MAX_BYTES,
|
|
612
|
+
EMAIL_ATTACHMENT_MAX_COUNT,
|
|
585
613
|
EMAIL_DRIVER,
|
|
586
614
|
INTRUSIVE_CHANNELS,
|
|
587
615
|
InvalidWebhookSignatureError,
|
|
@@ -599,12 +627,14 @@ export {
|
|
|
599
627
|
SUPPRESSION_REASON,
|
|
600
628
|
SuppressedTargetError,
|
|
601
629
|
TEMPLATE_CONSTRAINTS_BY_CHANNEL,
|
|
630
|
+
TEMPLATE_VARIABLE_KIND,
|
|
602
631
|
TemplateIdNotFoundError,
|
|
603
632
|
TemplateNotFoundError,
|
|
604
633
|
ThrottledError,
|
|
605
634
|
UnknownTemplateVariablesError,
|
|
606
635
|
buildPreviewPayload,
|
|
607
636
|
categoryPolicyEntrySchema,
|
|
637
|
+
checkEmailAttachment,
|
|
608
638
|
createWhatsAppDriverFromChannel,
|
|
609
639
|
deliveryWebhookSchema,
|
|
610
640
|
deriveTitleFromBody,
|
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/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;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vE,QAAMC,OAAOC,4BAA4B,GAAGF,OAAOG,WAAW,EAAA;EAAOH,OAAOI,IAAI,EAAE;AAElF,MAAI,CAACJ,OAAOK,UAAW,QAAO;IAAEJ;IAAMK,SAAS,CAAA;IAAIC,iBAAiB,CAAA;EAAG;AAEvE,QAAMC,WAAW,IAAIC,IAAIT,OAAOK,UAAUK,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"]}
|
|
1
|
+
{"version":3,"sources":["../src/notification.types.ts","../src/emailAttachment.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 * Anexo de e-mail — por REFERÊNCIA, nunca por conteúdo.\n *\n * O template é linha versionada no Postgres e o job é payload no Redis. Um PDF em qualquer um dos\n * dois é blob replicado a cada versão e a cada tentativa, e uma nota fiscal é dado pessoal — o\n * `security.md` §6 já manda o payload de fila carregar referência, e o §7 manda entregar arquivo por\n * URL assinada de vida curta. Anexo segue a mesma regra: o que trafega é onde o arquivo está.\n *\n * Quem baixa é o DRIVER, no momento do envio, e é ele que aplica o teto de tamanho. Baixar antes\n * (no módulo) seria carregar bytes na memória de um processo que pode nem chegar a enviar.\n */\n\n/**\n * 25MB é o teto prático: Gmail e Outlook recusam acima disso, e o SES conta o MIME inteiro já em\n * base64 — que infla ~33%. O driver reprova ANTES de montar a mensagem, senão o erro vem do\n * provedor como uma falha genérica de envio.\n */\nexport const EMAIL_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024\n\n/** Um e-mail com trinta anexos é engano de laço, não um caso de uso. */\nexport const EMAIL_ATTACHMENT_MAX_COUNT = 10\n\nexport type EmailAttachment = {\n /** O nome que o destinatário vê. Sem caminho: `../` num nome de anexo é travessia de diretório. */\n readonly filename: string\n /**\n * URL de onde o driver baixa no momento do envio. Assinada e de vida curta quando o arquivo for\n * privado — o driver não autentica, ele só faz `GET`.\n */\n readonly url: string\n /** Declarado pelo produto, e não adivinhado da extensão: extensão mente, e cliente de e-mail confia. */\n readonly contentType: string\n}\n\n/**\n * Recusa o que não pode virar anexo antes de qualquer rede.\n *\n * Devolve o motivo em vez de lançar: o chamador é um driver, e uma tentativa de entrega registra o\n * porquê da recusa na `delivery` — `throw` viraria erro genérico e o operador ficaria sem a causa.\n */\nexport function checkEmailAttachment(attachment: EmailAttachment): string | undefined {\n if (!attachment.filename.trim()) return 'ATTACHMENT_FILENAME_EMPTY'\n\n // Travessia de diretório: o nome vai para o cabeçalho MIME e, do outro lado, para o disco de quem\n // salva. `/`, `\\` e `..` não têm por que existir num nome de arquivo anexado.\n if (/[/\\\\]|\\.\\./.test(attachment.filename)) return 'ATTACHMENT_FILENAME_UNSAFE'\n\n if (!attachment.contentType.trim()) return 'ATTACHMENT_CONTENT_TYPE_EMPTY'\n\n // Só `https`: `file:`, `data:` e `http:` puxariam do disco do servidor, inflariam a mensagem ou\n // trafegariam um documento pessoal em claro.\n if (!attachment.url.startsWith('https://')) return 'ATTACHMENT_URL_NOT_HTTPS'\n\n return undefined\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\n/**\n * Dispositivo, e nao \"desktop/mobile\".\n *\n * iOS e Android nao sao o mesmo preview com outra largura: o cartao de push tem raio, tipografia e\n * numero de linhas diferentes em cada um, e a largura padrao tambem difere (375 contra 360). Quem\n * escreve a mensagem precisa ver os dois, porque o corte acontece em um antes do outro.\n */\nexport const PREVIEW_VIEWPORT = {\n BROWSER: 'browser',\n IOS: 'ios',\n ANDROID: 'android',\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 IOS: PreviewViewportSpec = { viewport: PREVIEW_VIEWPORT.IOS, width: 375 }\nconst ANDROID: PreviewViewportSpec = { viewport: PREVIEW_VIEWPORT.ANDROID, width: 360 }\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 /** O unico canal lido no computador tambem — e o assunto corta diferente em cada lugar. */\n [NOTIFICATION_CHANNEL.EMAIL]: [{ viewport: PREVIEW_VIEWPORT.BROWSER, width: 600 }, IOS, ANDROID],\n /**\n * Push, WhatsApp e SMS sao de aparelho. Um quadro largo ao lado sugeriria uma leitura em tela\n * grande que nao existe — e o corte que importa (duas linhas no push, 160 caracteres no SMS)\n * so acontece no celular.\n */\n [NOTIFICATION_CHANNEL.PUSH]: [IOS, ANDROID],\n [NOTIFICATION_CHANNEL.WHATSAPP]: [IOS, ANDROID],\n [NOTIFICATION_CHANNEL.SMS]: [IOS, ANDROID],\n /** Inbox e a tela do proprio produto, que e de computador neste ecossistema. */\n [NOTIFICATION_CHANNEL.INBOX]: [{ viewport: PREVIEW_VIEWPORT.BROWSER, width: 480 }],\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\n/**\n * `text` entra no corpo por interpolação; `attachment` NÃO — ele viaja ao lado da mensagem.\n *\n * A distinção existe porque as duas regras de validação são opostas: variável de texto declarada e\n * ausente do corpo é um aviso, e variável de anexo ausente do corpo é o normal. Sem o tipo, todo\n * anexo obrigatório apareceria eternamente como \"faltando no texto\".\n */\nexport const TEMPLATE_VARIABLE_KIND = {\n TEXT: 'text',\n ATTACHMENT: 'attachment',\n} as const\nexport type TemplateVariableKind = (typeof TEMPLATE_VARIABLE_KIND)[keyof typeof TEMPLATE_VARIABLE_KIND]\n\nexport type TemplateVariableDefinition = {\n readonly name: string\n /** Ausente é `text`: todo catálogo escrito antes disto continua valendo sem alteração. */\n readonly kind?: TemplateVariableKind\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. Só variáveis de texto entram aqui. */\n readonly missingRequired: readonly string[]\n /**\n * Anexos referenciados DENTRO do texto — quase sempre engano.\n *\n * `{{nota}}` no corpo de um anexo renderiza a URL crua no meio da frase, e não anexa nada. Se a\n * intenção era mandar o link, a variável devia ser de texto; se era anexar, ela não pertence ao\n * corpo. Aviso e não erro: link para o arquivo é uma escolha legítima, só não é esta.\n */\n readonly attachmentsInText: 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: [], attachmentsInText: [] }\n\n const declared = new Set(params.variables.map((variable) => variable.name))\n const usedSet = new Set(used)\n const attachments = new Set(\n params.variables\n .filter((variable) => variable.kind === TEMPLATE_VARIABLE_KIND.ATTACHMENT)\n .map((variable) => variable.name),\n )\n\n return {\n used,\n unknown: used.filter((name) => !declared.has(name)),\n missingRequired: params.variables\n .filter(\n (variable) =>\n variable.required && variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT && !usedSet.has(variable.name),\n )\n .map((variable) => variable.name),\n attachmentsInText: used.filter((name) => attachments.has(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\n // Anexo não é interpolado: incluí-lo aqui faria o preview desenhar a URL no meio do texto de um\n // corpo que nunca vai conter essa URL.\n return Object.fromEntries(\n variables\n .filter((variable) => variable.kind !== TEMPLATE_VARIABLE_KIND.ATTACHMENT)\n .map((variable) => [variable.name, variable.example]),\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;;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,cAAc;EACzBC,MAAM;EACNC,KAAK;AACP;AAGO,IAAMC,eAAe;EAC1BC,MA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IVE_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","EMAIL_ATTACHMENT_MAX_BYTES","EMAIL_ATTACHMENT_MAX_COUNT","checkEmailAttachment","attachment","filename","trim","test","contentType","url","startsWith","undefined","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","BROWSER","IOS","ANDROID","viewport","width","PREVIEW_VIEWPORT_BY_CHANNEL","NOTIFICATION_CHANNEL","EMAIL","PUSH","WHATSAPP","SMS","INBOX","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","TEMPLATE_VARIABLE_KIND","TEXT","ATTACHMENT","diffTemplateVariables","params","used","extractTemplatePlaceholders","subject","body","variables","unknown","missingRequired","attachmentsInText","declared","Set","map","variable","name","usedSet","attachments","filter","kind","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.5",
|
|
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": {
|