@adatechnology/notification-client 0.2.2 → 0.3.0

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 CHANGED
@@ -21,9 +21,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  // src/index.ts
22
22
  var index_exports = {};
23
23
  __export(index_exports, {
24
+ arrayBufferToBase64Url: () => arrayBufferToBase64Url,
24
25
  createDeviceRegistration: () => createDeviceRegistration,
26
+ createExpoPushRegistration: () => createExpoPushRegistration,
25
27
  createNotificationClient: () => createNotificationClient,
26
- subscribeToNotificationStream: () => subscribeToNotificationStream
28
+ getExpoPushToken: () => getExpoPushToken,
29
+ getStandardWebPushServiceWorkerScript: () => getStandardWebPushServiceWorkerScript,
30
+ isWebPushSupported: () => isWebPushSupported,
31
+ subscribeToNotificationStream: () => subscribeToNotificationStream,
32
+ subscribeWebPush: () => subscribeWebPush,
33
+ unsubscribeWebPush: () => unsubscribeWebPush,
34
+ urlBase64ToUint8Array: () => urlBase64ToUint8Array
27
35
  });
28
36
  module.exports = __toCommonJS(index_exports);
29
37
 
@@ -201,6 +209,48 @@ function createNotificationClient(config) {
201
209
  url: `${baseUrl}/notifications/stream`,
202
210
  headers: await config.getAuthHeaders?.() ?? {}
203
211
  };
212
+ },
213
+ async getVapidPublicKey() {
214
+ const payload = await request({
215
+ method: "GET",
216
+ path: "/push/vapid-public-key"
217
+ });
218
+ if (!payload?.data?.publicKey) throw new Error("notification-client: chave p\xFAblica VAPID n\xE3o retornada");
219
+ return payload.data.publicKey;
220
+ },
221
+ async sendPush(input) {
222
+ const payload = await request({
223
+ method: "POST",
224
+ path: "/push/send",
225
+ body: input
226
+ });
227
+ if (!payload?.data) throw new Error("notification-client: resposta vazia ao enviar push");
228
+ return payload.data;
229
+ },
230
+ async broadcastPush(input) {
231
+ const payload = await request({
232
+ method: "POST",
233
+ path: "/push/broadcast",
234
+ body: input
235
+ });
236
+ if (!payload?.data) throw new Error("notification-client: resposta vazia em broadcastPush");
237
+ return payload.data;
238
+ },
239
+ async registerWebPush(subscription, options) {
240
+ const payload = await request({
241
+ method: "POST",
242
+ path: "/notification-devices",
243
+ body: {
244
+ platform: "web",
245
+ driver: "webpush",
246
+ token: JSON.stringify(subscription),
247
+ appVersion: options?.appVersion,
248
+ locale: options?.locale,
249
+ timezone: options?.timezone
250
+ }
251
+ });
252
+ if (!payload?.data) throw new Error("notification-client: resposta vazia em registerWebPush");
253
+ return payload.data;
204
254
  }
205
255
  };
206
256
  }
@@ -318,10 +368,162 @@ function subscribeToNotificationStream(params) {
318
368
  };
319
369
  }
320
370
  __name(subscribeToNotificationStream, "subscribeToNotificationStream");
371
+
372
+ // src/webPush.ts
373
+ function urlBase64ToUint8Array(base64String) {
374
+ const padding = "=".repeat((4 - base64String.length % 4) % 4);
375
+ const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
376
+ const rawData = atob(base64);
377
+ const outputArray = new Uint8Array(rawData.length);
378
+ for (let i = 0; i < rawData.length; ++i) {
379
+ outputArray[i] = rawData.charCodeAt(i);
380
+ }
381
+ return outputArray;
382
+ }
383
+ __name(urlBase64ToUint8Array, "urlBase64ToUint8Array");
384
+ function arrayBufferToBase64Url(buffer) {
385
+ if (!buffer) return "";
386
+ const bytes = new Uint8Array(buffer);
387
+ let binary = "";
388
+ for (let i = 0; i < bytes.byteLength; i++) {
389
+ binary += String.fromCharCode(bytes[i]);
390
+ }
391
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
392
+ }
393
+ __name(arrayBufferToBase64Url, "arrayBufferToBase64Url");
394
+ function isWebPushSupported() {
395
+ if (typeof window === "undefined" || typeof navigator === "undefined") return false;
396
+ return "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
397
+ }
398
+ __name(isWebPushSupported, "isWebPushSupported");
399
+ async function subscribeWebPush(options) {
400
+ if (!isWebPushSupported()) return void 0;
401
+ if (Notification.permission === "default") {
402
+ const permission = await Notification.requestPermission();
403
+ if (permission !== "granted") return void 0;
404
+ } else if (Notification.permission !== "granted") {
405
+ return void 0;
406
+ }
407
+ const registration = options.serviceWorkerRegistration ?? await navigator.serviceWorker.ready;
408
+ const applicationServerKey = urlBase64ToUint8Array(options.vapidPublicKey);
409
+ let subscription = await registration.pushManager.getSubscription();
410
+ if (!subscription) {
411
+ subscription = await registration.pushManager.subscribe({
412
+ userVisibleOnly: true,
413
+ applicationServerKey
414
+ });
415
+ }
416
+ const p256dh = arrayBufferToBase64Url(subscription.getKey("p256dh"));
417
+ const auth = arrayBufferToBase64Url(subscription.getKey("auth"));
418
+ return {
419
+ endpoint: subscription.endpoint,
420
+ keys: {
421
+ p256dh,
422
+ auth
423
+ },
424
+ expirationTime: subscription.expirationTime
425
+ };
426
+ }
427
+ __name(subscribeWebPush, "subscribeWebPush");
428
+ async function unsubscribeWebPush(serviceWorkerRegistration) {
429
+ if (!isWebPushSupported()) return false;
430
+ const registration = serviceWorkerRegistration ?? await navigator.serviceWorker.ready;
431
+ const subscription = await registration.pushManager.getSubscription();
432
+ if (!subscription) return false;
433
+ return subscription.unsubscribe();
434
+ }
435
+ __name(unsubscribeWebPush, "unsubscribeWebPush");
436
+ function getStandardWebPushServiceWorkerScript() {
437
+ return `
438
+ self.addEventListener('push', (event) => {
439
+ if (!event.data) return;
440
+ let payload;
441
+ try {
442
+ payload = event.data.json();
443
+ } catch {
444
+ payload = { title: 'Notifica\xE7\xE3o', body: event.data.text() };
445
+ }
446
+
447
+ const title = payload.title || 'Nova Notifica\xE7\xE3o';
448
+ const options = {
449
+ body: payload.body || '',
450
+ icon: payload.icon || '/pwa-192x192.png',
451
+ badge: payload.badge || '/badge-72x72.png',
452
+ tag: payload.tag,
453
+ data: payload.data || { url: payload.url || '/' },
454
+ };
455
+
456
+ event.waitUntil(self.registration.showNotification(title, options));
457
+ });
458
+
459
+ self.addEventListener('notificationclick', (event) => {
460
+ event.notification.close();
461
+ const targetUrl = event.notification.data?.url || '/';
462
+
463
+ event.waitUntil(
464
+ clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
465
+ for (const client of clientList) {
466
+ if (client.url === targetUrl && 'focus' in client) {
467
+ return client.focus();
468
+ }
469
+ }
470
+ if (clients.openWindow) {
471
+ return clients.openWindow(targetUrl);
472
+ }
473
+ })
474
+ );
475
+ });
476
+ `.trim();
477
+ }
478
+ __name(getStandardWebPushServiceWorkerScript, "getStandardWebPushServiceWorkerScript");
479
+
480
+ // src/expoPush.ts
481
+ async function getExpoPushToken(options) {
482
+ const { module: module2 } = options;
483
+ const currentPerms = await module2.getPermissionsAsync();
484
+ let isGranted = currentPerms.granted;
485
+ if (!isGranted) {
486
+ const requested = await module2.requestPermissionsAsync();
487
+ isGranted = requested.granted;
488
+ }
489
+ if (!isGranted) return void 0;
490
+ if (typeof module2.setNotificationChannelAsync === "function") {
491
+ await module2.setNotificationChannelAsync(options.channelId ?? "default", {
492
+ name: options.channelName ?? "Geral",
493
+ importance: 4,
494
+ sound: true
495
+ });
496
+ }
497
+ const tokenResult = await module2.getExpoPushTokenAsync({
498
+ projectId: options.projectId
499
+ });
500
+ return tokenResult.data;
501
+ }
502
+ __name(getExpoPushToken, "getExpoPushToken");
503
+ function createExpoPushRegistration(config) {
504
+ return createDeviceRegistration({
505
+ client: config.client,
506
+ driver: "expo",
507
+ storage: config.storage,
508
+ getToken: /* @__PURE__ */ __name(() => getExpoPushToken({
509
+ module: config.module,
510
+ projectId: config.projectId
511
+ }), "getToken")
512
+ });
513
+ }
514
+ __name(createExpoPushRegistration, "createExpoPushRegistration");
321
515
  // Annotate the CommonJS export names for ESM import in node:
322
516
  0 && (module.exports = {
517
+ arrayBufferToBase64Url,
323
518
  createDeviceRegistration,
519
+ createExpoPushRegistration,
324
520
  createNotificationClient,
325
- subscribeToNotificationStream
521
+ getExpoPushToken,
522
+ getStandardWebPushServiceWorkerScript,
523
+ isWebPushSupported,
524
+ subscribeToNotificationStream,
525
+ subscribeWebPush,
526
+ unsubscribeWebPush,
527
+ urlBase64ToUint8Array
326
528
  });
