@zerodot/whatsapp 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1147 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let zod = require("zod");
3
+ let _zerodot_node_sdk = require("@zerodot/node-sdk");
4
+ let node_crypto = require("node:crypto");
5
+ // src/api.ts
6
+ const WHATSAPP_CREDENTIAL = "whatsapp.api";
7
+ const WHATSAPP_TRIGGER_CREDENTIAL = "whatsapp.trigger";
8
+ const GRAPH_URL = "https://graph.facebook.com";
9
+ const DEFAULT_VERSION = "v23.0";
10
+ /** The version for the app calls: the app token and the webhook subscriptions. */
11
+ const APP_VERSION = "v19.0";
12
+ /** The access token and the business account ID of a credential. */
13
+ function whatsappAccess(credential) {
14
+ if (!credential || credential.type !== "whatsapp.api") throw new Error("The node needs a WhatsApp credential");
15
+ const { accessToken, businessAccountId } = credential.data;
16
+ if (typeof accessToken !== "string" || accessToken === "") throw new Error("The credential has no \"accessToken\"");
17
+ return {
18
+ accessToken,
19
+ businessAccountId: typeof businessAccountId === "string" ? businessAccountId : ""
20
+ };
21
+ }
22
+ /** The app ID and the app secret of a trigger credential. */
23
+ function whatsappAppAccess(credential) {
24
+ if (!credential || credential.type !== "whatsapp.trigger") throw new Error("The trigger needs a WhatsApp trigger credential");
25
+ const { appId, appSecret } = credential.data;
26
+ if (typeof appId !== "string" || appId === "") throw new Error("The credential has no \"appId\"");
27
+ if (typeof appSecret !== "string" || appSecret === "") throw new Error("The credential has no \"appSecret\"");
28
+ return {
29
+ appId,
30
+ appSecret
31
+ };
32
+ }
33
+ /** The ID part of a path. It cannot add a path segment. */
34
+ const segment = (value) => {
35
+ const trimmed = value.trim();
36
+ if (trimmed === "" || trimmed === "." || trimmed === "..") throw new Error("An ID of the WhatsApp API is empty or not valid");
37
+ return encodeURIComponent(trimmed);
38
+ };
39
+ /** An error that the API gave. */
40
+ var WhatsAppError = class extends Error {
41
+ status;
42
+ code;
43
+ constructor(message, status, code) {
44
+ super(message);
45
+ this.name = "WhatsAppError";
46
+ this.status = status;
47
+ this.code = code;
48
+ }
49
+ };
50
+ const SEND_FAILED = "Sending failed. If you send to a new test number, send a message to it from the Meta developer portal first";
51
+ /**
52
+ * The error for a failed call. The messages of the two most common input errors name the
53
+ * message type. The text never has the token.
54
+ */
55
+ function whatsappErrorOf(label, status, answer, messageType = "media") {
56
+ const problem = answer?.error;
57
+ const code = String(problem?.code ?? "no_answer");
58
+ if (status === 500) return new WhatsAppError(`${label} failed (500). ${SEND_FAILED}`, status, code);
59
+ const text = (problem?.message ?? "").replace(/^\(#\d+\) /, "");
60
+ if (status === 400 && text.endsWith("is not a valid whatsapp business account media attachment ID")) return new WhatsAppError(`Invalid ${messageType} ID. ${text}`, status, code);
61
+ if (status === 400 && text.endsWith("is not a valid URI.")) return new WhatsAppError(`Invalid ${messageType} URL. ${text}`, status, code);
62
+ const parts = [`${label} failed (${status})`];
63
+ if (text) parts.push(text);
64
+ if (problem?.error_user_msg) parts.push(problem.error_user_msg);
65
+ return new WhatsAppError(parts.join(". "), status, code);
66
+ }
67
+ const signalOf = (signal, timeoutMs) => AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
68
+ async function parse(response) {
69
+ return await response.json().catch(() => null);
70
+ }
71
+ /** One call to the Cloud API. The token goes in a header, never in the URL. */
72
+ async function callWhatsApp(access, request, options, form) {
73
+ const url = new URL(`${GRAPH_URL}/${options.version}${request.path}`);
74
+ for (const [key, value] of Object.entries(request.query ?? {})) url.searchParams.set(key, value);
75
+ const response = await fetch(url, {
76
+ method: request.method,
77
+ headers: {
78
+ accept: "application/json",
79
+ authorization: `Bearer ${access.accessToken}`,
80
+ ...request.body !== void 0 && form === void 0 ? { "content-type": "application/json" } : {}
81
+ },
82
+ body: form ?? (request.body !== void 0 ? JSON.stringify(request.body) : void 0),
83
+ redirect: "error",
84
+ signal: signalOf(options.signal, options.timeoutMs)
85
+ });
86
+ const answer = await parse(response);
87
+ if (!response.ok || answer?.error) throw whatsappErrorOf(`WhatsApp ${request.method} ${request.path}`, response.status, answer, options.messageType);
88
+ return answer ?? {};
89
+ }
90
+ /** The form of a file upload: the file and the messaging product. */
91
+ function uploadForm(file, fileName) {
92
+ const form = new FormData();
93
+ form.set("file", new Blob([Buffer.from(file.data, "base64")], { type: file.mimeType }), fileName);
94
+ form.set("messaging_product", "whatsapp");
95
+ form.set("type", file.mimeType);
96
+ return form;
97
+ }
98
+ /** The token of the app, for the webhook subscriptions of the trigger. */
99
+ async function appAccessToken(app, options) {
100
+ const response = await fetch(`${GRAPH_URL}/${APP_VERSION}/oauth/access_token`, {
101
+ method: "POST",
102
+ headers: { "content-type": "application/x-www-form-urlencoded" },
103
+ body: new URLSearchParams({
104
+ client_id: app.appId,
105
+ client_secret: app.appSecret,
106
+ grant_type: "client_credentials"
107
+ }),
108
+ redirect: "error",
109
+ signal: signalOf(options.signal, options.timeoutMs)
110
+ });
111
+ const answer = await parse(response);
112
+ if (!response.ok || answer?.error || typeof answer?.access_token !== "string") throw whatsappErrorOf("WhatsApp app token", response.status, answer);
113
+ return answer.access_token;
114
+ }
115
+ /** One call on the webhook subscriptions of the app. */
116
+ async function callSubscriptions(app, call, options) {
117
+ const token = await appAccessToken(app, options);
118
+ const response = await fetch(`${GRAPH_URL}/${APP_VERSION}/${segment(app.appId)}/subscriptions`, {
119
+ method: call.method,
120
+ headers: {
121
+ accept: "application/json",
122
+ authorization: `Bearer ${token}`,
123
+ ...call.form ? { "content-type": "application/x-www-form-urlencoded" } : {}
124
+ },
125
+ body: call.form ? new URLSearchParams(call.form) : void 0,
126
+ redirect: "error",
127
+ signal: signalOf(options.signal, options.timeoutMs)
128
+ });
129
+ const answer = await parse(response);
130
+ if (!response.ok || answer?.error) throw whatsappErrorOf(`WhatsApp ${call.method} subscriptions`, response.status, answer);
131
+ return answer ?? {};
132
+ }
133
+ // src/icon.ts
134
+ const WHATSAPP_ICON = (0, _zerodot_node_sdk.fileIcon)(require("url").pathToFileURL(__filename).href, "../whatsapp.svg");
135
+ // src/credential.ts
136
+ const TIMEOUT_MS$2 = 1e4;
137
+ const whatsappCredential = {
138
+ type: WHATSAPP_CREDENTIAL,
139
+ label: "WhatsApp API",
140
+ fields: zod.z.object({
141
+ /** A permanent System User token. The test token of the API Setup page ends in 24 hours. */
142
+ accessToken: zod.z.string().min(1).meta({ placeholder: "EAAG…" }),
143
+ /** The ID of the WhatsApp Business Account, from the API Setup page of the Meta app. */
144
+ businessAccountId: zod.z.string().min(1).meta({ placeholder: "WhatsApp Business Account ID" })
145
+ }),
146
+ secretFields: ["accessToken"],
147
+ icon: "WhatsappIcon",
148
+ iconUrl: WHATSAPP_ICON,
149
+ async test(credential) {
150
+ const access = whatsappAccess(credential);
151
+ await callWhatsApp(access, {
152
+ method: "GET",
153
+ path: `/${encodeURIComponent(access.businessAccountId)}`,
154
+ query: { fields: "id,name" }
155
+ }, {
156
+ signal: AbortSignal.timeout(TIMEOUT_MS$2),
157
+ timeoutMs: TIMEOUT_MS$2,
158
+ version: DEFAULT_VERSION
159
+ });
160
+ }
161
+ };
162
+ const whatsappTriggerCredential = {
163
+ type: WHATSAPP_TRIGGER_CREDENTIAL,
164
+ label: "WhatsApp Trigger API",
165
+ fields: zod.z.object({
166
+ /** The App ID, from App Settings > Basic in the Meta app. */
167
+ appId: zod.z.string().min(1).meta({ placeholder: "App ID of the Meta app" }),
168
+ /** The App secret. The trigger signs and checks the webhook with it. */
169
+ appSecret: zod.z.string().min(1).meta({ placeholder: "App secret of the Meta app" })
170
+ }),
171
+ secretFields: ["appSecret"],
172
+ icon: "WhatsappIcon",
173
+ iconUrl: WHATSAPP_ICON,
174
+ async test(credential) {
175
+ await appAccessToken(whatsappAppAccess(credential), {
176
+ signal: AbortSignal.timeout(TIMEOUT_MS$2),
177
+ timeoutMs: TIMEOUT_MS$2
178
+ });
179
+ }
180
+ };
181
+ // src/config.ts
182
+ const RESOURCES = ["message", "media"];
183
+ const OPERATIONS_OF = {
184
+ message: [
185
+ "send",
186
+ "sendAndWait",
187
+ "sendTemplate"
188
+ ],
189
+ media: [
190
+ "mediaUpload",
191
+ "mediaUrlGet",
192
+ "mediaDelete"
193
+ ]
194
+ };
195
+ const ALL_OPERATIONS = Object.values(OPERATIONS_OF).flat();
196
+ const MESSAGE_TYPES = [
197
+ "audio",
198
+ "contacts",
199
+ "document",
200
+ "image",
201
+ "location",
202
+ "text",
203
+ "video"
204
+ ];
205
+ const media = [...[
206
+ "audio",
207
+ "document",
208
+ "image",
209
+ "video"
210
+ ]];
211
+ const contactKind = zod.z.enum(["HOME", "WORK"]);
212
+ const contactName = zod.z.object({ data: zod.z.object({
213
+ formatted_name: zod.z.string(),
214
+ first_name: zod.z.string(),
215
+ last_name: zod.z.string(),
216
+ middle_name: zod.z.string(),
217
+ suffix: zod.z.string(),
218
+ prefix: zod.z.string()
219
+ }).partial() });
220
+ /**
221
+ * The extra fields. Each field belongs to one message type or operation. The collections have
222
+ * the shape of the fixed collections of the editor: the list is under a key with the item name.
223
+ */
224
+ const additionalFields = zod.z.object({
225
+ addresses: zod.z.object({ address: zod.z.array(zod.z.object({
226
+ type: contactKind,
227
+ street: zod.z.string(),
228
+ city: zod.z.string(),
229
+ state: zod.z.string(),
230
+ zip: zod.z.string(),
231
+ country: zod.z.string(),
232
+ country_code: zod.z.string()
233
+ }).partial()) }),
234
+ birthday: zod.z.string(),
235
+ emails: zod.z.object({ data: zod.z.array(zod.z.object({
236
+ type: contactKind,
237
+ email: zod.z.string()
238
+ }).partial()) }),
239
+ organization: zod.z.object({ data: zod.z.object({
240
+ company: zod.z.string(),
241
+ department: zod.z.string(),
242
+ title: zod.z.string()
243
+ }).partial() }),
244
+ phones: zod.z.object({ data: zod.z.array(zod.z.object({
245
+ type: zod.z.enum([
246
+ "CELL",
247
+ "HOME",
248
+ "IPHONE",
249
+ "MAIN",
250
+ "WORK"
251
+ ]),
252
+ phone: zod.z.string(),
253
+ whatsapp_user_id: zod.z.string()
254
+ }).partial()) }),
255
+ urls: zod.z.object({ url: zod.z.array(zod.z.object({
256
+ type: contactKind,
257
+ url: zod.z.string()
258
+ }).partial()) }),
259
+ nameAndAddress: zod.z.object({
260
+ name: zod.z.string(),
261
+ address: zod.z.string()
262
+ }).partial(),
263
+ previewUrl: zod.z.boolean(),
264
+ mediaFilename: zod.z.string(),
265
+ mediaCaption: zod.z.string(),
266
+ mediaFileName: zod.z.string()
267
+ }).partial();
268
+ const parameterType = zod.z.enum([
269
+ "text",
270
+ "currency",
271
+ "date_time"
272
+ ]);
273
+ const templateParameter = zod.z.object({
274
+ type: parameterType,
275
+ text: zod.z.string(),
276
+ /** The ISO 4217 code, such as USD. */
277
+ code: zod.z.string(),
278
+ /** The amount in the normal unit. The node sends it times 1000. */
279
+ amount_1000: zod.z.number(),
280
+ date_time: zod.z.string(),
281
+ fallback_value: zod.z.string()
282
+ }).partial();
283
+ const headerParameter = zod.z.object({
284
+ type: zod.z.enum([
285
+ "text",
286
+ "currency",
287
+ "date_time",
288
+ "image"
289
+ ]),
290
+ text: zod.z.string(),
291
+ code: zod.z.string(),
292
+ amount_1000: zod.z.number(),
293
+ date_time: zod.z.string(),
294
+ fallback_value: zod.z.string(),
295
+ imageLink: zod.z.string()
296
+ }).partial();
297
+ const templateComponent = zod.z.object({
298
+ type: zod.z.enum([
299
+ "body",
300
+ "button",
301
+ "header"
302
+ ]).default("body"),
303
+ bodyParameters: zod.z.object({ parameter: zod.z.array(templateParameter) }).partial(),
304
+ sub_type: zod.z.enum(["quick_reply", "url"]).default("quick_reply"),
305
+ index: zod.z.number().int().min(0).max(2).default(0),
306
+ buttonParameters: zod.z.object({ parameter: zod.z.object({
307
+ type: zod.z.enum(["payload", "text"]).default("payload"),
308
+ payload: zod.z.string(),
309
+ text: zod.z.string()
310
+ }).partial() }).partial(),
311
+ headerParameters: zod.z.object({ parameter: zod.z.array(headerParameter) }).partial()
312
+ }).partial();
313
+ const approvalOptions = zod.z.object({
314
+ approvalType: zod.z.enum(["single", "double"]).default("single"),
315
+ approveLabel: zod.z.string().default("✓ Approve"),
316
+ disapproveLabel: zod.z.string().default("✗ Decline")
317
+ }).partial();
318
+ const formFields = zod.z.array(zod.z.object({
319
+ fieldLabel: zod.z.string(),
320
+ fieldType: zod.z.enum(_zerodot_node_sdk.FORM_FIELD_TYPES).optional(),
321
+ placeholder: zod.z.string().optional(),
322
+ requiredField: zod.z.boolean().optional(),
323
+ fieldOptions: zod.z.object({ values: zod.z.array(zod.z.object({ option: zod.z.string() })) }).optional()
324
+ }));
325
+ const on = (...conditions) => ({ showWhen: conditions });
326
+ const whatsappConfig = zod.z.object({
327
+ resource: zod.z.enum(RESOURCES).default("message").meta({
328
+ labels: {
329
+ message: "Message",
330
+ media: "Media"
331
+ },
332
+ hints: {
333
+ message: "Send a message or a template, or send and wait for an answer",
334
+ media: "Upload, get, or delete a file that WhatsApp keeps"
335
+ }
336
+ }),
337
+ operation: zod.z.enum(ALL_OPERATIONS).default("sendTemplate").meta({
338
+ labels: {
339
+ send: "Send",
340
+ sendAndWait: "Send and Wait for Response",
341
+ sendTemplate: "Send Template",
342
+ mediaUpload: "Upload",
343
+ mediaUrlGet: "Download",
344
+ mediaDelete: "Delete"
345
+ },
346
+ hints: {
347
+ send: "Send a text, a file, a location, or a contact",
348
+ sendAndWait: "Send a message with links, and pause the workflow until the user answers",
349
+ sendTemplate: "Send a message template that Meta approved",
350
+ mediaUpload: "Upload a file from the binary data of the input",
351
+ mediaUrlGet: "Get the URL and the details of a file",
352
+ mediaDelete: "Delete a file"
353
+ }
354
+ }),
355
+ apiVersion: zod.z.string().regex(/^v\d+\.\d+$/).default("v23.0").meta({ description: "The Graph API version, such as v23.0" }),
356
+ phoneNumberId: zod.z.string().optional().meta({
357
+ ...on({ resource: ["message"] }, {
358
+ resource: ["media"],
359
+ operation: ["mediaUpload"]
360
+ }),
361
+ loadOptions: "getPhoneNumbers",
362
+ title: "Sender Phone Number (or ID)",
363
+ description: "ID of the phone number of the business account. The messages come from it, and the files go to it"
364
+ }),
365
+ recipientPhoneNumber: zod.z.string().optional().meta({
366
+ ...on({ resource: ["message"] }),
367
+ title: "Recipient's Phone Number",
368
+ description: "Phone number of the recipient of the message. Include the country code. The characters + - ( ) are removed"
369
+ }),
370
+ messageType: zod.z.enum(MESSAGE_TYPES).default("text").meta({
371
+ ...on({
372
+ resource: ["message"],
373
+ operation: ["send"]
374
+ }),
375
+ title: "Message Type",
376
+ labels: {
377
+ audio: "Audio",
378
+ contacts: "Contacts",
379
+ document: "Document",
380
+ image: "Image",
381
+ location: "Location",
382
+ text: "Text",
383
+ video: "Video"
384
+ }
385
+ }),
386
+ name: contactName.optional().meta({
387
+ ...on({
388
+ operation: ["send"],
389
+ messageType: ["contacts"]
390
+ }),
391
+ description: "The name of the contact. The formatted name is needed"
392
+ }),
393
+ longitude: zod.z.number().min(-180).max(180).optional().meta(on({
394
+ operation: ["send"],
395
+ messageType: ["location"]
396
+ })),
397
+ latitude: zod.z.number().min(-90).max(90).optional().meta(on({
398
+ operation: ["send"],
399
+ messageType: ["location"]
400
+ })),
401
+ textBody: zod.z.string().optional().meta({
402
+ ...on({
403
+ operation: ["send"],
404
+ messageType: ["text"]
405
+ }),
406
+ ui: "textarea",
407
+ description: "The body of the message (at most 4096 characters)"
408
+ }),
409
+ mediaPath: zod.z.enum([
410
+ "useMediaLink",
411
+ "useMediaId",
412
+ "useBinaryData"
413
+ ]).default("useMediaLink").meta({
414
+ ...on({
415
+ operation: ["send"],
416
+ messageType: media
417
+ }),
418
+ title: "Take File From",
419
+ labels: {
420
+ useMediaLink: "Link",
421
+ useMediaId: "WhatsApp Media",
422
+ useBinaryData: "Binary Data"
423
+ },
424
+ hints: {
425
+ useMediaLink: "WhatsApp downloads the file, so you do not upload it first",
426
+ useMediaId: "The ID of a file that you already uploaded to WhatsApp",
427
+ useBinaryData: "Upload the binary data of the input, and send it"
428
+ }
429
+ }),
430
+ mediaLink: zod.z.string().optional().meta({
431
+ ...on({
432
+ operation: ["send"],
433
+ messageType: media,
434
+ mediaPath: ["useMediaLink"]
435
+ }),
436
+ title: "Link",
437
+ description: "Link of the file to send"
438
+ }),
439
+ mediaId: zod.z.string().optional().meta({
440
+ ...on({
441
+ operation: ["send"],
442
+ messageType: media,
443
+ mediaPath: ["useMediaId"]
444
+ }),
445
+ title: "ID",
446
+ description: "ID of the file to send"
447
+ }),
448
+ mediaGetId: zod.z.string().optional().meta({
449
+ ...on({ operation: ["mediaUrlGet"] }),
450
+ title: "Media ID",
451
+ description: "The ID of the media"
452
+ }),
453
+ mediaDeleteId: zod.z.string().optional().meta({
454
+ ...on({ operation: ["mediaDelete"] }),
455
+ title: "Media ID",
456
+ description: "The ID of the media"
457
+ }),
458
+ mediaPropertyName: zod.z.string().default("data").meta({
459
+ ...on({
460
+ operation: ["send"],
461
+ messageType: media,
462
+ mediaPath: ["useBinaryData"]
463
+ }, {
464
+ resource: ["media"],
465
+ operation: ["mediaUpload"]
466
+ }),
467
+ title: "Property Name",
468
+ description: "The property of `binary` in the input that holds the file"
469
+ }),
470
+ mediaFilename: zod.z.string().optional().meta({
471
+ ...on({
472
+ operation: ["send"],
473
+ messageType: ["document"],
474
+ mediaPath: ["useMediaId"]
475
+ }),
476
+ title: "Filename",
477
+ description: "The name of the file. It is needed when you use a file ID"
478
+ }),
479
+ template: zod.z.string().optional().meta({
480
+ ...on({ operation: ["sendTemplate"] }),
481
+ loadOptions: "getTemplates",
482
+ description: "Pick a template, or type one in the format name|language, for example hello_world|en_US"
483
+ }),
484
+ components: zod.z.object({ component: zod.z.array(templateComponent) }).partial().optional().meta(on({ operation: ["sendTemplate"] })),
485
+ message: zod.z.string().optional().meta({
486
+ ...on({ operation: ["sendAndWait"] }),
487
+ ui: "textarea",
488
+ description: "The message to send. The links to answer come after it"
489
+ }),
490
+ responseType: zod.z.enum([
491
+ "approval",
492
+ "freeText",
493
+ "customForm"
494
+ ]).default("approval").meta({
495
+ ...on({ operation: ["sendAndWait"] }),
496
+ title: "Response Type",
497
+ labels: {
498
+ approval: "Approval",
499
+ freeText: "Free Text",
500
+ customForm: "Custom Form"
501
+ },
502
+ hints: {
503
+ approval: "The user opens an approve or decline link",
504
+ freeText: "The user writes an answer in text",
505
+ customForm: "The user fills in a form with the fields that you set"
506
+ }
507
+ }),
508
+ approvalOptions: approvalOptions.optional().meta(on({
509
+ operation: ["sendAndWait"],
510
+ responseType: ["approval"]
511
+ })),
512
+ formFields: formFields.optional().meta(on({
513
+ operation: ["sendAndWait"],
514
+ responseType: ["customForm"]
515
+ })),
516
+ options: zod.z.object({
517
+ messageButtonLabel: zod.z.string(),
518
+ responseFormTitle: zod.z.string(),
519
+ responseFormDescription: zod.z.string(),
520
+ responseFormButtonLabel: zod.z.string(),
521
+ limitWaitTimeHours: zod.z.number().min(.01).max(720)
522
+ }).partial().optional().meta({
523
+ ...on({ operation: ["sendAndWait"] }),
524
+ ui: "collection",
525
+ description: "limitWaitTimeHours: how long to wait for an answer. Default 168 (7 days)."
526
+ }),
527
+ additionalFields: additionalFields.default({}).meta({
528
+ ...on({ operation: ["send"] }, {
529
+ resource: ["media"],
530
+ operation: ["mediaUpload"]
531
+ }),
532
+ ui: "collection"
533
+ }),
534
+ timeoutMs: zod.z.number().int().min(1).max(3e5).default(3e4)
535
+ }).superRefine((config, context) => {
536
+ if (!OPERATIONS_OF[config.resource].includes(config.operation)) context.addIssue({
537
+ code: "custom",
538
+ path: ["operation"],
539
+ message: `"${config.operation}" is not an operation of "${config.resource}"`
540
+ });
541
+ });
542
+ // src/loaders.ts
543
+ const TIMEOUT_MS$1 = 15e3;
544
+ const byLabel = (a, b) => {
545
+ const left = a.label.toLowerCase();
546
+ const right = b.label.toLowerCase();
547
+ return left < right ? -1 : left > right ? 1 : 0;
548
+ };
549
+ /** The version of the config, or the default. The config in the editor can be partial. */
550
+ const versionOf = (config) => typeof config.apiVersion === "string" && /^v\d+\.\d+$/.test(config.apiVersion) ? config.apiVersion : DEFAULT_VERSION;
551
+ /** One page of a list of the business account, with the cursor of the next page. */
552
+ async function listOf(ctx, edge, query) {
553
+ const access = whatsappAccess(ctx.credential);
554
+ if (access.businessAccountId === "") return null;
555
+ const answer = await callWhatsApp(access, {
556
+ method: "GET",
557
+ path: `/${segment(access.businessAccountId)}/${edge}`,
558
+ query: ctx.cursor ? {
559
+ ...query,
560
+ after: ctx.cursor
561
+ } : query
562
+ }, {
563
+ signal: ctx.signal,
564
+ timeoutMs: TIMEOUT_MS$1,
565
+ version: versionOf(ctx.config)
566
+ });
567
+ const after = answer.paging?.next ? answer.paging.cursors?.after : void 0;
568
+ return {
569
+ items: answer.data ?? [],
570
+ nextCursor: after ?? null
571
+ };
572
+ }
573
+ /** The phone numbers of the business account: "number - verified name", sorted by that text. */
574
+ async function getPhoneNumbers(ctx) {
575
+ const page = await listOf(ctx, "phone_numbers", {});
576
+ if (!page) return [];
577
+ return {
578
+ options: page.items.filter((item) => typeof item.id === "string").map((item) => ({
579
+ label: `${item.display_phone_number ?? ""} - ${item.verified_name ?? ""}`,
580
+ value: item.id
581
+ })).sort(byLabel),
582
+ nextCursor: page.nextCursor
583
+ };
584
+ }
585
+ /** The templates of the business account: "name - language", with the value `name|language`. */
586
+ async function getTemplates(ctx) {
587
+ const page = await listOf(ctx, "message_templates", { fields: "name,language" });
588
+ if (!page) return [];
589
+ return {
590
+ options: page.items.filter((item) => typeof item.name === "string" && typeof item.language === "string").map(({ name, language }) => ({
591
+ label: `${name} - ${language}`,
592
+ value: `${name}|${language}`
593
+ })).sort(byLabel),
594
+ nextCursor: page.nextCursor
595
+ };
596
+ }
597
+ // src/request.ts
598
+ const need = (value, name, label) => {
599
+ if (value === void 0 || value.trim() === "") throw new Error(`WhatsApp ${label} needs "${name}"`);
600
+ return value.trim();
601
+ };
602
+ /** The phone number without the characters + - ( ). */
603
+ const sanitizePhoneNumber = (phoneNumber) => phoneNumber.replace(/[-()+]/g, "");
604
+ /** One text, currency, date, or image parameter of a template. */
605
+ function parameterOf(parameter) {
606
+ if (parameter.type === "text") return {
607
+ type: "text",
608
+ text: parameter.text ?? ""
609
+ };
610
+ if (parameter.type === "currency") return {
611
+ type: "currency",
612
+ currency: {
613
+ code: parameter.code,
614
+ fallback_value: parameter.fallback_value,
615
+ amount_1000: (parameter.amount_1000 ?? 0) * 1e3
616
+ }
617
+ };
618
+ if (parameter.type === "date_time") return {
619
+ type: "date_time",
620
+ date_time: { fallback_value: parameter.date_time }
621
+ };
622
+ if (parameter.type === "image") return {
623
+ type: "image",
624
+ image: { link: parameter.imageLink }
625
+ };
626
+ }
627
+ const parametersOf = (list) => (list ?? []).map(parameterOf).filter((item) => item !== void 0);
628
+ /** The `components` of a template message. */
629
+ function templateComponents(list) {
630
+ return (list ?? []).map((component) => {
631
+ const type = component.type ?? "body";
632
+ if (type === "button") return {
633
+ type,
634
+ index: String(component.index ?? 0),
635
+ sub_type: component.sub_type ?? "quick_reply",
636
+ parameters: [component.buttonParameters?.parameter ?? {}]
637
+ };
638
+ if (type === "header") return {
639
+ type,
640
+ parameters: parametersOf(component.headerParameters?.parameter)
641
+ };
642
+ return {
643
+ type,
644
+ parameters: parametersOf(component.bodyParameters?.parameter)
645
+ };
646
+ });
647
+ }
648
+ /** The `contacts` of a contacts message: one contact with a name and the extra fields. */
649
+ function contactOf(c) {
650
+ const name = c.name?.data;
651
+ if (!name?.formatted_name?.trim()) throw new Error("WhatsApp message.send of contacts needs the \"formatted_name\" of the name");
652
+ const extra = c.additionalFields;
653
+ const contact = { name: { ...name } };
654
+ if (extra.addresses?.address?.length) contact.addresses = extra.addresses.address;
655
+ if (extra.birthday) contact.birthday = extra.birthday;
656
+ if (extra.emails?.data?.length) contact.emails = extra.emails.data;
657
+ if (extra.organization?.data && Object.keys(extra.organization.data).length > 0) contact.org = extra.organization.data;
658
+ if (extra.phones?.data?.length) contact.phones = extra.phones.data.map(({ whatsapp_user_id, ...phone }) => ({
659
+ ...phone,
660
+ ...whatsapp_user_id ? { wa_id: whatsapp_user_id } : {}
661
+ }));
662
+ if (extra.urls?.url?.length) contact.urls = extra.urls.url;
663
+ return contact;
664
+ }
665
+ /** The file object of an image, video, audio, or document message. */
666
+ function mediaOf(c, uploaded) {
667
+ const label = "message.send";
668
+ const file = {};
669
+ if (c.mediaPath === "useMediaId") {
670
+ file.id = need(c.mediaId, "mediaId", label);
671
+ if (c.messageType === "document") file.filename = need(c.mediaFilename, "mediaFilename", label);
672
+ } else if (c.mediaPath === "useBinaryData") {
673
+ if (!uploaded) throw new Error("The file must be uploaded before the message is sent");
674
+ file.id = uploaded.id;
675
+ if (c.messageType === "document") file.filename = uploaded.fileName;
676
+ } else file.link = need(c.mediaLink, "mediaLink", label);
677
+ const extra = c.additionalFields;
678
+ if (c.messageType === "document" && extra.mediaFilename) file.filename = extra.mediaFilename;
679
+ if (extra.mediaCaption) file.caption = extra.mediaCaption;
680
+ return file;
681
+ }
682
+ /** The call for `message.send`. A file from binary data must be uploaded first. */
683
+ function buildSend(c, uploaded) {
684
+ const label = "message.send";
685
+ const type = c.messageType;
686
+ const body = {
687
+ messaging_product: "whatsapp",
688
+ to: sanitizePhoneNumber(need(c.recipientPhoneNumber, "recipientPhoneNumber", label)),
689
+ type
690
+ };
691
+ if (type === "text") {
692
+ const text = { body: need(c.textBody, "textBody", label) };
693
+ if (c.additionalFields.previewUrl !== void 0) text.preview_url = c.additionalFields.previewUrl;
694
+ body.text = text;
695
+ } else if (type === "location") {
696
+ if (c.latitude === void 0 || c.longitude === void 0) throw new Error(`WhatsApp ${label} of location needs "latitude" and "longitude"`);
697
+ const location = {
698
+ longitude: c.longitude,
699
+ latitude: c.latitude
700
+ };
701
+ const extra = c.additionalFields.nameAndAddress;
702
+ if (extra?.name) location.name = extra.name;
703
+ if (extra?.address) location.address = extra.address;
704
+ body.location = location;
705
+ } else if (type === "contacts") body.contacts = [contactOf(c)];
706
+ else body[type] = mediaOf(c, uploaded);
707
+ return {
708
+ method: "POST",
709
+ path: `/${segment(need(c.phoneNumberId, "phoneNumberId", label))}/messages`,
710
+ body
711
+ };
712
+ }
713
+ /** The call for `message.sendTemplate`. The template is `name|language`. */
714
+ function buildSendTemplate(c) {
715
+ const label = "message.sendTemplate";
716
+ const [name, language] = need(c.template, "template", label).split("|");
717
+ if (!name || !language) throw new Error(`WhatsApp ${label} needs a template in the format "name|language"`);
718
+ const template = {
719
+ name,
720
+ language: { code: language }
721
+ };
722
+ const components = c.components?.component;
723
+ if (components?.length) template.components = templateComponents(components);
724
+ return {
725
+ method: "POST",
726
+ path: `/${segment(need(c.phoneNumberId, "phoneNumberId", label))}/messages`,
727
+ body: {
728
+ messaging_product: "whatsapp",
729
+ to: sanitizePhoneNumber(need(c.recipientPhoneNumber, "recipientPhoneNumber", label)),
730
+ type: "template",
731
+ template
732
+ }
733
+ };
734
+ }
735
+ /** The call that uploads a file. The form is made apart, from the binary data. */
736
+ function buildMediaUpload(c) {
737
+ return {
738
+ method: "POST",
739
+ path: `/${segment(need(c.phoneNumberId, "phoneNumberId", "media.mediaUpload"))}/media`
740
+ };
741
+ }
742
+ /** The call that gets the URL and the details of a file. */
743
+ function buildMediaUrlGet(c) {
744
+ return {
745
+ method: "GET",
746
+ path: `/${segment(need(c.mediaGetId, "mediaGetId", "media.mediaUrlGet"))}`
747
+ };
748
+ }
749
+ /** The call that deletes a file. */
750
+ function buildMediaDelete(c) {
751
+ return {
752
+ method: "DELETE",
753
+ path: `/${segment(need(c.mediaDeleteId, "mediaDeleteId", "media.mediaDelete"))}`
754
+ };
755
+ }
756
+ /** The call of an operation that needs no upload. */
757
+ function buildRequest(c, uploaded) {
758
+ switch (c.operation) {
759
+ case "send": return buildSend(c, uploaded);
760
+ case "sendTemplate": return buildSendTemplate(c);
761
+ case "mediaUpload": return buildMediaUpload(c);
762
+ case "mediaUrlGet": return buildMediaUrlGet(c);
763
+ case "mediaDelete": return buildMediaDelete(c);
764
+ default: throw new Error(`Unknown WhatsApp operation "${c.resource}.${c.operation}"`);
765
+ }
766
+ }
767
+ const DEFAULT_APPROVE = "✓ Approve";
768
+ const DEFAULT_DISAPPROVE = "✗ Decline";
769
+ /** The form of the resume page. Approval needs none: the link carries the answer. */
770
+ function waitFormOf(config) {
771
+ const { responseType, formFields, options } = config;
772
+ const base = {
773
+ title: options?.responseFormTitle,
774
+ description: options?.responseFormDescription,
775
+ buttonLabel: options?.responseFormButtonLabel
776
+ };
777
+ if (responseType === "freeText") return {
778
+ ...base,
779
+ fields: [{
780
+ fieldLabel: "Response",
781
+ key: "text",
782
+ fieldType: "textarea",
783
+ requiredField: true
784
+ }]
785
+ };
786
+ if (responseType === "customForm") return {
787
+ ...base,
788
+ fields: formFields ?? []
789
+ };
790
+ return null;
791
+ }
792
+ /**
793
+ * The call for `sendAndWait`. WhatsApp has no link buttons in a text message, so the links are
794
+ * in the text: the message, then each label in bold and its link in italics.
795
+ */
796
+ function buildSendAndWait(config, resumeUrl) {
797
+ const label = "message.sendAndWait";
798
+ const phoneNumberId = config.phoneNumberId?.trim();
799
+ if (!phoneNumberId) throw new Error(`WhatsApp ${label} needs "phoneNumberId"`);
800
+ const recipient = config.recipientPhoneNumber?.trim();
801
+ if (!recipient) throw new Error(`WhatsApp ${label} needs "recipientPhoneNumber"`);
802
+ if (!config.message) throw new Error(`WhatsApp ${label} needs "message"`);
803
+ let links;
804
+ if (config.responseType === "approval") {
805
+ const { approvalType = "single", approveLabel = DEFAULT_APPROVE, disapproveLabel = DEFAULT_DISAPPROVE } = config.approvalOptions ?? {};
806
+ links = [{
807
+ label: approveLabel,
808
+ url: `${resumeUrl}&approved=true`
809
+ }];
810
+ if (approvalType === "double") links.push({
811
+ label: disapproveLabel,
812
+ url: `${resumeUrl}&approved=false`
813
+ });
814
+ } else links = [{
815
+ label: config.options?.messageButtonLabel ?? "Respond",
816
+ url: resumeUrl
817
+ }];
818
+ const buttons = links.map((link) => `*${link.label}:*\n_${link.url}_\n\n`).join("");
819
+ return {
820
+ method: "POST",
821
+ path: `/${segment(phoneNumberId)}/messages`,
822
+ body: {
823
+ messaging_product: "whatsapp",
824
+ text: { body: `${config.message}\n\n${buttons}` },
825
+ type: "text",
826
+ to: sanitizePhoneNumber(recipient)
827
+ }
828
+ };
829
+ }
830
+ /** When the wait ends without an answer. */
831
+ const waitDeadline = (config) => Date.now() + (config.options?.limitWaitTimeHours ?? 168) * 36e5;
832
+ // src/node.ts
833
+ /** The file of the input, as a form. The name is the name of the binary data, or `fileName`. */
834
+ function fileOf(input, property, fileName) {
835
+ const file = (0, _zerodot_node_sdk.readBinary)(input, property.trim());
836
+ const name = fileName || file.fileName;
837
+ if (!name) throw new Error("No file name is given for the upload");
838
+ return {
839
+ file,
840
+ name
841
+ };
842
+ }
843
+ var node_default = (0, _zerodot_node_sdk.defineNode)({
844
+ type: "whatsapp.api",
845
+ label: "WhatsApp Business Cloud",
846
+ description: "Send WhatsApp messages and templates, wait for an answer, and upload, get, or delete media with the WhatsApp Business Cloud API",
847
+ category: "integration",
848
+ app: "WhatsApp",
849
+ actions: [
850
+ {
851
+ label: "Send message",
852
+ config: {
853
+ resource: "message",
854
+ operation: "send"
855
+ }
856
+ },
857
+ {
858
+ label: "Send message and wait for response",
859
+ config: {
860
+ resource: "message",
861
+ operation: "sendAndWait"
862
+ }
863
+ },
864
+ {
865
+ label: "Send template",
866
+ config: {
867
+ resource: "message",
868
+ operation: "sendTemplate"
869
+ }
870
+ },
871
+ {
872
+ label: "Upload media",
873
+ config: {
874
+ resource: "media",
875
+ operation: "mediaUpload"
876
+ }
877
+ },
878
+ {
879
+ label: "Download media",
880
+ config: {
881
+ resource: "media",
882
+ operation: "mediaUrlGet"
883
+ }
884
+ },
885
+ {
886
+ label: "Delete media",
887
+ config: {
888
+ resource: "media",
889
+ operation: "mediaDelete"
890
+ }
891
+ }
892
+ ],
893
+ icon: "WhatsappIcon",
894
+ iconUrl: WHATSAPP_ICON,
895
+ config: whatsappConfig,
896
+ defaultConfig: {
897
+ resource: "message",
898
+ operation: "sendTemplate",
899
+ apiVersion: "v23.0",
900
+ messageType: "text",
901
+ mediaPath: "useMediaLink",
902
+ mediaPropertyName: "data",
903
+ responseType: "approval",
904
+ additionalFields: {},
905
+ timeoutMs: 3e4
906
+ },
907
+ credentialTypes: [WHATSAPP_CREDENTIAL],
908
+ ports: {
909
+ in: ["in"],
910
+ out: ["out"]
911
+ },
912
+ subtitle: (config) => typeof config.operation === "string" ? `${String(config.resource ?? "message")}: ${config.operation}` : void 0,
913
+ loadOptions: {
914
+ getPhoneNumbers,
915
+ getTemplates
916
+ },
917
+ waitForm: waitFormOf,
918
+ async run({ config: c, input, credential, signal, resumeUrl }) {
919
+ const access = whatsappAccess(credential);
920
+ const options = {
921
+ signal,
922
+ timeoutMs: c.timeoutMs,
923
+ version: c.apiVersion,
924
+ messageType: c.operation === "send" ? c.messageType : void 0
925
+ };
926
+ if (c.operation === "sendAndWait") {
927
+ if (!resumeUrl) throw new Error("This worker cannot ask for an answer. Set ZERODOT_BASE_URL on the worker");
928
+ await callWhatsApp(access, buildSendAndWait(c, resumeUrl), options);
929
+ return {
930
+ port: "out",
931
+ data: { data: { timedOut: true } },
932
+ waitUntil: waitDeadline(c)
933
+ };
934
+ }
935
+ if (c.operation === "mediaUpload") {
936
+ const { file, name } = fileOf(input, c.mediaPropertyName, c.additionalFields.mediaFileName);
937
+ return {
938
+ port: "out",
939
+ data: await callWhatsApp(access, buildMediaUpload(c), options, uploadForm(file, name))
940
+ };
941
+ }
942
+ let uploaded;
943
+ if (c.operation === "send" && c.mediaPath === "useBinaryData" && c.messageType !== "text") {
944
+ const { file, name } = fileOf(input, c.mediaPropertyName, void 0);
945
+ const answer = await callWhatsApp(access, buildMediaUpload(c), options, uploadForm(file, name));
946
+ if (typeof answer.id !== "string") throw new Error("WhatsApp did not give a media ID");
947
+ uploaded = {
948
+ id: answer.id,
949
+ fileName: name
950
+ };
951
+ }
952
+ return {
953
+ port: "out",
954
+ data: await callWhatsApp(access, buildRequest(c, uploaded), options)
955
+ };
956
+ }
957
+ });
958
+ // src/trigger.ts
959
+ const WEBHOOK_OBJECT = "whatsapp_business_account";
960
+ const TIMEOUT_MS = 15e3;
961
+ const triggerConfig = zod.z.object({
962
+ updates: zod.z.array(zod.z.enum([
963
+ "account_review_update",
964
+ "account_update",
965
+ "business_capability_update",
966
+ "message_template_quality_update",
967
+ "message_template_status_update",
968
+ "messages",
969
+ "phone_number_name_update",
970
+ "phone_number_quality_update",
971
+ "security",
972
+ "template_category_update"
973
+ ])).default([]).meta({
974
+ title: "Trigger On",
975
+ labels: {
976
+ account_review_update: "Account Review Update",
977
+ account_update: "Account Update",
978
+ business_capability_update: "Business Capability Update",
979
+ message_template_quality_update: "Message Template Quality Update",
980
+ message_template_status_update: "Message Template Status Update",
981
+ messages: "Messages",
982
+ phone_number_name_update: "Phone Number Name Update",
983
+ phone_number_quality_update: "Phone Number Quality Update",
984
+ security: "Security",
985
+ template_category_update: "Template Category Update"
986
+ },
987
+ description: "Meta allows one WhatsApp trigger for each Meta app. A second trigger on the same app replaces the first one"
988
+ }),
989
+ options: zod.z.object({ messageStatusUpdates: zod.z.array(zod.z.enum([
990
+ "all",
991
+ "deleted",
992
+ "delivered",
993
+ "failed",
994
+ "read",
995
+ "sent"
996
+ ])).default(["all"]).meta({
997
+ title: "Receive Message Status Updates",
998
+ labels: {
999
+ all: "All",
1000
+ deleted: "Deleted",
1001
+ delivered: "Delivered",
1002
+ failed: "Failed",
1003
+ read: "Read",
1004
+ sent: "Sent"
1005
+ },
1006
+ description: "WhatsApp sends a notice when the status of a message changes, for example from Sent to Delivered and from Delivered to Read. Select the statuses that start the workflow, to avoid more than one run for one message"
1007
+ }) }).partial().optional().meta({ ui: "collection" })
1008
+ });
1009
+ /** The `X-Hub-Signature-256` value of a webhook request from Meta. */
1010
+ function whatsappSignature(secret, rawBody) {
1011
+ return `sha256=${(0, node_crypto.createHmac)("sha256", secret).update(rawBody, "utf8").digest("hex")}`;
1012
+ }
1013
+ /** Checks the signature of a request. The body must be the raw text that Meta sent. */
1014
+ function verifyWhatsappRequest(secret, request) {
1015
+ const given = Buffer.from(request.headers["x-hub-signature-256"] ?? "");
1016
+ const wanted = Buffer.from(whatsappSignature(secret, request.rawBody ?? ""));
1017
+ return given.byteLength === wanted.byteLength && (0, node_crypto.timingSafeEqual)(given, wanted);
1018
+ }
1019
+ /**
1020
+ * Filters the events by the status updates. No setting keeps all events. An empty list drops the
1021
+ * events that have statuses. A list without "all" keeps the events of the listed statuses, and
1022
+ * the events that have no statuses.
1023
+ */
1024
+ function filterStatuses(events, allowed) {
1025
+ if (!allowed) return events;
1026
+ if (allowed.length === 0) return events.filter((event) => !event.statuses);
1027
+ if (!allowed.includes("all")) return events.filter((event) => {
1028
+ const statuses = event.statuses;
1029
+ if (statuses?.length) return statuses.some((status) => allowed.includes(status.status));
1030
+ return true;
1031
+ });
1032
+ return events;
1033
+ }
1034
+ /** Decides about a request that has a valid signature. */
1035
+ function checkWhatsappWebhook(config, body) {
1036
+ const payload = body ?? {};
1037
+ if (payload.object !== WEBHOOK_OBJECT) return { verdict: "ignore" };
1038
+ const accepted = filterStatuses((Array.isArray(payload.entry) ? payload.entry : []).flatMap((entry) => Array.isArray(entry.changes) ? entry.changes : []).map((change) => ({
1039
+ ...change.value,
1040
+ field: change.field ?? ""
1041
+ })), config.options?.messageStatusUpdates);
1042
+ if (accepted.length === 0) return { verdict: "ignore" };
1043
+ return {
1044
+ verdict: "accept",
1045
+ input: accepted
1046
+ };
1047
+ }
1048
+ const sameFields = (subscription, wanted) => subscription.fields.map((field) => field.name).sort().join(",") === [...wanted].sort().join(",");
1049
+ // src/index.ts
1050
+ const nodes = [(0, _zerodot_node_sdk.defineNode)({
1051
+ type: "trigger.whatsapp",
1052
+ label: "WhatsApp Trigger",
1053
+ description: "Start the workflow on a WhatsApp event, such as a new message, a message status, or a template update",
1054
+ category: "trigger",
1055
+ app: "WhatsApp",
1056
+ icon: "WhatsappIcon",
1057
+ iconUrl: WHATSAPP_ICON,
1058
+ config: triggerConfig,
1059
+ defaultConfig: {
1060
+ updates: [],
1061
+ options: {}
1062
+ },
1063
+ credentialTypes: [WHATSAPP_TRIGGER_CREDENTIAL],
1064
+ ports: {
1065
+ in: [],
1066
+ out: ["out"]
1067
+ },
1068
+ subtitle: (config) => Array.isArray(config.updates) && config.updates.length > 0 ? config.updates.join(", ") : void 0,
1069
+ webhook: {
1070
+ async receive({ config: raw, credential, request, node }) {
1071
+ if (request.method === "GET") {
1072
+ const challenge = request.query["hub.challenge"];
1073
+ if (typeof challenge !== "string" || challenge === "") return {
1074
+ verdict: "ignore",
1075
+ response: {
1076
+ status: 400,
1077
+ body: ""
1078
+ }
1079
+ };
1080
+ if (request.query["hub.verify_token"] !== node.id) return {
1081
+ verdict: "forbidden",
1082
+ status: 403
1083
+ };
1084
+ return {
1085
+ verdict: "ignore",
1086
+ response: {
1087
+ status: 200,
1088
+ body: challenge
1089
+ }
1090
+ };
1091
+ }
1092
+ const { appSecret } = whatsappAppAccess(credential);
1093
+ if (!verifyWhatsappRequest(appSecret, request)) return {
1094
+ verdict: "forbidden",
1095
+ status: 401
1096
+ };
1097
+ return checkWhatsappWebhook(triggerConfig.parse(raw), request.body);
1098
+ },
1099
+ /** Subscribes the app to the events. Meta calls the webhook address with a challenge. */
1100
+ async activate({ config: raw, credential, url, node, signal }) {
1101
+ const app = whatsappAppAccess(credential);
1102
+ const { updates } = triggerConfig.parse(raw);
1103
+ if (updates.length === 0) throw new Error("The WhatsApp trigger needs one or more \"updates\"");
1104
+ const options = {
1105
+ signal,
1106
+ timeoutMs: TIMEOUT_MS
1107
+ };
1108
+ const listed = await callSubscriptions(app, { method: "GET" }, options);
1109
+ const existing = (Array.isArray(listed.data) ? listed.data : []).find((subscription) => subscription.object === WEBHOOK_OBJECT);
1110
+ if (existing && existing.callback_url !== url) throw new Error(`The WhatsApp App ID ${app.appId} already has a webhook subscription. Delete it or use another app before you start the trigger. WhatsApp allows one trigger for each app`);
1111
+ if (existing?.active && sameFields(existing, updates)) return null;
1112
+ await callSubscriptions(app, {
1113
+ method: "POST",
1114
+ form: {
1115
+ object: WEBHOOK_OBJECT,
1116
+ callback_url: url,
1117
+ verify_token: node.id,
1118
+ fields: JSON.stringify(updates),
1119
+ include_values: "true"
1120
+ }
1121
+ }, options);
1122
+ return null;
1123
+ },
1124
+ /** Removes the subscription of the app. */
1125
+ async deactivate({ credential, url, signal }) {
1126
+ const app = whatsappAppAccess(credential);
1127
+ const options = {
1128
+ signal,
1129
+ timeoutMs: TIMEOUT_MS
1130
+ };
1131
+ const listed = await callSubscriptions(app, { method: "GET" }, options);
1132
+ if ((Array.isArray(listed.data) ? listed.data : []).find((subscription) => subscription.object === WEBHOOK_OBJECT && subscription.callback_url === url)) await callSubscriptions(app, {
1133
+ method: "DELETE",
1134
+ form: { object: WEBHOOK_OBJECT }
1135
+ }, options);
1136
+ return null;
1137
+ }
1138
+ },
1139
+ webhookTest: { hint: "The trigger subscribes the Meta app to the events. Send a WhatsApp message to the business number" },
1140
+ run: ({ input }) => ({
1141
+ port: "out",
1142
+ data: input
1143
+ })
1144
+ }), node_default];
1145
+ const credentialTypes = [whatsappCredential, whatsappTriggerCredential];
1146
+ exports.credentialTypes = credentialTypes;
1147
+ exports.nodes = nodes;