@venturekit/notify 0.0.29 → 0.0.30

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/README.md CHANGED
@@ -283,6 +283,70 @@ A few Meta quirks the provider papers over, worth knowing about:
283
283
  - **Reads are paginated and field-gated.** `getTemplateStatus` asks for `rejected_reason` explicitly (it is absent from Meta's default field set) and follows `paging.next` up to 10 pages, because one name can exist once per language.
284
284
  - **Failures split by retryability.** `ProviderSendError` means Meta was unreachable, rate-limited or broken — retrying the identical call may work. `ProviderHardError` means the request or the configuration is wrong.
285
285
 
286
+ ## Receiving Meta webhooks
287
+
288
+ Meta pushes a webhook when a template's approval status changes (`message_template_status_update`) and when it re-categorises a template after approval (`template_category_update` — e.g. `UTILITY` → `MARKETING`, which changes what each message is billed as). The package ships the wire-format half of an endpoint; you own the route, the secrets and whatever happens to the events.
289
+
290
+ ### Provisioning the secrets
291
+
292
+ Declare `whatsapp.webhooks: true` on the notify intent:
293
+
294
+ ```ts
295
+ notify: [{
296
+ id: 'transactional',
297
+ channels: ['email', 'whatsapp'],
298
+ defaultFrom: 'noreply@example.com',
299
+ whatsapp: {
300
+ phoneNumberId: '…',
301
+ wabaId: '…',
302
+ webhooks: true, // ← provisions the two webhook secrets
303
+ },
304
+ }],
305
+ ```
306
+
307
+ The messaging stack creates two Secrets Manager secrets (operator-paste-in, same pattern as the token secret) and the app stack injects their ARNs as `VENTURE_NOTIFY_WHATSAPP_APP_SECRET` and `VENTURE_NOTIFY_WHATSAPP_VERIFY_TOKEN_SECRET`. After first deploy, paste the Meta App Secret (App Dashboard → Settings → Basic) and your chosen verify token into the two secrets via `aws secretsmanager put-secret-value`; type the same verify token into the App Dashboard when registering the callback URL.
308
+
309
+ ### Building the handler
310
+
311
+ `createMetaWhatsAppWebhookHandler()` resolves both secrets automatically from those env vars (lazy, cached per cold start), so consumer route code passes zero credential arguments:
312
+
313
+ ```ts
314
+ import { createMetaWhatsAppWebhookHandler, fromMetaLanguage } from '@venturekit/notify';
315
+
316
+ const wa = createMetaWhatsAppWebhookHandler(); // zero-arg in prod
317
+
318
+ // GET — one-time handshake when the callback URL is saved in the App Dashboard.
319
+ if (method === 'GET') {
320
+ const challenge = await wa.handleVerification(query);
321
+ return { statusCode: 200, headers: { 'content-type': 'text/plain' }, body: challenge };
322
+ }
323
+
324
+ // POST — verify against the *raw* body, then parse the same bytes.
325
+ await wa.verifySignature(rawBody, headers['x-hub-signature-256']);
326
+
327
+ for (const event of wa.parseEvents(rawBody)) {
328
+ const locale = 'language' in event ? fromMetaLanguage(event.language) : undefined; // 'en-US' -> 'en'
329
+ switch (event.type) {
330
+ case 'template_category_changed': // previousCategory -> newCategory, in effect now
331
+ case 'template_category_change_scheduled': // currentCategory -> correctCategory at scheduledAtMs
332
+ case 'template_status_updated': // status, reason?, category?, disabledAtMs?, …
333
+ case 'unknown': // any other field (`messages`, `account_update`, …), value passed through
334
+ }
335
+ }
336
+ return { statusCode: 200 }; // Meta retries anything but a 2xx
337
+ ```
338
+
339
+ Override the resolvers for tests or when the secrets are not provisioned by VentureKit:
340
+
341
+ ```ts
342
+ const wa = createMetaWhatsAppWebhookHandler({
343
+ appSecretResolver: async () => process.env.META_APP_SECRET!,
344
+ verifyTokenResolver: async () => process.env.META_VERIFY_TOKEN!,
345
+ });
346
+ ```
347
+
348
+ The three error classes (`MetaWebhookSignatureError`, `MetaWebhookVerificationError`, `MetaWebhookPayloadError`) map to a `403`/`401`; never process a payload whose signature failed. The pure functions (`verifyMetaWebhookSignature`, `handleMetaWebhookVerification`, `parseMetaWebhookEvents`) are also exported for consumers that prefer to manage credential resolution themselves. `toMetaLanguage('en')` → `'en_US'` is the forward mapping for `createTemplate` / `languageCode`; pass a custom map (`{ en: 'en_GB', pt: 'pt_PT' }`) to change the regional defaults.
349
+
286
350
  ## Admin / inbox helpers
287
351
 
288
352
  `@venturekit/notify/admin` exposes route-helper functions consumers wire into their own handlers (no automatic mounting — pick your own auth/scope conventions):
@@ -338,6 +402,8 @@ The infra package injects these on every Lambda when a notify intent is declared
338
402
  | `VENTURE_NOTIFY_WHATSAPP_WABA_ID` | First notify intent's `whatsapp.wabaId` (optional; needed by `createTemplate` / `getTemplateStatus` / `deleteTemplate`) |
339
403
  | `VENTURE_NOTIFY_WHATSAPP_API_VERSION` | First notify intent's `whatsapp.apiVersion` |
340
404
  | `VENTURE_NOTIFY_WHATSAPP_TOKEN_SECRET` | Secrets Manager ARN for the WhatsApp token |
405
+ | `VENTURE_NOTIFY_WHATSAPP_APP_SECRET` | Secrets Manager ARN for the Meta App Secret (only when `whatsapp.webhooks: true`) |
406
+ | `VENTURE_NOTIFY_WHATSAPP_VERIFY_TOKEN_SECRET` | Secrets Manager ARN for the webhook verify token (only when `whatsapp.webhooks: true`) |
341
407
  | `NOTIFY_<ID>_FROM` / `NOTIFY_<ID>_CONFIG_SET` / `NOTIFY_<ID>_EVENTS_TOPIC_ARN` | Per-id overrides for projects with multiple intents |
342
408
  | `VENTURE_NOTIFY_BATCH_SIZE` | Dispatcher cron — overrides default 50 |
343
409
  | `VENTURE_NOTIFY_CLIENT_MODULE` | Path to the consumer's notify-client module (default `./lib/notify.js`) |
package/dist/index.d.ts CHANGED
@@ -55,7 +55,7 @@ export type { NotifyChannel, NotificationStatus, NotifyAddress, NotificationRow,
55
55
  export { createNotifyClient, type NotifyClient, type CreateNotifyClientOptions, type AddressResolver, } from './client.js';
56
56
  export { createTemplateRegistry, TemplateNotFoundError, type TemplateRegistry, } from './templates/registry.js';
57
57
  export { createPostgresNotifyStore, type CreatePostgresNotifyStoreOptions, type NotifyStore, type CreateNotificationInput, type UpdateNotificationStatusInput, type ListForUserOptions, type AdminListOptions, } from './store/index.js';
58
- export { ProviderHardError, ProviderSendError, type NotifyProvider, type ProviderSendRequest, type ProviderSendResult, createSesEmailProvider, type SesEmailProviderConfig, __resetSesClientForTests, createMetaWhatsAppProvider, createSecretsTokenResolver, type MetaWhatsAppProvider, type MetaWhatsAppProviderConfig, type WhatsAppTemplateCategory, type WhatsAppTemplateCategoryReported, type WhatsAppTemplateStatus, type WhatsAppTemplateRejectedReason, type WhatsAppTemplateComponent, type WhatsAppTemplateInput, type WhatsAppTemplateCreateResult, type WhatsAppTemplateStatusResult, type WhatsAppTemplateUpdateInput, type WhatsAppTemplateUpdateResult, type WhatsAppTemplateDeleteInput, type WhatsAppTemplateDeleteResult, createSmsNoopProvider, createPushNoopProvider, createEmailNoopProvider, type EmailNoopOptions, createMailHogProvider, type MailHogProviderConfig, } from './providers/index.js';
58
+ export { ProviderHardError, ProviderSendError, type NotifyProvider, type ProviderSendRequest, type ProviderSendResult, createSesEmailProvider, type SesEmailProviderConfig, __resetSesClientForTests, createMetaWhatsAppProvider, createSecretsTokenResolver, type MetaWhatsAppProvider, type MetaWhatsAppProviderConfig, type WhatsAppTemplateCategory, type WhatsAppTemplateCategoryReported, type WhatsAppTemplateStatus, type WhatsAppTemplateRejectedReason, type WhatsAppTemplateComponent, type WhatsAppTemplateInput, type WhatsAppTemplateCreateResult, type WhatsAppTemplateStatusResult, type WhatsAppTemplateUpdateInput, type WhatsAppTemplateUpdateResult, type WhatsAppTemplateDeleteInput, type WhatsAppTemplateDeleteResult, toMetaLanguage, fromMetaLanguage, DEFAULT_META_LANGUAGE_MAP, verifyMetaWebhookSignature, handleMetaWebhookVerification, parseMetaWebhookEvents, MetaWebhookSignatureError, MetaWebhookVerificationError, MetaWebhookPayloadError, META_SIGNATURE_HEADER, type VerifyMetaWebhookSignatureInput, type HandleMetaWebhookVerificationInput, type MetaWebhookQuery, type MetaWebhookEvent, type MetaTemplateWebhookEventBase, type MetaTemplateCategoryChangedEvent, type MetaTemplateCategoryChangeScheduledEvent, type MetaTemplateStatusUpdatedEvent, type MetaUnknownWebhookEvent, type WhatsAppTemplateStatusEvent, createMetaWhatsAppWebhookHandler, type MetaWhatsAppWebhookHandler, type MetaWhatsAppWebhookHandlerConfig, WHATSAPP_APP_SECRET_ENV, WHATSAPP_VERIFY_TOKEN_SECRET_ENV, createSmsNoopProvider, createPushNoopProvider, createEmailNoopProvider, type EmailNoopOptions, createMailHogProvider, type MailHogProviderConfig, } from './providers/index.js';
59
59
  export { dispatchOnce, makeDispatchHandler, type DispatchOutcome, type DispatchSummary, type DispatchOnceOptions, } from './dispatcher.js';
60
60
  export { makeBounceHandler, type BounceHandlerOutcome, } from './bounce-handler.js';
61
61
  export { adminListNotifications, adminGetNotification, adminSendNotification, adminRetryNotification, adminCancelNotification, adminClearSuppression, listUserPreferences, upsertUserPreference, listNotificationsForUser, type AdminListResult, type AdminSendInput, } from './admin/index.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AAGH,YAAY,EACV,aAAa,EACb,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,yBAAyB,EACzB,uBAAuB,EACvB,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,aAAa,EACb,eAAe,EACf,cAAc,GACf,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,kBAAkB,EAClB,KAAK,YAAY,EACjB,KAAK,yBAAyB,EAC9B,KAAK,eAAe,GACrB,MAAM,aAAa,CAAC;AAGrB,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACrB,KAAK,gBAAgB,GACtB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EACL,yBAAyB,EACzB,KAAK,gCAAgC,EACrC,KAAK,WAAW,EAChB,KAAK,uBAAuB,EAC5B,KAAK,6BAA6B,EAClC,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,GACtB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACvB,sBAAsB,EACtB,KAAK,sBAAsB,EAC3B,wBAAwB,EACxB,0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,sBAAsB,EACtB,uBAAuB,EACvB,KAAK,gBAAgB,EACrB,qBAAqB,EACrB,KAAK,qBAAqB,GAC3B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,mBAAmB,GACzB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,iBAAiB,EACjB,KAAK,oBAAoB,GAC1B,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,EACxB,KAAK,eAAe,EACpB,KAAK,cAAc,GACpB,MAAM,kBAAkB,CAAC"}
package/dist/index.js CHANGED
@@ -58,7 +58,7 @@ export { createTemplateRegistry, TemplateNotFoundError, } from './templates/regi
58
58
  // Store -------------------------------------------------------------
59
59
  export { createPostgresNotifyStore, } from './store/index.js';
60
60
  // Providers ---------------------------------------------------------
61
- export { ProviderHardError, ProviderSendError, createSesEmailProvider, __resetSesClientForTests, createMetaWhatsAppProvider, createSecretsTokenResolver, createSmsNoopProvider, createPushNoopProvider, createEmailNoopProvider, createMailHogProvider, } from './providers/index.js';
61
+ export { ProviderHardError, ProviderSendError, createSesEmailProvider, __resetSesClientForTests, createMetaWhatsAppProvider, createSecretsTokenResolver, toMetaLanguage, fromMetaLanguage, DEFAULT_META_LANGUAGE_MAP, verifyMetaWebhookSignature, handleMetaWebhookVerification, parseMetaWebhookEvents, MetaWebhookSignatureError, MetaWebhookVerificationError, MetaWebhookPayloadError, META_SIGNATURE_HEADER, createMetaWhatsAppWebhookHandler, WHATSAPP_APP_SECRET_ENV, WHATSAPP_VERIFY_TOKEN_SECRET_ENV, createSmsNoopProvider, createPushNoopProvider, createEmailNoopProvider, createMailHogProvider, } from './providers/index.js';
62
62
  // Dispatcher --------------------------------------------------------
63
63
  export { dispatchOnce, makeDispatchHandler, } from './dispatcher.js';
64
64
  // Bounce handler ----------------------------------------------------
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AAkBH,sEAAsE;AACtE,OAAO,EACL,kBAAkB,GAInB,MAAM,aAAa,CAAC;AAErB,sEAAsE;AACtE,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GAEtB,MAAM,yBAAyB,CAAC;AAEjC,sEAAsE;AACtE,OAAO,EACL,yBAAyB,GAO1B,MAAM,kBAAkB,CAAC;AAE1B,sEAAsE;AACtE,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EAIjB,sBAAsB,EAEtB,wBAAwB,EACxB,0BAA0B,EAC1B,0BAA0B,EAe1B,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EAEvB,qBAAqB,GAEtB,MAAM,sBAAsB,CAAC;AAE9B,sEAAsE;AACtE,OAAO,EACL,YAAY,EACZ,mBAAmB,GAIpB,MAAM,iBAAiB,CAAC;AAEzB,sEAAsE;AACtE,OAAO,EACL,iBAAiB,GAElB,MAAM,qBAAqB,CAAC;AAE7B,sEAAsE;AACtE,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,GAGzB,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AAkBH,sEAAsE;AACtE,OAAO,EACL,kBAAkB,GAInB,MAAM,aAAa,CAAC;AAErB,sEAAsE;AACtE,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GAEtB,MAAM,yBAAyB,CAAC;AAEjC,sEAAsE;AACtE,OAAO,EACL,yBAAyB,GAO1B,MAAM,kBAAkB,CAAC;AAE1B,sEAAsE;AACtE,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EAIjB,sBAAsB,EAEtB,wBAAwB,EACxB,0BAA0B,EAC1B,0BAA0B,EAe1B,cAAc,EACd,gBAAgB,EAChB,yBAAyB,EACzB,0BAA0B,EAC1B,6BAA6B,EAC7B,sBAAsB,EACtB,yBAAyB,EACzB,4BAA4B,EAC5B,uBAAuB,EACvB,qBAAqB,EAWrB,gCAAgC,EAGhC,uBAAuB,EACvB,gCAAgC,EAChC,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EAEvB,qBAAqB,GAEtB,MAAM,sBAAsB,CAAC;AAE9B,sEAAsE;AACtE,OAAO,EACL,YAAY,EACZ,mBAAmB,GAIpB,MAAM,iBAAiB,CAAC;AAEzB,sEAAsE;AACtE,OAAO,EACL,iBAAiB,GAElB,MAAM,qBAAqB,CAAC;AAE7B,sEAAsE;AACtE,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,GAGzB,MAAM,kBAAkB,CAAC"}
@@ -14,6 +14,8 @@
14
14
  export { ProviderHardError, ProviderSendError, type NotifyProvider, type ProviderSendRequest, type ProviderSendResult, } from './types.js';
15
15
  export { createSesEmailProvider, type SesEmailProviderConfig, __resetSesClientForTests, } from './email-ses.js';
16
16
  export { createMetaWhatsAppProvider, createSecretsTokenResolver, type MetaWhatsAppProvider, type MetaWhatsAppProviderConfig, type WhatsAppTemplateCategory, type WhatsAppTemplateCategoryReported, type WhatsAppTemplateStatus, type WhatsAppTemplateRejectedReason, type WhatsAppTemplateComponent, type WhatsAppTemplateInput, type WhatsAppTemplateCreateResult, type WhatsAppTemplateStatusResult, type WhatsAppTemplateUpdateInput, type WhatsAppTemplateUpdateResult, type WhatsAppTemplateDeleteInput, type WhatsAppTemplateDeleteResult, } from './whatsapp-meta.js';
17
+ export { toMetaLanguage, fromMetaLanguage, DEFAULT_META_LANGUAGE_MAP, } from './whatsapp-meta-language.js';
18
+ export { verifyMetaWebhookSignature, handleMetaWebhookVerification, parseMetaWebhookEvents, MetaWebhookSignatureError, MetaWebhookVerificationError, MetaWebhookPayloadError, META_SIGNATURE_HEADER, type VerifyMetaWebhookSignatureInput, type HandleMetaWebhookVerificationInput, type MetaWebhookQuery, type MetaWebhookEvent, type MetaTemplateWebhookEventBase, type MetaTemplateCategoryChangedEvent, type MetaTemplateCategoryChangeScheduledEvent, type MetaTemplateStatusUpdatedEvent, type MetaUnknownWebhookEvent, type WhatsAppTemplateStatusEvent, createMetaWhatsAppWebhookHandler, type MetaWhatsAppWebhookHandler, type MetaWhatsAppWebhookHandlerConfig, WHATSAPP_APP_SECRET_ENV, WHATSAPP_VERIFY_TOKEN_SECRET_ENV, } from './whatsapp-meta-webhook.js';
17
19
  export { createSmsNoopProvider } from './sms-noop.js';
18
20
  export { createPushNoopProvider } from './push-noop.js';
19
21
  export { createEmailNoopProvider, type EmailNoopOptions } from './email-noop.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,GACxB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,sBAAsB,EACtB,KAAK,sBAAsB,EAC3B,wBAAwB,GACzB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,KAAK,oBAAoB,EACzB,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAC7B,KAAK,gCAAgC,EACrC,KAAK,sB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,EACL,0BAA0B,EAC1B,6BAA6B,EAC7B,sBAAsB,EACtB,yBAAyB,EACzB,4BAA4B,EAC5B,uBAAuB,EACvB,qBAAqB,EACrB,KAAK,+BAA+B,EACpC,KAAK,kCAAkC,EACvC,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,4BAA4B,EACjC,KAAK,gCAAgC,EACrC,KAAK,wCAAwC,EAC7C,KAAK,8BAA8B,EACnC,KAAK,uBAAuB,EAC5B,KAAK,2BAA2B,EAChC,gCAAgC,EAChC,KAAK,0BAA0B,EAC/B,KAAK,gCAAgC,EACrC,uBAAuB,EACvB,gCAAgC,GACjC,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,KAAK,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,KAAK,qBAAqB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -14,6 +14,8 @@
14
14
  export { ProviderHardError, ProviderSendError, } from './types.js';
15
15
  export { createSesEmailProvider, __resetSesClientForTests, } from './email-ses.js';
16
16
  export { createMetaWhatsAppProvider, createSecretsTokenResolver, } from './whatsapp-meta.js';
17
+ export { toMetaLanguage, fromMetaLanguage, DEFAULT_META_LANGUAGE_MAP, } from './whatsapp-meta-language.js';
18
+ export { verifyMetaWebhookSignature, handleMetaWebhookVerification, parseMetaWebhookEvents, MetaWebhookSignatureError, MetaWebhookVerificationError, MetaWebhookPayloadError, META_SIGNATURE_HEADER, createMetaWhatsAppWebhookHandler, WHATSAPP_APP_SECRET_ENV, WHATSAPP_VERIFY_TOKEN_SECRET_ENV, } from './whatsapp-meta-webhook.js';
17
19
  export { createSmsNoopProvider } from './sms-noop.js';
18
20
  export { createPushNoopProvider } from './push-noop.js';
19
21
  export { createEmailNoopProvider } from './email-noop.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,iBAAiB,EACjB,iBAAiB,GAIlB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,sBAAsB,EAEtB,wBAAwB,GACzB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAe3B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAyB,MAAM,iBAAiB,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAA8B,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,iBAAiB,EACjB,iBAAiB,GAIlB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,sBAAsB,EAEtB,wBAAwB,GACzB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAe3B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,0BAA0B,EAC1B,6BAA6B,EAC7B,sBAAsB,EACtB,yBAAyB,EACzB,4BAA4B,EAC5B,uBAAuB,EACvB,qBAAqB,EAWrB,gCAAgC,EAGhC,uBAAuB,EACvB,gCAAgC,GACjC,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAyB,MAAM,iBAAiB,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAA8B,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @venturekit/notify — WhatsApp language-code mapping
3
+ *
4
+ * Meta identifies a template's language with a *language-and-locale*
5
+ * code: `en_US`, `pt_BR`, `zh_CN`, but also bare `fr`, `de`, `ar` for
6
+ * languages Meta does not split by region. Consumer apps almost always
7
+ * key their own content by the short ISO 639-1 code (`en`, `fr`, `pt`).
8
+ *
9
+ * Two functions bridge the gap:
10
+ *
11
+ * - {@link toMetaLanguage} — app locale → Meta code, used when creating
12
+ * or sending templates.
13
+ * - {@link fromMetaLanguage} — Meta code → app locale, used when reading
14
+ * Meta's responses and webhooks back into the app's own vocabulary.
15
+ *
16
+ * Both are pure, table-driven and deliberately small. Meta's supported
17
+ * list is long and shifts over time, so the default table only pins the
18
+ * cases where the short code alone is *not* a valid Meta code and a
19
+ * region has to be chosen; everything else passes through unchanged.
20
+ *
21
+ * Meta is also inconsistent about the separator: the Graph API speaks
22
+ * `en_US`, webhooks report `en-US`. {@link fromMetaLanguage} accepts
23
+ * either; {@link toMetaLanguage} always emits the underscore form the
24
+ * API expects.
25
+ */
26
+ /**
27
+ * Short locales that have no bare Meta equivalent and therefore need a
28
+ * default region. Override per call via `toMetaLanguage(locale, map)`.
29
+ */
30
+ export declare const DEFAULT_META_LANGUAGE_MAP: Readonly<Record<string, string>>;
31
+ /**
32
+ * Map an app locale to the language code Meta expects.
33
+ *
34
+ * - `'en'` → `'en_US'`, `'pt'` → `'pt_BR'`, `'zh'` → `'zh_CN'` (table)
35
+ * - `'fr'` → `'fr'` (pass-through)
36
+ * - `'en-GB'` / `'en_gb'` → `'en_GB'` (normalised: `xx_YY`)
37
+ * - `'zh-Hant-TW'` → `'zh_TW'` (script / variant subtags are skipped;
38
+ * only a two-letter region is kept, since Meta codes have no script
39
+ * component). `'zh-Hant'` alone therefore falls back to the table.
40
+ *
41
+ * Pass a custom `map` to change the regional defaults — e.g.
42
+ * `{ en: 'en_GB', pt: 'pt_PT' }` — it is consulted *instead of* the
43
+ * default table, so include every override you rely on.
44
+ */
45
+ export declare function toMetaLanguage(locale: string, map?: Readonly<Record<string, string>>): string;
46
+ /**
47
+ * Map a Meta language code back to the short app locale.
48
+ *
49
+ * `'en_US'` → `'en'`, `'en-US'` → `'en'`, `'pt_BR'` → `'pt'`,
50
+ * `'fr'` → `'fr'`. The region is dropped: the app owns its locale
51
+ * granularity, and if it *does* distinguish `en_GB` from `en_US` it
52
+ * should keep Meta's raw code instead of calling this.
53
+ */
54
+ export declare function fromMetaLanguage(metaLanguage: string): string;
55
+ //# sourceMappingURL=whatsapp-meta-language.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whatsapp-meta-language.d.ts","sourceRoot":"","sources":["../../src/providers/whatsapp-meta-language.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;;GAGG;AACH,eAAO,MAAM,yBAAyB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAItE,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EACd,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAA6B,GAChE,MAAM,CAQR;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAG7D"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * @venturekit/notify — WhatsApp language-code mapping
3
+ *
4
+ * Meta identifies a template's language with a *language-and-locale*
5
+ * code: `en_US`, `pt_BR`, `zh_CN`, but also bare `fr`, `de`, `ar` for
6
+ * languages Meta does not split by region. Consumer apps almost always
7
+ * key their own content by the short ISO 639-1 code (`en`, `fr`, `pt`).
8
+ *
9
+ * Two functions bridge the gap:
10
+ *
11
+ * - {@link toMetaLanguage} — app locale → Meta code, used when creating
12
+ * or sending templates.
13
+ * - {@link fromMetaLanguage} — Meta code → app locale, used when reading
14
+ * Meta's responses and webhooks back into the app's own vocabulary.
15
+ *
16
+ * Both are pure, table-driven and deliberately small. Meta's supported
17
+ * list is long and shifts over time, so the default table only pins the
18
+ * cases where the short code alone is *not* a valid Meta code and a
19
+ * region has to be chosen; everything else passes through unchanged.
20
+ *
21
+ * Meta is also inconsistent about the separator: the Graph API speaks
22
+ * `en_US`, webhooks report `en-US`. {@link fromMetaLanguage} accepts
23
+ * either; {@link toMetaLanguage} always emits the underscore form the
24
+ * API expects.
25
+ */
26
+ /**
27
+ * Short locales that have no bare Meta equivalent and therefore need a
28
+ * default region. Override per call via `toMetaLanguage(locale, map)`.
29
+ */
30
+ export const DEFAULT_META_LANGUAGE_MAP = {
31
+ en: 'en_US',
32
+ pt: 'pt_BR',
33
+ zh: 'zh_CN',
34
+ };
35
+ /**
36
+ * Map an app locale to the language code Meta expects.
37
+ *
38
+ * - `'en'` → `'en_US'`, `'pt'` → `'pt_BR'`, `'zh'` → `'zh_CN'` (table)
39
+ * - `'fr'` → `'fr'` (pass-through)
40
+ * - `'en-GB'` / `'en_gb'` → `'en_GB'` (normalised: `xx_YY`)
41
+ * - `'zh-Hant-TW'` → `'zh_TW'` (script / variant subtags are skipped;
42
+ * only a two-letter region is kept, since Meta codes have no script
43
+ * component). `'zh-Hant'` alone therefore falls back to the table.
44
+ *
45
+ * Pass a custom `map` to change the regional defaults — e.g.
46
+ * `{ en: 'en_GB', pt: 'pt_PT' }` — it is consulted *instead of* the
47
+ * default table, so include every override you rely on.
48
+ */
49
+ export function toMetaLanguage(locale, map = DEFAULT_META_LANGUAGE_MAP) {
50
+ const [lang = '', ...subtags] = locale.trim().split(/[-_]/);
51
+ const language = lang.toLowerCase();
52
+ // BCP 47: scripts are 4 letters, variants 5–8, so a 2-letter subtag
53
+ // after the language is unambiguously the region.
54
+ const region = subtags.find((tag) => /^[a-z]{2}$/i.test(tag));
55
+ if (region)
56
+ return `${language}_${region.toUpperCase()}`;
57
+ return map[language] ?? language;
58
+ }
59
+ /**
60
+ * Map a Meta language code back to the short app locale.
61
+ *
62
+ * `'en_US'` → `'en'`, `'en-US'` → `'en'`, `'pt_BR'` → `'pt'`,
63
+ * `'fr'` → `'fr'`. The region is dropped: the app owns its locale
64
+ * granularity, and if it *does* distinguish `en_GB` from `en_US` it
65
+ * should keep Meta's raw code instead of calling this.
66
+ */
67
+ export function fromMetaLanguage(metaLanguage) {
68
+ const [lang = ''] = metaLanguage.trim().split(/[-_]/, 1);
69
+ return lang.toLowerCase();
70
+ }
71
+ //# sourceMappingURL=whatsapp-meta-language.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whatsapp-meta-language.js","sourceRoot":"","sources":["../../src/providers/whatsapp-meta-language.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAqC;IACzE,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,OAAO;CACZ,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,cAAc,CAC5B,MAAc,EACd,MAAwC,yBAAyB;IAEjE,MAAM,CAAC,IAAI,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5D,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;IACpC,oEAAoE;IACpE,kDAAkD;IAClD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9D,IAAI,MAAM;QAAE,OAAO,GAAG,QAAQ,IAAI,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC;IACzD,OAAO,GAAG,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC;AACnC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,gBAAgB,CAAC,YAAoB;IACnD,MAAM,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,YAAY,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IACzD,OAAO,IAAI,CAAC,WAAW,EAAE,CAAC;AAC5B,CAAC"}
@@ -0,0 +1,291 @@
1
+ /**
2
+ * @venturekit/notify — Meta WhatsApp webhook infrastructure
3
+ *
4
+ * Meta pushes a webhook whenever something about a template changes on
5
+ * its side: approval status (`message_template_status_update`) and,
6
+ * more insidiously, *category* (`template_category_update`) — Meta
7
+ * re-classifies templates after approval, which changes what each
8
+ * message costs. Without webhooks the only way to notice is polling.
9
+ *
10
+ * This module is the framework half of a webhook endpoint. It knows
11
+ * Meta's wire format and nothing else:
12
+ *
13
+ * - {@link verifyMetaWebhookSignature} — check `x-hub-signature-256`
14
+ * (HMAC-SHA256 of the raw body, keyed by the App Secret).
15
+ * - {@link handleMetaWebhookVerification} — answer the one-time GET
16
+ * handshake Meta sends when the endpoint is registered.
17
+ * - {@link parseMetaWebhookEvents} — flatten `entry[].changes[]` into
18
+ * typed events.
19
+ *
20
+ * The consumer owns the route, the App Secret / verify token storage,
21
+ * and whatever happens to the parsed events (DB writes, alerts, …).
22
+ * A typical Lambda handler:
23
+ *
24
+ * ```ts
25
+ * if (method === 'GET') {
26
+ * return text(handleMetaWebhookVerification({ query, verifyToken }));
27
+ * }
28
+ * verifyMetaWebhookSignature({
29
+ * rawBody, appSecret, signature: headers['x-hub-signature-256'],
30
+ * });
31
+ * for (const event of parseMetaWebhookEvents(rawBody)) {
32
+ * if (event.type === 'template_category_changed') { … }
33
+ * }
34
+ * return ok(); // Meta retries on anything but a 2xx
35
+ * ```
36
+ *
37
+ * `rawBody` must be the bytes exactly as received — re-serialising a
38
+ * parsed JSON object changes key order and whitespace and breaks the
39
+ * signature. On API Gateway, base64-decode `event.body` when
40
+ * `isBase64Encoded` is set and pass the resulting string/Buffer.
41
+ */
42
+ import { type WhatsAppTemplateCategoryReported, type WhatsAppTemplateRejectedReason, type WhatsAppTemplateStatus } from './whatsapp-meta.js';
43
+ /**
44
+ * `x-hub-signature-256` is missing, malformed or does not match the
45
+ * body. Answer 401/403 and do **not** process the payload.
46
+ */
47
+ export declare class MetaWebhookSignatureError extends Error {
48
+ constructor(message: string);
49
+ }
50
+ /**
51
+ * The GET verification handshake failed: wrong `hub.mode`, wrong
52
+ * `hub.verify_token`, or no `hub.challenge` to echo. Answer 403.
53
+ */
54
+ export declare class MetaWebhookVerificationError extends Error {
55
+ constructor(message: string);
56
+ }
57
+ /**
58
+ * The body is not a Meta webhook envelope (`{ entry: [{ changes: [] }] }`).
59
+ * Only thrown for structural problems; unknown `field`s are surfaced as
60
+ * {@link MetaUnknownWebhookEvent} instead so new Meta fields never break
61
+ * the endpoint.
62
+ */
63
+ export declare class MetaWebhookPayloadError extends Error {
64
+ constructor(message: string);
65
+ }
66
+ /** Header Meta signs every webhook POST with. */
67
+ export declare const META_SIGNATURE_HEADER = "x-hub-signature-256";
68
+ /** Input for {@link verifyMetaWebhookSignature}. */
69
+ export interface VerifyMetaWebhookSignatureInput {
70
+ /** The request body exactly as received (string or bytes). */
71
+ rawBody: string | Uint8Array;
72
+ /**
73
+ * Value of the `x-hub-signature-256` header: `sha256=<hex digest>`.
74
+ * `undefined`/`null` is accepted so the header lookup can be passed
75
+ * straight through — it fails verification like any other mismatch.
76
+ */
77
+ signature: string | null | undefined;
78
+ /** The Meta App Secret (App Dashboard → Settings → Basic). */
79
+ appSecret: string;
80
+ }
81
+ /**
82
+ * Verify Meta's HMAC-SHA256 body signature. Throws
83
+ * {@link MetaWebhookSignatureError} on any mismatch; returns normally
84
+ * when the signature is valid.
85
+ *
86
+ * Comparison is constant-time. The `sha256=` prefix is required —
87
+ * Meta always sends it, and accepting a bare digest would also accept
88
+ * the legacy SHA-1 `x-hub-signature` header by accident.
89
+ */
90
+ export declare function verifyMetaWebhookSignature(input: VerifyMetaWebhookSignatureInput): void;
91
+ /**
92
+ * Query string of the verification GET. Accepts the shapes the common
93
+ * HTTP layers hand out: API Gateway's `queryStringParameters`
94
+ * (`Record<string, string | undefined>`), Node/Express-style records
95
+ * that may carry arrays, or a `URLSearchParams`.
96
+ */
97
+ export type MetaWebhookQuery = URLSearchParams | Readonly<Record<string, string | readonly string[] | undefined | null>> | null | undefined;
98
+ /** Input for {@link handleMetaWebhookVerification}. */
99
+ export interface HandleMetaWebhookVerificationInput {
100
+ /** Parsed query string of the incoming GET. */
101
+ query: MetaWebhookQuery;
102
+ /**
103
+ * The verify token you typed into the App Dashboard when registering
104
+ * the callback URL. Any opaque string; treat it as a secret.
105
+ */
106
+ verifyToken: string;
107
+ }
108
+ /**
109
+ * Handle Meta's subscription handshake. Meta sends
110
+ * `GET ?hub.mode=subscribe&hub.verify_token=…&hub.challenge=…` once,
111
+ * when the callback URL is saved in the App Dashboard, and expects the
112
+ * challenge echoed back as a `200 text/plain` body.
113
+ *
114
+ * Returns the challenge string to respond with. Throws
115
+ * {@link MetaWebhookVerificationError} when the mode is not `subscribe`,
116
+ * the token does not match, or the challenge is missing — respond 403.
117
+ */
118
+ export declare function handleMetaWebhookVerification(input: HandleMetaWebhookVerificationInput): string;
119
+ /**
120
+ * Status values Meta emits in `message_template_status_update`. A
121
+ * superset of {@link WhatsAppTemplateStatus} — the webhook also reports
122
+ * transitions (`REINSTATED`, `UNARCHIVED`) and warnings (`FLAGGED`)
123
+ * that never appear as a stored status. Open union, like the rest.
124
+ */
125
+ export type WhatsAppTemplateStatusEvent = WhatsAppTemplateStatus | 'ARCHIVED' | 'UNARCHIVED' | 'FLAGGED' | 'LOCKED' | 'REINSTATED' | (string & {});
126
+ /** Fields shared by every template-scoped webhook event. */
127
+ export interface MetaTemplateWebhookEventBase {
128
+ /** WhatsApp Business Account the template belongs to (`entry.id`). */
129
+ wabaId: string;
130
+ /** When Meta triggered the webhook (`entry.time`), in ms since epoch. */
131
+ occurredAtMs?: number;
132
+ /**
133
+ * Meta template ID. Meta sends a number; normalised to a string. When
134
+ * parsed from the raw body the digits are preserved exactly even above
135
+ * `Number.MAX_SAFE_INTEGER`; a pre-parsed object has already been
136
+ * through `JSON.parse` and may have lost precision.
137
+ */
138
+ templateId: string;
139
+ /** Template name. */
140
+ templateName: string;
141
+ /**
142
+ * Language exactly as Meta reported it — webhooks use `en-US`, the
143
+ * API `en_US`. Run through `fromMetaLanguage` for the app locale.
144
+ */
145
+ language: string;
146
+ }
147
+ /**
148
+ * Meta re-categorised a template. `newCategory` is now in effect and
149
+ * is what messages are billed as from here on.
150
+ */
151
+ export interface MetaTemplateCategoryChangedEvent extends MetaTemplateWebhookEventBase {
152
+ type: 'template_category_changed';
153
+ previousCategory: WhatsAppTemplateCategoryReported;
154
+ newCategory: WhatsAppTemplateCategoryReported;
155
+ }
156
+ /**
157
+ * Meta will re-categorise a template at `scheduledAtMs` (typically 24h
158
+ * out). `currentCategory` still applies until then. Meta sends this in
159
+ * the field it confusingly names `new_category`; it is renamed here so
160
+ * it cannot be mistaken for the post-change value.
161
+ */
162
+ export interface MetaTemplateCategoryChangeScheduledEvent extends MetaTemplateWebhookEventBase {
163
+ type: 'template_category_change_scheduled';
164
+ currentCategory: WhatsAppTemplateCategoryReported;
165
+ correctCategory: WhatsAppTemplateCategoryReported;
166
+ scheduledAtMs: number;
167
+ }
168
+ /** A template's approval status changed. */
169
+ export interface MetaTemplateStatusUpdatedEvent extends MetaTemplateWebhookEventBase {
170
+ type: 'template_status_updated';
171
+ status: WhatsAppTemplateStatusEvent;
172
+ /** Rejection reason; `'NONE'` or absent unless `status` is `REJECTED`. */
173
+ reason?: WhatsAppTemplateRejectedReason;
174
+ /** Category at the time of the event, when Meta includes it. */
175
+ category?: WhatsAppTemplateCategoryReported;
176
+ /** Set when `status` is `DISABLED`. */
177
+ disabledAtMs?: number;
178
+ /** Pause / unpause detail (`other_info`). */
179
+ info?: {
180
+ title?: string;
181
+ description?: string;
182
+ };
183
+ /** Detailed rejection guidance (`rejection_info`, `INVALID_FORMAT` only). */
184
+ rejectionInfo?: {
185
+ reason?: string;
186
+ recommendation?: string;
187
+ };
188
+ }
189
+ /**
190
+ * A change whose `field` this module does not model (`messages`,
191
+ * `account_update`, …), or a template field whose `value` was missing
192
+ * the keys needed to build a typed event. Carried through untouched so
193
+ * consumers can log or handle it themselves.
194
+ */
195
+ export interface MetaUnknownWebhookEvent {
196
+ type: 'unknown';
197
+ wabaId: string;
198
+ occurredAtMs?: number;
199
+ field: string;
200
+ value: unknown;
201
+ }
202
+ /** Union of everything {@link parseMetaWebhookEvents} can produce. */
203
+ export type MetaWebhookEvent = MetaTemplateCategoryChangedEvent | MetaTemplateCategoryChangeScheduledEvent | MetaTemplateStatusUpdatedEvent | MetaUnknownWebhookEvent;
204
+ /**
205
+ * Parse a Meta webhook body into a flat list of typed events.
206
+ *
207
+ * Accepts the raw body (`string` or `Uint8Array` — preferred, it is what
208
+ * you already hold for signature verification) or an already-parsed
209
+ * object. Every `entry[].changes[]` becomes one event; entries with no
210
+ * changes contribute nothing. Throws {@link MetaWebhookPayloadError}
211
+ * only when the envelope itself is malformed.
212
+ */
213
+ export declare function parseMetaWebhookEvents(body: unknown): MetaWebhookEvent[];
214
+ /**
215
+ * Env var holding the ARN of the Meta App Secret (provisioned by the
216
+ * messaging stack when `whatsapp.webhooks: true`).
217
+ */
218
+ export declare const WHATSAPP_APP_SECRET_ENV = "VENTURE_NOTIFY_WHATSAPP_APP_SECRET";
219
+ /**
220
+ * Env var holding the ARN of the webhook verify-token secret
221
+ * (provisioned by the messaging stack when `whatsapp.webhooks: true`).
222
+ */
223
+ export declare const WHATSAPP_VERIFY_TOKEN_SECRET_ENV = "VENTURE_NOTIFY_WHATSAPP_VERIFY_TOKEN_SECRET";
224
+ /** Construction options for {@link createMetaWhatsAppWebhookHandler}. */
225
+ export interface MetaWhatsAppWebhookHandlerConfig {
226
+ /**
227
+ * Resolves the Meta App Secret used to verify `x-hub-signature-256`.
228
+ * Defaults to a Secrets Manager resolver reading the ARN from
229
+ * `VENTURE_NOTIFY_WHATSAPP_APP_SECRET` (the env var the app stack
230
+ * injects when `whatsapp.webhooks: true` is declared).
231
+ *
232
+ * Override for tests or when the secret lives elsewhere — e.g.
233
+ * `() => Promise.resolve(process.env.META_APP_SECRET!)` for a
234
+ * dev setup that injects the value directly.
235
+ */
236
+ appSecretResolver?: () => Promise<string>;
237
+ /**
238
+ * Resolves the webhook verify token used for the one-time Meta
239
+ * subscription handshake. Defaults to a Secrets Manager resolver
240
+ * reading the ARN from `VENTURE_NOTIFY_WHATSAPP_VERIFY_TOKEN_SECRET`.
241
+ */
242
+ verifyTokenResolver?: () => Promise<string>;
243
+ }
244
+ /**
245
+ * A handler with the App Secret and verify token bound, so consumer
246
+ * route code calls methods with no credential arguments.
247
+ */
248
+ export interface MetaWhatsAppWebhookHandler {
249
+ /**
250
+ * Verify `x-hub-signature-256` against the raw body. Async because
251
+ * the App Secret is fetched from Secrets Manager on first call
252
+ * (cached for the rest of the cold start). Throws
253
+ * {@link MetaWebhookSignatureError} on mismatch.
254
+ */
255
+ verifySignature(rawBody: string | Uint8Array, signature: string | null | undefined): Promise<void>;
256
+ /**
257
+ * Handle the one-time GET verification handshake. Async because the
258
+ * verify token is fetched from Secrets Manager on first call (cached
259
+ * for the rest of the cold start). Returns the challenge string.
260
+ * Throws {@link MetaWebhookVerificationError} on failure.
261
+ */
262
+ handleVerification(query: MetaWebhookQuery): Promise<string>;
263
+ /**
264
+ * Parse a webhook body (raw `string` / `Uint8Array`, or a pre-parsed
265
+ * object) into typed events. Synchronous — no secrets needed. Thin
266
+ * wrapper over {@link parseMetaWebhookEvents}.
267
+ */
268
+ parseEvents(body: unknown): MetaWebhookEvent[];
269
+ }
270
+ /**
271
+ * Build a webhook handler that resolves the App Secret and verify
272
+ * token automatically from the env vars the VentureKit app stack
273
+ * injects when `whatsapp.webhooks: true` is declared in the notify
274
+ * intent.
275
+ *
276
+ * ```ts
277
+ * const wa = createMetaWhatsAppWebhookHandler(); // zero-arg in prod
278
+ *
279
+ * if (method === 'GET') return text(await wa.handleVerification(query));
280
+ * await wa.verifySignature(rawBody, headers['x-hub-signature-256']);
281
+ * for (const event of wa.parseEvents(rawBody)) { … }
282
+ * ```
283
+ *
284
+ * Both resolvers are lazy and memoised per cold start (same pattern as
285
+ * `createSecretsTokenResolver`), so the Secrets Manager round-trip
286
+ * happens at most once per Lambda lifecycle. Pass explicit resolvers
287
+ * to override — e.g. in tests or when the secrets are not provisioned
288
+ * by VentureKit.
289
+ */
290
+ export declare function createMetaWhatsAppWebhookHandler(config?: MetaWhatsAppWebhookHandlerConfig): MetaWhatsAppWebhookHandler;
291
+ //# sourceMappingURL=whatsapp-meta-webhook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whatsapp-meta-webhook.d.ts","sourceRoot":"","sources":["../../src/providers/whatsapp-meta-webhook.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAKH,OAAO,EAEL,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,EACnC,KAAK,sBAAsB,EAC5B,MAAM,oBAAoB,CAAC;AAI5B;;;GAGG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;gBACtC,OAAO,EAAE,MAAM;CAI5B;AAED;;;GAGG;AACH,qBAAa,4BAA6B,SAAQ,KAAK;gBACzC,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;GAKG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;gBACpC,OAAO,EAAE,MAAM;CAI5B;AAID,iDAAiD;AACjD,eAAO,MAAM,qBAAqB,wBAAwB,CAAC;AAE3D,oDAAoD;AACpD,MAAM,WAAW,+BAA+B;IAC9C,8DAA8D;IAC9D,OAAO,EAAE,MAAM,GAAG,UAAU,CAAC;IAC7B;;;;OAIG;IACH,SAAS,E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gC;IAC/C;;;;;;;;;OASG;IACH,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1C;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;CAC7C;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA0B;IACzC;;;;;OAKG;IACH,eAAe,CACb,OAAO,EAAE,MAAM,GAAG,UAAU,EAC5B,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACnC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB;;;;;OAKG;IACH,kBAAkB,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7D;;;;OAIG;IACH,WAAW,CAAC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAAE,CAAC;CAChD;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gCAAgC,CAC9C,MAAM,GAAE,gCAAqC,GAC5C,0BAA0B,CAqB5B"}
@@ -0,0 +1,405 @@
1
+ /**
2
+ * @venturekit/notify — Meta WhatsApp webhook infrastructure
3
+ *
4
+ * Meta pushes a webhook whenever something about a template changes on
5
+ * its side: approval status (`message_template_status_update`) and,
6
+ * more insidiously, *category* (`template_category_update`) — Meta
7
+ * re-classifies templates after approval, which changes what each
8
+ * message costs. Without webhooks the only way to notice is polling.
9
+ *
10
+ * This module is the framework half of a webhook endpoint. It knows
11
+ * Meta's wire format and nothing else:
12
+ *
13
+ * - {@link verifyMetaWebhookSignature} — check `x-hub-signature-256`
14
+ * (HMAC-SHA256 of the raw body, keyed by the App Secret).
15
+ * - {@link handleMetaWebhookVerification} — answer the one-time GET
16
+ * handshake Meta sends when the endpoint is registered.
17
+ * - {@link parseMetaWebhookEvents} — flatten `entry[].changes[]` into
18
+ * typed events.
19
+ *
20
+ * The consumer owns the route, the App Secret / verify token storage,
21
+ * and whatever happens to the parsed events (DB writes, alerts, …).
22
+ * A typical Lambda handler:
23
+ *
24
+ * ```ts
25
+ * if (method === 'GET') {
26
+ * return text(handleMetaWebhookVerification({ query, verifyToken }));
27
+ * }
28
+ * verifyMetaWebhookSignature({
29
+ * rawBody, appSecret, signature: headers['x-hub-signature-256'],
30
+ * });
31
+ * for (const event of parseMetaWebhookEvents(rawBody)) {
32
+ * if (event.type === 'template_category_changed') { … }
33
+ * }
34
+ * return ok(); // Meta retries on anything but a 2xx
35
+ * ```
36
+ *
37
+ * `rawBody` must be the bytes exactly as received — re-serialising a
38
+ * parsed JSON object changes key order and whitespace and breaks the
39
+ * signature. On API Gateway, base64-decode `event.body` when
40
+ * `isBase64Encoded` is set and pass the resulting string/Buffer.
41
+ */
42
+ import { createHmac, timingSafeEqual } from 'node:crypto';
43
+ import { ProviderHardError } from './types.js';
44
+ import { createSecretsTokenResolver, } from './whatsapp-meta.js';
45
+ // ─── Errors ────────────────────────────────────────────────────────
46
+ /**
47
+ * `x-hub-signature-256` is missing, malformed or does not match the
48
+ * body. Answer 401/403 and do **not** process the payload.
49
+ */
50
+ export class MetaWebhookSignatureError extends Error {
51
+ constructor(message) {
52
+ super(message);
53
+ this.name = 'MetaWebhookSignatureError';
54
+ }
55
+ }
56
+ /**
57
+ * The GET verification handshake failed: wrong `hub.mode`, wrong
58
+ * `hub.verify_token`, or no `hub.challenge` to echo. Answer 403.
59
+ */
60
+ export class MetaWebhookVerificationError extends Error {
61
+ constructor(message) {
62
+ super(message);
63
+ this.name = 'MetaWebhookVerificationError';
64
+ }
65
+ }
66
+ /**
67
+ * The body is not a Meta webhook envelope (`{ entry: [{ changes: [] }] }`).
68
+ * Only thrown for structural problems; unknown `field`s are surfaced as
69
+ * {@link MetaUnknownWebhookEvent} instead so new Meta fields never break
70
+ * the endpoint.
71
+ */
72
+ export class MetaWebhookPayloadError extends Error {
73
+ constructor(message) {
74
+ super(message);
75
+ this.name = 'MetaWebhookPayloadError';
76
+ }
77
+ }
78
+ // ─── Signature verification ────────────────────────────────────────
79
+ /** Header Meta signs every webhook POST with. */
80
+ export const META_SIGNATURE_HEADER = 'x-hub-signature-256';
81
+ /**
82
+ * Verify Meta's HMAC-SHA256 body signature. Throws
83
+ * {@link MetaWebhookSignatureError} on any mismatch; returns normally
84
+ * when the signature is valid.
85
+ *
86
+ * Comparison is constant-time. The `sha256=` prefix is required —
87
+ * Meta always sends it, and accepting a bare digest would also accept
88
+ * the legacy SHA-1 `x-hub-signature` header by accident.
89
+ */
90
+ export function verifyMetaWebhookSignature(input) {
91
+ const { rawBody, signature, appSecret } = input;
92
+ if (!appSecret) {
93
+ throw new MetaWebhookSignatureError('Meta webhook: appSecret is empty — cannot verify signature');
94
+ }
95
+ if (!signature) {
96
+ throw new MetaWebhookSignatureError(`Meta webhook: missing ${META_SIGNATURE_HEADER} header`);
97
+ }
98
+ const [scheme, hex, ...rest] = signature.trim().split('=');
99
+ if (scheme !== 'sha256' || !hex || rest.length > 0) {
100
+ throw new MetaWebhookSignatureError(`Meta webhook: malformed ${META_SIGNATURE_HEADER} header (expected sha256=<hex>)`);
101
+ }
102
+ const expected = createHmac('sha256', appSecret).update(rawBody).digest();
103
+ const received = Buffer.from(hex, 'hex');
104
+ // A hex string that is not the digest's length can never match, and
105
+ // `timingSafeEqual` throws on length mismatch rather than returning
106
+ // false. `Buffer.from(hex, 'hex')` also silently truncates on non-hex
107
+ // input, so the length check covers that as well.
108
+ if (received.length !== expected.length ||
109
+ !timingSafeEqual(received, expected)) {
110
+ throw new MetaWebhookSignatureError('Meta webhook: signature does not match body');
111
+ }
112
+ }
113
+ function queryParam(query, key) {
114
+ if (!query)
115
+ return undefined;
116
+ if (query instanceof URLSearchParams)
117
+ return query.get(key) ?? undefined;
118
+ const value = query[key];
119
+ if (Array.isArray(value))
120
+ return value[0];
121
+ return value ?? undefined;
122
+ }
123
+ /**
124
+ * Handle Meta's subscription handshake. Meta sends
125
+ * `GET ?hub.mode=subscribe&hub.verify_token=…&hub.challenge=…` once,
126
+ * when the callback URL is saved in the App Dashboard, and expects the
127
+ * challenge echoed back as a `200 text/plain` body.
128
+ *
129
+ * Returns the challenge string to respond with. Throws
130
+ * {@link MetaWebhookVerificationError} when the mode is not `subscribe`,
131
+ * the token does not match, or the challenge is missing — respond 403.
132
+ */
133
+ export function handleMetaWebhookVerification(input) {
134
+ const { query, verifyToken } = input;
135
+ if (!verifyToken) {
136
+ throw new MetaWebhookVerificationError('Meta webhook: verifyToken is empty — cannot complete verification');
137
+ }
138
+ const mode = queryParam(query, 'hub.mode');
139
+ const token = queryParam(query, 'hub.verify_token');
140
+ const challenge = queryParam(query, 'hub.challenge');
141
+ if (mode !== 'subscribe') {
142
+ throw new MetaWebhookVerificationError("Meta webhook: hub.mode is not 'subscribe'");
143
+ }
144
+ if (!token || !constantTimeEquals(token, verifyToken)) {
145
+ throw new MetaWebhookVerificationError('Meta webhook: hub.verify_token does not match');
146
+ }
147
+ if (!challenge) {
148
+ throw new MetaWebhookVerificationError('Meta webhook: hub.challenge is missing');
149
+ }
150
+ return challenge;
151
+ }
152
+ function constantTimeEquals(a, b) {
153
+ const ab = Buffer.from(a, 'utf8');
154
+ const bb = Buffer.from(b, 'utf8');
155
+ return ab.length === bb.length && timingSafeEqual(ab, bb);
156
+ }
157
+ function isDict(value) {
158
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
159
+ }
160
+ function str(value) {
161
+ if (typeof value === 'string')
162
+ return value;
163
+ if (typeof value === 'number')
164
+ return String(value);
165
+ return undefined;
166
+ }
167
+ /** Meta sends unix seconds; the rest of the package speaks ms. */
168
+ function secondsToMs(value) {
169
+ // `Number('')` is 0, so a blank string must not become the epoch.
170
+ const n = typeof value === 'string' ? (value.trim() ? Number(value) : undefined) : value;
171
+ return typeof n === 'number' && Number.isFinite(n) ? n * 1000 : undefined;
172
+ }
173
+ /**
174
+ * Meta sends `message_template_id` as a bare JSON number. `JSON.parse`
175
+ * rounds anything above `Number.MAX_SAFE_INTEGER` before `str()` can
176
+ * stringify it, so quote long digit runs first. Anchored on the `{` / `,`
177
+ * that precedes a key so an escaped occurrence inside a string value
178
+ * (`\"message_template_id\"`) is never touched.
179
+ */
180
+ const BIG_TEMPLATE_ID = /([{,]\s*"message_template_id"\s*:\s*)(\d{16,})(?=\s*[,}])/g;
181
+ function quoteBigTemplateIds(text) {
182
+ return text.replace(BIG_TEMPLATE_ID, '$1"$2"');
183
+ }
184
+ /**
185
+ * Parse a Meta webhook body into a flat list of typed events.
186
+ *
187
+ * Accepts the raw body (`string` or `Uint8Array` — preferred, it is what
188
+ * you already hold for signature verification) or an already-parsed
189
+ * object. Every `entry[].changes[]` becomes one event; entries with no
190
+ * changes contribute nothing. Throws {@link MetaWebhookPayloadError}
191
+ * only when the envelope itself is malformed.
192
+ */
193
+ export function parseMetaWebhookEvents(body) {
194
+ let envelope = body;
195
+ if (typeof body === 'string' || body instanceof Uint8Array) {
196
+ const text = typeof body === 'string' ? body : Buffer.from(body).toString('utf8');
197
+ try {
198
+ envelope = JSON.parse(quoteBigTemplateIds(text));
199
+ }
200
+ catch (err) {
201
+ throw new MetaWebhookPayloadError(`Meta webhook: body is not valid JSON (${err.message})`);
202
+ }
203
+ }
204
+ if (!isDict(envelope)) {
205
+ throw new MetaWebhookPayloadError('Meta webhook: body is not an object');
206
+ }
207
+ const { entry } = envelope;
208
+ if (!Array.isArray(entry)) {
209
+ throw new MetaWebhookPayloadError('Meta webhook: body has no `entry` array');
210
+ }
211
+ const events = [];
212
+ for (const e of entry) {
213
+ if (!isDict(e)) {
214
+ throw new MetaWebhookPayloadError('Meta webhook: entry is not an object');
215
+ }
216
+ const wabaId = str(e.id) ?? '';
217
+ const occurredAtMs = secondsToMs(e.time);
218
+ const changes = Array.isArray(e.changes) ? e.changes : [];
219
+ for (const change of changes) {
220
+ if (!isDict(change) || typeof change.field !== 'string') {
221
+ throw new MetaWebhookPayloadError('Meta webhook: change is missing `field`');
222
+ }
223
+ events.push(toEvent({ wabaId, occurredAtMs, field: change.field, value: change.value }));
224
+ }
225
+ }
226
+ return events;
227
+ }
228
+ function toEvent(raw) {
229
+ const { wabaId, occurredAtMs, field, value } = raw;
230
+ const unknown = {
231
+ type: 'unknown',
232
+ wabaId,
233
+ occurredAtMs,
234
+ field,
235
+ value,
236
+ };
237
+ if (!isDict(value))
238
+ return unknown;
239
+ const templateId = str(value.message_template_id);
240
+ const templateName = str(value.message_template_name);
241
+ const language = str(value.message_template_language);
242
+ if (!templateId || !templateName || !language)
243
+ return unknown;
244
+ const base = {
245
+ wabaId,
246
+ occurredAtMs,
247
+ templateId,
248
+ templateName,
249
+ language,
250
+ };
251
+ switch (field) {
252
+ case 'template_category_update': {
253
+ const newCategory = str(value.new_category);
254
+ const previousCategory = str(value.previous_category);
255
+ const correctCategory = str(value.correct_category);
256
+ const scheduledAtMs = secondsToMs(value.category_update_timestamp);
257
+ // Completed change: previous → new. The scheduled notice reuses
258
+ // `new_category` for the *current* category, so the presence of
259
+ // `previous_category` is what tells the two apart.
260
+ if (previousCategory && newCategory) {
261
+ return {
262
+ ...base,
263
+ type: 'template_category_changed',
264
+ previousCategory,
265
+ newCategory,
266
+ };
267
+ }
268
+ if (correctCategory && newCategory && scheduledAtMs !== undefined) {
269
+ return {
270
+ ...base,
271
+ type: 'template_category_change_scheduled',
272
+ currentCategory: newCategory,
273
+ correctCategory,
274
+ scheduledAtMs,
275
+ };
276
+ }
277
+ return unknown;
278
+ }
279
+ case 'message_template_status_update': {
280
+ const status = str(value.event);
281
+ if (!status)
282
+ return unknown;
283
+ const event = {
284
+ ...base,
285
+ type: 'template_status_updated',
286
+ status,
287
+ };
288
+ const reason = str(value.reason);
289
+ if (reason)
290
+ event.reason = reason;
291
+ const category = str(value.message_template_category);
292
+ if (category)
293
+ event.category = category;
294
+ if (isDict(value.disable_info)) {
295
+ const disabledAtMs = secondsToMs(value.disable_info.disable_date);
296
+ if (disabledAtMs !== undefined)
297
+ event.disabledAtMs = disabledAtMs;
298
+ }
299
+ if (isDict(value.other_info)) {
300
+ event.info = {
301
+ title: str(value.other_info.title),
302
+ description: str(value.other_info.description),
303
+ };
304
+ }
305
+ if (isDict(value.rejection_info)) {
306
+ event.rejectionInfo = {
307
+ reason: str(value.rejection_info.reason),
308
+ recommendation: str(value.rejection_info.recommendation),
309
+ };
310
+ }
311
+ return event;
312
+ }
313
+ default:
314
+ return unknown;
315
+ }
316
+ }
317
+ // ─── Auto-resolving handler factory ────────────────────────────────
318
+ /**
319
+ * Env var holding the ARN of the Meta App Secret (provisioned by the
320
+ * messaging stack when `whatsapp.webhooks: true`).
321
+ */
322
+ export const WHATSAPP_APP_SECRET_ENV = 'VENTURE_NOTIFY_WHATSAPP_APP_SECRET';
323
+ /**
324
+ * Env var holding the ARN of the webhook verify-token secret
325
+ * (provisioned by the messaging stack when `whatsapp.webhooks: true`).
326
+ */
327
+ export const WHATSAPP_VERIFY_TOKEN_SECRET_ENV = 'VENTURE_NOTIFY_WHATSAPP_VERIFY_TOKEN_SECRET';
328
+ /**
329
+ * Build a webhook handler that resolves the App Secret and verify
330
+ * token automatically from the env vars the VentureKit app stack
331
+ * injects when `whatsapp.webhooks: true` is declared in the notify
332
+ * intent.
333
+ *
334
+ * ```ts
335
+ * const wa = createMetaWhatsAppWebhookHandler(); // zero-arg in prod
336
+ *
337
+ * if (method === 'GET') return text(await wa.handleVerification(query));
338
+ * await wa.verifySignature(rawBody, headers['x-hub-signature-256']);
339
+ * for (const event of wa.parseEvents(rawBody)) { … }
340
+ * ```
341
+ *
342
+ * Both resolvers are lazy and memoised per cold start (same pattern as
343
+ * `createSecretsTokenResolver`), so the Secrets Manager round-trip
344
+ * happens at most once per Lambda lifecycle. Pass explicit resolvers
345
+ * to override — e.g. in tests or when the secrets are not provisioned
346
+ * by VentureKit.
347
+ */
348
+ export function createMetaWhatsAppWebhookHandler(config = {}) {
349
+ const resolveAppSecret = memoise(config.appSecretResolver ?? envSecretResolver(WHATSAPP_APP_SECRET_ENV));
350
+ const resolveVerifyToken = memoise(config.verifyTokenResolver ?? envSecretResolver(WHATSAPP_VERIFY_TOKEN_SECRET_ENV));
351
+ return {
352
+ async verifySignature(rawBody, signature) {
353
+ const appSecret = await resolveAppSecret();
354
+ verifyMetaWebhookSignature({ rawBody, signature, appSecret });
355
+ },
356
+ async handleVerification(query) {
357
+ const verifyToken = await resolveVerifyToken();
358
+ return handleMetaWebhookVerification({ query, verifyToken });
359
+ },
360
+ parseEvents(body) {
361
+ return parseMetaWebhookEvents(body);
362
+ },
363
+ };
364
+ }
365
+ /**
366
+ * Default resolver: read the Secret ARN from `envVar` and fetch it from
367
+ * Secrets Manager. The env var is checked lazily (on first use, not at
368
+ * construction) so a module-level `createMetaWhatsAppWebhookHandler()`
369
+ * never breaks a cold start — but when it *is* missing the error names
370
+ * the env var and the intent flag instead of surfacing as an opaque
371
+ * SDK `ValidationException` for an empty `SecretId`.
372
+ */
373
+ function envSecretResolver(envVar) {
374
+ return async () => {
375
+ const secretArn = process.env[envVar];
376
+ if (!secretArn) {
377
+ throw new ProviderHardError(`Meta webhook: ${envVar} is not set. Declare 'whatsapp.webhooks: true' ` +
378
+ `on the notify intent so the messaging stack provisions the secret ` +
379
+ `and the app stack injects its ARN, or pass an explicit resolver to ` +
380
+ `createMetaWhatsAppWebhookHandler().`);
381
+ }
382
+ return createSecretsTokenResolver({ secretArn })();
383
+ };
384
+ }
385
+ /**
386
+ * Memoise per cold start so a custom resolver (not just the default
387
+ * Secrets Manager one) is also called at most once per Lambda life.
388
+ * The in-flight promise is cached — not the value — so concurrent first
389
+ * requests (Express-style hosts) share one fetch; a rejection clears the
390
+ * slot so a transient Secrets Manager failure does not poison the
391
+ * instance.
392
+ */
393
+ function memoise(resolve) {
394
+ let pending = null;
395
+ return () => {
396
+ if (!pending) {
397
+ pending = resolve().catch((err) => {
398
+ pending = null;
399
+ throw err;
400
+ });
401
+ }
402
+ return pending;
403
+ };
404
+ }
405
+ //# sourceMappingURL=whatsapp-meta-webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whatsapp-meta-webhook.js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AW,CAAC,IAAI;YACd,OAAO,sBAAsB,CAAC,IAAI,CAAC,CAAC;QACtC,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,iBAAiB,CAAC,MAAc;IACvC,OAAO,KAAK,IAAI,EAAE;QAChB,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACtC,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,IAAI,iBAAiB,CACzB,iBAAiB,MAAM,iDAAiD;gBACtE,oEAAoE;gBACpE,qEAAqE;gBACrE,qCAAqC,CACxC,CAAC;QACJ,CAAC;QACD,OAAO,0BAA0B,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC;IACrD,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,OAAO,CAAC,OAA8B;IAC7C,IAAI,OAAO,GAA2B,IAAI,CAAC;IAC3C,OAAO,GAAG,EAAE;QACV,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;gBACzC,OAAO,GAAG,IAAI,CAAC;gBACf,MAAM,GAAG,CAAC;YACZ,CAAC,CAAC,CAAC;QACL,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venturekit/notify",
3
- "version": "0.0.29",
3
+ "version": "0.0.30",
4
4
  "description": "Transactional notifications for VentureKit — email (SES), WhatsApp (Meta Cloud), with a Postgres outbox + cron dispatcher.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -52,6 +52,14 @@
52
52
  "types": "./dist/providers/whatsapp-meta.d.ts",
53
53
  "import": "./dist/providers/whatsapp-meta.js"
54
54
  },
55
+ "./providers/whatsapp-meta-webhook": {
56
+ "types": "./dist/providers/whatsapp-meta-webhook.d.ts",
57
+ "import": "./dist/providers/whatsapp-meta-webhook.js"
58
+ },
59
+ "./providers/whatsapp-meta-language": {
60
+ "types": "./dist/providers/whatsapp-meta-language.d.ts",
61
+ "import": "./dist/providers/whatsapp-meta-language.js"
62
+ },
55
63
  "./store/postgres": {
56
64
  "types": "./dist/store/postgres.d.ts",
57
65
  "import": "./dist/store/postgres.js"
@@ -76,13 +84,13 @@
76
84
  "outbox"
77
85
  ],
78
86
  "dependencies": {
79
- "@venturekit/core": "0.0.29"
87
+ "@venturekit/core": "0.0.30"
80
88
  },
81
89
  "peerDependencies": {
82
- "@venturekit/data": "0.0.29",
83
- "@venturekit/runtime": "0.0.29",
84
- "@aws-sdk/client-sesv2": "^3.1091.0",
85
- "@aws-sdk/client-secrets-manager": "^3.1091.0"
90
+ "@venturekit/data": "0.0.30",
91
+ "@venturekit/runtime": "0.0.30",
92
+ "@aws-sdk/client-sesv2": "^3.1126.0",
93
+ "@aws-sdk/client-secrets-manager": "^3.1126.0"
86
94
  },
87
95
  "peerDependenciesMeta": {
88
96
  "@venturekit/data": {
@@ -99,10 +107,10 @@
99
107
  }
100
108
  },
101
109
  "devDependencies": {
102
- "@venturekit/data": "0.0.29",
103
- "@venturekit/runtime": "0.0.29",
104
- "@aws-sdk/client-sesv2": "^3.1091.0",
105
- "@aws-sdk/client-secrets-manager": "^3.1091.0",
110
+ "@venturekit/data": "0.0.30",
111
+ "@venturekit/runtime": "0.0.30",
112
+ "@aws-sdk/client-sesv2": "^3.1126.0",
113
+ "@aws-sdk/client-secrets-manager": "^3.1126.0",
106
114
  "@types/aws-lambda": "^8.10.131",
107
115
  "@types/node": "^26.1.2",
108
116
  "typescript": "^5.3.0",