327
529
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { createNotificationClient } from './httpClient'\nexport type {\n NotificationClient,\n NotificationClientConfig,\n ListNotificationsOptions,\n ListNotificationsPage,\n RegisterDeviceInput,\n NotificationApiError,\n} from './httpClient'\n\nexport { createDeviceRegistration } from './deviceRegistration'\nexport type {\n DeviceRegistrationConfig,\n DeviceRegistrationHandle,\n DeviceRegistrationStorage,\n RegisterOptions,\n} from './deviceRegistration'\n\nexport { subscribeToNotificationStream } from './streamSubscription'\nexport type {\n NotificationStreamEvent,\n NotificationStreamSubscription,\n SubscribeToNotificationStreamParams,\n} from './streamSubscription'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o\n * default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do\n * quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.\n */\n\nimport type {\n DeviceRegistration,\n NotificationPreference,\n NotificationSummary,\n NotificationTemplate,\n NotificationCategoryPolicy,\n TemplateVariableCatalog,\n UpsertTemplateBody,\n} from '@adatechnology/notification-contracts'\n\nexport type NotificationClientConfig = {\n /** Base do host, sem barra final: `https://api.exemplo.com/v1`. */\n readonly baseUrl: string\n /**\n * Devolve o header de autorização a cada chamada — função, não string, porque o token do host\n * rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.\n */\n readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n readonly fetchImpl?: typeof fetch\n}\n\nexport type ListNotificationsOptions = {\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsPage = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type RegisterDeviceInput = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly driver: 'expo' | 'fcm'\n readonly token: string\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type NotificationApiError = Error & {\n readonly status: number\n readonly code: string\n readonly issues?: readonly { path: string; message: string }[]\n}\n\nfunction buildApiError(status: number, payload: unknown): NotificationApiError {\n const envelope = payload as {\n error?: { code?: string; message?: string; issues?: { path: string; message: string }[] }\n }\n const error = new Error(envelope?.error?.message ?? `Falha na requisição (${status}).`) as NotificationApiError\n return Object.assign(error, {\n status,\n code: envelope?.error?.code ?? 'NOTIFICATION_UNKNOWN_ERROR',\n issues: envelope?.error?.issues,\n })\n}\n\nexport type NotificationClient = {\n listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>\n countUnread(): Promise<number>\n markAsRead(id: string): Promise<NotificationSummary>\n markAllAsRead(): Promise<number>\n deleteNotification(id: string): Promise<void>\n registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>\n unregisterDevice(id: string): Promise<void>\n getPreferences(): Promise<readonly NotificationPreference[]>\n updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>\n /** O teto de canais da empresa por categoria — acima da preferência de quem recebe. */\n getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]>\n /** Substitui a política das categorias enviadas; as demais ficam intactas. */\n updateCategoryPolicies(\n policies: readonly NotificationCategoryPolicy[],\n ): Promise<readonly NotificationCategoryPolicy[]>\n listTemplates(): Promise<readonly NotificationTemplate[]>\n /**\n * Cria uma VERSÃO nova do template, não edita a atual.\n *\n * O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e\n * a leitura só devolve a ativa mais alta. Então \"editar a copy\" e \"reverter\" são a mesma operação\n * — o que a tela de configuração precisa para alguém corrigir um texto sem medo.\n */\n upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>\n /**\n * \"Remover\" é desativar: o servidor derruba todas as versões ativas da identidade e mantém as\n * linhas, porque entrega já enviada precisa continuar auditável com o texto que usou.\n */\n deactivateTemplate(id: string): Promise<void>\n /**\n * \"Restaurar padrão\": o servidor grava uma versão nova com o conteúdo embutido do modelo padrão\n * (`notification.standard-email`). 400 se o id não é dele; 409 se a restauração é recusada.\n */\n restoreDefault(id: string): Promise<NotificationTemplate>\n /** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */\n listTemplateVariables(): Promise<TemplateVariableCatalog>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\n}\n\nexport function createNotificationClient(config: NotificationClientConfig): NotificationClient {\n const fetchImpl = config.fetchImpl ?? fetch\n const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl\n\n async function request<TResponse>(params: {\n method: string\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n }): Promise<TResponse | undefined> {\n const url = new URL(`${baseUrl}${params.path}`)\n for (const [key, value] of Object.entries(params.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const authHeaders = (await config.getAuthHeaders?.()) ?? {}\n const response = await fetchImpl(url.toString(), {\n method: params.method,\n headers: { ...(params.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...authHeaders },\n body: params.body === undefined ? undefined : JSON.stringify(params.body),\n })\n\n if (response.status === 204) return undefined\n\n const text = await response.text()\n const payload: unknown = text === '' ? undefined : JSON.parse(text)\n if (!response.ok) throw buildApiError(response.status, payload)\n return payload as TResponse\n }\n\n return {\n async listNotifications(options): Promise<ListNotificationsPage> {\n const payload = await request<{\n data: NotificationSummary[]\n pagination: { nextCursor?: string }\n meta: { unreadCount: number }\n }>({\n method: 'GET',\n path: '/notifications',\n query: { category: options?.category, read: options?.read, cursor: options?.cursor, perPage: options?.perPage },\n })\n\n return {\n data: payload?.data ?? [],\n nextCursor: payload?.pagination.nextCursor,\n unreadCount: payload?.meta.unreadCount ?? 0,\n }\n },\n\n async countUnread(): Promise<number> {\n const payload = await request<{ data: { unreadCount: number } }>({\n method: 'GET',\n path: '/notifications/unread-count',\n })\n return payload?.data.unreadCount ?? 0\n },\n\n async markAsRead(id): Promise<NotificationSummary> {\n const payload = await request<{ data: NotificationSummary }>({\n method: 'PATCH',\n path: `/notifications/${encodeURIComponent(id)}/read`,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em markAsRead')\n return payload.data\n },\n\n async markAllAsRead(): Promise<number> {\n const payload = await request<{ data: { updated: number } }>({ method: 'POST', path: '/notifications/read-all' })\n return payload?.data.updated ?? 0\n },\n\n async deleteNotification(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notifications/${encodeURIComponent(id)}` })\n },\n\n async registerDevice(input): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: input,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em registerDevice')\n return payload.data\n },\n\n async unregisterDevice(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-devices/${encodeURIComponent(id)}` })\n },\n\n async getPreferences(): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'GET',\n path: '/notification-preferences',\n })\n return payload?.data ?? []\n },\n\n async updatePreferences(preferences): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'PUT',\n path: '/notification-preferences',\n body: { preferences },\n })\n return payload?.data ?? []\n },\n\n async listTemplates(): Promise<readonly NotificationTemplate[]> {\n const payload = await request<{ data: NotificationTemplate[] }>({\n method: 'GET',\n path: '/notification-templates',\n })\n return payload?.data ?? []\n },\n\n async getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'GET',\n path: '/notification-category-policies',\n })\n return payload?.data ?? []\n },\n\n async updateCategoryPolicies(policies): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'PUT',\n path: '/notification-category-policies',\n body: { policies },\n })\n return payload?.data ?? []\n },\n\n async deactivateTemplate(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-templates/${encodeURIComponent(id)}` })\n },\n\n async restoreDefault(id): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: `/notification-templates/${encodeURIComponent(id)}/restore-default`,\n })\n if (!payload?.data) throw new Error('notification-client: restoreDefault não devolveu o template')\n return payload.data\n },\n\n async listTemplateVariables(): Promise<TemplateVariableCatalog> {\n const payload = await request<{ data: TemplateVariableCatalog }>({\n method: 'GET',\n path: '/notification-template-variables',\n })\n return payload?.data ?? {}\n },\n\n async upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: '/notification-templates',\n body: input,\n })\n // Sem fallback: a rota responde 201 com o template criado, e devolver `undefined as never`\n // aqui esconderia uma mudança de contrato até estourar na tela.\n if (!payload?.data) throw new Error('notification-client: upsertTemplate não devolveu o template')\n return payload.data\n },\n\n async resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe\n * `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o\n * PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.\n */\n\nimport type { DeviceRegistration } from '@adatechnology/notification-contracts'\n\nimport type { NotificationClient, RegisterDeviceInput } from './httpClient'\n\nexport type DeviceRegistrationConfig = {\n readonly client: NotificationClient\n readonly driver: 'expo' | 'fcm'\n /** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */\n getToken(): Promise<string | undefined>\n /** Persiste o id entre execuções, para o logout conseguir remover o device certo. */\n readonly storage?: DeviceRegistrationStorage\n}\n\n/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */\nexport type DeviceRegistrationStorage = {\n getItem(key: string): Promise<string | null> | string | null\n setItem(key: string, value: string): Promise<void> | void\n removeItem(key: string): Promise<void> | void\n}\n\nexport type RegisterOptions = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type DeviceRegistrationHandle = {\n /** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */\n register(options: RegisterOptions): Promise<DeviceRegistration | undefined>\n /** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */\n unregister(): Promise<void>\n}\n\nconst STORAGE_KEY = 'adatechnology:notification:device-id'\n\nexport function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle {\n async function rememberDeviceId(deviceId: string): Promise<void> {\n await config.storage?.setItem(STORAGE_KEY, deviceId)\n }\n\n return {\n async register(options): Promise<DeviceRegistration | undefined> {\n const token = await config.getToken()\n // Permissão negada é o caminho normal, não erro: o usuário pode recusar push e o resto do\n // app continua funcionando (inbox e e-mail seguem).\n if (!token) return undefined\n\n const input: RegisterDeviceInput = {\n platform: options.platform,\n driver: config.driver,\n token,\n appVersion: options.appVersion,\n locale: options.locale,\n timezone: options.timezone,\n }\n\n const device = await config.client.registerDevice(input)\n await rememberDeviceId(device.id)\n return device\n },\n\n async unregister(): Promise<void> {\n const deviceId = await config.storage?.getItem(STORAGE_KEY)\n if (!deviceId) return\n\n await config.client.unregisterDevice(deviceId)\n await config.storage?.removeItem(STORAGE_KEY)\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Assinatura do SSE do inbox.\n *\n * **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a\n * autenticação do host é `Authorization: Bearer`. Passar token por query string violaria\n * `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React\n * Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois\n * de uma vez, e é o que roda igual no web e no RN moderno.\n */\n\nexport type NotificationStreamEvent = {\n readonly event: string\n readonly data: unknown\n}\n\nexport type SubscribeToNotificationStreamParams = {\n readonly url: string\n readonly headers: Record<string, string>\n readonly onEvent: (event: NotificationStreamEvent) => void\n readonly onError?: (error: Error) => void\n readonly fetchImpl?: typeof fetch\n /** Reconexão com backoff; `0` desliga (o chamador cuida). */\n readonly reconnectDelayMs?: number\n}\n\nexport type NotificationStreamSubscription = {\n close(): void\n}\n\nconst DEFAULT_RECONNECT_DELAY_MS = 3000\n\nfunction parseSseBlock(block: string): NotificationStreamEvent | undefined {\n let eventName = 'message'\n const dataLines: string[] = []\n\n for (const line of block.split('\\n')) {\n // Comentário SSE — é o heartbeat do servidor, e não deve virar evento no cliente.\n if (line.startsWith(':')) continue\n if (line.startsWith('event:')) eventName = line.slice('event:'.length).trim()\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trim())\n }\n\n if (dataLines.length === 0) return undefined\n\n const raw = dataLines.join('\\n')\n try {\n return { event: eventName, data: JSON.parse(raw) }\n } catch {\n return { event: eventName, data: raw }\n }\n}\n\nexport function subscribeToNotificationStream(\n params: SubscribeToNotificationStreamParams,\n): NotificationStreamSubscription {\n const fetchImpl = params.fetchImpl ?? fetch\n const controller = new AbortController()\n let closed = false\n\n async function connect(): Promise<void> {\n const response = await fetchImpl(params.url, {\n headers: { ...params.headers, Accept: 'text/event-stream' },\n signal: controller.signal,\n })\n\n if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`)\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n // Eventos SSE são separados por linha em branco; o resto fica no buffer porque um chunk\n // de rede pode cortar um evento no meio.\n const blocks = buffer.split('\\n\\n')\n buffer = blocks.pop() ?? ''\n\n for (const block of blocks) {\n const event = parseSseBlock(block)\n if (event) params.onEvent(event)\n }\n }\n }\n\n async function runWithReconnect(): Promise<void> {\n const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS\n\n while (!closed) {\n try {\n await connect()\n } catch (error) {\n if (closed) return\n params.onError?.(error instanceof Error ? error : new Error(String(error)))\n }\n\n // Conexão encerrada pelo servidor (deploy, timeout de proxy) é o caso comum — reconectar é\n // o comportamento certo, e sem `delay` viraria laço apertado contra um servidor caído.\n if (closed || delay === 0) return\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n void runWithReconnect()\n\n return {\n close(): void {\n closed = true\n controller.abort()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACyDA,SAASA,cAAcC,QAAgBC,SAAgB;AACrD,QAAMC,WAAWD;AAGjB,QAAME,QAAQ,IAAIC,MAAMF,UAAUC,OAAOE,WAAW,8BAAwBL,MAAAA,IAAU;AACtF,SAAOM,OAAOC,OAAOJ,OAAO;IAC1BH;IACAQ,MAAMN,UAAUC,OAAOK,QAAQ;IAC/BC,QAAQP,UAAUC,OAAOM;EAC3B,CAAA;AACF;AAVSV;AAqDF,SAASW,yBAAyBC,QAAgC;AACvE,QAAMC,YAAYD,OAAOC,aAAaC;AACtC,QAAMC,UAAUH,OAAOG,QAAQC,SAAS,GAAA,IAAOJ,OAAOG,QAAQE,MAAM,GAAG,EAAC,IAAKL,OAAOG;AAEpF,iBAAeG,QAAmBC,QAKjC;AACC,UAAMC,MAAM,IAAIC,IAAI,GAAGN,OAAAA,GAAUI,OAAOG,IAAI,EAAE;AAC9C,eAAW,CAACC,KAAKC,KAAAA,KAAUjB,OAAOkB,QAAQN,OAAOO,SA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D,SAASN,KAAAA,CAAAA;IACrD;EACF;AAhBeD;AAkBf,OAAKA,iBAAAA;AAEL,SAAO;IACLS,QAAAA;AACEjC,eAAS;AACTF,iBAAWoC,MAAK;IAClB;EACF;AACF;AA9DgBxC;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","url","URL","path","key","value","entries","query","undefined","searchParams","set","String","authHeaders","getAuthHeaders","response","toString","method","headers","body","JSON","stringify","text","parse","ok","listNotifications","options","category","read","cursor","perPage","data","nextCursor","pagination","unreadCount","meta","countUnread","markAsRead","id","encodeURIComponent","markAllAsRead","updated","deleteNotification","registerDevice","input","unregisterDevice","getPreferences","updatePreferences","preferences","listTemplates","getCategoryPolicies","updateCategoryPolicies","policies","deactivateTemplate","restoreDefault","listTemplateVariables","upsertTemplate","resolveStreamRequest","STORAGE_KEY","createDeviceRegistration","config","rememberDeviceId","deviceId","storage","setItem","register","options","token","getToken","undefined","input","platform","driver","appVersion","locale","timezone","device","client","registerDevice","id","unregister","getItem","unregisterDevice","removeItem","DEFAULT_RECONNECT_DELAY_MS","parseSseBlock","block","eventName","dataLines","line","split","startsWith","slice","length","trim","push","undefined","raw","join","event","data","JSON","parse","subscribeToNotificationStream","params","fetchImpl","fetch","controller","AbortController","closed","connect","response","url","headers","Accept","signal","ok","body","Error","status","reader","getReader","decoder","TextDecoder","buffer","value","done","read","decode","stream","blocks","pop","onEvent","runWithReconnect","delay","reconnectDelayMs","error","onError","String","Promise","resolve","setTimeout","close","abort"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.ts","../src/webPush.ts","../src/expoPush.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { createNotificationClient } from './httpClient'\nexport type {\n NotificationClient,\n NotificationClientConfig,\n ListNotificationsOptions,\n ListNotificationsPage,\n RegisterDeviceInput,\n NotificationApiError,\n} from './httpClient'\n\nexport { createDeviceRegistration } from './deviceRegistration'\nexport type {\n DeviceRegistrationConfig,\n DeviceRegistrationHandle,\n DeviceRegistrationStorage,\n RegisterOptions,\n} from './deviceRegistration'\n\nexport { subscribeToNotificationStream } from './streamSubscription'\nexport type {\n NotificationStreamEvent,\n NotificationStreamSubscription,\n SubscribeToNotificationStreamParams,\n} from './streamSubscription'\n\nexport {\n isWebPushSupported,\n urlBase64ToUint8Array,\n arrayBufferToBase64Url,\n subscribeWebPush,\n unsubscribeWebPush,\n getStandardWebPushServiceWorkerScript,\n} from './webPush'\nexport type { SubscribeWebPushOptions } from './webPush'\n\nexport { getExpoPushToken, createExpoPushRegistration } from './expoPush'\nexport type {\n ExpoNotificationsModule,\n ExpoPermissionResponse,\n ExpoPushTokenResult,\n GetExpoPushTokenOptions,\n CreateExpoPushRegistrationConfig,\n} from './expoPush'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o\n * default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do\n * quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.\n */\n\nimport type {\n DeviceRegistration,\n NotificationPreference,\n NotificationSummary,\n NotificationTemplate,\n NotificationCategoryPolicy,\n TemplateVariableCatalog,\n UpsertTemplateBody,\n WebPushSubscription,\n SendPushDirectBody,\n SendPushDirectResult,\n BroadcastPushBody,\n BroadcastPushResult,\n} from '@adatechnology/notification-contracts'\n\nexport type NotificationClientConfig = {\n /** Base do host, sem barra final: `https://api.exemplo.com/v1`. */\n readonly baseUrl: string\n /**\n * Devolve o header de autorização a cada chamada — função, não string, porque o token do host\n * rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.\n */\n readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n readonly fetchImpl?: typeof fetch\n}\n\nexport type ListNotificationsOptions = {\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsPage = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type RegisterDeviceInput = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly driver: 'expo' | 'fcm'\n readonly token: string\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type NotificationApiError = Error & {\n readonly status: number\n readonly code: string\n readonly issues?: readonly { path: string; message: string }[]\n}\n\nfunction buildApiError(status: number, payload: unknown): NotificationApiError {\n const envelope = payload as {\n error?: { code?: string; message?: string; issues?: { path: string; message: string }[] }\n }\n const error = new Error(envelope?.error?.message ?? `Falha na requisição (${status}).`) as NotificationApiError\n return Object.assign(error, {\n status,\n code: envelope?.error?.code ?? 'NOTIFICATION_UNKNOWN_ERROR',\n issues: envelope?.error?.issues,\n })\n}\n\nexport type NotificationClient = {\n listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>\n countUnread(): Promise<number>\n markAsRead(id: string): Promise<NotificationSummary>\n markAllAsRead(): Promise<number>\n deleteNotification(id: string): Promise<void>\n registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>\n unregisterDevice(id: string): Promise<void>\n getPreferences(): Promise<readonly NotificationPreference[]>\n updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>\n /** O teto de canais da empresa por categoria — acima da preferência de quem recebe. */\n getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]>\n /** Substitui a política das categorias enviadas; as demais ficam intactas. */\n updateCategoryPolicies(\n policies: readonly NotificationCategoryPolicy[],\n ): Promise<readonly NotificationCategoryPolicy[]>\n listTemplates(): Promise<readonly NotificationTemplate[]>\n /**\n * Cria uma VERSÃO nova do template, não edita a atual.\n *\n * O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e\n * a leitura só devolve a ativa mais alta. Então \"editar a copy\" e \"reverter\" são a mesma operação\n * — o que a tela de configuração precisa para alguém corrigir um texto sem medo.\n */\n upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>\n /**\n * \"Remover\" é desativar: o servidor derruba todas as versões ativas da identidade e mantém as\n * linhas, porque entrega já enviada precisa continuar auditável com o texto que usou.\n */\n deactivateTemplate(id: string): Promise<void>\n /**\n * \"Restaurar padrão\": o servidor grava uma versão nova com o conteúdo embutido do modelo padrão\n * (`notification.standard-email`). 400 se o id não é dele; 409 se a restauração é recusada.\n */\n restoreDefault(id: string): Promise<NotificationTemplate>\n /** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */\n listTemplateVariables(): Promise<TemplateVariableCatalog>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\n /** Obtém a chave pública VAPID do servidor para inscrição Web Push no navegador */\n getVapidPublicKey(): Promise<string>\n /** Dispara uma notificação push direta (para token, user ou subscription) */\n sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult>\n /** Dispara push em broadcast por tópico ou filtro */\n broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult>\n /** Registra uma assinatura Web Push nativa (PWA) no backend */\n registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration>\n}\n\nexport function createNotificationClient(config: NotificationClientConfig): NotificationClient {\n const fetchImpl = config.fetchImpl ?? fetch\n const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl\n\n async function request<TResponse>(params: {\n method: string\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n }): Promise<TResponse | undefined> {\n const url = new URL(`${baseUrl}${params.path}`)\n for (const [key, value] of Object.entries(params.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const authHeaders = (await config.getAuthHeaders?.()) ?? {}\n const response = await fetchImpl(url.toString(), {\n method: params.method,\n headers: { ...(params.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...authHeaders },\n body: params.body === undefined ? undefined : JSON.stringify(params.body),\n })\n\n if (response.status === 204) return undefined\n\n const text = await response.text()\n const payload: unknown = text === '' ? undefined : JSON.parse(text)\n if (!response.ok) throw buildApiError(response.status, payload)\n return payload as TResponse\n }\n\n return {\n async listNotifications(options): Promise<ListNotificationsPage> {\n const payload = await request<{\n data: NotificationSummary[]\n pagination: { nextCursor?: string }\n meta: { unreadCount: number }\n }>({\n method: 'GET',\n path: '/notifications',\n query: { category: options?.category, read: options?.read, cursor: options?.cursor, perPage: options?.perPage },\n })\n\n return {\n data: payload?.data ?? [],\n nextCursor: payload?.pagination.nextCursor,\n unreadCount: payload?.meta.unreadCount ?? 0,\n }\n },\n\n async countUnread(): Promise<number> {\n const payload = await request<{ data: { unreadCount: number } }>({\n method: 'GET',\n path: '/notifications/unread-count',\n })\n return payload?.data.unreadCount ?? 0\n },\n\n async markAsRead(id): Promise<NotificationSummary> {\n const payload = await request<{ data: NotificationSummary }>({\n method: 'PATCH',\n path: `/notifications/${encodeURIComponent(id)}/read`,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em markAsRead')\n return payload.data\n },\n\n async markAllAsRead(): Promise<number> {\n const payload = await request<{ data: { updated: number } }>({ method: 'POST', path: '/notifications/read-all' })\n return payload?.data.updated ?? 0\n },\n\n async deleteNotification(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notifications/${encodeURIComponent(id)}` })\n },\n\n async registerDevice(input): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: input,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em registerDevice')\n return payload.data\n },\n\n async unregisterDevice(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-devices/${encodeURIComponent(id)}` })\n },\n\n async getPreferences(): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'GET',\n path: '/notification-preferences',\n })\n return payload?.data ?? []\n },\n\n async updatePreferences(preferences): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'PUT',\n path: '/notification-preferences',\n body: { preferences },\n })\n return payload?.data ?? []\n },\n\n async listTemplates(): Promise<readonly NotificationTemplate[]> {\n const payload = await request<{ data: NotificationTemplate[] }>({\n method: 'GET',\n path: '/notification-templates',\n })\n return payload?.data ?? []\n },\n\n async getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'GET',\n path: '/notification-category-policies',\n })\n return payload?.data ?? []\n },\n\n async updateCategoryPolicies(policies): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'PUT',\n path: '/notification-category-policies',\n body: { policies },\n })\n return payload?.data ?? []\n },\n\n async deactivateTemplate(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-templates/${encodeURIComponent(id)}` })\n },\n\n async restoreDefault(id): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: `/notification-templates/${encodeURIComponent(id)}/restore-default`,\n })\n if (!payload?.data) throw new Error('notification-client: restoreDefault não devolveu o template')\n return payload.data\n },\n\n async listTemplateVariables(): Promise<TemplateVariableCatalog> {\n const payload = await request<{ data: TemplateVariableCatalog }>({\n method: 'GET',\n path: '/notification-template-variables',\n })\n return payload?.data ?? {}\n },\n\n async upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: '/notification-templates',\n body: input,\n })\n // Sem fallback: a rota responde 201 com o template criado, e devolver `undefined as never`\n // aqui esconderia uma mudança de contrato até estourar na tela.\n if (!payload?.data) throw new Error('notification-client: upsertTemplate não devolveu o template')\n return payload.data\n },\n\n async resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\n },\n\n async getVapidPublicKey(): Promise<string> {\n const payload = await request<{ data: { publicKey: string } }>({\n method: 'GET',\n path: '/push/vapid-public-key',\n })\n if (!payload?.data?.publicKey) throw new Error('notification-client: chave pública VAPID não retornada')\n return payload.data.publicKey\n },\n\n async sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult> {\n const payload = await request<{ data: SendPushDirectResult }>({\n method: 'POST',\n path: '/push/send',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia ao enviar push')\n return payload.data\n },\n\n async broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult> {\n const payload = await request<{ data: BroadcastPushResult }>({\n method: 'POST',\n path: '/push/broadcast',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em broadcastPush')\n return payload.data\n },\n\n async registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: {\n platform: 'web',\n driver: 'webpush',\n token: JSON.stringify(subscription),\n appVersion: options?.appVersion,\n locale: options?.locale,\n timezone: options?.timezone,\n },\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em registerWebPush')\n return payload.data\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe\n * `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o\n * PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.\n */\n\nimport type { DeviceRegistration } from '@adatechnology/notification-contracts'\n\nimport type { NotificationClient, RegisterDeviceInput } from './httpClient'\n\nexport type DeviceRegistrationConfig = {\n readonly client: NotificationClient\n readonly driver: 'expo' | 'fcm'\n /** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */\n getToken(): Promise<string | undefined>\n /** Persiste o id entre execuções, para o logout conseguir remover o device certo. */\n readonly storage?: DeviceRegistrationStorage\n}\n\n/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */\nexport type DeviceRegistrationStorage = {\n getItem(key: string): Promise<string | null> | string | null\n setItem(key: string, value: string): Promise<void> | void\n removeItem(key: string): Promise<void> | void\n}\n\nexport type RegisterOptions = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type DeviceRegistrationHandle = {\n /** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */\n register(options: RegisterOptions): Promise<DeviceRegistration | undefined>\n /** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */\n unregister(): Promise<void>\n}\n\nconst STORAGE_KEY = 'adatechnology:notification:device-id'\n\nexport function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle {\n async function rememberDeviceId(deviceId: string): Promise<void> {\n await config.storage?.setItem(STORAGE_KEY, deviceId)\n }\n\n return {\n async register(options): Promise<DeviceRegistration | undefined> {\n const token = await config.getToken()\n // Permissão negada é o caminho normal, não erro: o usuário pode recusar push e o resto do\n // app continua funcionando (inbox e e-mail seguem).\n if (!token) return undefined\n\n const input: RegisterDeviceInput = {\n platform: options.platform,\n driver: config.driver,\n token,\n appVersion: options.appVersion,\n locale: options.locale,\n timezone: options.timezone,\n }\n\n const device = await config.client.registerDevice(input)\n await rememberDeviceId(device.id)\n return device\n },\n\n async unregister(): Promise<void> {\n const deviceId = await config.storage?.getItem(STORAGE_KEY)\n if (!deviceId) return\n\n await config.client.unregisterDevice(deviceId)\n await config.storage?.removeItem(STORAGE_KEY)\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Assinatura do SSE do inbox.\n *\n * **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a\n * autenticação do host é `Authorization: Bearer`. Passar token por query string violaria\n * `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React\n * Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois\n * de uma vez, e é o que roda igual no web e no RN moderno.\n */\n\nexport type NotificationStreamEvent = {\n readonly event: string\n readonly data: unknown\n}\n\nexport type SubscribeToNotificationStreamParams = {\n readonly url: string\n readonly headers: Record<string, string>\n readonly onEvent: (event: NotificationStreamEvent) => void\n readonly onError?: (error: Error) => void\n readonly fetchImpl?: typeof fetch\n /** Reconexão com backoff; `0` desliga (o chamador cuida). */\n readonly reconnectDelayMs?: number\n}\n\nexport type NotificationStreamSubscription = {\n close(): void\n}\n\nconst DEFAULT_RECONNECT_DELAY_MS = 3000\n\nfunction parseSseBlock(block: string): NotificationStreamEvent | undefined {\n let eventName = 'message'\n const dataLines: string[] = []\n\n for (const line of block.split('\\n')) {\n // Comentário SSE — é o heartbeat do servidor, e não deve virar evento no cliente.\n if (line.startsWith(':')) continue\n if (line.startsWith('event:')) eventName = line.slice('event:'.length).trim()\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trim())\n }\n\n if (dataLines.length === 0) return undefined\n\n const raw = dataLines.join('\\n')\n try {\n return { event: eventName, data: JSON.parse(raw) }\n } catch {\n return { event: eventName, data: raw }\n }\n}\n\nexport function subscribeToNotificationStream(\n params: SubscribeToNotificationStreamParams,\n): NotificationStreamSubscription {\n const fetchImpl = params.fetchImpl ?? fetch\n const controller = new AbortController()\n let closed = false\n\n async function connect(): Promise<void> {\n const response = await fetchImpl(params.url, {\n headers: { ...params.headers, Accept: 'text/event-stream' },\n signal: controller.signal,\n })\n\n if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`)\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n // Eventos SSE são separados por linha em branco; o resto fica no buffer porque um chunk\n // de rede pode cortar um evento no meio.\n const blocks = buffer.split('\\n\\n')\n buffer = blocks.pop() ?? ''\n\n for (const block of blocks) {\n const event = parseSseBlock(block)\n if (event) params.onEvent(event)\n }\n }\n }\n\n async function runWithReconnect(): Promise<void> {\n const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS\n\n while (!closed) {\n try {\n await connect()\n } catch (error) {\n if (closed) return\n params.onError?.(error instanceof Error ? error : new Error(String(error)))\n }\n\n // Conexão encerrada pelo servidor (deploy, timeout de proxy) é o caso comum — reconectar é\n // o comportamento certo, e sem `delay` viraria laço apertado contra um servidor caído.\n if (closed || delay === 0) return\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n void runWithReconnect()\n\n return {\n close(): void {\n closed = true\n controller.abort()\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helpers isomórficos para Web Push nativo (W3C Push API) em PWAs.\n * Não depende de Firebase nem de bibliotecas externas: funciona nativamente no Chrome,\n * Firefox, Edge e Safari (iOS 16.4+ e macOS).\n */\n\nimport type { WebPushSubscription } from '@adatechnology/notification-contracts'\n\nexport type SubscribeWebPushOptions = {\n readonly vapidPublicKey: string\n readonly serviceWorkerRegistration?: ServiceWorkerRegistration\n}\n\n/**\n * Converte chave pública VAPID em base64url para Uint8Array.\n * Exigido pelo navegador em `pushManager.subscribe({ applicationServerKey })`.\n */\nexport function urlBase64ToUint8Array(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4)\n const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')\n const rawData = atob(base64)\n const outputArray = new Uint8Array(rawData.length)\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i)\n }\n return outputArray\n}\n\nexport function arrayBufferToBase64Url(buffer: ArrayBufferLike | ArrayBuffer | null): string {\n if (!buffer) return ''\n const bytes = new Uint8Array(buffer as ArrayBuffer)\n let binary = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Verifica se o ambiente de execução suporta Web Push nativo via Service Worker.\n */\nexport function isWebPushSupported(): boolean {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return false\n return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window\n}\n\n/**\n * Inscreve o navegador no Push Service nativo usando as chaves VAPID fornecidas.\n * Retorna `undefined` caso a permissão seja negada pelo usuário (caminho normal, sem lançar erro).\n */\nexport async function subscribeWebPush(options: SubscribeWebPushOptions): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n if (Notification.permission === 'default') {\n const permission = await Notification.requestPermission()\n if (permission !== 'granted') return undefined\n } else if (Notification.permission !== 'granted') {\n return undefined\n }\n\n const registration = options.serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const applicationServerKey = urlBase64ToUint8Array(options.vapidPublicKey)\n\n let subscription = await registration.pushManager.getSubscription()\n if (!subscription) {\n subscription = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: applicationServerKey as unknown as BufferSource,\n })\n }\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Remove a inscrição ativa de push no navegador.\n */\nexport async function unsubscribeWebPush(serviceWorkerRegistration?: ServiceWorkerRegistration): Promise<boolean> {\n if (!isWebPushSupported()) return false\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return false\n\n return subscription.unsubscribe()\n}\n\n/**\n * Retorna o script padrão do Service Worker para manipulação de notificações em PWAs.\n */\nexport function getStandardWebPushServiceWorkerScript(): string {\n return `\nself.addEventListener('push', (event) => {\n if (!event.data) return;\n let payload;\n try {\n payload = event.data.json();\n } catch {\n payload = { title: 'Notificação', body: event.data.text() };\n }\n\n const title = payload.title || 'Nova Notificação';\n const options = {\n body: payload.body || '',\n icon: payload.icon || '/pwa-192x192.png',\n badge: payload.badge || '/badge-72x72.png',\n tag: payload.tag,\n data: payload.data || { url: payload.url || '/' },\n };\n\n event.waitUntil(self.registration.showNotification(title, options));\n});\n\nself.addEventListener('notificationclick', (event) => {\n event.notification.close();\n const targetUrl = event.notification.data?.url || '/';\n\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {\n for (const client of clientList) {\n if (client.url === targetUrl && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(targetUrl);\n }\n })\n );\n});\n`.trim()\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helper de push para React Native com Expo.\n * **Não importa `expo-notifications` estaticamente**: recebe o módulo por injeção\n * (duck-typing) para não poluir nem quebrar o bundle web/PWA.\n */\n\nimport {\n createDeviceRegistration,\n type DeviceRegistrationHandle,\n type DeviceRegistrationStorage,\n} from './deviceRegistration'\nimport type { NotificationClient } from './httpClient'\n\nexport type ExpoPermissionResponse = {\n readonly status: string\n readonly granted: boolean\n}\n\nexport type ExpoPushTokenResult = {\n readonly data: string\n}\n\nexport interface ExpoNotificationsModule {\n getPermissionsAsync(): Promise<ExpoPermissionResponse>\n requestPermissionsAsync(): Promise<ExpoPermissionResponse>\n getExpoPushTokenAsync(options?: { projectId?: string }): Promise<ExpoPushTokenResult>\n setNotificationChannelAsync?(\n channelId: string,\n channel: {\n name: string\n importance: number\n sound?: boolean\n vibrationPattern?: number[]\n },\n ): Promise<unknown>\n}\n\nexport type GetExpoPushTokenOptions = {\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly channelId?: string\n readonly channelName?: string\n}\n\n/**\n * Solicita permissões e obtém o Expo Push Token.\n * Se a permissão for negada, devolve `undefined` (caminho normal, sem erro).\n */\nexport async function getExpoPushToken(options: GetExpoPushTokenOptions): Promise<string | undefined> {\n const { module } = options\n\n const currentPerms = await module.getPermissionsAsync()\n let isGranted = currentPerms.granted\n\n if (!isGranted) {\n const requested = await module.requestPermissionsAsync()\n isGranted = requested.granted\n }\n\n if (!isGranted) return undefined\n\n if (typeof module.setNotificationChannelAsync === 'function') {\n await module.setNotificationChannelAsync(options.channelId ?? 'default', {\n name: options.channelName ?? 'Geral',\n importance: 4, // Android IMPORTANCE_HIGH\n sound: true,\n })\n }\n\n const tokenResult = await module.getExpoPushTokenAsync({\n projectId: options.projectId,\n })\n\n return tokenResult.data\n}\n\nexport type CreateExpoPushRegistrationConfig = {\n readonly client: NotificationClient\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly storage?: DeviceRegistrationStorage\n}\n\n/**\n * Cria o ciclo de vida completo de registro do dispositivo Expo integrado ao NotificationClient.\n */\nexport function createExpoPushRegistration(config: CreateExpoPushRegistrationConfig): DeviceRegistrationHandle {\n return createDeviceRegistration({\n client: config.client,\n driver: 'expo',\n storage: config.storage,\n getToken: () => getExpoPushToken({ module: config.module, projectId: config.projectId }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;AC8DA,SAASA,cAAcC,QAAgBC,SAAgB;AACrD,QAAMC,WAAWD;AAGjB,QAAME,QAAQ,IAAIC,MAAMF,UAAUC,OAAOE,WAAW,8BAAwBL,MAAAA,IAAU;AACtF,SAAOM,OAAOC,OAAOJ,OAAO;IAC1BH;IACAQ,MAAMN,UAAUC,OAAOK,QAAQ;IAC/BC,QAAQP,UAAUC,OAAOM;EAC3B,CAAA;AACF;AAVSV;AAgEF,SAASW,yBAAyBC,QAAgC;AACvE,QAAMC,YAAYD,OAAOC,aAAaC;AACtC,QAAMC,UAAUH,OAAOG,QAAQC,SAAS,GAAA,IAAOJ,OAAOG,QAAQE,MAAM,GA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AAe;MAC7BC,YAAY;MACZC,OAAO;IACT,CAAA;EACF;AAEA,QAAMC,cAAc,MAAMd,QAAOe,sBAAsB;IACrDC,WAAWjB,QAAQiB;EACrB,CAAA;AAEA,SAAOF,YAAYG;AACrB;AA1BsBnB;AAsCf,SAASoB,2BAA2BC,QAAwC;AACjF,SAAOC,yBAAyB;IAC9BC,QAAQF,OAAOE;IACfC,QAAQ;IACRC,SAASJ,OAAOI;IAChBC,UAAU,6BAAM1B,iBAAiB;MAAEE,QAAQmB,OAAOnB;MAAQgB,WAAWG,OAAOH;IAAU,CAAA,GAA5E;EACZ,CAAA;AACF;AAPgBE;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","url","URL","path","key","value","entries","query","undefined","searchParams","set","String","authHeaders","getAuthHeaders","response","toString","method","headers","body","JSON","stringify","text","parse","ok","listNotifications","options","category","read","cursor","perPage","data","nextCursor","pagination","unreadCount","meta","countUnread","markAsRead","id","encodeURIComponent","markAllAsRead","updated","deleteNotification","registerDevice","input","unregisterDevice","getPreferences","updatePreferences","preferences","listTemplates","getCategoryPolicies","updateCategoryPolicies","policies","deactivateTemplate","restoreDefault","listTemplateVariables","upsertTemplate","resolveStreamRequest","getVapidPublicKey","publicKey","sendPush","broadcastPush","registerWebPush","subscription","platform","driver","token","appVersion","locale","timezone","STORAGE_KEY","createDeviceRegistration","config","rememberDeviceId","deviceId","storage","setItem","register","options","token","getToken","undefined","input","platform","driver","appVersion","locale","timezone","device","client","registerDevice","id","unregister","getItem","unregisterDevice","removeItem","DEFAULT_RECONNECT_DELAY_MS","parseSseBlock","block","eventName","dataLines","line","split","startsWith","slice","length","trim","push","undefined","raw","join","event","data","JSON","parse","subscribeToNotificationStream","params","fetchImpl","fetch","controller","AbortController","closed","connect","response","url","headers","Accept","signal","ok","body","Error","status","reader","getReader","decoder","TextDecoder","buffer","value","done","read","decode","stream","blocks","pop","onEvent","runWithReconnect","delay","reconnectDelayMs","error","onError","String","Promise","resolve","setTimeout","close","abort","urlBase64ToUint8Array","base64String","padding","repeat","length","base64","replace","rawData","atob","outputArray","Uint8Array","i","charCodeAt","arrayBufferToBase64Url","buffer","bytes","binary","byteLength","String","fromCharCode","btoa","isWebPushSupported","window","navigator","subscribeWebPush","options","undefined","Notification","permission","requestPermission","registration","serviceWorkerRegistration","serviceWorker","ready","applicationServerKey","vapidPublicKey","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","p256dh","getKey","auth","endpoint","keys","expirationTime","unsubscribeWebPush","unsubscribe","getStandardWebPushServiceWorkerScript","trim","getExpoPushToken","options","module","currentPerms","getPermissionsAsync","isGranted","granted","requested","requestPermissionsAsync","undefined","setNotificationChannelAsync","channelId","name","channelName","importance","sound","tokenResult","getExpoPushTokenAsync","projectId","data","createExpoPushRegistration","config","createDeviceRegistration","client","driver","storage","getToken"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationCategoryPolicy, NotificationTemplate, UpsertTemplateBody, TemplateVariableCatalog } from '@adatechnology/notification-contracts';
1
+ import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationCategoryPolicy, NotificationTemplate, UpsertTemplateBody, TemplateVariableCatalog, SendPushDirectBody, SendPushDirectResult, BroadcastPushBody, BroadcastPushResult, WebPushSubscription } from '@adatechnology/notification-contracts';
2
2
 
