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.
package/bin/waba.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../lib/cli.js';
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
package/lib/cli.js ADDED
@@ -0,0 +1,407 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import {
5
+ check,
6
+ createBackup,
7
+ deploy,
8
+ discoverWabas,
9
+ importCsv,
10
+ listTemplates,
11
+ retrieve,
12
+ } from './commands.js';
13
+ import { compareBackups, compareWabas, compareWithLive } from './compare.js';
14
+ import { loadConfig, loadDotenvFile, parseJson } from './config.js';
15
+ import { UsageError } from './errors.js';
16
+ import { formatReport } from './report.js';
17
+
18
+ /**
19
+ * Exit codes, documented in the README.
20
+ */
21
+ export const EXIT = { ok: 0, failed: 1, usage: 2 };
22
+
23
+ const HELP = `waba — WABA DevTools: deploy WhatsApp message templates between WABAs
24
+
25
+ Usage:
26
+ waba retrieve <source> [-m <name>…] [--json]
27
+ waba import --csv <file> [--json]
28
+ waba deploy <target> [-m <name>…] [--dry-run] [--json] (from the template files)
29
+ waba deploy <source> <target> [-m <name>…] [--dry-run] [--json] (WABA to WABA)
30
+ waba deploy --csv <file> <target> [--dry-run] [--json]
31
+ waba deploy [<source>] <target> --prune [--yes]
32
+ waba deploy … --backup <folder> (snapshot targets first)
33
+ waba list <source> | <target> [--json]
34
+ waba check [--stage <stage>] [--json]
35
+ waba discover --token-env <NAME> [--business <id>] [--json]
36
+ waba compare <backup set> <backup set> [--json] (older vs newer, by backup time)
37
+ waba compare <backup set> --live [--waba <id>] [--json] (backup vs the WABA right now)
38
+ waba compare --before-waba <id> --after-waba <id> [--json] (two WABAs right now)
39
+ waba backup --stage <stage> | --waba <id>… --backup <folder> [--json] (restore point)
40
+
41
+ <source> --from <stage> and/or --from-waba <id>
42
+ <target> --to <stage> and/or --to-waba <id>…
43
+
44
+ Options:
45
+ -m, --template <name> Only this template (all its languages). Repeatable.
46
+ --from <stage> Source: the WABA of this stage.
47
+ --from-waba <id> Source: this WABA. Needed when the --from stage has several.
48
+ --to <stage> Target: every WABA of this stage.
49
+ --to-waba <id> Target: only this WABA. Repeatable. With --to: must be in that stage.
50
+ --dry-run Show the planned actions and live statuses; send nothing.
51
+ --prune Full-set deploys only: delete templates that exist only in the target.
52
+ Without --yes the deletes are listed but not run — creates and updates
53
+ ARE sent. Preview everything with --dry-run.
54
+ --yes Confirm the deletes of --prune.
55
+ --expect <file> Send only what this preview showed: the --json output of a previous
56
+ deploy --dry-run. A WABA whose plan changed since gets nothing.
57
+ --backup <folder> Before changing a WABA, save all its templates as a backup set
58
+ <folder>/<wabaId>_<time>_before/.
59
+ --backup-after With --backup: also save each changed WABA after the changes
60
+ (<wabaId>_<time>_after/).
61
+ --from-dir <folder> Source: template files in this folder instead of templatesDir
62
+ (e.g. a backup set: <backup>/<wabaId>_<time>).
63
+ --token-env <NAME> discover: the environment variable that holds the access token.
64
+ --business <id> discover: the business portfolio whose WABAs to list (needed when Meta
65
+ does not name the WABAs for the token).
66
+ --live compare: compare with the WABA's templates right now (nothing is saved).
67
+ --waba <id> backup: this WABA (repeatable); compare --live: another WABA than the
68
+ backup's own.
69
+ --before-waba <id> compare: this WABA (right now) is "before" …
70
+ --after-waba <id> … and this one "after". Nothing is saved.
71
+ --json Print the report as JSON.
72
+ -h, --help Show this help.
73
+ -v, --version Show the version.
74
+
75
+ Configuration: .wabadevrc.json in the current folder. Tokens: environment variables named
76
+ in the config (a .env file in the current folder is loaded too).`;
77
+
78
+ const OPTIONS = {
79
+ from: { type: 'string' },
80
+ to: { type: 'string' },
81
+ 'from-waba': { type: 'string' },
82
+ 'to-waba': { type: 'string', multiple: true },
83
+ stage: { type: 'string' },
84
+ waba: { type: 'string', multiple: true },
85
+ live: { type: 'boolean' },
86
+ 'before-waba': { type: 'string' },
87
+ 'after-waba': { type: 'string' },
88
+ csv: { type: 'string' },
89
+ template: { type: 'string', short: 'm', multiple: true },
90
+ 'dry-run': { type: 'boolean' },
91
+ backup: { type: 'string' },
92
+ 'backup-after': { type: 'boolean' },
93
+ expect: { type: 'string' },
94
+ 'from-dir': { type: 'string' },
95
+ prune: { type: 'boolean' },
96
+ yes: { type: 'boolean' },
97
+ 'token-env': { type: 'string' },
98
+ business: { type: 'string' },
99
+ json: { type: 'boolean' },
100
+ help: { type: 'boolean', short: 'h' },
101
+ version: { type: 'boolean', short: 'v' },
102
+ };
103
+
104
+ /**
105
+ * Options each command accepts (besides --json and --help).
106
+ */
107
+ const ALLOWED = new Map([
108
+ ['retrieve', ['from', 'from-waba', 'template']],
109
+ ['import', ['csv']],
110
+ [
111
+ 'deploy',
112
+ [
113
+ 'from',
114
+ 'from-waba',
115
+ 'to',
116
+ 'to-waba',
117
+ 'csv',
118
+ 'template',
119
+ 'dry-run',
120
+ 'prune',
121
+ 'yes',
122
+ 'backup',
123
+ 'backup-after',
124
+ 'expect',
125
+ 'from-dir',
126
+ ],
127
+ ],
128
+ ['check', ['stage']],
129
+ ['list', ['from', 'from-waba', 'to', 'to-waba']],
130
+ ['discover', ['token-env', 'business']],
131
+ ['compare', ['live', 'waba', 'before-waba', 'after-waba']],
132
+ ['backup', ['stage', 'waba', 'backup']],
133
+ ]);
134
+
135
+ /**
136
+ * Runs the CLI. Returns the exit code instead of exiting, so it can be tested.
137
+ *
138
+ * @param {string[]} argv - Arguments after the executable and script.
139
+ * @param {object} [io]
140
+ * @param {string} [io.cwd]
141
+ * @param {NodeJS.ProcessEnv} [io.environment]
142
+ * @param {(text: string) => void} [io.out]
143
+ * @param {(text: string) => void} [io.err]
144
+ * @param {typeof fetch} [io.fetchImpl]
145
+ * @returns {Promise.<number>}
146
+ */
147
+ export async function main(argv, io = {}) {
148
+ const {
149
+ cwd = process.cwd(),
150
+ environment = process.env,
151
+ out = (text) => process.stdout.write(`${text}\n`),
152
+ err: error = (text) => process.stderr.write(`${text}\n`),
153
+ fetchImpl,
154
+ } = io;
155
+ let parsed;
156
+ try {
157
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
158
+ } catch (ex) {
159
+ error(`${ex.message}\n\n${HELP}`);
160
+ return EXIT.usage;
161
+ }
162
+ const { values, positionals } = parsed;
163
+ if (values.version) {
164
+ const package_ = JSON.parse(
165
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
166
+ );
167
+ out(package_.version);
168
+ return EXIT.ok;
169
+ }
170
+ const [command, ...extra] = positionals;
171
+ if (!command || values.help) {
172
+ out(HELP);
173
+ return values.help ? EXIT.ok : EXIT.usage;
174
+ }
175
+ try {
176
+ const allowed = ALLOWED.get(command);
177
+ if (!allowed || (command !== 'compare' && extra.length > 0)) {
178
+ throw new UsageError(`Unknown command "${positionals.join(' ')}".`);
179
+ }
180
+ const isTwoWabas = Boolean(values['before-waba'] || values['after-waba']);
181
+ if (
182
+ command === 'compare' &&
183
+ isTwoWabas &&
184
+ (extra.length > 0 || values.live || values.waba)
185
+ ) {
186
+ throw new UsageError(
187
+ 'compare --before-waba/--after-waba compares two WABAs live; give no backup set, --live or --waba.',
188
+ );
189
+ }
190
+ if (command === 'compare' && values.waba && (!values.live || values.waba.length > 1)) {
191
+ throw new UsageError('compare takes one --waba, together with --live.');
192
+ }
193
+ if (command === 'compare' && values.live && extra.length !== 1) {
194
+ throw new UsageError('compare --live needs one backup set folder.');
195
+ }
196
+ const unsupported = Object.keys(values).filter(
197
+ (key) => !['json', 'help'].includes(key) && !allowed.includes(key),
198
+ );
199
+ if (unsupported.length > 0) {
200
+ throw new UsageError(`"${command}" does not take --${unsupported.join(', --')}.`);
201
+ }
202
+ loadDotenvFile(cwd, environment);
203
+ if (!isTwoWabas && command === 'compare' && !values.live) {
204
+ if (extra.length !== 2) {
205
+ throw new UsageError('compare needs two backup set folders.');
206
+ }
207
+ const report = await compareBackups(
208
+ path.resolve(cwd, extra[0]),
209
+ path.resolve(cwd, extra[1]),
210
+ );
211
+ out(
212
+ values.json
213
+ ? JSON.stringify(report, undefined, 2)
214
+ : formatReport(report).join('\n'),
215
+ );
216
+ return EXIT.ok;
217
+ }
218
+ if (command === 'discover') {
219
+ const report = await discover(
220
+ values['token-env'],
221
+ values.business,
222
+ environment,
223
+ fetchImpl,
224
+ );
225
+ out(
226
+ values.json
227
+ ? JSON.stringify(report, undefined, 2)
228
+ : formatReport(report).join('\n'),
229
+ );
230
+ return report.ok ? EXIT.ok : EXIT.failed;
231
+ }
232
+ const config = loadConfig(cwd);
233
+ for (const warning of config.warnings) {
234
+ error(`Warning: ${warning}`);
235
+ }
236
+ const common = { cwd, config, environment, fetchImpl };
237
+ const names = values.template ?? [];
238
+ let report;
239
+ switch (command) {
240
+ case 'retrieve': {
241
+ requireOption(values.from ?? values['from-waba'], 'from or --from-waba');
242
+ report = await retrieve({
243
+ ...common,
244
+ from: values.from,
245
+ fromWaba: values['from-waba'],
246
+ names,
247
+ });
248
+ break;
249
+ }
250
+ case 'import': {
251
+ requireOption(values.csv, 'csv');
252
+ report = await importCsv({ ...common, csv: values.csv });
253
+ break;
254
+ }
255
+ case 'deploy': {
256
+ requireOption(values.to ?? values['to-waba'], 'to or --to-waba');
257
+ report = await deploy({
258
+ ...common,
259
+ to: values.to,
260
+ from: values.from,
261
+ toWabas: values['to-waba'] ?? [],
262
+ fromWaba: values['from-waba'],
263
+ csv: values.csv,
264
+ names,
265
+ dryRun: values['dry-run'] === true,
266
+ prune: values.prune === true,
267
+ yes: values.yes === true,
268
+ backupDir: values.backup && path.resolve(cwd, values.backup),
269
+ backupAfter: values['backup-after'] === true,
270
+ expectedActions: values.expect
271
+ ? readExpectedActions(path.resolve(cwd, values.expect))
272
+ : undefined,
273
+ sourceDir: values['from-dir'] && path.resolve(cwd, values['from-dir']),
274
+ });
275
+ break;
276
+ }
277
+ case 'compare': {
278
+ if (isTwoWabas) {
279
+ report = await compareWabas({
280
+ ...common,
281
+ beforeWaba: values['before-waba'],
282
+ afterWaba: values['after-waba'],
283
+ });
284
+ break;
285
+ }
286
+ report = await compareWithLive({
287
+ ...common,
288
+ set: path.resolve(cwd, extra[0]),
289
+ wabaId: values.waba?.[0],
290
+ });
291
+ break;
292
+ }
293
+ case 'backup': {
294
+ requireOption(values.backup, 'backup');
295
+ report = await createBackup({
296
+ ...common,
297
+ stage: values.stage,
298
+ wabaIds: values.waba ?? [],
299
+ backupDir: path.resolve(cwd, values.backup),
300
+ });
301
+ break;
302
+ }
303
+ case 'list': {
304
+ report = await listTemplates({
305
+ ...common,
306
+ from: values.from,
307
+ fromWaba: values['from-waba'],
308
+ to: values.to,
309
+ toWabas: values['to-waba'] ?? [],
310
+ });
311
+ break;
312
+ }
313
+ default: {
314
+ report = await check({ ...common, stage: values.stage });
315
+ }
316
+ }
317
+ out(values.json ? JSON.stringify(report, undefined, 2) : formatReport(report).join('\n'));
318
+ return report.ok ? EXIT.ok : EXIT.failed;
319
+ } catch (ex) {
320
+ if (values.json) {
321
+ out(
322
+ JSON.stringify(
323
+ {
324
+ command,
325
+ ok: false,
326
+ error: ex.message,
327
+ ...(ex instanceof UsageError && ex.code && { code: ex.code }),
328
+ },
329
+ undefined,
330
+ 2,
331
+ ),
332
+ );
333
+ } else {
334
+ error(`Error: ${ex.message}`);
335
+ }
336
+ return ex instanceof UsageError ? EXIT.usage : EXIT.failed;
337
+ }
338
+ }
339
+
340
+ /**
341
+ * `discover` needs no config: the token comes from the named environment variable.
342
+ *
343
+ * @param {string|undefined} variableName - `--token-env` value.
344
+ * @param {string|undefined} businessId - `--business` value.
345
+ * @param {NodeJS.ProcessEnv} environment
346
+ * @param {typeof fetch} [fetchImpl]
347
+ * @returns {Promise.<object>} Report.
348
+ */
349
+ function discover(variableName, businessId, environment, fetchImpl) {
350
+ requireOption(variableName, 'token-env');
351
+ const token = environment[variableName];
352
+ if (!token) {
353
+ throw new UsageError(
354
+ `The environment variable ${variableName} is not set (or not in .env).`,
355
+ );
356
+ }
357
+ return discoverWabas({ token, businessId, fetchImpl });
358
+ }
359
+
360
+ /**
361
+ * Reads `--expect <file>`: the `--json` report of a `deploy --dry-run` (or just its `targets`).
362
+ *
363
+ * @param {string} file
364
+ * @returns {{wabaId: string, actions: {name: string, language: string, action: string}[]}[]}
365
+ */
366
+ function readExpectedActions(file) {
367
+ let parsed;
368
+ try {
369
+ parsed = parseJson(readFileSync(file, 'utf8'));
370
+ } catch (ex) {
371
+ throw new UsageError(`--expect: cannot read ${file}: ${ex.message}`);
372
+ }
373
+ const targets = Array.isArray(parsed) ? parsed : parsed?.targets;
374
+ const isValid =
375
+ Array.isArray(targets) &&
376
+ targets.every(
377
+ (target) =>
378
+ typeof target?.wabaId === 'string' &&
379
+ Array.isArray(target.actions) &&
380
+ target.actions.every(
381
+ (action) =>
382
+ typeof action?.name === 'string' &&
383
+ typeof action.language === 'string' &&
384
+ typeof action.action === 'string',
385
+ ),
386
+ );
387
+ if (!isValid) {
388
+ throw new UsageError(
389
+ `--expect: ${file} is not the --json output of "deploy --dry-run" (targets[].wabaId, targets[].actions[].name/language/action).`,
390
+ );
391
+ }
392
+ if (parsed?.dryRun === false) {
393
+ throw new UsageError(`--expect: ${file} is from a real deploy, not from --dry-run.`);
394
+ }
395
+ return targets;
396
+ }
397
+
398
+ /**
399
+ * @param {string|undefined} value - Parsed option value.
400
+ * @param {string} name - Option name for the message.
401
+ * @returns {void}
402
+ */
403
+ function requireOption(value, name) {
404
+ if (!value) {
405
+ throw new UsageError(`Missing --${name}.`);
406
+ }
407
+ }