waba-devtools 0.0.0-stage → 0.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.
@@ -0,0 +1,790 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import {
5
+ DEFAULT_GRAPH_VERSION,
6
+ getStage,
7
+ pickSourceWaba,
8
+ pickTargetWabas,
9
+ resolveToken,
10
+ } from './config.js';
11
+ import { readCsvTemplates } from './csv.js';
12
+ import { GraphError, UsageError } from './errors.js';
13
+ import {
14
+ readTemplateDirectory,
15
+ readTemplateFile,
16
+ templatePath,
17
+ writeTemplateFile,
18
+ } from './files.js';
19
+ import { createGraphClient, SUMMARY_FIELDS } from './graph.js';
20
+ import {
21
+ comparableContent,
22
+ mergeParts,
23
+ normalizeTemplate,
24
+ sortKeys,
25
+ templateKey,
26
+ } from './normalize.js';
27
+ import { planDeploy } from './plan.js';
28
+
29
+ /**
30
+ * @typedef {object} CommonOptions
31
+ * @property {string} cwd - Project root.
32
+ * @property {import('./config.js').Config} config
33
+ * @property {NodeJS.ProcessEnv} [environment] - Environment with the tokens (default `process.env`).
34
+ * @property {typeof fetch} [fetchImpl] - Injected `fetch` (tests).
35
+ */
36
+
37
+ /**
38
+ * @param {import('./config.js').WabaEntry} entry
39
+ * @param {CommonOptions} options
40
+ * @returns {import('./graph.js').GraphClient}
41
+ */
42
+ function clientFor(entry, { config, environment = process.env, fetchImpl }) {
43
+ return createGraphClient({
44
+ token: resolveToken(entry, environment),
45
+ version: config.graphVersion,
46
+ fetchImpl,
47
+ });
48
+ }
49
+
50
+ /**
51
+ * @param {unknown} ex
52
+ * @returns {string}
53
+ */
54
+ function describeError(ex) {
55
+ return ex instanceof GraphError ? ex.describe() : ex.message;
56
+ }
57
+
58
+ /**
59
+ * Keeps only the named templates; fails when a name is not in the list.
60
+ *
61
+ * @template T
62
+ * @param {T[]} items
63
+ * @param {(item: T) => string} nameOf
64
+ * @param {string[]} names
65
+ * @param {string} where - Used in the error message.
66
+ * @returns {T[]}
67
+ */
68
+ function selectByName(items, nameOf, names, where) {
69
+ if (names.length === 0) {
70
+ return items;
71
+ }
72
+ const available = new Set(items.map(nameOf));
73
+ const missing = names.filter((name) => !available.has(name));
74
+ if (missing.length > 0) {
75
+ throw new UsageError(`Not found in ${where}: ${missing.join(', ')}.`);
76
+ }
77
+ const wanted = new Set(names);
78
+ return items.filter((item) => wanted.has(nameOf(item)));
79
+ }
80
+
81
+ /**
82
+ * Writes the templates of one WABA into the templates folder.
83
+ *
84
+ * @param {CommonOptions & {from?: string, fromWaba?: string, names?: string[]}} options
85
+ * @returns {Promise.<object>} Report.
86
+ */
87
+ export async function retrieve(options) {
88
+ const { config, cwd, from, fromWaba, names = [] } = options;
89
+ const { stage, stages, entry } = pickSourceWaba(config, from, fromWaba);
90
+ const live = await clientFor(entry, options).listTemplates(entry.wabaId);
91
+ const templates = selectByName(
92
+ live.map(normalizeTemplate),
93
+ (template) => template.name,
94
+ names,
95
+ `WABA ${entry.wabaId}`,
96
+ );
97
+ const files = [];
98
+ for (const template of templates) {
99
+ const result = await writeTemplateFile(config.templatesDir, template);
100
+ files.push({
101
+ name: template.name,
102
+ language: template.language,
103
+ result,
104
+ path: path.relative(cwd, templatePath(config.templatesDir, template)),
105
+ });
106
+ }
107
+ return { command: 'retrieve', stage, stages, wabaId: entry.wabaId, files, ok: true };
108
+ }
109
+
110
+ /**
111
+ * Writes CSV rows into template files. Only the body (and, for new files, the category) comes
112
+ * from the CSV; header, footer and buttons of existing files are kept.
113
+ *
114
+ * @param {CommonOptions & {csv: string}} options
115
+ * @returns {Promise.<object>} Report.
116
+ */
117
+ export async function importCsv({ config, cwd, csv }) {
118
+ const { templates, errors, cleanup, parts } = await readCsvTemplates(path.resolve(cwd, csv));
119
+ const files = [];
120
+ for (const template of templates) {
121
+ const existing = await readTemplateFile(config.templatesDir, template);
122
+ const merged = existing ? mergeParts(existing, template, parts) : template;
123
+ const result = await writeTemplateFile(config.templatesDir, merged);
124
+ files.push({
125
+ name: template.name,
126
+ language: template.language,
127
+ result,
128
+ path: path.relative(cwd, templatePath(config.templatesDir, template)),
129
+ });
130
+ }
131
+ return {
132
+ command: 'import',
133
+ csv,
134
+ csvCleanup: cleanup,
135
+ files,
136
+ rowErrors: errors,
137
+ ok: errors.length === 0,
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Loads what should be deployed: CSV rows, a live source WABA, or the templates folder.
143
+ *
144
+ * @param {CommonOptions & {from?: string, fromWaba?: string, csv?: string, sourceDir?: string}} options
145
+ * @returns {Promise.<{source: import('./plan.js').SourceTemplate[], description: object, rowErrors: object[]}>}
146
+ */
147
+ async function loadSource(options) {
148
+ const { config, cwd, from, fromWaba, csv } = options;
149
+ if (csv) {
150
+ const { templates, errors, cleanup, parts } = await readCsvTemplates(
151
+ path.resolve(cwd, csv),
152
+ );
153
+ return {
154
+ source: templates.map((template) => ({ template, parts })),
155
+ description: { type: 'csv', csv, cleanup },
156
+ rowErrors: errors,
157
+ };
158
+ }
159
+ if (from || fromWaba) {
160
+ const { stage, stages, entry } = pickSourceWaba(config, from, fromWaba);
161
+ const live = await clientFor(entry, options).listTemplates(entry.wabaId);
162
+ return {
163
+ source: live.map((template) => ({ template: normalizeTemplate(template) })),
164
+ description: { type: 'waba', stage, stages, wabaId: entry.wabaId },
165
+ rowErrors: [],
166
+ };
167
+ }
168
+ const directory = options.sourceDir ?? config.templatesDir;
169
+ const templates = await readTemplateDirectory(directory);
170
+ return {
171
+ source: templates.map((template) => ({ template })),
172
+ description: { type: 'files', dir: path.relative(cwd, directory) || '.' },
173
+ rowErrors: [],
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Creates missing and updates changed templates in every WABA of the target stage.
179
+ *
180
+ * @param {CommonOptions & {
181
+ * to?: string, toWabas?: string[], from?: string, fromWaba?: string, csv?: string,
182
+ * names?: string[],
183
+ * dryRun?: boolean, prune?: boolean, yes?: boolean,
184
+ * onProgress?: (event: object) => void,
185
+ * expectedActions?: {wabaId: string, actions: {name: string, language: string, action: string}[]}[],
186
+ * backupDir?: string, backupBefore?: boolean, backupAfter?: boolean, sourceDir?: string,
187
+ * templateKeys?: string[] - only these templates, as `name::language` (e.g. a selection from a backup)
188
+ * }} options
189
+ * @returns {Promise.<object>} Report.
190
+ */
191
+ export async function deploy(options) {
192
+ const {
193
+ config,
194
+ to,
195
+ toWabas = [],
196
+ from,
197
+ fromWaba,
198
+ csv,
199
+ names = [],
200
+ dryRun = false,
201
+ prune = false,
202
+ yes = false,
203
+ onProgress,
204
+ expectedActions,
205
+ backupDir,
206
+ backupBefore = true,
207
+ backupAfter = false,
208
+ templateKeys,
209
+ } = options;
210
+ if (backupDir && !backupBefore && !backupAfter) {
211
+ throw new UsageError(
212
+ 'A backup folder was given, but both before- and after-backups are off.',
213
+ );
214
+ }
215
+ if (backupAfter && !backupDir) {
216
+ throw new UsageError('--backup-after needs --backup <folder>.');
217
+ }
218
+ const sources = [csv, from || fromWaba, options.sourceDir].filter(Boolean);
219
+ if (sources.length > 1) {
220
+ throw new UsageError('Use only one source: --csv, --from/--from-waba or --from-dir.');
221
+ }
222
+ if (prune && (csv || templateKeys || names.length > 0)) {
223
+ throw new UsageError(
224
+ '--prune only works when deploying the full set (not with -m or --csv).',
225
+ );
226
+ }
227
+ const targets = pickTargetWabas(config, to, toWabas);
228
+ const loaded = await loadSource(options);
229
+ if (templateKeys?.length === 0) {
230
+ throw new UsageError('No templates selected — select at least one template.');
231
+ }
232
+ const byName = selectByName(loaded.source, (item) => item.template.name, names, 'the source');
233
+ const source = templateKeys
234
+ ? selectByName(byName, (item) => templateKey(item.template), templateKeys, 'the source')
235
+ : byName;
236
+ if (prune && source.length === 0) {
237
+ throw new UsageError(
238
+ 'The source has no templates; refusing --prune (it would delete all).',
239
+ );
240
+ }
241
+ const isFullSet = names.length === 0 && !templateKeys && !csv;
242
+ const results = [];
243
+ const createdAt = new Date().toISOString();
244
+ const backup = backupDir
245
+ ? { root: backupDir, runAt: createdAt, source: loaded.description }
246
+ : undefined;
247
+ for (const [targetIndex, { stage, stages, entry }] of targets.entries()) {
248
+ const target = { stage, stages, wabaId: entry.wabaId, actions: [] };
249
+ results.push(target);
250
+ let client;
251
+ let live;
252
+ try {
253
+ client = clientFor(entry, options);
254
+ live = await client.listTemplates(entry.wabaId);
255
+ } catch (ex) {
256
+ target.error = describeError(ex);
257
+ continue;
258
+ }
259
+ const liveById = new Map(live.map((template) => [template.id, template]));
260
+ const planned = planDeploy({ source, target: live, fullSet: isFullSet, prune }).map(
261
+ (action) => withFingerprint(action, liveById),
262
+ );
263
+ const hasChanged =
264
+ expectedActions !== undefined &&
265
+ !isSameSendSet(planned, expectedFor(expectedActions, entry.wabaId));
266
+ if (hasChanged) {
267
+ target.error = 'changed since preview — run the preview again';
268
+ }
269
+ const total = planned.filter((action) => SENDING.has(action.action)).length;
270
+ let isBlocked = hasChanged;
271
+ if (backup && backupBefore && !dryRun && !hasChanged && total > 0) {
272
+ try {
273
+ target.backup = await backupTarget(backup, {
274
+ stage,
275
+ wabaId: entry.wabaId,
276
+ live,
277
+ phase: 'before',
278
+ });
279
+ } catch (ex) {
280
+ target.error = `backup failed, nothing sent: ${ex.message}`;
281
+ isBlocked = true;
282
+ }
283
+ }
284
+ let done = 0;
285
+ let sent = 0;
286
+ for (const plannedAction of planned) {
287
+ const { body, ...action } = plannedAction;
288
+ target.actions.push(action);
289
+ if (dryRun || isBlocked || !SENDING.has(action.action)) {
290
+ continue;
291
+ }
292
+ if (!yes && action.action === 'delete') {
293
+ action.result = 'not run (add --yes)';
294
+ } else {
295
+ await sendAction(client, entry.wabaId, action, body);
296
+ if (action.result === 'done') {
297
+ sent++;
298
+ }
299
+ }
300
+ done++;
301
+ onProgress?.({
302
+ wabaId: entry.wabaId,
303
+ targetIndex,
304
+ targetCount: targets.length,
305
+ name: action.name,
306
+ language: action.language,
307
+ action: action.action,
308
+ result: action.result,
309
+ done,
310
+ total,
311
+ });
312
+ }
313
+ if (backup && backupAfter && sent > 0) {
314
+ try {
315
+ target.backupAfter = await backupTarget(backup, {
316
+ stage,
317
+ wabaId: entry.wabaId,
318
+ live: await client.listTemplates(entry.wabaId),
319
+ phase: 'after',
320
+ });
321
+ } catch (ex) {
322
+ target.backupAfterError = `after-backup failed (changes were sent): ${describeError(ex)}`;
323
+ }
324
+ }
325
+ }
326
+ const isOk =
327
+ loaded.rowErrors.length === 0 &&
328
+ results.every(
329
+ (target) =>
330
+ !target.error &&
331
+ target.actions.every(
332
+ (action) => action.result !== 'failed' && action.action !== 'blocked',
333
+ ),
334
+ );
335
+ return {
336
+ command: 'deploy',
337
+ dryRun,
338
+ source: loaded.description,
339
+ rowErrors: loaded.rowErrors,
340
+ targets: results,
341
+ ok: isOk,
342
+ };
343
+ }
344
+
345
+ /**
346
+ * Folder name of one backup set: the WABA ID, the UTC time of the deploy run (file-name safe) and
347
+ * whether it was taken before or after the changes,
348
+ * e.g. `444444444444444_2026-11-20T18-26-04-123Z_before`.
349
+ *
350
+ * @param {string} wabaId
351
+ * @param {string} runAt - ISO timestamp of the deploy run (same for the before and after set).
352
+ * @param {'before'|'after'|'manual'} phase
353
+ * @returns {string}
354
+ */
355
+ export function backupSetName(wabaId, runAt, phase) {
356
+ return `${wabaId}_${runAt.replaceAll(/[:.]/g, '-')}_${phase}`;
357
+ }
358
+
359
+ /**
360
+ * Writes one backup set: the full template set of one target WABA plus a manifest that lists the
361
+ * templates, so a backup can be browsed without reading every file. An existing set folder is never
362
+ * overwritten.
363
+ *
364
+ * @param {{root: string, runAt: string, source: object}} backup - Run state.
365
+ * @param {{stage: string, wabaId: string, live: object[], phase: 'before'|'after'|'manual'}} target
366
+ * @returns {Promise.<string>} Folder of the backup set.
367
+ */
368
+ async function backupTarget(backup, { stage, wabaId, live, phase }) {
369
+ const directory = path.join(backup.root, backupSetName(wabaId, backup.runAt, phase));
370
+ await mkdir(backup.root, { recursive: true });
371
+ try {
372
+ await mkdir(directory);
373
+ } catch (ex) {
374
+ throw ex.code === 'EEXIST' ? new Error(`backup set ${directory} already exists`) : ex;
375
+ }
376
+ const entries = live
377
+ .map((template) => ({ template: normalizeTemplate(template), status: template.status }))
378
+ .toSorted((a, b) => templateKey(a.template).localeCompare(templateKey(b.template)));
379
+ const templates = entries.map((item) => item.template);
380
+ for (const template of templates) {
381
+ await writeTemplateFile(directory, template);
382
+ }
383
+ const { version } = JSON.parse(
384
+ await readFile(new URL('../package.json', import.meta.url), 'utf8'),
385
+ );
386
+ const manifest = {
387
+ tool: 'waba-devtools',
388
+ version,
389
+ createdAt: new Date().toISOString(),
390
+ runAt: backup.runAt,
391
+ phase,
392
+ wabaId,
393
+ stage,
394
+ source: backup.source,
395
+ templates: entries.map(({ template, status }) => ({
396
+ name: template.name,
397
+ language: template.language,
398
+ category: template.category,
399
+ status,
400
+ })),
401
+ };
402
+ await writeFile(
403
+ path.join(directory, 'manifest.json'),
404
+ `${JSON.stringify(manifest, undefined, 4)}\n`,
405
+ );
406
+ return directory;
407
+ }
408
+
409
+ /**
410
+ * Actions that send something to Meta.
411
+ */
412
+ const SENDING = new Set(['create', 'update', 'delete']);
413
+
414
+ /**
415
+ * The confirmed preview actions of one target WABA.
416
+ *
417
+ * @param {{wabaId: string, actions?: {name: string, language: string, action: string}[]}[]} expected
418
+ * @param {string} wabaId
419
+ * @returns {{name: string, language: string, action: string}[]}
420
+ */
421
+ function expectedFor(expected, wabaId) {
422
+ return expected.find((target) => target.wabaId === wabaId)?.actions ?? [];
423
+ }
424
+
425
+ /**
426
+ * True when both lists would send the same create/update/delete for the same templates.
427
+ *
428
+ * @param {{name: string, language: string, action: string}[]} planned
429
+ * @param {{name: string, language: string, action: string}[]} expected
430
+ * @returns {boolean}
431
+ */
432
+ function isSameSendSet(planned, expected) {
433
+ if (sendKey(planned) !== sendKey(expected)) {
434
+ return false;
435
+ }
436
+ const fingerprints = new Map(
437
+ expected
438
+ .filter((action) => SENDING.has(action.action))
439
+ .map((action) => [actionKey(action), action.fingerprint]),
440
+ );
441
+ // A preview without any fingerprints (older file) only binds what happens to which template.
442
+ // Once a preview has fingerprints, every sending action must match its own.
443
+ const hasFingerprints = fingerprints.values().some((value) => value !== undefined);
444
+ return planned
445
+ .filter((action) => SENDING.has(action.action))
446
+ .every(
447
+ (action) =>
448
+ !hasFingerprints || fingerprints.get(actionKey(action)) === action.fingerprint,
449
+ );
450
+ }
451
+
452
+ /**
453
+ * @param {{name: string, language: string, action: string}} action
454
+ * @returns {string}
455
+ */
456
+ function actionKey(action) {
457
+ return `${action.action}:${action.name}:${action.language}`;
458
+ }
459
+
460
+ /**
461
+ * Adds `fingerprint` to every create, update and delete: a short hash of the exact request body and,
462
+ * for updates and deletes, of the live template it replaces (ID, status, content). A confirmed preview
463
+ * then binds both what is sent and what it overwrites or deletes.
464
+ *
465
+ * @param {object} action - Planned action.
466
+ * @param {Map.<string, object>} liveById - Live templates of the target by ID.
467
+ * @returns {object}
468
+ */
469
+ function withFingerprint(action, liveById) {
470
+ if (!SENDING.has(action.action)) {
471
+ return action;
472
+ }
473
+ const current = action.templateId ? liveById.get(action.templateId) : undefined;
474
+ const bound = {
475
+ body: action.body ?? null,
476
+ live: current
477
+ ? {
478
+ id: current.id,
479
+ status: current.status,
480
+ content: comparableContent(normalizeTemplate(current)),
481
+ }
482
+ : null,
483
+ };
484
+ const fingerprint = createHash('sha256')
485
+ .update(JSON.stringify(sortKeys(bound)))
486
+ .digest('hex')
487
+ .slice(0, 16);
488
+ return { ...action, fingerprint };
489
+ }
490
+
491
+ /**
492
+ * @param {{name: string, language: string, action: string}[]} actions
493
+ * @returns {string} Sorted create/update/delete keys.
494
+ */
495
+ function sendKey(actions) {
496
+ return actions
497
+ .filter((action) => SENDING.has(action.action))
498
+ .map((action) => actionKey(action))
499
+ .toSorted((a, b) => a.localeCompare(b))
500
+ .join('\n');
501
+ }
502
+
503
+ /**
504
+ * Sends one planned action and records the result on it.
505
+ *
506
+ * @param {import('./graph.js').GraphClient} client
507
+ * @param {string} wabaId
508
+ * @param {object} action - Report entry, updated in place.
509
+ * @param {object} [body] - Request body from the plan.
510
+ * @returns {Promise.<void>}
511
+ */
512
+ async function sendAction(client, wabaId, action, body) {
513
+ try {
514
+ if (action.action === 'create') {
515
+ const response = await client.createTemplate(wabaId, body);
516
+ action.templateId = response.id;
517
+ action.statusAfter = response.status;
518
+ } else if (action.action === 'update') {
519
+ await client.updateTemplate(action.templateId, body);
520
+ } else {
521
+ await client.deleteTemplate(wabaId, action.name, action.templateId);
522
+ }
523
+ action.result = 'done';
524
+ } catch (ex) {
525
+ action.result = 'failed';
526
+ action.error = describeError(ex);
527
+ }
528
+ }
529
+
530
+ /**
531
+ * Template overview per WABA (name, language, category, status) without components or files.
532
+ * Takes either a source (`from`/`fromWaba`) or targets (`to`/`toWabas`).
533
+ *
534
+ * @param {CommonOptions & {
535
+ * from?: string, fromWaba?: string, to?: string, toWabas?: string[]
536
+ * }} options
537
+ * @returns {Promise.<object>} Report.
538
+ */
539
+ export async function listTemplates(options) {
540
+ const { config, from, fromWaba, to, toWabas = [] } = options;
541
+ const isSource = Boolean(from || fromWaba);
542
+ if (isSource && (to || toWabas.length > 0)) {
543
+ throw new UsageError(
544
+ 'List either a source (--from/--from-waba) or targets (--to/--to-waba).',
545
+ );
546
+ }
547
+ const entries = isSource
548
+ ? [pickSourceWaba(config, from, fromWaba)]
549
+ : pickTargetWabas(config, to, toWabas);
550
+ const wabas = [];
551
+ for (const { stage, stages, entry } of entries) {
552
+ const result = { stage, stages, wabaId: entry.wabaId };
553
+ wabas.push(result);
554
+ try {
555
+ const live = await clientFor(entry, options).listTemplates(
556
+ entry.wabaId,
557
+ SUMMARY_FIELDS,
558
+ );
559
+ result.templates = live
560
+ .map(({ name, language, category, status }) => ({
561
+ name,
562
+ language,
563
+ category,
564
+ status,
565
+ }))
566
+ .toSorted(
567
+ (a, b) => a.name.localeCompare(b.name) || a.language.localeCompare(b.language),
568
+ );
569
+ } catch (ex) {
570
+ result.error = describeError(ex);
571
+ }
572
+ }
573
+ return { command: 'list', wabas, ok: wabas.every((waba) => !waba.error) };
574
+ }
575
+
576
+ /**
577
+ * Token type and expiry from Meta's `debug_token` answer, for warnings about short-lived tokens.
578
+ *
579
+ * @param {{type?: string, expires_at?: number}} info
580
+ * @returns {{type: string|undefined, expiresAt: string|null}} `expiresAt` is `null` when the token
581
+ * never expires.
582
+ */
583
+ function describeTokenInfo(info) {
584
+ return {
585
+ type: info.type,
586
+ expiresAt: info.expires_at ? new Date(info.expires_at * 1000).toISOString() : null,
587
+ };
588
+ }
589
+
590
+ /**
591
+ * The WABAs an access token can manage, with their names and phone numbers. Read-only; needs no
592
+ * config, so it helps to write one.
593
+ *
594
+ * @param {object} options
595
+ * @param {string} options.token - Access token (never logged or returned).
596
+ * @param {string} [options.businessId] - Business portfolio to list the WABAs of, when Meta does not
597
+ * name them for the token.
598
+ * @param {string} [options.graphVersion]
599
+ * @param {typeof fetch} [options.fetchImpl]
600
+ * @returns {Promise.<object>} Report.
601
+ */
602
+ export async function discoverWabas({
603
+ token,
604
+ businessId,
605
+ graphVersion = DEFAULT_GRAPH_VERSION,
606
+ fetchImpl,
607
+ }) {
608
+ const client = createGraphClient({ token, version: graphVersion, fetchImpl });
609
+ let info;
610
+ try {
611
+ info = await client.debugToken();
612
+ } catch (ex) {
613
+ // A system user with only the "Test app" role may use its token but not describe it.
614
+ if (!(
615
+ ex instanceof GraphError &&
616
+ ex.code === 100 &&
617
+ /owner or developer/i.test(ex.message)
618
+ )) {
619
+ throw ex;
620
+ }
621
+ if (!businessId) {
622
+ throw new UsageError(
623
+ 'Meta does not describe this token: its system user needs the "Develop app" role on ' +
624
+ 'the app (Business settings → System users → Manage next to the app). Or give ' +
625
+ 'the business portfolio ID with --business <id>.',
626
+ 'TOKEN_INFO_REFUSED',
627
+ );
628
+ }
629
+ }
630
+ let ids = [];
631
+ if (info) {
632
+ if (info.is_valid === false) {
633
+ throw new UsageError(
634
+ 'Meta says this access token is not valid (expired or revoked).',
635
+ 'TOKEN_INVALID',
636
+ );
637
+ }
638
+ const scope = (info.granular_scopes ?? []).find(
639
+ (candidate) => candidate.scope === 'whatsapp_business_management',
640
+ );
641
+ if (!scope) {
642
+ throw new UsageError(
643
+ 'This access token has no whatsapp_business_management permission. Generate it again with that permission.',
644
+ 'TOKEN_MISSING_PERMISSION',
645
+ );
646
+ }
647
+ ids = scope.target_ids ?? [];
648
+ }
649
+ if (businessId && ids.length === 0) {
650
+ // Meta omits target_ids for tokens that reach everything (dashboard user tokens and
651
+ // system-user tokens alike); the portfolio's WABA lists work with business_management.
652
+ ids = (await client.listBusinessWabas(businessId)).map((waba) => waba.id);
653
+ }
654
+ if (ids.length === 0) {
655
+ throw new UsageError(
656
+ businessId
657
+ ? `Business portfolio ${businessId} has no WhatsApp accounts this token can see.`
658
+ : 'Meta did not list which WABAs this token can reach. Give the business portfolio ID ' +
659
+ 'with --business <id> (Business settings: the number after business_id= in the ' +
660
+ 'address bar), or add the WABA IDs to .wabadevrc.json by hand.',
661
+ businessId ? 'BUSINESS_HAS_NO_WABAS' : 'BUSINESS_ID_REQUIRED',
662
+ );
663
+ }
664
+ const wabas = [];
665
+ for (const wabaId of ids) {
666
+ const result = { wabaId };
667
+ wabas.push(result);
668
+ try {
669
+ result.name = (await client.getWaba(wabaId)).name;
670
+ result.phoneNumbers = (await client.listPhoneNumbers(wabaId)).map((phone) => ({
671
+ id: phone.id,
672
+ displayPhoneNumber: phone.display_phone_number,
673
+ verifiedName: phone.verified_name,
674
+ }));
675
+ } catch (ex) {
676
+ result.error = describeError(ex);
677
+ }
678
+ }
679
+ return {
680
+ command: 'discover',
681
+ ...(info && { tokenInfo: describeTokenInfo(info) }),
682
+ wabas,
683
+ ok: wabas.every((waba) => !waba.error),
684
+ };
685
+ }
686
+
687
+ /**
688
+ * Creates restore points without deploying: one backup set `<wabaId>_<time>_manual` per WABA.
689
+ *
690
+ * @param {CommonOptions & {stage?: string, wabaIds?: string[], backupDir: string}} options
691
+ * @returns {Promise.<object>} Report.
692
+ */
693
+ export async function createBackup(options) {
694
+ const { config, stage, wabaIds = [], backupDir } = options;
695
+ if (!backupDir) {
696
+ throw new UsageError('Missing --backup <folder>.');
697
+ }
698
+ if (!stage && wabaIds.length === 0) {
699
+ throw new UsageError('Missing --stage or --waba.');
700
+ }
701
+ const backup = { root: backupDir, runAt: new Date().toISOString(), source: { type: 'manual' } };
702
+ const sets = [];
703
+ const targets = pickTargetWabas(config, stage, wabaIds, 'add --stage <stage>');
704
+ for (const { stage: stageName, stages, entry } of targets) {
705
+ const result = { stage: stageName, stages, wabaId: entry.wabaId };
706
+ sets.push(result);
707
+ try {
708
+ const live = await clientFor(entry, options).listTemplates(entry.wabaId);
709
+ result.backup = await backupTarget(backup, {
710
+ stage: stageName,
711
+ wabaId: entry.wabaId,
712
+ live,
713
+ phase: 'manual',
714
+ });
715
+ result.templateCount = live.length;
716
+ } catch (ex) {
717
+ result.error = describeError(ex);
718
+ }
719
+ }
720
+ return { command: 'backup', sets, ok: sets.every((set) => !set.error) };
721
+ }
722
+
723
+ /**
724
+ * Meta's error code on the WABA entity of `health_status` when it disabled the WABA.
725
+ */
726
+ const WABA_BANNED_CODE = 141_014;
727
+
728
+ /**
729
+ * Warning when Meta has disabled the WABA. Meta still answers reads then (and reports
730
+ * `status: ACTIVE`), so only `account_review_status` and the WABA's health errors show it.
731
+ * Errors every unverified test portfolio has (no payment method, no business verification) are
732
+ * not warnings: they only block sending messages, which waba never does.
733
+ *
734
+ * @param {object} waba - Graph answer with `account_review_status` and `health_status`.
735
+ * @returns {{code: string, message: string}[]}
736
+ */
737
+ function wabaWarnings(waba) {
738
+ const banned = (waba.health_status?.entities ?? [])
739
+ .filter((entity) => entity.entity_type === 'WABA')
740
+ .flatMap((entity) => entity.errors ?? [])
741
+ .find((error) => error.error_code === WABA_BANNED_CODE);
742
+ if (!banned && waba.account_review_status !== 'REJECTED') {
743
+ return [];
744
+ }
745
+ const review = waba.account_review_status
746
+ ? ` (account review: ${waba.account_review_status})`
747
+ : '';
748
+ return [
749
+ {
750
+ code: 'WABA_DISABLED',
751
+ message:
752
+ `Meta has disabled this WABA${review}. Templates can still be read. ` +
753
+ 'Details and appeal: Business Support Home (https://business.facebook.com/accountquality).',
754
+ },
755
+ ];
756
+ }
757
+
758
+ /**
759
+ * Read-only access check: token present, WABA reachable, templates listable, and whether Meta has
760
+ * disabled the WABA.
761
+ *
762
+ * @param {CommonOptions & {stage?: string}} options
763
+ * @returns {Promise.<object>} Report.
764
+ */
765
+ export async function check(options) {
766
+ const { config, stage } = options;
767
+ const stages = stage ? [stage] : Object.keys(config.stages);
768
+ const entries = [];
769
+ for (const name of stages) {
770
+ for (const entry of getStage(config, name)) {
771
+ const result = { stage: name, wabaId: entry.wabaId, tokenEnv: entry.tokenEnv };
772
+ entries.push(result);
773
+ try {
774
+ const client = clientFor(entry, options);
775
+ const waba = await client.getWaba(
776
+ entry.wabaId,
777
+ 'id,name,account_review_status,health_status',
778
+ );
779
+ result.wabaName = waba.name;
780
+ result.warnings = wabaWarnings(waba);
781
+ await client.probeTemplates(entry.wabaId);
782
+ result.ok = true;
783
+ } catch (ex) {
784
+ result.ok = false;
785
+ result.error = describeError(ex);
786
+ }
787
+ }
788
+ }
789
+ return { command: 'check', entries, ok: entries.every((entry) => entry.ok) };
790
+ }