3
3
  /**
4
4
  * Copyright (c) 2026 Ada Technology. MIT License.
@@ -85,6 +85,18 @@ type NotificationClient = {
85
85
  url: string;
86
86
  headers: Record<string, string>;
87
87
  }>;
88
+ /** Obtém a chave pública VAPID do servidor para inscrição Web Push no navegador */
89
+ getVapidPublicKey(): Promise<string>;
90
+ /** Dispara uma notificação push direta (para token, user ou subscription) */
91
+ sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult>;
92
+ /** Dispara push em broadcast por tópico ou filtro */
93
+ broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult>;
94
+ /** Registra uma assinatura Web Push nativa (PWA) no backend */
95
+ registerWebPush(subscription: WebPushSubscription, options?: {
96
+ readonly appVersion?: string;
97
+ readonly locale?: string;
98
+ readonly timezone?: string;
99
+ }): Promise<DeviceRegistration>;
88
100
  };
89
101
  declare function createNotificationClient(config: NotificationClientConfig): NotificationClient;
90
102
 
@@ -153,4 +165,90 @@ type NotificationStreamSubscription = {
153
165
  };
154
166
  declare function subscribeToNotificationStream(params: SubscribeToNotificationStreamParams): NotificationStreamSubscription;
155
167
 
