meta-cloud-api 0.2.23 → 0.2.25
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/{chunk-EYGUX4EA.js → chunk-2NCV35XS.js} +2 -2
- package/dist/{chunk-EYGUX4EA.js.map → chunk-2NCV35XS.js.map} +1 -1
- package/dist/chunk-M2GC5VFJ.js +2 -0
- package/dist/{chunk-4C666HHU.js.map → chunk-M2GC5VFJ.js.map} +1 -1
- package/dist/{chunk-BSNA6RYF.js → chunk-XQDM2WBV.js} +3 -3
- package/dist/{chunk-BSNA6RYF.js.map → chunk-XQDM2WBV.js.map} +1 -1
- package/dist/chunk-ZJV5NIQ7.js +3 -0
- package/dist/chunk-ZJV5NIQ7.js.map +1 -0
- package/dist/core/webhook/index.d.ts +328 -74
- package/dist/core/webhook/index.js +1 -1
- package/dist/core/whatsapp/index.js +1 -1
- package/dist/features/encryption/index.js +1 -1
- package/dist/features/flow/index.js +1 -1
- package/dist/features/media/index.js +1 -1
- package/dist/features/messages/index.js +1 -1
- package/dist/features/phone/index.js +1 -1
- package/dist/features/profile/index.js +1 -1
- package/dist/features/qrCode/index.js +1 -1
- package/dist/features/registration/index.js +1 -1
- package/dist/features/template/index.js +1 -1
- package/dist/features/twoStepVerification/index.js +1 -1
- package/dist/features/waba/index.js +1 -1
- package/dist/index.d.ts +7 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/shared/types/enums.js +1 -1
- package/dist/shared/utils/isMetaError.js +1 -1
- package/package.json +43 -1
- package/dist/chunk-4C666HHU.js +0 -2
- package/dist/chunk-ADHNXDTF.js +0 -3
- package/dist/chunk-ADHNXDTF.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/webhook/types.ts","../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts","../src/core/webhook/adapters/expressAdapter.ts","../src/core/webhook/adapters/fastifyAdapter.ts","../src/core/webhook/adapters/nestjsAdapter.ts","../src/core/webhook/adapters/nextjsApiRouteAdapter.ts","../src/core/webhook/adapters/nextjsRouteHandlerAdapter.ts"],"names":["MessageStatus","EventField","isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","verifyWebhook","verificationToken","mode","token","challenge","processWebhookMessages","whatsapp","handlers","body","errors","errorMsg","entry","changes","change","processMessages","processStatuses","processEvent","error","processFlowRequest","config","flowHandlers","isRequestSignatureValid","decryptedBody","decryptFlowRequest","handler","result","encryptFlowResponse","metadata","displayPhoneNumber","phoneNumberId","profileName","messages","message","messageType","processedMessage","getMessageTypeData","executeHandler","statuses","statusHandlers","status","processedStatus","typeData","handlerType","field","eventHandlers","event","signature","formattedExpectedSignature","crypto","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","type","generateXHub256Sig","appSecret","G","fromExpressRequest","req","toExpressResponse","webhookResponse","res","key","createExpressAdapter","webhookRequest","fromFastifyRequest","toFastifyReply","reply","createFastifyAdapter","fromNestJSRequest","toNestJSResponse","WebhookReq","createParamDecorator","ctx","_WebhookResponseInterceptor_decorators","_init","Injectable","WebhookResponseInterceptor","context","next","map","__decoratorStart","__decorateElement","__runInitializers","createNestJSAdapter","target","propertyName","descriptor","method","args","arg","fromNextJSRequest","toNextJSResponse","createNextJSAdapter","fromRouteHandlerRequest","searchParams","toRouteHandlerResponse","headers","createNextJSRouteHandlerAdapter","text"],"mappings":"oSAqpBYA,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AAA,CAAAA,CAAI,OAAQ,CAAA,YAAA,CAC3BM,CAAiB8B,CAAAA,CAAAA,CAAwBpC,CAAKqC,CAAAA,CAAY,CAC1DnC,CAAAA,CAAAA,CAAkBvE,CAAS,CAAA,YAAA,CAAa2E,CAAc,CAAA,CAC5D,OAAOgC,CAAAA,CAAuBpC,CAAe,CACjD,CAEA,CAAA,IAAA,CAAM,MAAOF,CAAAA,EAAiB,CAC1B,GAAI,CACA,IAAMM,CAAiB8B,CAAAA,CAAAA,CAAwBpC,CAAG,CAAA,CAKlD,GAFoBA,CAAAA,CAAAA,CAAI,OAAQ,CAAA,GAAA,CAAI,cAAc,CAAA,EAAK,EAEvC,EAAA,QAAA,CAAS,kBAAkB,CAAA,CACvCM,CAAe,CAAA,IAAA,CAAO,MAAMN,CAAAA,CAAI,IAAK,EAAA,CACrCM,CAAe,CAAA,OAAA,CAAU,IAAK,CAAA,SAAA,CAAUA,CAAe,CAAA,IAAI,CACxD,CAAA,KAAA,CACH,IAAMmC,CAAAA,CAAO,MAAMzC,CAAAA,CAAI,IAAK,EAAA,CAC5BM,CAAe,CAAA,OAAA,CAAUmC,CACzBnC,CAAAA,CAAAA,CAAe,IAAOmC,CAAAA,EAC1B,CAEA,IAAMvC,CAAkB,CAAA,MAAMvE,CAAS,CAAA,OAAA,CAAQ2E,CAAc,CAAA,CAC7D,OAAOgC,CAAAA,CAAuBpC,CAAe,CACjD,CAAgB,KAAA,CACZ,OAAO,IAAI,QAAS,CAAA,IAAA,CAAK,SAAU,CAAA,CAAE,KAAO,CAAA,uBAAwB,CAAC,CAAA,CAAG,CACpE,MAAA,CAAQ,GACR,CAAA,OAAA,CAAS,CAAE,cAAA,CAAgB,kBAAmB,CAClD,CAAC,CACL,CACJ,CACJ,EAER,CACJ","file":"chunk-ZJV5NIQ7.js","sourcesContent":["import { MessageTypesEnum } from '@shared/types/enums';\n\nexport interface WebhookContact {\n /**\n * WhatsApp ID of the contact. Business can respond to this contact using this ID.\n */\n wa_id: string;\n /**\n * Additional unique, alphanumeric identifier for a WhatsApp user\n */\n user_id?: string;\n /**\n * Profile of Whatsapp user\n */\n profile: {\n /**\n * The display name of the contact\n */\n name: string;\n };\n}\n\n/**\n * Represents a message received through the webhook\n * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#messages-object\n */\nexport interface WebhookMessage {\n /**\n * The message ID\n */\n id: string;\n\n /**\n * The sender's phone number\n */\n from: string;\n\n /**\n * The timestamp of the message\n */\n timestamp: string;\n\n /**\n * The type of message (text, image, etc.)\n */\n type: MessageTypesEnum;\n\n /**\n * The phone number ID that received the message\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the message\n */\n displayPhoneNumber: string;\n\n /**\n * The profile name of the sender\n */\n profileName: string;\n\n /**\n * Text object for text messages\n */\n text?: {\n /**\n * The text content of the message\n */\n body: string;\n };\n\n /**\n * Image object for image messages\n */\n image?: {\n /**\n * The image caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the image\n */\n sha256?: string;\n /**\n * The ID for the image\n */\n id: string;\n /**\n * The MIME type of the image\n */\n mime_type: string;\n };\n\n /**\n * Video object for video messages\n */\n video?: {\n /**\n * The video caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the video\n */\n sha256?: string;\n /**\n * The ID for the video\n */\n id: string;\n /**\n * The MIME type of the video\n */\n mime_type: string;\n };\n\n /**\n * Audio object for audio messages\n */\n audio?: {\n /**\n * The ID for the audio file\n */\n id: string;\n /**\n * The MIME type of the audio file\n */\n mime_type: string;\n /**\n * Whether the audio is a voice message\n */\n voice?: boolean;\n };\n\n /**\n * Document object for document messages\n */\n document?: {\n /**\n * The document caption (if provided)\n */\n caption?: string;\n /**\n * The document filename\n */\n filename: string;\n /**\n * The SHA256 hash of the document\n */\n sha256?: string;\n /**\n * The ID for the document\n */\n id: string;\n /**\n * The MIME type of the document\n */\n mime_type: string;\n };\n\n /**\n * Sticker object for sticker messages\n */\n sticker?: {\n /**\n * The ID for the sticker\n */\n id: string;\n /**\n * Whether this is an animated sticker\n */\n animated: boolean;\n /**\n * The MIME type of the sticker\n */\n mime_type: string;\n };\n\n /**\n * Reaction object for reaction messages\n */\n reaction?: {\n /**\n * The ID of the message being reacted to\n */\n message_id: string;\n /**\n * Emoji used for the reaction\n */\n emoji: string;\n };\n\n /**\n * Contacts object for contact messages\n */\n contacts?: Array<{\n /**\n * The contact's name\n */\n name: {\n /**\n * The formatted name\n */\n formatted_name: string;\n /**\n * The first name\n */\n first_name?: string;\n /**\n * The last name\n */\n last_name?: string;\n /**\n * The middle name\n */\n middle_name?: string;\n /**\n * The suffix\n */\n suffix?: string;\n /**\n * The prefix\n */\n prefix?: string;\n };\n /**\n * The contact's phone numbers\n */\n phones?: Array<{\n phone: string;\n type?: string;\n wa_id?: string;\n }>;\n /**\n * The contact's emails\n */\n emails?: Array<{\n email: string;\n type?: string;\n }>;\n /**\n * The contact's addresses\n */\n addresses?: Array<{\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n country?: string;\n country_code?: string;\n type?: string;\n }>;\n /**\n * The contact's organizations\n */\n org?: {\n company?: string;\n department?: string;\n title?: string;\n };\n /**\n * The contact's URLs\n */\n urls?: Array<{\n url: string;\n type?: string;\n }>;\n /**\n * The contact's birthday (YYYY-MM-DD format)\n */\n birthday?: string;\n }>;\n\n /**\n * Location object for location messages\n */\n location?: {\n /**\n * Latitude of the location\n */\n latitude: number;\n /**\n * Longitude of the location\n */\n longitude: number;\n /**\n * Name of the location\n */\n name?: string;\n /**\n * Address of the location\n */\n address?: string;\n };\n\n /**\n * Interactive object for interactive messages\n */\n interactive?: {\n /**\n * Type of the interactive message\n * Can be: button_reply, list_reply, flow, nfm_reply, etc.\n */\n type: string;\n /**\n * ID for the button that was clicked\n */\n button_reply?: {\n id: string;\n title: string;\n };\n /**\n * ID for the list item that was selected\n */\n list_reply?: {\n id: string;\n title: string;\n description?: string;\n };\n\n /**\n * NFM (No-Code Flow Message) reply data\n */\n nfm_reply?: {\n /**\n * Response data in JSON format\n */\n response_json: string;\n /**\n * Body text of the reply\n */\n body: string;\n /**\n * Name of the flow\n */\n name: string;\n };\n };\n\n /**\n * System object for system messages (like user phone number changes)\n */\n system?: {\n /**\n * The type of system update\n */\n type: string;\n /**\n * User's identity if the update is a customer identity change\n */\n identity?: string;\n /**\n * Old and new phone numbers if the update is a phone number change\n */\n customer?: {\n /**\n * The previous phone number\n */\n previous_wa_id: string;\n /**\n * The new phone number\n */\n wa_id: string;\n };\n };\n\n /**\n * Order object for order messages\n */\n order?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product items in the order\n */\n product_items: Array<{\n /**\n * Product ID\n */\n product_retailer_id: string;\n /**\n * Quantity of the product\n */\n quantity: number;\n /**\n * Item price\n */\n item_price: number;\n /**\n * Currency code\n */\n currency: string;\n }>;\n /**\n * Text message included with the order\n */\n text?: string;\n };\n\n /**\n * Context object, included when a user replies or interacts\n */\n context?: {\n /**\n * ID of the message\n */\n id?: string;\n /**\n * ID of the sender\n */\n from?: string;\n /**\n * ID of the message being replied to or interacted with\n */\n message_id: string;\n /**\n * ID of the forwarded message, if applicable\n */\n forwarded?: boolean;\n /**\n * Frequently forwarded status\n */\n frequently_forwarded?: boolean;\n /**\n * Original message information if the message was referred\n */\n referred_product?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product ID\n */\n product_retailer_id: string;\n };\n };\n\n /**\n * Errors array, if the message had errors\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error title\n */\n title: string;\n /**\n * Error message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * Button object for button messages\n */\n button?: {\n /**\n * The payload for the button\n */\n payload: string;\n /**\n * Button text\n */\n text: string;\n };\n\n /**\n * The original message data as received from the webhook\n */\n originalData: any;\n}\n\n/**\n * Represents a message status update received through the webhook\n * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#statuses-object\n */\nexport interface WebhookMessageStatus {\n /**\n * The phone number ID that received the status update\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the status update\n */\n displayPhoneNumber: string;\n\n /**\n * Arbitrary string included in sent message\n */\n biz_opaque_callback_data?: string;\n\n /**\n * Information about the conversation\n */\n conversation?: {\n /**\n * Represents the ID of the conversation the given status notification belongs to\n */\n id: string;\n /**\n * Describes conversation category\n */\n origin: {\n /**\n * Indicates conversation category. This can also be referred to as a conversation entry point\n * - authentication: Conversation opened by business sending template categorized as AUTHENTICATION\n * - marketing: Conversation opened by business sending template categorized as MARKETING\n * - utility: Conversation opened by business sending template categorized as UTILITY\n * - service: Conversation opened by business replying to customer within service window\n * - referral_conversion: Free entry point conversation\n */\n type: 'authentication' | 'marketing' | 'utility' | 'service' | 'referral_conversion';\n };\n /**\n * Date when the conversation expires. Only present for messages with status 'sent'\n */\n expiration_timestamp?: string;\n };\n\n /**\n * Array of error objects describing the error\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error code title\n */\n title: string;\n /**\n * Error code message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * The ID for the message that the business sent to a customer\n */\n id: string;\n\n /**\n * Pricing information for the message/conversation\n */\n pricing?: {\n /**\n * Indicates if the given message or conversation is billable\n * @deprecated This field is deprecated. Visit the WhatsApp Changelog for more information.\n */\n billable?: boolean;\n /**\n * Indicates the conversation category:\n * - authentication: Authentication conversation\n * - authentication_international: Authentication-international conversation\n * - marketing: Marketing conversation\n * - utility: Utility conversation\n * - service: Service conversation\n * - referral_conversion: Free entry point conversation\n */\n category:\n | 'authentication'\n | 'authentication_international'\n | 'marketing'\n | 'utility'\n | 'service'\n | 'referral_conversion';\n /**\n * Type of pricing model used by the business. Current supported value is CBP\n */\n pricing_model: 'CBP';\n };\n\n /**\n * The customer's WhatsApp ID. Business can respond to customer using this ID.\n * This ID may not match the customer's phone number.\n */\n recipient_id: string;\n\n /**\n * Status of the message:\n * - delivered: Message has been delivered\n * - read: Message has been read by the customer\n * - sent: Message has been sent to the customer\n */\n status: 'delivered' | 'read' | 'sent';\n\n /**\n * Unix timestamp for the status message\n */\n timestamp: string;\n\n /**\n * The original status data as received from the webhook\n */\n originalData: any;\n}\n\n/**\n * Webhook event received from WhatsApp\n */\nexport interface WebhookEvent {\n /**\n * The field type of the event\n */\n field: string;\n\n /**\n * The event data\n */\n value: any;\n\n /**\n * The timestamp when the event was received\n */\n timestamp: number;\n}\n\n/**\n * Message handler function type\n */\nexport type MessageHandler = (message: WebhookMessage) => void | Promise<void>;\n\n/**\n * Event handler function type\n */\nexport type EventHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * Status handler function type\n */\nexport type StatusHandler = (statuses: WebhookMessageStatus[]) => void | Promise<void>;\n\n/**\n * Message status enum\n */\nexport enum MessageStatus {\n DELIVERED = 'delivered',\n READ = 'read',\n SENT = 'sent',\n}\n\n/**\n * Event field enum for webhook events\n */\nexport enum EventField {\n MESSAGES = 'messages',\n STATUSES = 'statuses',\n MESSAGE_TEMPLATE_STATUS_UPDATE = 'message_template_status_update',\n PHONE_NUMBER_QUALITY_UPDATE = 'phone_number_quality_update',\n PHONE_NUMBER_NAME_UPDATE = 'phone_number_name_update',\n UNKNOWN = 'unknown',\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { EventField, MessageStatus, WebhookEvent, WebhookMessage, WebhookMessageStatus } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n// Framework-agnostic request/response types\nexport interface WebhookRequest {\n method: string;\n query: Record<string, any>;\n body: any;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: string;\n}\n\nexport interface WebhookResponse {\n statusCode: number;\n body?: any;\n headers?: Record<string, string>;\n}\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type EventHandler = (event: WebhookEvent) => void | Promise<void>;\nexport type StatusHandler = (whatsapp: WhatsApp, statuses: WebhookMessageStatus) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Pure function to handle webhook verification\n */\nexport function verifyWebhook(request: WebhookRequest, verificationToken: string): WebhookResponse {\n const mode = request.query['hub.mode'];\n const token = request.query['hub.verify_token'];\n const challenge = request.query['hub.challenge'];\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === verificationToken;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n return {\n statusCode: 200,\n body: challenge,\n };\n } else {\n LOGGER.log('Webhook verification failed');\n return {\n statusCode: 403,\n };\n }\n}\n\n/**\n * Pure function to process webhook messages\n */\nexport async function processWebhookMessages(\n request: WebhookRequest,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n eventHandlers: Map<string, EventHandler>;\n statusHandlers?: Map<MessageStatus, StatusHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<WebhookResponse> {\n const body = request.body;\n const errors: string[] = [];\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return {\n statusCode: 404,\n body: { error: errorMsg },\n };\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === EventField.MESSAGES) {\n await processMessages(change.value, whatsapp, handlers);\n\n // Process statuses if they exist\n if (change.value.statuses && handlers.statusHandlers) {\n await processStatuses(\n change.value.statuses,\n change.value.metadata,\n whatsapp,\n handlers.statusHandlers,\n );\n }\n } else {\n await processEvent(change.field, change.value, handlers.eventHandlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return {\n statusCode: 200,\n body: errors.length > 0 ? { errors } : undefined,\n };\n}\n\n/**\n * Pure function to handle flow requests\n */\nexport async function processFlowRequest(\n request: WebhookRequest,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<WebhookResponse> {\n try {\n // Validate request signature\n if (!isRequestSignatureValid(request, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return {\n statusCode: 401,\n body: { error: 'Unauthorized' },\n };\n }\n\n const body = JSON.parse(request.rawBody || '{}');\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(body, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return {\n statusCode: 404,\n body: { error: 'Handler not found' },\n };\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return {\n statusCode: 200,\n body: {\n version: '3.0',\n data: { status: 'active' },\n },\n };\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 200,\n body: {},\n };\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n return {\n statusCode: 200,\n body: encryptedResponse,\n };\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 400,\n body: { error: 'Unknown request type' },\n };\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return {\n statusCode: 500,\n body: { error: 'Internal server error' },\n };\n }\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n value: any,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n const profileName = value.contacts[0]?.profile?.name || '';\n const messages = value.messages as WebhookMessage[];\n\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n // Add type-specific data\n Object.assign(processedMessage, getMessageTypeData(message));\n\n // Add context and errors if available\n if (message.context) processedMessage.context = message.context;\n if (message.errors) processedMessage.errors = message.errors;\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function processStatuses(\n statuses: any[],\n metadata: any,\n whatsapp: WhatsApp,\n statusHandlers: Map<MessageStatus, StatusHandler>,\n): Promise<void> {\n if (statuses && statuses.length > 0) {\n for (const status of statuses) {\n const processedStatus: WebhookMessageStatus = {\n phoneNumberId: metadata.phone_number_id,\n displayPhoneNumber: metadata.display_phone_number,\n id: status.id,\n status: status.status,\n timestamp: status.timestamp,\n recipient_id: status.recipient_id,\n conversation: status.conversation,\n pricing: status.pricing,\n biz_opaque_callback_data: status.biz_opaque_callback_data,\n errors: status.errors,\n originalData: status,\n };\n\n const handler = statusHandlers.get(status.status as MessageStatus);\n if (handler) {\n try {\n await handler(whatsapp, processedStatus);\n } catch (error) {\n LOGGER.log(`Error in status handler for ${status.status}: ${error}`);\n }\n }\n }\n }\n}\n\nfunction getMessageTypeData(message: any): Partial<WebhookMessage> {\n const typeData: Partial<WebhookMessage> = {};\n\n switch (message.type) {\n case MessageTypesEnum.Text:\n typeData.text = message.text;\n break;\n case MessageTypesEnum.Image:\n typeData.image = message.image;\n break;\n case MessageTypesEnum.Video:\n typeData.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n typeData.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n typeData.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n typeData.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n typeData.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n typeData.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n typeData.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n typeData.button = message.button;\n break;\n case MessageTypesEnum.Order:\n typeData.order = message.order;\n break;\n case MessageTypesEnum.System:\n typeData.system = message.system;\n break;\n }\n\n return typeData;\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nasync function processEvent(field: string, value: any, eventHandlers: Map<string, EventHandler>): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n timestamp: Date.now(),\n };\n\n const handler = eventHandlers.get(field);\n if (handler) {\n try {\n await handler(event);\n } catch (error) {\n LOGGER.log(`Error in event handler for ${field}: ${error}`);\n }\n }\n}\n\nfunction isRequestSignatureValid(request: WebhookRequest, verificationToken: string): boolean {\n const signature = request.headers['x-hub-signature-256'] as string;\n if (!signature || !request.rawBody) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', verificationToken)\n .update(request.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport Logger from '@shared/utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport {\n EventHandler,\n FlowHandler,\n MessageHandler,\n processFlowRequest,\n processWebhookMessages,\n StatusHandler,\n verifyWebhook,\n WebhookRequest,\n WebhookResponse,\n} from './utils/webhookUtils';\nimport { MessageStatus } from './types';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Framework-agnostic WebhookHandler using pure functions\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private statusHandlers: Map<MessageStatus, StatusHandler> = new Map();\n private eventHandlers: Map<string, EventHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook verification (framework-agnostic)\n */\n public handleVerification = (request: WebhookRequest): WebhookResponse => {\n return verifyWebhook(request, this.config.WEBHOOK_VERIFICATION_TOKEN || '');\n };\n\n /**\n * Handle webhook messages (framework-agnostic)\n */\n public handleWebhook = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n eventHandlers: this.eventHandlers,\n statusHandlers: this.statusHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n };\n\n /**\n * Handle flow requests (framework-agnostic)\n */\n public handleFlow = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n };\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a status handler for a specific status type\n */\n public onStatus(type: MessageStatus, handler: StatusHandler): void {\n this.statusHandlers.set(type, handler);\n LOGGER.log(`Registered status handler`);\n }\n\n /**\n * Register an event handler for a specific field\n */\n public onEvent(field: string, handler: EventHandler): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered event handler for ${field}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n /**\n * Get the WhatsApp client instance\n */\n public getClient(): WhatsApp {\n return this.client;\n }\n\n /**\n * Get the configuration\n */\n public getConfig(): WabaConfigType {\n return this.config;\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","import { Request, Response } from 'express';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Express request to framework-agnostic request\n */\nfunction fromExpressRequest(req: Request): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Express response\n */\nfunction toExpressResponse(webhookResponse: WebhookResponse, res: Response): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Create Express.js adapter for webhook handlers\n */\nexport function createExpressAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: Request, res: Response) => {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { FastifyReply, FastifyRequest } from 'fastify';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Fastify request to framework-agnostic request\n */\nfunction fromFastifyRequest(req: FastifyRequest): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Fastify reply\n */\nasync function toFastifyReply(webhookResponse: WebhookResponse, reply: FastifyReply): Promise<void> {\n reply.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n reply.header(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n return reply.send(webhookResponse.body);\n } else {\n return reply.send();\n }\n}\n\n/**\n * Create Fastify adapter for webhook handlers\n */\nexport function createFastifyAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = await handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = await handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } else {\n return reply.status(405).send({ error: 'Method not allowed' });\n }\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { CallHandler, createParamDecorator, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert NestJS request to framework-agnostic request\n */\nfunction fromNestJSRequest(req: Request): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to NestJS response\n */\nfunction toNestJSResponse(webhookResponse: WebhookResponse, res: Response): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Custom parameter decorator to inject WebhookRequest\n */\nexport const WebhookReq = createParamDecorator((data: unknown, ctx: ExecutionContext): WebhookRequest => {\n const request = ctx.switchToHttp().getRequest<Request>();\n return fromNestJSRequest(request);\n});\n\n/**\n * Interceptor to handle WebhookResponse conversion\n */\n@Injectable()\nexport class WebhookResponseInterceptor implements NestInterceptor<WebhookResponse, void> {\n intercept(context: ExecutionContext, next: CallHandler<WebhookResponse>): Observable<void> {\n const response = context.switchToHttp().getResponse<Response>();\n\n return next.handle().pipe(\n map((webhookResponse: WebhookResponse) => {\n toNestJSResponse(webhookResponse, response);\n return;\n }),\n );\n }\n}\n\n/**\n * Create NestJS adapter for webhook handlers\n */\nexport function createNestJSAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: Request, res: Response) => {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Create controller method decorator for webhook verification\n */\n createVerificationHandler: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (target: any, propertyName: string, descriptor: PropertyDescriptor) => {\n const method = descriptor.value;\n descriptor.value = function (...args: any[]) {\n const context = args.find((arg) => arg && arg.switchToHttp) as ExecutionContext;\n if (context) {\n const request = context.switchToHttp().getRequest<Request>();\n const response = context.switchToHttp().getResponse<Response>();\n const webhookRequest = fromNestJSRequest(request);\n const webhookResponse = handler(webhookRequest);\n toNestJSResponse(webhookResponse, response);\n return;\n }\n return method.apply(this, args);\n };\n };\n },\n\n /**\n * Create controller method decorator for webhook POST handling\n */\n createWebhookHandler: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return (target: any, propertyName: string, descriptor: PropertyDescriptor) => {\n const method = descriptor.value;\n descriptor.value = async function (...args: any[]) {\n const context = args.find((arg) => arg && arg.switchToHttp) as ExecutionContext;\n if (context) {\n try {\n const request = context.switchToHttp().getRequest<Request>();\n const response = context.switchToHttp().getResponse<Response>();\n const webhookRequest = fromNestJSRequest(request);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, response);\n return;\n } catch (error) {\n const response = context.switchToHttp().getResponse<Response>();\n response.status(500).json({ error: 'Internal server error' });\n return;\n }\n }\n return method.apply(this, args);\n };\n };\n },\n };\n}\n","import { NextApiRequest, NextApiResponse } from 'next';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Next.js request to framework-agnostic request\n */\nfunction fromNextJSRequest(req: NextApiRequest): WebhookRequest {\n return {\n method: req.method || 'GET',\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Next.js response\n */\nfunction toNextJSResponse(webhookResponse: WebhookResponse, res: NextApiResponse): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Create Next.js Pages Router adapter for webhook handlers\n * For App Router, use createNextJSRouteHandlerAdapter instead\n */\nexport function createNextJSAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: NextApiRequest, res: NextApiResponse) => {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { NextRequest } from 'next/server';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Route Handler request to framework-agnostic request\n */\nfunction fromRouteHandlerRequest(req: Request, searchParams?: URLSearchParams): WebhookRequest {\n return {\n method: req.method || 'GET',\n query: searchParams ? Object.fromEntries(searchParams.entries()) : {},\n body: undefined, // Will be populated when body is read\n headers: Object.fromEntries(req.headers.entries()),\n rawBody: undefined, // Will be populated when body is read\n };\n}\n\n/**\n * Apply framework-agnostic response to Route Handler response\n */\nfunction toRouteHandlerResponse(webhookResponse: WebhookResponse): Response {\n const headers = new Headers();\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n return new Response(webhookResponse.body, {\n status: webhookResponse.statusCode,\n headers,\n });\n } else {\n headers.set('Content-Type', 'application/json');\n return new Response(JSON.stringify(webhookResponse.body), {\n status: webhookResponse.statusCode,\n headers,\n });\n }\n } else {\n return new Response(null, {\n status: webhookResponse.statusCode,\n headers,\n });\n }\n}\n\n/**\n * Create Next.js Route Handler adapter for webhook handlers\n */\nexport function createNextJSRouteHandlerAdapter() {\n return {\n /**\n * Handle webhook verification requests (GET)\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: NextRequest) => {\n const searchParams = req.nextUrl.searchParams;\n const webhookRequest = fromRouteHandlerRequest(req, searchParams);\n const webhookResponse = handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n if (req.method === 'POST') {\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n }\n\n const webhookResponse = await handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n if (req.method === 'POST') {\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n }\n\n const webhookResponse = await handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n },\n\n /**\n * Universal handler that creates separate GET and POST handlers\n * Usage: export const { GET, POST } = adapter.createHandlers({ verification, webhook })\n */\n createHandlers: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return {\n GET: (req: NextRequest) => {\n const searchParams = req.nextUrl.searchParams;\n const webhookRequest = fromRouteHandlerRequest(req, searchParams);\n const webhookResponse = handlers.verification(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n },\n\n POST: async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n\n const webhookResponse = await handlers.webhook(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n };\n },\n };\n}\n"]}
|