@adatechnology/notification-contracts 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,396 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/notification.types.ts
5
+ var NOTIFICATION_CHANNEL = {
6
+ INBOX: "inbox",
7
+ PUSH: "push",
8
+ EMAIL: "email",
9
+ WHATSAPP: "whatsapp",
10
+ SMS: "sms"
11
+ };
12
+ var INTRUSIVE_CHANNELS = [
13
+ NOTIFICATION_CHANNEL.PUSH,
14
+ NOTIFICATION_CHANNEL.WHATSAPP,
15
+ NOTIFICATION_CHANNEL.SMS
16
+ ];
17
+ var NOTIFICATION_STATUS = {
18
+ PENDING: "pending",
19
+ SCHEDULED: "scheduled",
20
+ QUEUED: "queued",
21
+ DISPATCHED: "dispatched",
22
+ PARTIALLY_FAILED: "partially_failed",
23
+ FAILED: "failed"
24
+ };
25
+ var DELIVERY_STATUS = {
26
+ QUEUED: "queued",
27
+ SENT: "sent",
28
+ DELIVERED: "delivered",
29
+ FAILED: "failed",
30
+ BOUNCED: "bounced",
31
+ SKIPPED: "skipped"
32
+ };
33
+ var DEVICE_PLATFORM = {
34
+ IOS: "ios",
35
+ ANDROID: "android",
36
+ WEB: "web"
37
+ };
38
+ var PUSH_DRIVER = {
39
+ EXPO: "expo",
40
+ FCM: "fcm"
41
+ };
42
+ var EMAIL_DRIVER = {
43
+ SMTP: "smtp",
44
+ RESEND: "resend",
45
+ SES: "ses"
46
+ };
47
+ var SUPPRESSION_REASON = {
48
+ BOUNCE: "bounce",
49
+ COMPLAINT: "complaint",
50
+ OPT_OUT: "opt_out"
51
+ };
52
+ var NOTIFICATION_CATEGORY_HINT = {
53
+ ORDER_STATUS: "order_status",
54
+ PAYMENT: "payment",
55
+ SECURITY: "security",
56
+ MARKETING: "marketing",
57
+ SYSTEM: "system"
58
+ };
59
+
60
+ // src/schemas.ts
61
+ import { z } from "zod";
62
+ var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
63
+ var MAX_PER_PAGE = 100;
64
+ var quietHoursShape = {
65
+ quietHoursStart: z.string().regex(HHMM, "Use HH:mm").optional(),
66
+ quietHoursEnd: z.string().regex(HHMM, "Use HH:mm").optional(),
67
+ timezone: z.string().min(1).optional()
68
+ };
69
+ var sendNotificationSchema = z.object({
70
+ recipientUserId: z.string().uuid(),
71
+ category: z.string().min(1).max(64),
72
+ templateKey: z.string().min(1).max(128),
73
+ payload: z.record(z.unknown()).optional(),
74
+ channels: z.array(z.nativeEnum(NOTIFICATION_CHANNEL)).nonempty().optional(),
75
+ dedupeKey: z.string().min(1).max(256).optional(),
76
+ scheduledFor: z.coerce.date().optional(),
77
+ locale: z.string().min(2).max(16).optional()
78
+ });
79
+ var registerDeviceSchema = z.object({
80
+ platform: z.nativeEnum(DEVICE_PLATFORM),
81
+ driver: z.nativeEnum(PUSH_DRIVER),
82
+ token: z.string().min(1).max(4096),
83
+ appVersion: z.string().max(32).optional(),
84
+ locale: z.string().min(2).max(16).optional(),
85
+ timezone: z.string().min(1).max(64).optional()
86
+ });
87
+ var preferenceEntrySchema = z.object({
88
+ category: z.string().min(1).max(64),
89
+ channel: z.nativeEnum(NOTIFICATION_CHANNEL),
90
+ enabled: z.boolean(),
91
+ ...quietHoursShape
92
+ });
93
+ var updatePreferencesSchema = z.object({
94
+ preferences: z.array(preferenceEntrySchema).max(200)
95
+ });
96
+ var upsertTemplateSchema = z.object({
97
+ key: z.string().min(1).max(128),
98
+ channel: z.nativeEnum(NOTIFICATION_CHANNEL),
99
+ locale: z.string().min(2).max(16),
100
+ subject: z.string().max(256).optional(),
101
+ body: z.string().min(1).max(8192),
102
+ whatsappTemplateName: z.string().max(128).optional(),
103
+ active: z.boolean().default(true)
104
+ });
105
+ var listNotificationsQuerySchema = z.object({
106
+ category: z.string().min(1).max(64).optional(),
107
+ read: z.enum([
108
+ "true",
109
+ "false"
110
+ ]).transform((value) => value === "true").optional(),
111
+ cursor: z.string().max(512).optional(),
112
+ perPage: z.coerce.number().int().min(1).max(MAX_PER_PAGE).default(20)
113
+ });
114
+ var deliveryWebhookSchema = z.object({
115
+ providerMessageId: z.string().min(1),
116
+ status: z.enum([
117
+ "delivered",
118
+ "bounced",
119
+ "failed"
120
+ ]),
121
+ errorCode: z.string().max(64).optional(),
122
+ occurredAt: z.coerce.date(),
123
+ suppressionReason: z.nativeEnum(SUPPRESSION_REASON).optional()
124
+ });
125
+
126
+ // src/events.ts
127
+ var NOTIFICATION_EVENT = {
128
+ CREATED: "notification.created",
129
+ DISPATCHED: "notification.dispatched",
130
+ READ: "notification.read",
131
+ DELIVERY_SENT: "delivery.sent",
132
+ DELIVERY_FAILED: "delivery.failed",
133
+ DELIVERY_BOUNCED: "delivery.bounced",
134
+ DEVICE_REGISTERED: "device.registered",
135
+ DEVICE_INVALIDATED: "device.invalidated",
136
+ PREFERENCES_UPDATED: "preferences.updated"
137
+ };
138
+
139
+ // src/errors.ts
140
+ var NotificationError = class extends Error {
141
+ static {
142
+ __name(this, "NotificationError");
143
+ }
144
+ statusCode;
145
+ code;
146
+ details;
147
+ constructor(message, statusCode, code, details) {
148
+ super(message), this.statusCode = statusCode, this.code = code, this.details = details;
149
+ this.name = "NotificationError";
150
+ }
151
+ };
152
+ var NOTIFICATION_ERROR_CODES = {
153
+ TEMPLATE_NOT_FOUND: "NOTIFICATION_TEMPLATE_NOT_FOUND",
154
+ CHANNEL_NOT_CONFIGURED: "NOTIFICATION_CHANNEL_NOT_CONFIGURED",
155
+ RECIPIENT_UNRESOLVED: "NOTIFICATION_RECIPIENT_UNRESOLVED",
156
+ SUPPRESSED_TARGET: "NOTIFICATION_SUPPRESSED_TARGET",
157
+ NOT_FOUND: "NOTIFICATION_NOT_FOUND",
158
+ INVALID_WEBHOOK_SIGNATURE: "NOTIFICATION_INVALID_WEBHOOK_SIGNATURE",
159
+ DUPLICATE_WEBHOOK_DELIVERY: "NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY",
160
+ DEVICE_NOT_FOUND: "NOTIFICATION_DEVICE_NOT_FOUND",
161
+ THROTTLED: "NOTIFICATION_THROTTLED",
162
+ CONFIG_MISSING: "NOTIFICATION_CONFIG_MISSING"
163
+ };
164
+ var TemplateNotFoundError = class extends NotificationError {
165
+ static {
166
+ __name(this, "TemplateNotFoundError");
167
+ }
168
+ templateKey;
169
+ channel;
170
+ locale;
171
+ constructor(templateKey, channel, locale) {
172
+ super(`Template n\xE3o encontrado para a chave informada neste canal e locale.`, 404, NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND, {
173
+ templateKey,
174
+ channel,
175
+ locale
176
+ }), this.templateKey = templateKey, this.channel = channel, this.locale = locale;
177
+ }
178
+ };
179
+ var ChannelNotConfiguredError = class extends NotificationError {
180
+ static {
181
+ __name(this, "ChannelNotConfiguredError");
182
+ }
183
+ channel;
184
+ constructor(channel) {
185
+ super(`Canal habilitado sem driver injetado \u2014 injete o driver em providers.channels ou desligue a feature.`, 500, NOTIFICATION_ERROR_CODES.CHANNEL_NOT_CONFIGURED, {
186
+ channel
187
+ }), this.channel = channel;
188
+ }
189
+ };
190
+ var RecipientUnresolvedError = class extends NotificationError {
191
+ static {
192
+ __name(this, "RecipientUnresolvedError");
193
+ }
194
+ userId;
195
+ channel;
196
+ constructor(userId, channel) {
197
+ super(`Destinat\xE1rio sem endere\xE7o utiliz\xE1vel para este canal.`, 422, NOTIFICATION_ERROR_CODES.RECIPIENT_UNRESOLVED, {
198
+ userId,
199
+ channel
200
+ }), this.userId = userId, this.channel = channel;
201
+ }
202
+ };
203
+ var SuppressedTargetError = class extends NotificationError {
204
+ static {
205
+ __name(this, "SuppressedTargetError");
206
+ }
207
+ channel;
208
+ reason;
209
+ constructor(channel, reason) {
210
+ super(`Endere\xE7o suprimido para este canal \u2014 envio bloqueado.`, 409, NOTIFICATION_ERROR_CODES.SUPPRESSED_TARGET, {
211
+ channel,
212
+ reason
213
+ }), this.channel = channel, this.reason = reason;
214
+ }
215
+ };
216
+ var NotificationNotFoundError = class extends NotificationError {
217
+ static {
218
+ __name(this, "NotificationNotFoundError");
219
+ }
220
+ notificationId;
221
+ constructor(notificationId) {
222
+ super(`Notifica\xE7\xE3o n\xE3o encontrada.`, 404, NOTIFICATION_ERROR_CODES.NOT_FOUND, {
223
+ notificationId
224
+ }), this.notificationId = notificationId;
225
+ }
226
+ };
227
+ var InvalidWebhookSignatureError = class extends NotificationError {
228
+ static {
229
+ __name(this, "InvalidWebhookSignatureError");
230
+ }
231
+ constructor() {
232
+ super(`Assinatura do webhook inv\xE1lida.`, 401, NOTIFICATION_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE);
233
+ }
234
+ };
235
+ var DuplicateWebhookDeliveryError = class extends NotificationError {
236
+ static {
237
+ __name(this, "DuplicateWebhookDeliveryError");
238
+ }
239
+ nonce;
240
+ constructor(nonce) {
241
+ super(`Entrega de webhook duplicada.`, 200, NOTIFICATION_ERROR_CODES.DUPLICATE_WEBHOOK_DELIVERY, {
242
+ nonce
243
+ }), this.nonce = nonce;
244
+ }
245
+ };
246
+ var DeviceNotFoundError = class extends NotificationError {
247
+ static {
248
+ __name(this, "DeviceNotFoundError");
249
+ }
250
+ deviceId;
251
+ constructor(deviceId) {
252
+ super(`Dispositivo n\xE3o encontrado.`, 404, NOTIFICATION_ERROR_CODES.DEVICE_NOT_FOUND, {
253
+ deviceId
254
+ }), this.deviceId = deviceId;
255
+ }
256
+ };
257
+ var ThrottledError = class extends NotificationError {
258
+ static {
259
+ __name(this, "ThrottledError");
260
+ }
261
+ channel;
262
+ retryAfterSeconds;
263
+ constructor(channel, retryAfterSeconds) {
264
+ super(`Limite de envios para este destinat\xE1rio atingido.`, 429, NOTIFICATION_ERROR_CODES.THROTTLED, {
265
+ channel,
266
+ retryAfterSeconds
267
+ }), this.channel = channel, this.retryAfterSeconds = retryAfterSeconds;
268
+ }
269
+ };
270
+ var ConfigMissingError = class extends NotificationError {
271
+ static {
272
+ __name(this, "ConfigMissingError");
273
+ }
274
+ field;
275
+ constructor(field) {
276
+ super(`Configura\xE7\xE3o obrigat\xF3ria ausente: ${field}.`, 500, NOTIFICATION_ERROR_CODES.CONFIG_MISSING, {
277
+ field
278
+ }), this.field = field;
279
+ }
280
+ };
281
+
282
+ // src/whatsappDriver.ts
283
+ var INVALID_TARGET_CODES = /* @__PURE__ */ new Set([
284
+ 131026,
285
+ 131051
286
+ ]);
287
+ var PERMANENT_CODES = /* @__PURE__ */ new Set([
288
+ 131047,
289
+ 131031,
290
+ 368
291
+ ]);
292
+ var RETRIABLE_CODES = /* @__PURE__ */ new Set([
293
+ 613,
294
+ 130429,
295
+ 131056
296
+ ]);
297
+ function readNumericField(error, field) {
298
+ if (typeof error !== "object" || error === null || !(field in error)) return void 0;
299
+ const value = error[field];
300
+ return typeof value === "number" ? value : void 0;
301
+ }
302
+ __name(readNumericField, "readNumericField");
303
+ function classifyError(error) {
304
+ const metaCode = readNumericField(error, "code");
305
+ if (metaCode !== void 0) {
306
+ if (INVALID_TARGET_CODES.has(metaCode)) {
307
+ return {
308
+ outcome: "invalid_target",
309
+ errorCode: `meta_${metaCode}`,
310
+ suppressionReason: SUPPRESSION_REASON.BOUNCE
311
+ };
312
+ }
313
+ if (PERMANENT_CODES.has(metaCode)) return {
314
+ outcome: "permanent",
315
+ errorCode: `meta_${metaCode}`
316
+ };
317
+ if (RETRIABLE_CODES.has(metaCode)) return {
318
+ outcome: "retriable",
319
+ errorCode: `meta_${metaCode}`
320
+ };
321
+ }
322
+ const statusCode = readNumericField(error, "statusCode") ?? readNumericField(error, "status");
323
+ if (statusCode === 429 || statusCode !== void 0 && statusCode >= 500) {
324
+ return {
325
+ outcome: "retriable",
326
+ errorCode: `http_${statusCode}`
327
+ };
328
+ }
329
+ if (statusCode !== void 0 && statusCode >= 400) {
330
+ return {
331
+ outcome: "permanent",
332
+ errorCode: `http_${statusCode}`
333
+ };
334
+ }
335
+ return {
336
+ outcome: "retriable",
337
+ errorCode: "unknown"
338
+ };
339
+ }
340
+ __name(classifyError, "classifyError");
341
+ function createWhatsAppDriverFromChannel(channel) {
342
+ return {
343
+ async send(params) {
344
+ try {
345
+ const result = params.template ? await channel.sendTemplate({
346
+ to: params.to,
347
+ templateName: params.template.templateName,
348
+ languageCode: params.template.languageCode,
349
+ bodyParameters: params.template.bodyParameters ? [
350
+ ...params.template.bodyParameters
351
+ ] : void 0
352
+ }) : await channel.sendText(params.to, params.body);
353
+ return {
354
+ outcome: "sent",
355
+ providerMessageId: result.externalMessageId ?? void 0
356
+ };
357
+ } catch (error) {
358
+ return classifyError(error);
359
+ }
360
+ }
361
+ };
362
+ }
363
+ __name(createWhatsAppDriverFromChannel, "createWhatsAppDriverFromChannel");
364
+ export {
365
+ ChannelNotConfiguredError,
366
+ ConfigMissingError,
367
+ DELIVERY_STATUS,
368
+ DEVICE_PLATFORM,
369
+ DeviceNotFoundError,
370
+ DuplicateWebhookDeliveryError,
371
+ EMAIL_DRIVER,
372
+ INTRUSIVE_CHANNELS,
373
+ InvalidWebhookSignatureError,
374
+ NOTIFICATION_CATEGORY_HINT,
375
+ NOTIFICATION_CHANNEL,
376
+ NOTIFICATION_ERROR_CODES,
377
+ NOTIFICATION_EVENT,
378
+ NOTIFICATION_STATUS,
379
+ NotificationError,
380
+ NotificationNotFoundError,
381
+ PUSH_DRIVER,
382
+ RecipientUnresolvedError,
383
+ SUPPRESSION_REASON,
384
+ SuppressedTargetError,
385
+ TemplateNotFoundError,
386
+ ThrottledError,
387
+ createWhatsAppDriverFromChannel,
388
+ deliveryWebhookSchema,
389
+ listNotificationsQuerySchema,
390
+ preferenceEntrySchema,
391
+ registerDeviceSchema,
392
+ sendNotificationSchema,
393
+ updatePreferencesSchema,
394
+ upsertTemplateSchema
395
+ };
396
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/notification.types.ts","../src/schemas.ts","../src/events.ts","../src/errors.ts","../src/whatsappDriver.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport const NOTIFICATION_CHANNEL = {\n INBOX: 'inbox',\n PUSH: 'push',\n EMAIL: 'email',\n WHATSAPP: 'whatsapp',\n SMS: 'sms',\n} as const\nexport type NotificationChannel = (typeof NOTIFICATION_CHANNEL)[keyof typeof NOTIFICATION_CHANNEL]\n\n/** Canais que interrompem o destinatário e por isso respeitam quiet hours (ver spec §10.4). */\nexport const INTRUSIVE_CHANNELS: readonly NotificationChannel[] = [\n NOTIFICATION_CHANNEL.PUSH,\n NOTIFICATION_CHANNEL.WHATSAPP,\n NOTIFICATION_CHANNEL.SMS,\n]\n\nexport const NOTIFICATION_STATUS = {\n PENDING: 'pending',\n SCHEDULED: 'scheduled',\n QUEUED: 'queued',\n DISPATCHED: 'dispatched',\n PARTIALLY_FAILED: 'partially_failed',\n FAILED: 'failed',\n} as const\nexport type NotificationStatus = (typeof NOTIFICATION_STATUS)[keyof typeof NOTIFICATION_STATUS]\n\nexport const DELIVERY_STATUS = {\n QUEUED: 'queued',\n SENT: 'sent',\n DELIVERED: 'delivered',\n FAILED: 'failed',\n BOUNCED: 'bounced',\n SKIPPED: 'skipped',\n} as const\nexport type DeliveryStatus = (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS]\n\nexport const DEVICE_PLATFORM = {\n IOS: 'ios',\n ANDROID: 'android',\n WEB: 'web',\n} as const\nexport type DevicePlatform = (typeof DEVICE_PLATFORM)[keyof typeof DEVICE_PLATFORM]\n\nexport const PUSH_DRIVER = {\n EXPO: 'expo',\n FCM: 'fcm',\n} as const\nexport type PushDriver = (typeof PUSH_DRIVER)[keyof typeof PUSH_DRIVER]\n\nexport const EMAIL_DRIVER = {\n SMTP: 'smtp',\n RESEND: 'resend',\n SES: 'ses',\n} as const\nexport type EmailDriver = (typeof EMAIL_DRIVER)[keyof typeof EMAIL_DRIVER]\n\nexport const SUPPRESSION_REASON = {\n BOUNCE: 'bounce',\n COMPLAINT: 'complaint',\n OPT_OUT: 'opt_out',\n} as const\nexport type SuppressionReason = (typeof SUPPRESSION_REASON)[keyof typeof SUPPRESSION_REASON]\n\n/**\n * Sugestão de nomenclatura, sem valor normativo (decisão Q2 da spec). `category` é `varchar`\n * livre porque é vocabulário de negócio do produto — fechá-la num enum aqui obrigaria uma major\n * do pacote a cada produto novo.\n */\nexport const NOTIFICATION_CATEGORY_HINT = {\n ORDER_STATUS: 'order_status',\n PAYMENT: 'payment',\n SECURITY: 'security',\n MARKETING: 'marketing',\n SYSTEM: 'system',\n} as const\n\nexport type NotificationId = string\nexport type CompanyId = string\nexport type UserId = string\n\nexport type NotificationSummary = {\n readonly id: NotificationId\n readonly category: string\n readonly templateKey: string\n readonly title: string\n readonly body: string\n readonly payload: Readonly<Record<string, unknown>>\n readonly status: NotificationStatus\n readonly scheduledFor?: string\n readonly readAt?: string\n readonly createdAt: string\n}\n\nexport type DeliverySummary = {\n readonly id: string\n readonly notificationId: NotificationId\n readonly channel: NotificationChannel\n readonly driver?: string\n /** Nunca o endereço em claro: `****1234`, `a***@dominio.com` (LGPD — ver spec §5). */\n readonly targetMasked?: string\n readonly status: DeliveryStatus\n readonly attempt: number\n readonly providerMessageId?: string\n readonly errorCode?: string\n readonly sentAt?: string\n readonly deliveredAt?: string\n readonly failedAt?: string\n}\n\nexport type DeviceRegistration = {\n readonly id: string\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n readonly lastSeenAt: string\n readonly disabledAt?: string\n readonly disabledReason?: string\n}\n\nexport type NotificationPreference = {\n readonly category: string\n readonly channel: NotificationChannel\n readonly enabled: boolean\n /** `HH:mm` no timezone resolvido para o destinatário; ambos ausentes = sem janela de silêncio. */\n readonly quietHoursStart?: string\n readonly quietHoursEnd?: string\n readonly timezone?: string\n}\n\nexport type NotificationTemplate = {\n readonly id: string\n readonly key: string\n readonly channel: NotificationChannel\n readonly locale: string\n readonly version: number\n readonly subject?: string\n readonly body: string\n /**\n * Nome do template aprovado na Meta. Sem ele, o canal WhatsApp é pulado fora da janela de 24 h\n * em vez de estourar erro na cara do usuário (spec §10.7).\n */\n readonly whatsappTemplateName?: string\n readonly active: boolean\n}\n\nexport type SendNotificationParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n readonly payload?: Readonly<Record<string, unknown>>\n /** Sem canais explícitos, o fan-out resolve pelas preferências do destinatário. */\n readonly channels?: readonly NotificationChannel[]\n /** Chave de negócio da entrega. Repetição devolve a notificação existente, não uma nova. */\n readonly dedupeKey?: string\n readonly scheduledFor?: Date\n readonly locale?: string\n}\n\nexport type SendNotificationResult = {\n readonly notificationId: NotificationId\n /** `true` quando um `dedupeKey` já visto devolveu a notificação anterior — nada foi reenviado. */\n readonly deduplicated: boolean\n readonly deliveries: readonly DeliverySummary[]\n}\n\nexport type ListNotificationsParams = {\n readonly companyId: CompanyId\n readonly recipientUserId: UserId\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsResult = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type DeliveryReceipt = {\n readonly providerMessageId: string\n readonly status: Extract<DeliveryStatus, 'delivered' | 'bounced' | 'failed'>\n readonly errorCode?: string\n readonly occurredAt: Date\n readonly suppressionReason?: SuppressionReason\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { z } from 'zod'\n\nimport { DEVICE_PLATFORM, NOTIFICATION_CHANNEL, PUSH_DRIVER, SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Schemas de fronteira. Regra que atravessa todos eles: **`companyId` nunca vem do corpo da\n * requisição** — é derivado do contexto autenticado (`database.md`, \"Consistência e\n * multiempresa\"). Aceitá-lo aqui seria entregar o isolamento multiempresa ao cliente.\n */\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/\nconst MAX_PER_PAGE = 100\n\nconst quietHoursShape = {\n quietHoursStart: z.string().regex(HHMM, 'Use HH:mm').optional(),\n quietHoursEnd: z.string().regex(HHMM, 'Use HH:mm').optional(),\n timezone: z.string().min(1).optional(),\n}\n\nexport const sendNotificationSchema = z.object({\n recipientUserId: z.string().uuid(),\n category: z.string().min(1).max(64),\n templateKey: z.string().min(1).max(128),\n payload: z.record(z.unknown()).optional(),\n channels: z.array(z.nativeEnum(NOTIFICATION_CHANNEL)).nonempty().optional(),\n dedupeKey: z.string().min(1).max(256).optional(),\n scheduledFor: z.coerce.date().optional(),\n locale: z.string().min(2).max(16).optional(),\n})\nexport type SendNotificationBody = z.infer<typeof sendNotificationSchema>\n\nexport const registerDeviceSchema = z.object({\n platform: z.nativeEnum(DEVICE_PLATFORM),\n driver: z.nativeEnum(PUSH_DRIVER),\n token: z.string().min(1).max(4096),\n appVersion: z.string().max(32).optional(),\n locale: z.string().min(2).max(16).optional(),\n timezone: z.string().min(1).max(64).optional(),\n})\nexport type RegisterDeviceBody = z.infer<typeof registerDeviceSchema>\n\nexport const preferenceEntrySchema = z.object({\n category: z.string().min(1).max(64),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n enabled: z.boolean(),\n ...quietHoursShape,\n})\n\nexport const updatePreferencesSchema = z.object({\n preferences: z.array(preferenceEntrySchema).max(200),\n})\nexport type UpdatePreferencesBody = z.infer<typeof updatePreferencesSchema>\n\nexport const upsertTemplateSchema = z.object({\n key: z.string().min(1).max(128),\n channel: z.nativeEnum(NOTIFICATION_CHANNEL),\n locale: z.string().min(2).max(16),\n subject: z.string().max(256).optional(),\n body: z.string().min(1).max(8192),\n whatsappTemplateName: z.string().max(128).optional(),\n active: z.boolean().default(true),\n})\nexport type UpsertTemplateBody = z.infer<typeof upsertTemplateSchema>\n\n/** Query string chega sempre como texto — daí o `coerce` e o booleano por literal. */\nexport const listNotificationsQuerySchema = z.object({\n category: z.string().min(1).max(64).optional(),\n read: z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional(),\n cursor: z.string().max(512).optional(),\n perPage: z.coerce.number().int().min(1).max(MAX_PER_PAGE).default(20),\n})\nexport type ListNotificationsQuery = z.infer<typeof listNotificationsQuerySchema>\n\n/**\n * Forma normalizada do recibo de entrega, depois que o parser do driver traduziu o payload do\n * provedor. A verificação de assinatura acontece antes disto, sobre o `rawBody`.\n */\nexport const deliveryWebhookSchema = z.object({\n providerMessageId: z.string().min(1),\n status: z.enum(['delivered', 'bounced', 'failed']),\n errorCode: z.string().max(64).optional(),\n occurredAt: z.coerce.date(),\n suppressionReason: z.nativeEnum(SUPPRESSION_REASON).optional(),\n})\nexport type DeliveryWebhookBody = z.infer<typeof deliveryWebhookSchema>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type {\n CompanyId,\n DevicePlatform,\n NotificationChannel,\n NotificationId,\n NotificationStatus,\n PushDriver,\n SuppressionReason,\n UserId,\n} from './notification.types'\n\n/**\n * Eventos de domínio — os pontos de extensão do produto. É aqui que entra a regra de negócio que\n * o módulo não pode ter (ex.: bounce de e-mail marca o contato como inválido no CRM), sem\n * ninguém editar código do pacote (regra de módulos plugáveis, §3).\n */\nexport const NOTIFICATION_EVENT = {\n CREATED: 'notification.created',\n DISPATCHED: 'notification.dispatched',\n READ: 'notification.read',\n DELIVERY_SENT: 'delivery.sent',\n DELIVERY_FAILED: 'delivery.failed',\n DELIVERY_BOUNCED: 'delivery.bounced',\n DEVICE_REGISTERED: 'device.registered',\n DEVICE_INVALIDATED: 'device.invalidated',\n PREFERENCES_UPDATED: 'preferences.updated',\n} as const\nexport type NotificationEvent = (typeof NOTIFICATION_EVENT)[keyof typeof NOTIFICATION_EVENT]\n\ntype BaseEvent = {\n readonly companyId: CompanyId\n readonly occurredAt: Date\n}\n\nexport type NotificationCreatedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n readonly category: string\n readonly templateKey: string\n /** Canais que sobreviveram ao fan-out; os pulados aparecem em `skippedChannels`. */\n readonly channels: readonly NotificationChannel[]\n readonly skippedChannels: readonly { readonly channel: NotificationChannel; readonly reason: string }[]\n}\n\nexport type NotificationDispatchedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly status: NotificationStatus\n}\n\nexport type NotificationReadEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly recipientUserId: UserId\n}\n\nexport type DeliverySentEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly providerMessageId?: string\n readonly attempt: number\n}\n\nexport type DeliveryFailedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly errorCode: string\n readonly attempt: number\n /** `false` quando o retry esgotou ou o erro é permanente — é o gancho para alerta do host. */\n readonly willRetry: boolean\n}\n\nexport type DeliveryBouncedEvent = BaseEvent & {\n readonly notificationId: NotificationId\n readonly deliveryId: string\n readonly channel: NotificationChannel\n readonly reason: SuppressionReason\n}\n\nexport type DeviceRegisteredEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly platform: DevicePlatform\n readonly driver: PushDriver\n}\n\nexport type DeviceInvalidatedEvent = BaseEvent & {\n readonly deviceId: string\n readonly userId: UserId\n readonly driver: PushDriver\n readonly errorCode: string\n}\n\nexport type PreferencesUpdatedEvent = BaseEvent & {\n readonly userId: UserId\n readonly categories: readonly string[]\n}\n\n/**\n * Hooks são `void`-tolerantes de propósito: falha de hook do produto não pode derrubar a entrega\n * da notificação. O módulo loga e segue — quem precisa de garantia transacional usa a fila.\n */\nexport type NotificationHooks = {\n onNotificationCreated?(event: NotificationCreatedEvent): Promise<void> | void\n onNotificationDispatched?(event: NotificationDispatchedEvent): Promise<void> | void\n onNotificationRead?(event: NotificationReadEvent): Promise<void> | void\n onDeliverySent?(event: DeliverySentEvent): Promise<void> | void\n onDeliveryFailed?(event: DeliveryFailedEvent): Promise<void> | void\n onDeliveryBounced?(event: DeliveryBouncedEvent): Promise<void> | void\n onDeviceRegistered?(event: DeviceRegisteredEvent): Promise<void> | void\n onDeviceInvalidated?(event: DeviceInvalidatedEvent): Promise<void> | void\n onPreferencesUpdated?(event: PreferencesUpdatedEvent): Promise<void> | void\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { NotificationChannel } from './notification.types'\n\n/**\n * Hierarquia autocontida: um pacote publicado não importa o `DomainError` do host. O host mapeia\n * estes erros no seu exception filter — e o próprio módulo já traz um, para o consumidor das rotas\n * não precisar escrever `try/catch` por endpoint.\n */\nexport class NotificationError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'NotificationError'\n }\n}\n\nexport const NOTIFICATION_ERROR_CODES = {\n TEMPLATE_NOT_FOUND: 'NOTIFICATION_TEMPLATE_NOT_FOUND',\n CHANNEL_NOT_CONFIGURED: 'NOTIFICATION_CHANNEL_NOT_CONFIGURED',\n RECIPIENT_UNRESOLVED: 'NOTIFICATION_RECIPIENT_UNRESOLVED',\n SUPPRESSED_TARGET: 'NOTIFICATION_SUPPRESSED_TARGET',\n NOT_FOUND: 'NOTIFICATION_NOT_FOUND',\n INVALID_WEBHOOK_SIGNATURE: 'NOTIFICATION_INVALID_WEBHOOK_SIGNATURE',\n DUPLICATE_WEBHOOK_DELIVERY: 'NOTIFICATION_DUPLICATE_WEBHOOK_DELIVERY',\n DEVICE_NOT_FOUND: 'NOTIFICATION_DEVICE_NOT_FOUND',\n THROTTLED: 'NOTIFICATION_THROTTLED',\n CONFIG_MISSING: 'NOTIFICATION_CONFIG_MISSING',\n} as const\n\nexport class TemplateNotFoundError extends NotificationError {\n constructor(\n public readonly templateKey: string,\n public readonly channel: NotificationChannel,\n public readonly locale: string,\n ) {\n super(\n `Template não encontrado para a chave informada neste canal e locale.`,\n 404,\n NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND,\n { templateKey, channel, locale },\n )\n }\n}\n\n/** Canal ligado em `features` sem driver injetado — erro de composição, detectado no boot. */\nexport class ChannelNotConfiguredError extends NotificationError {\n constructor(public readonly channel: NotificationChannel) {\n super(\n `Canal habilitado sem driver injetado — injete o driver em providers.channels ou desligue a feature.`,\n 500,\n NOTIFICATION_ERROR_CODES.CHANNEL_NOT_CONFIGURED,\n { channel },\n )\n }\n}\n\n/**\n * `RecipientResolverPort` não devolveu endereço para o canal. Mensagem sem PII de propósito: o\n * `userId` é identificador opaco, o e-mail ou telefone jamais entra no erro (`security.md` §1).\n */\nexport class RecipientUnresolvedError extends NotificationError {\n constructor(\n public readonly userId: string,\n public readonly channel: NotificationChannel,\n ) {\n super(`Destinatário sem endereço utilizável para este canal.`, 422, NOTIFICATION_ERROR_CODES.RECIPIENT_UNRESOLVED, {\n userId,\n channel,\n })\n }\n}\n\nexport class SuppressedTargetError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly reason: string,\n ) {\n super(`Endereço suprimido para este canal — envio bloqueado.`, 409, NOTIFICATION_ERROR_CODES.SUPPRESSED_TARGET, {\n channel,\n reason,\n })\n }\n}\n\n/**\n * Também é a resposta para notificação de OUTRO usuário: devolver 404 em vez de 403 não revela a\n * existência do recurso a quem não pode vê-lo (BOLA/API1).\n */\nexport class NotificationNotFoundError extends NotificationError {\n constructor(public readonly notificationId: string) {\n super(`Notificação não encontrada.`, 404, NOTIFICATION_ERROR_CODES.NOT_FOUND, { notificationId })\n }\n}\n\nexport class InvalidWebhookSignatureError extends NotificationError {\n constructor() {\n super(`Assinatura do webhook inválida.`, 401, NOTIFICATION_ERROR_CODES.INVALID_WEBHOOK_SIGNATURE)\n }\n}\n\n/** Recibo reenviado dentro da janela de replay (nonce já visto) — não é erro, é ruído esperado. */\nexport class DuplicateWebhookDeliveryError extends NotificationError {\n constructor(public readonly nonce: string) {\n super(`Entrega de webhook duplicada.`, 200, NOTIFICATION_ERROR_CODES.DUPLICATE_WEBHOOK_DELIVERY, { nonce })\n }\n}\n\nexport class DeviceNotFoundError extends NotificationError {\n constructor(public readonly deviceId: string) {\n super(`Dispositivo não encontrado.`, 404, NOTIFICATION_ERROR_CODES.DEVICE_NOT_FOUND, { deviceId })\n }\n}\n\nexport class ThrottledError extends NotificationError {\n constructor(\n public readonly channel: NotificationChannel,\n public readonly retryAfterSeconds: number,\n ) {\n super(`Limite de envios para este destinatário atingido.`, 429, NOTIFICATION_ERROR_CODES.THROTTLED, {\n channel,\n retryAfterSeconds,\n })\n }\n}\n\n/**\n * Configuração obrigatória ausente (chave de HMAC, segredo de webhook) — falha no boot.\n *\n * Único erro do módulo cuja mensagem nomeia o campo: ele é lido por quem está subindo o serviço,\n * não devolvido a um cliente, e \"algo está faltando\" sem dizer o quê custa uma bisca no código.\n * O nome do campo é identificador de configuração, nunca valor — o segredo em si não aparece.\n */\nexport class ConfigMissingError extends NotificationError {\n constructor(public readonly field: string) {\n super(`Configuração obrigatória ausente: ${field}.`, 500, NOTIFICATION_ERROR_CODES.CONFIG_MISSING, { field })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { DeliveryAttemptResult, SendWhatsAppParams, WhatsAppDriverPort } from './channelDrivers'\nimport { SUPPRESSION_REASON } from './notification.types'\n\n/**\n * Forma mínima que o `channel` do `meta-whatsapp-module` já satisfaz. Descrita aqui por\n * *estrutura*, e não importada do pacote de WhatsApp: é isso que mantém os dois trios\n * independentes — quem só usa inbox não carrega Meta, quem só usa WhatsApp não carrega\n * notificação, e a costura acontece no produto (regra de módulos plugáveis, §2).\n */\nexport type WhatsAppSendingChannel = {\n sendText(to: string, body: string): Promise<{ externalMessageId: string | null }>\n sendTemplate(params: {\n to: string\n templateName: string\n languageCode: string\n bodyParameters?: string[]\n }): Promise<{ externalMessageId: string | null }>\n}\n\n/**\n * Códigos da Graph API que o canal repassa. A lista é curta de propósito: cobre o que muda a\n * decisão do módulo (apagar destino × tentar de novo × desistir) e nada além disso.\n */\nconst INVALID_TARGET_CODES = new Set([131026, 131051])\nconst PERMANENT_CODES = new Set([131047, 131031, 368])\nconst RETRIABLE_CODES = new Set([613, 130429, 131056])\n\nfunction readNumericField(error: unknown, field: string): number | undefined {\n if (typeof error !== 'object' || error === null || !(field in error)) return undefined\n const value = (error as Record<string, unknown>)[field]\n return typeof value === 'number' ? value : undefined\n}\n\nfunction classifyError(error: unknown): DeliveryAttemptResult {\n const metaCode = readNumericField(error, 'code')\n if (metaCode !== undefined) {\n if (INVALID_TARGET_CODES.has(metaCode)) {\n return {\n outcome: 'invalid_target',\n errorCode: `meta_${metaCode}`,\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n }\n }\n if (PERMANENT_CODES.has(metaCode)) return { outcome: 'permanent', errorCode: `meta_${metaCode}` }\n if (RETRIABLE_CODES.has(metaCode)) return { outcome: 'retriable', errorCode: `meta_${metaCode}` }\n }\n\n const statusCode = readNumericField(error, 'statusCode') ?? readNumericField(error, 'status')\n if (statusCode === 429 || (statusCode !== undefined && statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: `http_${statusCode}` }\n }\n if (statusCode !== undefined && statusCode >= 400) {\n return { outcome: 'permanent', errorCode: `http_${statusCode}` }\n }\n\n // Sem código nenhum é quase sempre falha de rede/DNS, que passa numa segunda tentativa. O risco\n // do palpite é limitado: o retry é finito (`attempts`) e termina em `failed` de qualquer forma.\n return { outcome: 'retriable', errorCode: 'unknown' }\n}\n\nexport function createWhatsAppDriverFromChannel(channel: WhatsAppSendingChannel): WhatsAppDriverPort {\n return {\n async send(params: SendWhatsAppParams): Promise<DeliveryAttemptResult> {\n try {\n const result = params.template\n ? await channel.sendTemplate({\n to: params.to,\n templateName: params.template.templateName,\n languageCode: params.template.languageCode,\n bodyParameters: params.template.bodyParameters ? [...params.template.bodyParameters] : undefined,\n })\n : await channel.sendText(params.to, params.body)\n\n return { outcome: 'sent', providerMessageId: result.externalMessageId ?? undefined }\n } catch (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AIJ,OAAOI;UACXC,cAAcL,OAAOE,SAASG;UAC9BC,cAAcN,OAAOE,SAASI;UAC9BC,gBAAgBP,OAAOE,SAASK,iBAAiB;eAAIP,OAAOE,SAASK;cAAkBrB;QACzF,CAAA,IACA,MAAMY,QAAQU,SAASR,OAAOI,IAAIJ,OAAOS,IAAI;AAEjD,eAAO;UAAElB,SAAS;UAAQmB,mBAAmBT,OAAOU,qBAAqBzB;QAAU;MACrF,SAASF,OAAO;AACd,eAAOI,cAAcJ,KAAAA;MACvB;IACF;EACF;AACF;AAnBgBa;","names":["NOTIFICATION_CHANNEL","INBOX","PUSH","EMAIL","WHATSAPP","SMS","INTRUSIVE_CHANNELS","NOTIFICATION_STATUS","PENDING","SCHEDULED","QUEUED","DISPATCHED","PARTIALLY_FAILED","FAILED","DELIVERY_STATUS","SENT","DELIVERED","BOUNCED","SKIPPED","DEVICE_PLATFORM","IOS","ANDROID","WEB","PUSH_DRIVER","EXPO","FCM","EMAIL_DRIVER","SMTP","RESEND","SES","SUPPRESSION_REASON","BOUNCE","COMPLAINT","OPT_OUT","NOTIFICATION_CATEGORY_HINT","ORDER_STATUS","PAYMENT","SECURITY","MARKETING","SYSTEM","z","HHMM","MAX_PER_PAGE","quietHoursShape","quietHoursStart","z","string","regex","optional","quietHoursEnd","timezone","min","sendNotificationSchema","object","recipientUserId","uuid","category","max","templateKey","payload","record","unknown","channels","array","nativeEnum","NOTIFICATION_CHANNEL","nonempty","dedupeKey","scheduledFor","coerce","date","locale","registerDeviceSchema","platform","DEVICE_PLATFORM","driver","PUSH_DRIVER","token","appVersion","preferenceEntrySchema","channel","enabled","boolean","updatePreferencesSchema","preferences","upsertTemplateSchema","key","subject","body","whatsappTemplateName","active","default","listNotificationsQuerySchema","read","enum","transform","value","cursor","perPage","number","int","deliveryWebhookSchema","providerMessageId","status","errorCode","occurredAt","suppressionReason","SUPPRESSION_REASON","NOTIFICATION_EVENT","CREATED","DISPATCHED","READ","DELIVERY_SENT","DELIVERY_FAILED","DELIVERY_BOUNCED","DEVICE_REGISTERED","DEVICE_INVALIDATED","PREFERENCES_UPDATED","NotificationError","Error","message","statusCode","code","details","name","NOTIFICATION_ERROR_CODES","TEMPLATE_NOT_FOUND","CHANNEL_NOT_CONFIGURED","RECIPIENT_UNRESOLVED","SUPPRESSED_TARGET","NOT_FOUND","INVALID_WEBHOOK_SIGNATURE","DUPLICATE_WEBHOOK_DELIVERY","DEVICE_NOT_FOUND","THROTTLED","CONFIG_MISSING","TemplateNotFoundError","templateKey","channel","locale","ChannelNotConfiguredError","RecipientUnresolvedError","userId","SuppressedTargetError","reason","NotificationNotFoundError","notificationId","InvalidWebhookSignatureError","DuplicateWebhookDeliveryError","nonce","DeviceNotFoundError","deviceId","ThrottledError","retryAfterSeconds","ConfigMissingError","field","INVALID_TARGET_CODES","Set","PERMANENT_CODES","RETRIABLE_CODES","readNumericField","error","field","undefined","value","classifyError","metaCode","has","outcome","errorCode","suppressionReason","SUPPRESSION_REASON","BOUNCE","statusCode","createWhatsAppDriverFromChannel","channel","send","params","result","template","sendTemplate","to","templateName","languageCode","bodyParameters","sendText","body","providerMessageId","externalMessageId"]}
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@adatechnology/notification-contracts",
3
+ "version": "0.1.0-rc.1",
4
+ "description": "Shared types, zod schemas, and port interfaces for the notification trio (contracts only — no runtime behavior)",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "dependencies": {
23
+ "zod": "^3.24.1"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "1.3.14",
27
+ "tsup": "^8.5.1",
28
+ "typescript": "^5.7.3"
29
+ },
30
+ "scripts": {
31
+ "build": "tsup",
32
+ "check": "tsc -p tsconfig.json --noEmit",
33
+ "test": "bun test"
34
+ }
35
+ }