156
- export { type DeviceRegistrationConfig, type DeviceRegistrationHandle, type DeviceRegistrationStorage, type ListNotificationsOptions, type ListNotificationsPage, type NotificationApiError, type NotificationClient, type NotificationClientConfig, type NotificationStreamEvent, type NotificationStreamSubscription, type RegisterDeviceInput, type RegisterOptions, type SubscribeToNotificationStreamParams, createDeviceRegistration, createNotificationClient, subscribeToNotificationStream };
168
+ /**
169
+ * Copyright (c) 2026 Ada Technology. MIT License.
170
+ *
171
+ * Helpers isomórficos para Web Push nativo (W3C Push API) em PWAs.
172
+ * Não depende de Firebase nem de bibliotecas externas: funciona nativamente no Chrome,
173
+ * Firefox, Edge e Safari (iOS 16.4+ e macOS).
174
+ */
175
+
176
+ type SubscribeWebPushOptions = {
177
+ readonly vapidPublicKey: string;
178
+ readonly serviceWorkerRegistration?: ServiceWorkerRegistration;
179
+ };
180
+ /**
181
+ * Converte chave pública VAPID em base64url para Uint8Array.
182
+ * Exigido pelo navegador em `pushManager.subscribe({ applicationServerKey })`.
183
+ */
184
+ declare function urlBase64ToUint8Array(base64String: string): Uint8Array;
185
+ declare function arrayBufferToBase64Url(buffer: ArrayBufferLike | ArrayBuffer | null): string;
186
+ /**
187
+ * Verifica se o ambiente de execução suporta Web Push nativo via Service Worker.
188
+ */
189
+ declare function isWebPushSupported(): boolean;
190
+ /**
191
+ * Inscreve o navegador no Push Service nativo usando as chaves VAPID fornecidas.
192
+ * Retorna `undefined` caso a permissão seja negada pelo usuário (caminho normal, sem lançar erro).
193
+ */
194
+ declare function subscribeWebPush(options: SubscribeWebPushOptions): Promise<WebPushSubscription | undefined>;
195
+ /**
196
+ * Remove a inscrição ativa de push no navegador.
197
+ */
198
+ declare function unsubscribeWebPush(serviceWorkerRegistration?: ServiceWorkerRegistration): Promise<boolean>;
199
+ /**
200
+ * Retorna o script padrão do Service Worker para manipulação de notificações em PWAs.
201
+ */
202
+ declare function getStandardWebPushServiceWorkerScript(): string;
203
+
204
+ /**
205
+ * Copyright (c) 2026 Ada Technology. MIT License.
206
+ *
207
+ * Helper de push para React Native com Expo.
208
+ * **Não importa `expo-notifications` estaticamente**: recebe o módulo por injeção
209
+ * (duck-typing) para não poluir nem quebrar o bundle web/PWA.
210
+ */
211
+
212
+ type ExpoPermissionResponse = {
213
+ readonly status: string;
214
+ readonly granted: boolean;
215
+ };
216
+ type ExpoPushTokenResult = {
217
+ readonly data: string;
218
+ };
219
+ interface ExpoNotificationsModule {
220
+ getPermissionsAsync(): Promise<ExpoPermissionResponse>;
221
+ requestPermissionsAsync(): Promise<ExpoPermissionResponse>;
222
+ getExpoPushTokenAsync(options?: {
223
+ projectId?: string;
224
+ }): Promise<ExpoPushTokenResult>;
225
+ setNotificationChannelAsync?(channelId: string, channel: {
226
+ name: string;
227
+ importance: number;
228
+ sound?: boolean;
229
+ vibrationPattern?: number[];
230
+ }): Promise<unknown>;
231
+ }
232
+ type GetExpoPushTokenOptions = {
233
+ readonly module: ExpoNotificationsModule;
234
+ readonly projectId?: string;
235
+ readonly channelId?: string;
236
+ readonly channelName?: string;
237
+ };
238
+ /**
239
+ * Solicita permissões e obtém o Expo Push Token.
240
+ * Se a permissão for negada, devolve `undefined` (caminho normal, sem erro).
241
+ */
242
+ declare function getExpoPushToken(options: GetExpoPushTokenOptions): Promise<string | undefined>;
243
+ type CreateExpoPushRegistrationConfig = {
244
+ readonly client: NotificationClient;
245
+ readonly module: ExpoNotificationsModule;
246
+ readonly projectId?: string;
247
+ readonly storage?: DeviceRegistrationStorage;
248
+ };
249
+ /**
250
+ * Cria o ciclo de vida completo de registro do dispositivo Expo integrado ao NotificationClient.
251
+ */
252
+ declare function createExpoPushRegistration(config: CreateExpoPushRegistrationConfig): DeviceRegistrationHandle;
253
+
254
+ export { type CreateExpoPushRegistrationConfig, type DeviceRegistrationConfig, type DeviceRegistrationHandle, type DeviceRegistrationStorage, type ExpoNotificationsModule, type ExpoPermissionResponse, type ExpoPushTokenResult, type GetExpoPushTokenOptions, type ListNotificationsOptions, type ListNotificationsPage, type NotificationApiError, type NotificationClient, type NotificationClientConfig, type NotificationStreamEvent, type NotificationStreamSubscription, type RegisterDeviceInput, type RegisterOptions, type SubscribeToNotificationStreamParams, type SubscribeWebPushOptions, arrayBufferToBase64Url, createDeviceRegistration, createExpoPushRegistration, createNotificationClient, getExpoPushToken, getStandardWebPushServiceWorkerScript, isWebPushSupported, subscribeToNotificationStream, subscribeWebPush, unsubscribeWebPush, urlBase64ToUint8Array };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationCategoryPolicy, NotificationTemplate, UpsertTemplateBody, TemplateVariableCatalog } from '@adatechnology/notification-contracts';
1
+ import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationCategoryPolicy, NotificationTemplate, UpsertTemplateBody, TemplateVariableCatalog, SendPushDirectBody, SendPushDirectResult, BroadcastPushBody, BroadcastPushResult, WebPushSubscription } from '@adatechnology/notification-contracts';
2
2
 
3
3
  /**
4
4
  * Copyright (c) 2026 Ada Technology. MIT License.
@@ -85,6 +85,18 @@ type NotificationClient = {
85
85
  url: string;
86
86
  headers: Record<string, string>;
87
87
  }>;
88
+ /** Obtém a chave pública VAPID do servidor para inscrição Web Push no navegador */
89
+ getVapidPublicKey(): Promise<string>;
90
+ /** Dispara uma notificação push direta (para token, user ou subscription) */
91
+ sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult>;
92
+ /** Dispara push em broadcast por tópico ou filtro */
93
+ broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult>;
94
+ /** Registra uma assinatura Web Push nativa (PWA) no backend */
95
+ registerWebPush(subscription: WebPushSubscription, options?: {
96
+ readonly appVersion?: string;
97
+ readonly locale?: string;
98
+ readonly timezone?: string;
99
+ }): Promise<DeviceRegistration>;
88
100
  };
89
101
  declare function createNotificationClient(config: NotificationClientConfig): NotificationClient;
90
102
 
@@ -153,4 +165,90 @@ type NotificationStreamSubscription = {
153
165
  };
154
166
  declare function subscribeToNotificationStream(params: SubscribeToNotificationStreamParams): NotificationStreamSubscription;
155
167
 
156
- export { type DeviceRegistrationConfig, type DeviceRegistrationHandle, type DeviceRegistrationStorage, type ListNotificationsOptions, type ListNotificationsPage, type NotificationApiError, type NotificationClient, type NotificationClientConfig, type NotificationStreamEvent, type NotificationStreamSubscription, type RegisterDeviceInput, type RegisterOptions, type SubscribeToNotificationStreamParams, createDeviceRegistration, createNotificationClient, subscribeToNotificationStream };
168
+ /**
169
+ * Copyright (c) 2026 Ada Technology. MIT License.
170
+ *
171
+ * Helpers isomórficos para Web Push nativo (W3C Push API) em PWAs.
172
+ * Não depende de Firebase nem de bibliotecas externas: funciona nativamente no Chrome,
173
+ * Firefox, Edge e Safari (iOS 16.4+ e macOS).
174
+ */
175
+
176
+ type SubscribeWebPushOptions = {
177
+ readonly vapidPublicKey: string;
178
+ readonly serviceWorkerRegistration?: ServiceWorkerRegistration;
179
+ };
180
+ /**
181
+ * Converte chave pública VAPID em base64url para Uint8Array.
182
+ * Exigido pelo navegador em `pushManager.subscribe({ applicationServerKey })`.
183
+ */
184
+ declare function urlBase64ToUint8Array(base64String: string): Uint8Array;
185
+ declare function arrayBufferToBase64Url(buffer: ArrayBufferLike | ArrayBuffer | null): string;
186
+ /**
187
+ * Verifica se o ambiente de execução suporta Web Push nativo via Service Worker.
188
+ */
189
+ declare function isWebPushSupported(): boolean;
190
+ /**
191
+ * Inscreve o navegador no Push Service nativo usando as chaves VAPID fornecidas.
192
+ * Retorna `undefined` caso a permissão seja negada pelo usuário (caminho normal, sem lançar erro).
193
+ */
194
+ declare function subscribeWebPush(options: SubscribeWebPushOptions): Promise<WebPushSubscription | undefined>;
195
+ /**
196
+ * Remove a inscrição ativa de push no navegador.
197
+ */
198
+ declare function unsubscribeWebPush(serviceWorkerRegistration?: ServiceWorkerRegistration): Promise<boolean>;
199
+ /**
200
+ * Retorna o script padrão do Service Worker para manipulação de notificações em PWAs.
201
+ */
202
+ declare function getStandardWebPushServiceWorkerScript(): string;
203
+
204
+ /**
205
+ * Copyright (c) 2026 Ada Technology. MIT License.
206
+ *
207
+ * Helper de push para React Native com Expo.
208
+ * **Não importa `expo-notifications` estaticamente**: recebe o módulo por injeção
209
+ * (duck-typing) para não poluir nem quebrar o bundle web/PWA.
210
+ */
211
+
212
+ type ExpoPermissionResponse = {
213
+ readonly status: string;
214
+ readonly granted: boolean;
215
+ };
216
+ type ExpoPushTokenResult = {
217
+ readonly data: string;
218
+ };
219
+ interface ExpoNotificationsModule {
220
+ getPermissionsAsync(): Promise<ExpoPermissionResponse>;
221
+ requestPermissionsAsync(): Promise<ExpoPermissionResponse>;
222
+ getExpoPushTokenAsync(options?: {
223
+ projectId?: string;
224
+ }): Promise<ExpoPushTokenResult>;
225
+ setNotificationChannelAsync?(channelId: string, channel: {
226
+ name: string;
227
+ importance: number;
228
+ sound?: boolean;
229
+ vibrationPattern?: number[];
230
+ }): Promise<unknown>;
231
+ }
232
+ type GetExpoPushTokenOptions = {
233
+ readonly module: ExpoNotificationsModule;
234
+ readonly projectId?: string;
235
+ readonly channelId?: string;
236
+ readonly channelName?: string;
237
+ };
238
+ /**
239
+ * Solicita permissões e obtém o Expo Push Token.
240
+ * Se a permissão for negada, devolve `undefined` (caminho normal, sem erro).
241
+ */
242
+ declare function getExpoPushToken(options: GetExpoPushTokenOptions): Promise<string | undefined>;
243
+ type CreateExpoPushRegistrationConfig = {
244
+ readonly client: NotificationClient;
245
+ readonly module: ExpoNotificationsModule;
246
+ readonly projectId?: string;
247
+ readonly storage?: DeviceRegistrationStorage;
248
+ };
249
+ /**
250
+ * Cria o ciclo de vida completo de registro do dispositivo Expo integrado ao NotificationClient.
251
+ */
252
+ declare function createExpoPushRegistration(config: CreateExpoPushRegistrationConfig): DeviceRegistrationHandle;
253
+
254
+ export { type CreateExpoPushRegistrationConfig, type DeviceRegistrationConfig, type DeviceRegistrationHandle, type DeviceRegistrationStorage, type ExpoNotificationsModule, type ExpoPermissionResponse, type ExpoPushTokenResult, type GetExpoPushTokenOptions, type ListNotificationsOptions, type ListNotificationsPage, type NotificationApiError, type NotificationClient, type NotificationClientConfig, type NotificationStreamEvent, type NotificationStreamSubscription, type RegisterDeviceInput, type RegisterOptions, type SubscribeToNotificationStreamParams, type SubscribeWebPushOptions, arrayBufferToBase64Url, createDeviceRegistration, createExpoPushRegistration, createNotificationClient, getExpoPushToken, getStandardWebPushServiceWorkerScript, isWebPushSupported, subscribeToNotificationStream, subscribeWebPush, unsubscribeWebPush, urlBase64ToUint8Array };
package/dist/index.js CHANGED
@@ -175,6 +175,48 @@ function createNotificationClient(config) {
175
175
  url: `${baseUrl}/notifications/stream`,
176
176
  headers: await config.getAuthHeaders?.() ?? {}
177
177
  };
178
+ },
179
+ async getVapidPublicKey() {
180
+ const payload = await request({
181
+ method: "GET",
182
+ path: "/push/vapid-public-key"
183
+ });
184
+ if (!payload?.data?.publicKey) throw new Error("notification-client: chave p\xFAblica VAPID n\xE3o retornada");
185
+ return payload.data.publicKey;
186
+ },
187
+ async sendPush(input) {
188
+ const payload = await request({
189
+ method: "POST",
190
+ path: "/push/send",
191
+ body: input
192
+ });
193
+ if (!payload?.data) throw new Error("notification-client: resposta vazia ao enviar push");
194
+ return payload.data;
195
+ },
196
+ async broadcastPush(input) {
197
+ const payload = await request({
198
+ method: "POST",
199
+ path: "/push/broadcast",
200
+ body: input
201
+ });
202
+ if (!payload?.data) throw new Error("notification-client: resposta vazia em broadcastPush");
203
+ return payload.data;
204
+ },
205
+ async registerWebPush(subscription, options) {
206
+ const payload = await request({
207
+ method: "POST",
208
+ path: "/notification-devices",
209
+ body: {
210
+ platform: "web",
211
+ driver: "webpush",
212
+ token: JSON.stringify(subscription),
213
+ appVersion: options?.appVersion,
214
+ locale: options?.locale,
215
+ timezone: options?.timezone
216
+ }
217
+ });
218
+ if (!payload?.data) throw new Error("notification-client: resposta vazia em registerWebPush");
219
+ return payload.data;
178
220
  }
179
221
  };
180
222
  }
@@ -292,9 +334,161 @@ function subscribeToNotificationStream(params) {
292
334
  };
293
335
  }
294
336
  __name(subscribeToNotificationStream, "subscribeToNotificationStream");
337
+
338
+ // src/webPush.ts
339
+ function urlBase64ToUint8Array(base64String) {
340
+ const padding = "=".repeat((4 - base64String.length % 4) % 4);
341
+ const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
342
+ const rawData = atob(base64);
343
+ const outputArray = new Uint8Array(rawData.length);
344
+ for (let i = 0; i < rawData.length; ++i) {
345
+ outputArray[i] = rawData.charCodeAt(i);
346
+ }
347
+ return outputArray;
348
+ }
349
+ __name(urlBase64ToUint8Array, "urlBase64ToUint8Array");
350
+ function arrayBufferToBase64Url(buffer) {
351
+ if (!buffer) return "";
352
+ const bytes = new Uint8Array(buffer);
353
+ let binary = "";
354
+ for (let i = 0; i < bytes.byteLength; i++) {
355
+ binary += String.fromCharCode(bytes[i]);
356
+ }
357
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
358
+ }
359
+ __name(arrayBufferToBase64Url, "arrayBufferToBase64Url");
360
+ function isWebPushSupported() {
361
+ if (typeof window === "undefined" || typeof navigator === "undefined") return false;
362
+ return "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
363
+ }
364
+ __name(isWebPushSupported, "isWebPushSupported");
365
+ async function subscribeWebPush(options) {
366
+ if (!isWebPushSupported()) return void 0;
367
+ if (Notification.permission === "default") {
368
+ const permission = await Notification.requestPermission();
369
+ if (permission !== "granted") return void 0;
370
+ } else if (Notification.permission !== "granted") {
371
+ return void 0;
372
+ }
373
+ const registration = options.serviceWorkerRegistration ?? await navigator.serviceWorker.ready;
374
+ const applicationServerKey = urlBase64ToUint8Array(options.vapidPublicKey);
375
+ let subscription = await registration.pushManager.getSubscription();
376
+ if (!subscription) {
377
+ subscription = await registration.pushManager.subscribe({
378
+ userVisibleOnly: true,
379
+ applicationServerKey
380
+ });
381
+ }
382
+ const p256dh = arrayBufferToBase64Url(subscription.getKey("p256dh"));
383
+ const auth = arrayBufferToBase64Url(subscription.getKey("auth"));
384
+ return {
385
+ endpoint: subscription.endpoint,
386
+ keys: {
387
+ p256dh,
388
+ auth
389
+ },
390
+ expirationTime: subscription.expirationTime
391
+ };
392
+ }
393
+ __name(subscribeWebPush, "subscribeWebPush");
394
+ async function unsubscribeWebPush(serviceWorkerRegistration) {
395
+ if (!isWebPushSupported()) return false;
396
+ const registration = serviceWorkerRegistration ?? await navigator.serviceWorker.ready;
397
+ const subscription = await registration.pushManager.getSubscription();
398
+ if (!subscription) return false;
399
+ return subscription.unsubscribe();
400
+ }
401
+ __name(unsubscribeWebPush, "unsubscribeWebPush");
402
+ function getStandardWebPushServiceWorkerScript() {
403
+ return `
404
+ self.addEventListener('push', (event) => {
405
+ if (!event.data) return;
406
+ let payload;
407
+ try {
408
+ payload = event.data.json();
409
+ } catch {
410
+ payload = { title: 'Notifica\xE7\xE3o', body: event.data.text() };
411
+ }
412
+
413
+ const title = payload.title || 'Nova Notifica\xE7\xE3o';
414
+ const options = {
415
+ body: payload.body || '',
416
+ icon: payload.icon || '/pwa-192x192.png',
417
+ badge: payload.badge || '/badge-72x72.png',
418
+ tag: payload.tag,
419
+ data: payload.data || { url: payload.url || '/' },
420
+ };
421
+
422
+ event.waitUntil(self.registration.showNotification(title, options));
423
+ });
424
+
425
+ self.addEventListener('notificationclick', (event) => {
426
+ event.notification.close();
427
+ const targetUrl = event.notification.data?.url || '/';
428
+
429
+ event.waitUntil(
430
+ clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
431
+ for (const client of clientList) {
432
+ if (client.url === targetUrl && 'focus' in client) {
433
+ return client.focus();
434
+ }
435
+ }
436
+ if (clients.openWindow) {
437
+ return clients.openWindow(targetUrl);
438
+ }
439
+ })
440
+ );
441
+ });
442
+ `.trim();
443
+ }
444
+ __name(getStandardWebPushServiceWorkerScript, "getStandardWebPushServiceWorkerScript");
445
+
446
+ // src/expoPush.ts
447
+ async function getExpoPushToken(options) {
448
+ const { module } = options;
449
+ const currentPerms = await module.getPermissionsAsync();
450
+ let isGranted = currentPerms.granted;
451
+ if (!isGranted) {
452
+ const requested = await module.requestPermissionsAsync();
453
+ isGranted = requested.granted;
454
+ }
455
+ if (!isGranted) return void 0;
456
+ if (typeof module.setNotificationChannelAsync === "function") {
457
+ await module.setNotificationChannelAsync(options.channelId ?? "default", {
458
+ name: options.channelName ?? "Geral",
459
+ importance: 4,
460
+ sound: true
461
+ });
462
+ }
463
+ const tokenResult = await module.getExpoPushTokenAsync({
464
+ projectId: options.projectId
465
+ });
466
+ return tokenResult.data;
467
+ }
468
+ __name(getExpoPushToken, "getExpoPushToken");
469
+ function createExpoPushRegistration(config) {
470
+ return createDeviceRegistration({
471
+ client: config.client,
472
+ driver: "expo",
473
+ storage: config.storage,
474
+ getToken: /* @__PURE__ */ __name(() => getExpoPushToken({
475
+ module: config.module,
476
+ projectId: config.projectId
477
+ }), "getToken")
478
+ });
479
+ }
480
+ __name(createExpoPushRegistration, "createExpoPushRegistration");
295
481
  export {
482
+ arrayBufferToBase64Url,
296
483
  createDeviceRegistration,
484
+ createExpoPushRegistration,
297
485
  createNotificationClient,
298
- subscribeToNotificationStream
486
+ getExpoPushToken,
487
+ getStandardWebPushServiceWorkerScript,
488
+ isWebPushSupported,
489
+ subscribeToNotificationStream,
490
+ subscribeWebPush,
491
+ unsubscribeWebPush,
492
+ urlBase64ToUint8Array
299
493
  };
300
494
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o\n * default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do\n * quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.\n */\n\nimport type {\n DeviceRegistration,\n NotificationPreference,\n NotificationSummary,\n NotificationTemplate,\n NotificationCategoryPolicy,\n TemplateVariableCatalog,\n UpsertTemplateBody,\n} from '@adatechnology/notification-contracts'\n\nexport type NotificationClientConfig = {\n /** Base do host, sem barra final: `https://api.exemplo.com/v1`. */\n readonly baseUrl: string\n /**\n * Devolve o header de autorização a cada chamada — função, não string, porque o token do host\n * rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.\n */\n readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n readonly fetchImpl?: typeof fetch\n}\n\nexport type ListNotificationsOptions = {\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsPage = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type RegisterDeviceInput = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly driver: 'expo' | 'fcm'\n readonly token: string\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type NotificationApiError = Error & {\n readonly status: number\n readonly code: string\n readonly issues?: readonly { path: string; message: string }[]\n}\n\nfunction buildApiError(status: number, payload: unknown): NotificationApiError {\n const envelope = payload as {\n error?: { code?: string; message?: string; issues?: { path: string; message: string }[] }\n }\n const error = new Error(envelope?.error?.message ?? `Falha na requisição (${status}).`) as NotificationApiError\n return Object.assign(error, {\n status,\n code: envelope?.error?.code ?? 'NOTIFICATION_UNKNOWN_ERROR',\n issues: envelope?.error?.issues,\n })\n}\n\nexport type NotificationClient = {\n listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>\n countUnread(): Promise<number>\n markAsRead(id: string): Promise<NotificationSummary>\n markAllAsRead(): Promise<number>\n deleteNotification(id: string): Promise<void>\n registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>\n unregisterDevice(id: string): Promise<void>\n getPreferences(): Promise<readonly NotificationPreference[]>\n updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>\n /** O teto de canais da empresa por categoria — acima da preferência de quem recebe. */\n getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]>\n /** Substitui a política das categorias enviadas; as demais ficam intactas. */\n updateCategoryPolicies(\n policies: readonly NotificationCategoryPolicy[],\n ): Promise<readonly NotificationCategoryPolicy[]>\n listTemplates(): Promise<readonly NotificationTemplate[]>\n /**\n * Cria uma VERSÃO nova do template, não edita a atual.\n *\n * O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e\n * a leitura só devolve a ativa mais alta. Então \"editar a copy\" e \"reverter\" são a mesma operação\n * — o que a tela de configuração precisa para alguém corrigir um texto sem medo.\n */\n upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>\n /**\n * \"Remover\" é desativar: o servidor derruba todas as versões ativas da identidade e mantém as\n * linhas, porque entrega já enviada precisa continuar auditável com o texto que usou.\n */\n deactivateTemplate(id: string): Promise<void>\n /**\n * \"Restaurar padrão\": o servidor grava uma versão nova com o conteúdo embutido do modelo padrão\n * (`notification.standard-email`). 400 se o id não é dele; 409 se a restauração é recusada.\n */\n restoreDefault(id: string): Promise<NotificationTemplate>\n /** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */\n listTemplateVariables(): Promise<TemplateVariableCatalog>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\n}\n\nexport function createNotificationClient(config: NotificationClientConfig): NotificationClient {\n const fetchImpl = config.fetchImpl ?? fetch\n const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl\n\n async function request<TResponse>(params: {\n method: string\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n }): Promise<TResponse | undefined> {\n const url = new URL(`${baseUrl}${params.path}`)\n for (const [key, value] of Object.entries(params.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const authHeaders = (await config.getAuthHeaders?.()) ?? {}\n const response = await fetchImpl(url.toString(), {\n method: params.method,\n headers: { ...(params.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...authHeaders },\n body: params.body === undefined ? undefined : JSON.stringify(params.body),\n })\n\n if (response.status === 204) return undefined\n\n const text = await response.text()\n const payload: unknown = text === '' ? undefined : JSON.parse(text)\n if (!response.ok) throw buildApiError(response.status, payload)\n return payload as TResponse\n }\n\n return {\n async listNotifications(options): Promise<ListNotificationsPage> {\n const payload = await request<{\n data: NotificationSummary[]\n pagination: { nextCursor?: string }\n meta: { unreadCount: number }\n }>({\n method: 'GET',\n path: '/notifications',\n query: { category: options?.category, read: options?.read, cursor: options?.cursor, perPage: options?.perPage },\n })\n\n return {\n data: payload?.data ?? [],\n nextCursor: payload?.pagination.nextCursor,\n unreadCount: payload?.meta.unreadCount ?? 0,\n }\n },\n\n async countUnread(): Promise<number> {\n const payload = await request<{ data: { unreadCount: number } }>({\n method: 'GET',\n path: '/notifications/unread-count',\n })\n return payload?.data.unreadCount ?? 0\n },\n\n async markAsRead(id): Promise<NotificationSummary> {\n const payload = await request<{ data: NotificationSummary }>({\n method: 'PATCH',\n path: `/notifications/${encodeURIComponent(id)}/read`,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em markAsRead')\n return payload.data\n },\n\n async markAllAsRead(): Promise<number> {\n const payload = await request<{ data: { updated: number } }>({ method: 'POST', path: '/notifications/read-all' })\n return payload?.data.updated ?? 0\n },\n\n async deleteNotification(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notifications/${encodeURIComponent(id)}` })\n },\n\n async registerDevice(input): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: input,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em registerDevice')\n return payload.data\n },\n\n async unregisterDevice(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-devices/${encodeURIComponent(id)}` })\n },\n\n async getPreferences(): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'GET',\n path: '/notification-preferences',\n })\n return payload?.data ?? []\n },\n\n async updatePreferences(preferences): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'PUT',\n path: '/notification-preferences',\n body: { preferences },\n })\n return payload?.data ?? []\n },\n\n async listTemplates(): Promise<readonly NotificationTemplate[]> {\n const payload = await request<{ data: NotificationTemplate[] }>({\n method: 'GET',\n path: '/notification-templates',\n })\n return payload?.data ?? []\n },\n\n async getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'GET',\n path: '/notification-category-policies',\n })\n return payload?.data ?? []\n },\n\n async updateCategoryPolicies(policies): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'PUT',\n path: '/notification-category-policies',\n body: { policies },\n })\n return payload?.data ?? []\n },\n\n async deactivateTemplate(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-templates/${encodeURIComponent(id)}` })\n },\n\n async restoreDefault(id): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: `/notification-templates/${encodeURIComponent(id)}/restore-default`,\n })\n if (!payload?.data) throw new Error('notification-client: restoreDefault não devolveu o template')\n return payload.data\n },\n\n async listTemplateVariables(): Promise<TemplateVariableCatalog> {\n const payload = await request<{ data: TemplateVariableCatalog }>({\n method: 'GET',\n path: '/notification-template-variables',\n })\n return payload?.data ?? {}\n },\n\n async upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: '/notification-templates',\n body: input,\n })\n // Sem fallback: a rota responde 201 com o template criado, e devolver `undefined as never`\n // aqui esconderia uma mudança de contrato até estourar na tela.\n if (!payload?.data) throw new Error('notification-client: upsertTemplate não devolveu o template')\n return payload.data\n },\n\n async resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe\n * `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o\n * PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.\n */\n\nimport type { DeviceRegistration } from '@adatechnology/notification-contracts'\n\nimport type { NotificationClient, RegisterDeviceInput } from './httpClient'\n\nexport type DeviceRegistrationConfig = {\n readonly client: NotificationClient\n readonly driver: 'expo' | 'fcm'\n /** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */\n getToken(): Promise<string | undefined>\n /** Persiste o id entre execuções, para o logout conseguir remover o device certo. */\n readonly storage?: DeviceRegistrationStorage\n}\n\n/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */\nexport type DeviceRegistrationStorage = {\n getItem(key: string): Promise<string | null> | string | null\n setItem(key: string, value: string): Promise<void> | void\n removeItem(key: string): Promise<void> | void\n}\n\nexport type RegisterOptions = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type DeviceRegistrationHandle = {\n /** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */\n register(options: RegisterOptions): Promise<DeviceRegistration | undefined>\n /** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */\n unregister(): Promise<void>\n}\n\nconst STORAGE_KEY = 'adatechnology:notification:device-id'\n\nexport function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle {\n async function rememberDeviceId(deviceId: string): Promise<void> {\n await config.storage?.setItem(STORAGE_KEY, deviceId)\n }\n\n return {\n async register(options): Promise<DeviceRegistration | undefined> {\n const token = await config.getToken()\n // Permissão negada é o caminho normal, não erro: o usuário pode recusar push e o resto do\n // app continua funcionando (inbox e e-mail seguem).\n if (!token) return undefined\n\n const input: RegisterDeviceInput = {\n platform: options.platform,\n driver: config.driver,\n token,\n appVersion: options.appVersion,\n locale: options.locale,\n timezone: options.timezone,\n }\n\n const device = await config.client.registerDevice(input)\n await rememberDeviceId(device.id)\n return device\n },\n\n async unregister(): Promise<void> {\n const deviceId = await config.storage?.getItem(STORAGE_KEY)\n if (!deviceId) return\n\n await config.client.unregisterDevice(deviceId)\n await config.storage?.removeItem(STORAGE_KEY)\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Assinatura do SSE do inbox.\n *\n * **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a\n * autenticação do host é `Authorization: Bearer`. Passar token por query string violaria\n * `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React\n * Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois\n * de uma vez, e é o que roda igual no web e no RN moderno.\n */\n\nexport type NotificationStreamEvent = {\n readonly event: string\n readonly data: unknown\n}\n\nexport type SubscribeToNotificationStreamParams = {\n readonly url: string\n readonly headers: Record<string, string>\n readonly onEvent: (event: NotificationStreamEvent) => void\n readonly onError?: (error: Error) => void\n readonly fetchImpl?: typeof fetch\n /** Reconexão com backoff; `0` desliga (o chamador cuida). */\n readonly reconnectDelayMs?: number\n}\n\nexport type NotificationStreamSubscription = {\n close(): void\n}\n\nconst DEFAULT_RECONNECT_DELAY_MS = 3000\n\nfunction parseSseBlock(block: string): NotificationStreamEvent | undefined {\n let eventName = 'message'\n const dataLines: string[] = []\n\n for (const line of block.split('\\n')) {\n // Comentário SSE — é o heartbeat do servidor, e não deve virar evento no cliente.\n if (line.startsWith(':')) continue\n if (line.startsWith('event:')) eventName = line.slice('event:'.length).trim()\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trim())\n }\n\n if (dataLines.length === 0) return undefined\n\n const raw = dataLines.join('\\n')\n try {\n return { event: eventName, data: JSON.parse(raw) }\n } catch {\n return { event: eventName, data: raw }\n }\n}\n\nexport function subscribeToNotificationStream(\n params: SubscribeToNotificationStreamParams,\n): NotificationStreamSubscription {\n const fetchImpl = params.fetchImpl ?? fetch\n const controller = new AbortController()\n let closed = false\n\n async function connect(): Promise<void> {\n const response = await fetchImpl(params.url, {\n headers: { ...params.headers, Accept: 'text/event-stream' },\n signal: controller.signal,\n })\n\n if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`)\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n // Eventos SSE são separados por linha em branco; o resto fica no buffer porque um chunk\n // de rede pode cortar um evento no meio.\n const blocks = buffer.split('\\n\\n')\n buffer = blocks.pop() ?? ''\n\n for (const block of blocks) {\n const event = parseSseBlock(block)\n if (event) params.onEvent(event)\n }\n }\n }\n\n async function runWithReconnect(): Promise<void> {\n const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS\n\n while (!closed) {\n try {\n await connect()\n } catch (error) {\n if (closed) return\n params.onError?.(error instanceof Error ? error : new Error(String(error)))\n }\n\n // Conexão encerrada pelo servidor (deploy, timeout de proxy) é o caso comum — reconectar é\n // o comportamento certo, e sem `delay` viraria laço apertado contra um servidor caído.\n if (closed || delay === 0) return\n await new Promise((resolve) => setTimeout(res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,YAAM,EAAEC,OAAOC,KAAI,IAAK,MAAMN,OAAOO,KAAI;AACzC,UAAID,KAAM;AAEVF,gBAAUF,QAAQM,OAAOH,OAAO;QAAEI,QAAQ;MAAK,CAAA;AAG/C,YAAMC,SAASN,OAAOlC,MAAM,MAAA;AAC5BkC,eAASM,OAAOC,IAAG,KAAM;AAEzB,iBAAW7C,SAAS4C,QAAQ;AAC1B,cAAM/B,QAAQd,cAAcC,KAAAA;AAC5B,YAAIa,MAAOK,QAAO4B,QAAQjC,KAAAA;MAC5B;IACF;EACF;AA3BeW;AA6Bf,iBAAeuB,mBAAAA;AACb,UAAMC,QAAQ9B,OAAO+B,oBAAoBnD;AAEzC,WAAO,CAACyB,QAAQ;AACd,UAAI;AACF,cAAMC,QAAAA;MACR,SAAS0B,OAAO;AACd,YAAI3B,OAAQ;AACZL,eAAOiC,UAAUD,iBAAiBlB,QAAQkB,QAAQ,IAAIlB,MAAMoB,OAAOF,KAAAA,CAAAA,CAAAA;MACrE;AAIA,UAAI3B,UAAUyB,UAAU,EAAG;AAC3B,YAAM,IAAIK,QAAQ,CAACC,YAAYC,WAAWD,SAASN,KAAAA,CAAAA;IACrD;EACF;AAhBeD;AAkBf,OAAKA,iBAAAA;AAEL,SAAO;IACLS,QAAAA;AACEjC,eAAS;AACTF,iBAAWoC,MAAK;IAClB;EACF;AACF;AA9DgBxC;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","url","URL","path","key","value","entries","query","undefined","searchParams","set","String","authHeaders","getAuthHeaders","response","toString","method","headers","body","JSON","stringify","text","parse","ok","listNotifications","options","category","read","cursor","perPage","data","nextCursor","pagination","unreadCount","meta","countUnread","markAsRead","id","encodeURIComponent","markAllAsRead","updated","deleteNotification","registerDevice","input","unregisterDevice","getPreferences","updatePreferences","preferences","listTemplates","getCategoryPolicies","updateCategoryPolicies","policies","deactivateTemplate","restoreDefault","listTemplateVariables","upsertTemplate","resolveStreamRequest","STORAGE_KEY","createDeviceRegistration","config","rememberDeviceId","deviceId","storage","setItem","register","options","token","getToken","undefined","input","platform","driver","appVersion","locale","timezone","device","client","registerDevice","id","unregister","getItem","unregisterDevice","removeItem","DEFAULT_RECONNECT_DELAY_MS","parseSseBlock","block","eventName","dataLines","line","split","startsWith","slice","length","trim","push","undefined","raw","join","event","data","JSON","parse","subscribeToNotificationStream","params","fetchImpl","fetch","controller","AbortController","closed","connect","response","url","headers","Accept","signal","ok","body","Error","status","reader","getReader","decoder","TextDecoder","buffer","value","done","read","decode","stream","blocks","pop","onEvent","runWithReconnect","delay","reconnectDelayMs","error","onError","String","Promise","resolve","setTimeout","close","abort"]}
1
+ {"version":3,"sources":["../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.ts","../src/webPush.ts","../src/expoPush.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o\n * default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do\n * quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.\n */\n\nimport type {\n DeviceRegistration,\n NotificationPreference,\n NotificationSummary,\n NotificationTemplate,\n NotificationCategoryPolicy,\n TemplateVariableCatalog,\n UpsertTemplateBody,\n WebPushSubscription,\n SendPushDirectBody,\n SendPushDirectResult,\n BroadcastPushBody,\n BroadcastPushResult,\n} from '@adatechnology/notification-contracts'\n\nexport type NotificationClientConfig = {\n /** Base do host, sem barra final: `https://api.exemplo.com/v1`. */\n readonly baseUrl: string\n /**\n * Devolve o header de autorização a cada chamada — função, não string, porque o token do host\n * rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.\n */\n readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n readonly fetchImpl?: typeof fetch\n}\n\nexport type ListNotificationsOptions = {\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsPage = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type RegisterDeviceInput = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly driver: 'expo' | 'fcm'\n readonly token: string\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type NotificationApiError = Error & {\n readonly status: number\n readonly code: string\n readonly issues?: readonly { path: string; message: string }[]\n}\n\nfunction buildApiError(status: number, payload: unknown): NotificationApiError {\n const envelope = payload as {\n error?: { code?: string; message?: string; issues?: { path: string; message: string }[] }\n }\n const error = new Error(envelope?.error?.message ?? `Falha na requisição (${status}).`) as NotificationApiError\n return Object.assign(error, {\n status,\n code: envelope?.error?.code ?? 'NOTIFICATION_UNKNOWN_ERROR',\n issues: envelope?.error?.issues,\n })\n}\n\nexport type NotificationClient = {\n listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>\n countUnread(): Promise<number>\n markAsRead(id: string): Promise<NotificationSummary>\n markAllAsRead(): Promise<number>\n deleteNotification(id: string): Promise<void>\n registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>\n unregisterDevice(id: string): Promise<void>\n getPreferences(): Promise<readonly NotificationPreference[]>\n updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>\n /** O teto de canais da empresa por categoria — acima da preferência de quem recebe. */\n getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]>\n /** Substitui a política das categorias enviadas; as demais ficam intactas. */\n updateCategoryPolicies(\n policies: readonly NotificationCategoryPolicy[],\n ): Promise<readonly NotificationCategoryPolicy[]>\n listTemplates(): Promise<readonly NotificationTemplate[]>\n /**\n * Cria uma VERSÃO nova do template, não edita a atual.\n *\n * O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e\n * a leitura só devolve a ativa mais alta. Então \"editar a copy\" e \"reverter\" são a mesma operação\n * — o que a tela de configuração precisa para alguém corrigir um texto sem medo.\n */\n upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>\n /**\n * \"Remover\" é desativar: o servidor derruba todas as versões ativas da identidade e mantém as\n * linhas, porque entrega já enviada precisa continuar auditável com o texto que usou.\n */\n deactivateTemplate(id: string): Promise<void>\n /**\n * \"Restaurar padrão\": o servidor grava uma versão nova com o conteúdo embutido do modelo padrão\n * (`notification.standard-email`). 400 se o id não é dele; 409 se a restauração é recusada.\n */\n restoreDefault(id: string): Promise<NotificationTemplate>\n /** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */\n listTemplateVariables(): Promise<TemplateVariableCatalog>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\n /** Obtém a chave pública VAPID do servidor para inscrição Web Push no navegador */\n getVapidPublicKey(): Promise<string>\n /** Dispara uma notificação push direta (para token, user ou subscription) */\n sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult>\n /** Dispara push em broadcast por tópico ou filtro */\n broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult>\n /** Registra uma assinatura Web Push nativa (PWA) no backend */\n registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration>\n}\n\nexport function createNotificationClient(config: NotificationClientConfig): NotificationClient {\n const fetchImpl = config.fetchImpl ?? fetch\n const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl\n\n async function request<TResponse>(params: {\n method: string\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n }): Promise<TResponse | undefined> {\n const url = new URL(`${baseUrl}${params.path}`)\n for (const [key, value] of Object.entries(params.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const authHeaders = (await config.getAuthHeaders?.()) ?? {}\n const response = await fetchImpl(url.toString(), {\n method: params.method,\n headers: { ...(params.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...authHeaders },\n body: params.body === undefined ? undefined : JSON.stringify(params.body),\n })\n\n if (response.status === 204) return undefined\n\n const text = await response.text()\n const payload: unknown = text === '' ? undefined : JSON.parse(text)\n if (!response.ok) throw buildApiError(response.status, payload)\n return payload as TResponse\n }\n\n return {\n async listNotifications(options): Promise<ListNotificationsPage> {\n const payload = await request<{\n data: NotificationSummary[]\n pagination: { nextCursor?: string }\n meta: { unreadCount: number }\n }>({\n method: 'GET',\n path: '/notifications',\n query: { category: options?.category, read: options?.read, cursor: options?.cursor, perPage: options?.perPage },\n })\n\n return {\n data: payload?.data ?? [],\n nextCursor: payload?.pagination.nextCursor,\n unreadCount: payload?.meta.unreadCount ?? 0,\n }\n },\n\n async countUnread(): Promise<number> {\n const payload = await request<{ data: { unreadCount: number } }>({\n method: 'GET',\n path: '/notifications/unread-count',\n })\n return payload?.data.unreadCount ?? 0\n },\n\n async markAsRead(id): Promise<NotificationSummary> {\n const payload = await request<{ data: NotificationSummary }>({\n method: 'PATCH',\n path: `/notifications/${encodeURIComponent(id)}/read`,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em markAsRead')\n return payload.data\n },\n\n async markAllAsRead(): Promise<number> {\n const payload = await request<{ data: { updated: number } }>({ method: 'POST', path: '/notifications/read-all' })\n return payload?.data.updated ?? 0\n },\n\n async deleteNotification(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notifications/${encodeURIComponent(id)}` })\n },\n\n async registerDevice(input): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: input,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em registerDevice')\n return payload.data\n },\n\n async unregisterDevice(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-devices/${encodeURIComponent(id)}` })\n },\n\n async getPreferences(): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'GET',\n path: '/notification-preferences',\n })\n return payload?.data ?? []\n },\n\n async updatePreferences(preferences): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'PUT',\n path: '/notification-preferences',\n body: { preferences },\n })\n return payload?.data ?? []\n },\n\n async listTemplates(): Promise<readonly NotificationTemplate[]> {\n const payload = await request<{ data: NotificationTemplate[] }>({\n method: 'GET',\n path: '/notification-templates',\n })\n return payload?.data ?? []\n },\n\n async getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'GET',\n path: '/notification-category-policies',\n })\n return payload?.data ?? []\n },\n\n async updateCategoryPolicies(policies): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'PUT',\n path: '/notification-category-policies',\n body: { policies },\n })\n return payload?.data ?? []\n },\n\n async deactivateTemplate(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-templates/${encodeURIComponent(id)}` })\n },\n\n async restoreDefault(id): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: `/notification-templates/${encodeURIComponent(id)}/restore-default`,\n })\n if (!payload?.data) throw new Error('notification-client: restoreDefault não devolveu o template')\n return payload.data\n },\n\n async listTemplateVariables(): Promise<TemplateVariableCatalog> {\n const payload = await request<{ data: TemplateVariableCatalog }>({\n method: 'GET',\n path: '/notification-template-variables',\n })\n return payload?.data ?? {}\n },\n\n async upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: '/notification-templates',\n body: input,\n })\n // Sem fallback: a rota responde 201 com o template criado, e devolver `undefined as never`\n // aqui esconderia uma mudança de contrato até estourar na tela.\n if (!payload?.data) throw new Error('notification-client: upsertTemplate não devolveu o template')\n return payload.data\n },\n\n async resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\n },\n\n async getVapidPublicKey(): Promise<string> {\n const payload = await request<{ data: { publicKey: string } }>({\n method: 'GET',\n path: '/push/vapid-public-key',\n })\n if (!payload?.data?.publicKey) throw new Error('notification-client: chave pública VAPID não retornada')\n return payload.data.publicKey\n },\n\n async sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult> {\n const payload = await request<{ data: SendPushDirectResult }>({\n method: 'POST',\n path: '/push/send',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia ao enviar push')\n return payload.data\n },\n\n async broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult> {\n const payload = await request<{ data: BroadcastPushResult }>({\n method: 'POST',\n path: '/push/broadcast',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em broadcastPush')\n return payload.data\n },\n\n async registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: {\n platform: 'web',\n driver: 'webpush',\n token: JSON.stringify(subscription),\n appVersion: options?.appVersion,\n locale: options?.locale,\n timezone: options?.timezone,\n },\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em registerWebPush')\n return payload.data\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe\n * `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o\n * PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.\n */\n\nimport type { DeviceRegistration } from '@adatechnology/notification-contracts'\n\nimport type { NotificationClient, RegisterDeviceInput } from './httpClient'\n\nexport type DeviceRegistrationConfig = {\n readonly client: NotificationClient\n readonly driver: 'expo' | 'fcm'\n /** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */\n getToken(): Promise<string | undefined>\n /** Persiste o id entre execuções, para o logout conseguir remover o device certo. */\n readonly storage?: DeviceRegistrationStorage\n}\n\n/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */\nexport type DeviceRegistrationStorage = {\n getItem(key: string): Promise<string | null> | string | null\n setItem(key: string, value: string): Promise<void> | void\n removeItem(key: string): Promise<void> | void\n}\n\nexport type RegisterOptions = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type DeviceRegistrationHandle = {\n /** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */\n register(options: RegisterOptions): Promise<DeviceRegistration | undefined>\n /** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */\n unregister(): Promise<void>\n}\n\nconst STORAGE_KEY = 'adatechnology:notification:device-id'\n\nexport function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle {\n async function rememberDeviceId(deviceId: string): Promise<void> {\n await config.storage?.setItem(STORAGE_KEY, deviceId)\n }\n\n return {\n async register(options): Promise<DeviceRegistration | undefined> {\n const token = await config.getToken()\n // Permissão negada é o caminho normal, não erro: o usuário pode recusar push e o resto do\n // app continua funcionando (inbox e e-mail seguem).\n if (!token) return undefined\n\n const input: RegisterDeviceInput = {\n platform: options.platform,\n driver: config.driver,\n token,\n appVersion: options.appVersion,\n locale: options.locale,\n timezone: options.timezone,\n }\n\n const device = await config.client.registerDevice(input)\n await rememberDeviceId(device.id)\n return device\n },\n\n async unregister(): Promise<void> {\n const deviceId = await config.storage?.getItem(STORAGE_KEY)\n if (!deviceId) return\n\n await config.client.unregisterDevice(deviceId)\n await config.storage?.removeItem(STORAGE_KEY)\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Assinatura do SSE do inbox.\n *\n * **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a\n * autenticação do host é `Authorization: Bearer`. Passar token por query string violaria\n * `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React\n * Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois\n * de uma vez, e é o que roda igual no web e no RN moderno.\n */\n\nexport type NotificationStreamEvent = {\n readonly event: string\n readonly data: unknown\n}\n\nexport type SubscribeToNotificationStreamParams = {\n readonly url: string\n readonly headers: Record<string, string>\n readonly onEvent: (event: NotificationStreamEvent) => void\n readonly onError?: (error: Error) => void\n readonly fetchImpl?: typeof fetch\n /** Reconexão com backoff; `0` desliga (o chamador cuida). */\n readonly reconnectDelayMs?: number\n}\n\nexport type NotificationStreamSubscription = {\n close(): void\n}\n\nconst DEFAULT_RECONNECT_DELAY_MS = 3000\n\nfunction parseSseBlock(block: string): NotificationStreamEvent | undefined {\n let eventName = 'message'\n const dataLines: string[] = []\n\n for (const line of block.split('\\n')) {\n // Comentário SSE — é o heartbeat do servidor, e não deve virar evento no cliente.\n if (line.startsWith(':')) continue\n if (line.startsWith('event:')) eventName = line.slice('event:'.length).trim()\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trim())\n }\n\n if (dataLines.length === 0) return undefined\n\n const raw = dataLines.join('\\n')\n try {\n return { event: eventName, data: JSON.parse(raw) }\n } catch {\n return { event: eventName, data: raw }\n }\n}\n\nexport function subscribeToNotificationStream(\n params: SubscribeToNotificationStreamParams,\n): NotificationStreamSubscription {\n const fetchImpl = params.fetchImpl ?? fetch\n const controller = new AbortController()\n let closed = false\n\n async function connect(): Promise<void> {\n const response = await fetchImpl(params.url, {\n headers: { ...params.headers, Accept: 'text/event-stream' },\n signal: controller.signal,\n })\n\n if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`)\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n // Eventos SSE são separados por linha em branco; o resto fica no buffer porque um chunk\n // de rede pode cortar um evento no meio.\n const blocks = buffer.split('\\n\\n')\n buffer = blocks.pop() ?? ''\n\n for (const block of blocks) {\n const event = parseSseBlock(block)\n if (event) params.onEvent(event)\n }\n }\n }\n\n async function runWithReconnect(): Promise<void> {\n const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS\n\n while (!closed) {\n try {\n await connect()\n } catch (error) {\n if (closed) return\n params.onError?.(error instanceof Error ? error : new Error(String(error)))\n }\n\n // Conexão encerrada pelo servidor (deploy, timeout de proxy) é o caso comum — reconectar é\n // o comportamento certo, e sem `delay` viraria laço apertado contra um servidor caído.\n if (closed || delay === 0) return\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n void runWithReconnect()\n\n return {\n close(): void {\n closed = true\n controller.abort()\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helpers isomórficos para Web Push nativo (W3C Push API) em PWAs.\n * Não depende de Firebase nem de bibliotecas externas: funciona nativamente no Chrome,\n * Firefox, Edge e Safari (iOS 16.4+ e macOS).\n */\n\nimport type { WebPushSubscription } from '@adatechnology/notification-contracts'\n\nexport type SubscribeWebPushOptions = {\n readonly vapidPublicKey: string\n readonly serviceWorkerRegistration?: ServiceWorkerRegistration\n}\n\n/**\n * Converte chave pública VAPID em base64url para Uint8Array.\n * Exigido pelo navegador em `pushManager.subscribe({ applicationServerKey })`.\n */\nexport function urlBase64ToUint8Array(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4)\n const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')\n const rawData = atob(base64)\n const outputArray = new Uint8Array(rawData.length)\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i)\n }\n return outputArray\n}\n\nexport function arrayBufferToBase64Url(buffer: ArrayBufferLike | ArrayBuffer | null): string {\n if (!buffer) return ''\n const bytes = new Uint8Array(buffer as ArrayBuffer)\n let binary = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Verifica se o ambiente de execução suporta Web Push nativo via Service Worker.\n */\nexport function isWebPushSupported(): boolean {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return false\n return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window\n}\n\n/**\n * Inscreve o navegador no Push Service nativo usando as chaves VAPID fornecidas.\n * Retorna `undefined` caso a permissão seja negada pelo usuário (caminho normal, sem lançar erro).\n */\nexport async function subscribeWebPush(options: SubscribeWebPushOptions): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n if (Notification.permission === 'default') {\n const permission = await Notification.requestPermission()\n if (permission !== 'granted') return undefined\n } else if (Notification.permission !== 'granted') {\n return undefined\n }\n\n const registration = options.serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const applicationServerKey = urlBase64ToUint8Array(options.vapidPublicKey)\n\n let subscription = await registration.pushManager.getSubscription()\n if (!subscription) {\n subscription = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: applicationServerKey as unknown as BufferSource,\n })\n }\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Remove a inscrição ativa de push no navegador.\n */\nexport async function unsubscribeWebPush(serviceWorkerRegistration?: ServiceWorkerRegistration): Promise<boolean> {\n if (!isWebPushSupported()) return false\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return false\n\n return subscription.unsubscribe()\n}\n\n/**\n * Retorna o script padrão do Service Worker para manipulação de notificações em PWAs.\n */\nexport function getStandardWebPushServiceWorkerScript(): string {\n return `\nself.addEventListener('push', (event) => {\n if (!event.data) return;\n let payload;\n try {\n payload = event.data.json();\n } catch {\n payload = { title: 'Notificação', body: event.data.text() };\n }\n\n const title = payload.title || 'Nova Notificação';\n const options = {\n body: payload.body || '',\n icon: payload.icon || '/pwa-192x192.png',\n badge: payload.badge || '/badge-72x72.png',\n tag: payload.tag,\n data: payload.data || { url: payload.url || '/' },\n };\n\n event.waitUntil(self.registration.showNotification(title, options));\n});\n\nself.addEventListener('notificationclick', (event) => {\n event.notification.close();\n const targetUrl = event.notification.data?.url || '/';\n\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {\n for (const client of clientList) {\n if (client.url === targetUrl && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(targetUrl);\n }\n })\n );\n});\n`.trim()\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helper de push para React Native com Expo.\n * **Não importa `expo-notifications` estaticamente**: recebe o módulo por injeção\n * (duck-typing) para não poluir nem quebrar o bundle web/PWA.\n */\n\nimport {\n createDeviceRegistration,\n type DeviceRegistrationHandle,\n type DeviceRegistrationStorage,\n} from './deviceRegistration'\nimport type { NotificationClient } from './httpClient'\n\nexport type ExpoPermissionResponse = {\n readonly status: string\n readonly granted: boolean\n}\n\nexport type ExpoPushTokenResult = {\n readonly data: string\n}\n\nexport interface ExpoNotificationsModule {\n getPermissionsAsync(): Promise<ExpoPermissionResponse>\n requestPermissionsAsync(): Promise<ExpoPermissionResponse>\n getExpoPushTokenAsync(options?: { projectId?: string }): Promise<ExpoPushTokenResult>\n setNotificationChannelAsync?(\n channelId: string,\n channel: {\n name: string\n importance: number\n sound?: boolean\n vibrationPattern?: number[]\n },\n ): Promise<unknown>\n}\n\nexport type GetExpoPushTokenOptions = {\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly channelId?: string\n readonly channelName?: string\n}\n\n/**\n * Solicita permissões e obtém o Expo Push Token.\n * Se a permissão for negada, devolve `undefined` (caminho normal, sem erro).\n */\nexport async function getExpoPushToken(options: GetExpoPushTokenOptions): Promise<string | undefined> {\n const { module } = options\n\n const currentPerms = await module.getPermissionsAsync()\n let isGranted = currentPerms.granted\n\n if (!isGranted) {\n const requested = await module.requestPermissionsAsync()\n isGranted = requested.granted\n }\n\n if (!isGranted) return undefined\n\n if (typeof module.setNotificationChannelAsync === 'function') {\n await module.setNotificationChannelAsync(options.channelId ?? 'default', {\n name: options.channelName ?? 'Geral',\n importance: 4, // Android IMPORTANCE_HIGH\n sound: true,\n })\n }\n\n const tokenResult = await module.getExpoPushTokenAsync({\n projectId: options.projectId,\n })\n\n return tokenResult.data\n}\n\nexport type CreateExpoPushRegistrationConfig = {\n readonly client: NotificationClient\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly storage?: DeviceRegistrationStorage\n}\n\n/**\n * Cria o ciclo de vida completo de registro do dispositivo Expo integrado ao NotificationClient.\n */\nexport function createExpoPushRegistration(config: CreateExpoPushRegistrationConfig): DeviceRegistrationHandle {\n return createDeviceRegistration({\n client: config.client,\n driver: 'expo',\n storage: config.storage,\n getToken: () => getExpoPushToken({ module: config.module, projectId: config.projectId }),\n })\n}\n"],"mappings":";;;;AA8DA,SAASA,cAAcC,QAAgBC,SAAgB;AACrD,QAAMC,WAAWD;AAGjB,QAAME,QAAQ,IAAIC,MAAMF,UAAUC,OAAOE,WAAW,8BAAwBL,MAAAA,IAAU;AACtF,SAAOM,OAAOC,OAAOJ,OAAO;IAC1BH;IACAQ,MAAMN,UAAUC,OAAOK,QAAQ;IAC/BC,QAAQP,UAAUC,OAAOM;EAC3B,CAAA;AACF;AAVSV;AAgEF,SAASW,yBAAyBC,QAAgC;AACvE,QAAMC,YAAYD,OAAOC,aAAaC;AACtC,QAAMC,UAAUH,OAAOG,QAAQC,SAAS,GAAA,IAAOJ,OAAOG,QAAQE,MAAM,GAAG,EAAC,IAAKL,OAAOG;AAEpF,iBAAeG,QAAmBC,QAKjC;AACC,UAA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d,OAAOe,sBAAsB;IACrDC,WAAWjB,QAAQiB;EACrB,CAAA;AAEA,SAAOF,YAAYG;AACrB;AA1BsBnB;AAsCf,SAASoB,2BAA2BC,QAAwC;AACjF,SAAOC,yBAAyB;IAC9BC,QAAQF,OAAOE;IACfC,QAAQ;IACRC,SAASJ,OAAOI;IAChBC,UAAU,6BAAM1B,iBAAiB;MAAEE,QAAQmB,OAAOnB;MAAQgB,WAAWG,OAAOH;IAAU,CAAA,GAA5E;EACZ,CAAA;AACF;AAPgBE;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","url","URL","path","key","value","entries","query","undefined","searchParams","set","String","authHeaders","getAuthHeaders","response","toString","method","headers","body","JSON","stringify","text","parse","ok","listNotifications","options","category","read","cursor","perPage","data","nextCursor","pagination","unreadCount","meta","countUnread","markAsRead","id","encodeURIComponent","markAllAsRead","updated","deleteNotification","registerDevice","input","unregisterDevice","getPreferences","updatePreferences","preferences","listTemplates","getCategoryPolicies","updateCategoryPolicies","policies","deactivateTemplate","restoreDefault","listTemplateVariables","upsertTemplate","resolveStreamRequest","getVapidPublicKey","publicKey","sendPush","broadcastPush","registerWebPush","subscription","platform","driver","token","appVersion","locale","timezone","STORAGE_KEY","createDeviceRegistration","config","rememberDeviceId","deviceId","storage","setItem","register","options","token","getToken","undefined","input","platform","driver","appVersion","locale","timezone","device","client","registerDevice","id","unregister","getItem","unregisterDevice","removeItem","DEFAULT_RECONNECT_DELAY_MS","parseSseBlock","block","eventName","dataLines","line","split","startsWith","slice","length","trim","push","undefined","raw","join","event","data","JSON","parse","subscribeToNotificationStream","params","fetchImpl","fetch","controller","AbortController","closed","connect","response","url","headers","Accept","signal","ok","body","Error","status","reader","getReader","decoder","TextDecoder","buffer","value","done","read","decode","stream","blocks","pop","onEvent","runWithReconnect","delay","reconnectDelayMs","error","onError","String","Promise","resolve","setTimeout","close","abort","urlBase64ToUint8Array","base64String","padding","repeat","length","base64","replace","rawData","atob","outputArray","Uint8Array","i","charCodeAt","arrayBufferToBase64Url","buffer","bytes","binary","byteLength","String","fromCharCode","btoa","isWebPushSupported","window","navigator","subscribeWebPush","options","undefined","Notification","permission","requestPermission","registration","serviceWorkerRegistration","serviceWorker","ready","applicationServerKey","vapidPublicKey","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","p256dh","getKey","auth","endpoint","keys","expirationTime","unsubscribeWebPush","unsubscribe","getStandardWebPushServiceWorkerScript","trim","getExpoPushToken","options","module","currentPerms","getPermissionsAsync","isGranted","granted","requested","requestPermissionsAsync","undefined","setNotificationChannelAsync","channelId","name","channelName","importance","sound","tokenResult","getExpoPushTokenAsync","projectId","data","createExpoPushRegistration","config","createDeviceRegistration","client","driver","storage","getToken"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adatechnology/notification-client",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "description": "Isomorphic notification client — typed HTTP, device registration and SSE. Runs in React Native, web, Node and Bun.",
6
6
  "publishConfig": {
@@ -21,7 +21,7 @@
21
21
  "dist"
22
22
  ],
23
23
  "dependencies": {
24
- "@adatechnology/notification-contracts": "0.3.0"
24
+ "@adatechnology/notification-contracts": "0.4.0"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/bun": "1.3.14",