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/lib/compare.js ADDED
@@ -0,0 +1,400 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { pickTargetWabas, parseJson, resolveToken } from './config.js';
4
+ import { UsageError } from './errors.js';
5
+ import { readTemplateDirectory } from './files.js';
6
+ import { createGraphClient } from './graph.js';
7
+ import {
8
+ comparableContent,
9
+ normalizeNewlines,
10
+ normalizeTemplate,
11
+ templateKey,
12
+ } from './normalize.js';
13
+
14
+ /**
15
+ * @typedef {object} FieldChange
16
+ * @property {string} field - Readable field name, e.g. `Body text` or `Button 2 (URL) – URL`.
17
+ * @property {string} [before] - Value in the older set (missing = the field did not exist).
18
+ * @property {string} [after] - Value in the newer set (missing = the field was removed).
19
+ */
20
+
21
+ /**
22
+ * Compares two backup sets (restore points). The older one (by `createdAt` in its manifest) is
23
+ * always "before", whatever order they are given in, so a removed template never looks added.
24
+ *
25
+ * @param {string} setA - Backup set folder.
26
+ * @param {string} setB - Backup set folder.
27
+ * @returns {Promise.<object>} Report: before (the older set), after (the newer set), added, removed, changed (with field changes),
28
+ * unchanged count.
29
+ */
30
+ export async function compareBackups(setA, setB) {
31
+ const [first, second] = await Promise.all([readSet(setA), readSet(setB)]);
32
+ return isOlder(second, first) ? compareSets(second, first) : compareSets(first, second);
33
+ }
34
+
35
+ /**
36
+ * Compares a backup set with what is in a WABA right now. The live state is read into memory only and
37
+ * never saved. The WABA is the one the backup was taken from, unless `wabaId` names another one
38
+ * (it must be in the config, for its token).
39
+ *
40
+ * @param {object} options
41
+ * @param {import('./config.js').Config} options.config
42
+ * @param {NodeJS.ProcessEnv} [options.environment]
43
+ * @param {typeof fetch} [options.fetchImpl]
44
+ * @param {string} options.set - Backup set folder.
45
+ * @param {string} [options.wabaId] - Live WABA (default: the backup's WABA).
46
+ * @returns {Promise.<object>} Report like `compareBackups`; `after` is the live WABA.
47
+ */
48
+ export async function compareWithLive({
49
+ config,
50
+ environment = process.env,
51
+ fetchImpl,
52
+ set,
53
+ wabaId,
54
+ }) {
55
+ const backup = await readSet(set);
56
+ const now = await liveSet(liveTarget(config, backup.info, wabaId), {
57
+ config,
58
+ environment,
59
+ fetchImpl,
60
+ });
61
+ return compareSets(backup, now);
62
+ }
63
+
64
+ /**
65
+ * Compares two WABAs as they are right now. Both are read into memory only, nothing is saved. There is
66
+ * no time order here: the caller says which WABA counts as "before" and which as "after".
67
+ *
68
+ * @param {object} options
69
+ * @param {import('./config.js').Config} options.config
70
+ * @param {NodeJS.ProcessEnv} [options.environment]
71
+ * @param {typeof fetch} [options.fetchImpl]
72
+ * @param {string} options.beforeWaba - WABA ID shown as "before".
73
+ * @param {string} options.afterWaba - WABA ID shown as "after".
74
+ * @returns {Promise.<object>} Report like `compareBackups`; `before` and `after` as chosen.
75
+ */
76
+ export async function compareWabas({
77
+ config,
78
+ environment = process.env,
79
+ fetchImpl,
80
+ beforeWaba,
81
+ afterWaba,
82
+ }) {
83
+ if (!beforeWaba || !afterWaba) {
84
+ throw new UsageError('Give both --before-waba and --after-waba.');
85
+ }
86
+ if (beforeWaba === afterWaba) {
87
+ throw new UsageError('Pick two different WABAs to compare.');
88
+ }
89
+ const hint = 'list it in one stage only';
90
+ const [before, after] = await Promise.all(
91
+ [beforeWaba, afterWaba].map((wabaId) =>
92
+ liveSet(pickTargetWabas(config, undefined, [wabaId], hint)[0], {
93
+ config,
94
+ environment,
95
+ fetchImpl,
96
+ }),
97
+ ),
98
+ );
99
+ return compareSets(before, after);
100
+ }
101
+
102
+ /**
103
+ * A WABA's templates right now, shaped like a backup set (in memory only).
104
+ *
105
+ * @param {{stage: string, entry: import('./config.js').WabaEntry}} target
106
+ * @param {{config: import('./config.js').Config, environment: NodeJS.ProcessEnv, fetchImpl?: typeof fetch}} io
107
+ * @returns {Promise.<{info: object, templates: object[], status: Map.<string, string>}>}
108
+ */
109
+ async function liveSet({ stage, entry }, { config, environment, fetchImpl }) {
110
+ const client = createGraphClient({
111
+ token: resolveToken(entry, environment),
112
+ version: config.graphVersion,
113
+ fetchImpl,
114
+ });
115
+ const live = await client.listTemplates(entry.wabaId);
116
+ return {
117
+ info: { wabaId: entry.wabaId, stage, createdAt: new Date().toISOString(), phase: 'live' },
118
+ templates: live.map((template) => normalizeTemplate(template)),
119
+ status: new Map(live.map((template) => [templateKey(template), template.status])),
120
+ };
121
+ }
122
+
123
+ /**
124
+ * The live WABA and its config entry (for the token). Without `wabaId`, the backup's own WABA in the
125
+ * backup's own stage, so a WABA listed in several stages with different tokens still works.
126
+ *
127
+ * @param {import('./config.js').Config} config
128
+ * @param {{wabaId: string, stage?: string}} info - Backup set info.
129
+ * @param {string} [wabaId] - Another WABA.
130
+ * @returns {{stage: string, entry: import('./config.js').WabaEntry}}
131
+ */
132
+ function liveTarget(config, info, wabaId) {
133
+ const ownStage = config.stages[info.stage];
134
+ return !wabaId && ownStage?.some((entry) => entry.wabaId === info.wabaId)
135
+ ? pickTargetWabas(config, info.stage, [info.wabaId])[0]
136
+ : pickTargetWabas(
137
+ config,
138
+ undefined,
139
+ [wabaId ?? info.wabaId],
140
+ 'list it in one stage only, or use a backup taken from that stage',
141
+ )[0];
142
+ }
143
+
144
+ /**
145
+ * @param {{info: object, templates: object[], status: Map.<string, string>}} older
146
+ * @param {{info: object, templates: object[], status: Map.<string, string>}} newer
147
+ * @returns {object} Compare report.
148
+ */
149
+ function compareSets(older, newer) {
150
+ const before = new Map(older.templates.map((template) => [templateKey(template), template]));
151
+ const after = new Map(newer.templates.map((template) => [templateKey(template), template]));
152
+ const added = [];
153
+ const removed = [];
154
+ const changed = [];
155
+ let unchanged = 0;
156
+ for (const [key, template] of after) {
157
+ if (!before.has(key)) {
158
+ added.push(summary(template, newer));
159
+ }
160
+ }
161
+ for (const [key, template] of before) {
162
+ const next = after.get(key);
163
+ if (!next) {
164
+ removed.push(summary(template, older));
165
+ continue;
166
+ }
167
+ const changes = fieldChanges(template, next);
168
+ if (changes.length === 0) {
169
+ unchanged++;
170
+ } else {
171
+ changed.push({ ...summary(next, newer), statusBefore: older.status.get(key), changes });
172
+ }
173
+ }
174
+ return {
175
+ command: 'compare',
176
+ before: older.info,
177
+ after: newer.info,
178
+ sameWaba: older.info.wabaId === newer.info.wabaId,
179
+ added: added.toSorted(byKey),
180
+ removed: removed.toSorted(byKey),
181
+ changed: changed.toSorted(byKey),
182
+ unchanged,
183
+ ok: true,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * Sort order: name, then language.
189
+ *
190
+ * @param {{name: string, language: string}} a
191
+ * @param {{name: string, language: string}} b
192
+ * @returns {number}
193
+ */
194
+ function byKey(a, b) {
195
+ return templateKey(a).localeCompare(templateKey(b));
196
+ }
197
+
198
+ /**
199
+ * Button settings shown as their own fields; anything else ends up in "other settings".
200
+ */
201
+ const KNOWN_BUTTON_KEYS = new Set(['type', 'text', 'url', 'example', 'phone_number']);
202
+
203
+ /**
204
+ * @param {{info: {createdAt: string, phase?: string}}} a
205
+ * @param {{info: {createdAt: string, phase?: string}}} b
206
+ * @returns {boolean} True when `a` was taken before `b`.
207
+ */
208
+ function isOlder(a, b) {
209
+ return a.info.createdAt === b.info.createdAt
210
+ ? a.info.phase === 'before' && b.info.phase === 'after'
211
+ : a.info.createdAt < b.info.createdAt;
212
+ }
213
+
214
+ /**
215
+ * Reads a backup set: its manifest and its templates.
216
+ *
217
+ * @param {string} directory
218
+ * @returns {Promise.<{info: object, templates: object[], status: Map.<string, string>}>}
219
+ */
220
+ async function readSet(directory) {
221
+ let manifest;
222
+ try {
223
+ manifest = parseJson(await readFile(path.join(directory, 'manifest.json'), 'utf8'));
224
+ } catch (ex) {
225
+ throw new UsageError(
226
+ `${directory} is not a backup set (no readable manifest.json): ${ex.message}`,
227
+ );
228
+ }
229
+ if (manifest.tool !== 'waba-devtools' || !manifest.createdAt || !manifest.wabaId) {
230
+ throw new UsageError(`${directory}: manifest.json is not a waba-devtools backup manifest.`);
231
+ }
232
+ const templates = await readTemplateDirectory(directory);
233
+ const status = new Map(
234
+ (manifest.templates ?? []).map((template) => [templateKey(template), template.status]),
235
+ );
236
+ return {
237
+ info: {
238
+ dir: directory,
239
+ wabaId: manifest.wabaId,
240
+ stage: manifest.stage,
241
+ createdAt: manifest.createdAt,
242
+ phase: manifest.phase,
243
+ },
244
+ templates,
245
+ status,
246
+ };
247
+ }
248
+
249
+ /**
250
+ * @param {object} template
251
+ * @param {{status: Map.<string, string>}} set
252
+ * @returns {{name: string, language: string, category?: string, status?: string}}
253
+ */
254
+ function summary(template, set) {
255
+ return {
256
+ name: template.name,
257
+ language: template.language,
258
+ category: template.category,
259
+ status: set.status.get(templateKey(template)),
260
+ };
261
+ }
262
+
263
+ /**
264
+ * Field-by-field differences, with readable field names. Line endings do not count. If the templates
265
+ * differ in a way no named field shows, one "Other settings" change is reported, so a real change is
266
+ * never listed as unchanged.
267
+ *
268
+ * @param {object} before
269
+ * @param {object} after
270
+ * @returns {FieldChange[]}
271
+ */
272
+ export function fieldChanges(before, after) {
273
+ const old = readableFields(before);
274
+ const next = readableFields(after);
275
+ const changes = [];
276
+ const allFields = new Set([...old.keys(), ...next.keys()]);
277
+ for (const field of allFields) {
278
+ if (old.get(field) !== next.get(field)) {
279
+ changes.push({ field, before: old.get(field), after: next.get(field) });
280
+ }
281
+ }
282
+ if (changes.length === 0 && comparableContent(before) !== comparableContent(after)) {
283
+ changes.push({
284
+ field: 'Other settings',
285
+ before: comparableContent(before),
286
+ after: comparableContent(after),
287
+ });
288
+ }
289
+ return changes;
290
+ }
291
+
292
+ /**
293
+ * Shows a list of values: joined with ", " when that is unambiguous, otherwise as JSON.
294
+ *
295
+ * @param {string[]|undefined} values
296
+ * @returns {string|undefined}
297
+ */
298
+ function listText(values) {
299
+ if (!Array.isArray(values)) {
300
+ return values;
301
+ }
302
+ const isPlain = values.every((value) => typeof value === 'string' && !value.includes(', '));
303
+ return isPlain ? values.join(', ') : JSON.stringify(values);
304
+ }
305
+
306
+ /**
307
+ * Settings of a part that have no field of their own, as one JSON value.
308
+ *
309
+ * @param {object} object
310
+ * @param {Set.<string>} known - Keys already shown as fields.
311
+ * @returns {object|undefined}
312
+ */
313
+ function otherSettings(object, known) {
314
+ const rest = Object.fromEntries(
315
+ Object.entries(object ?? {}).filter(([key]) => !known.has(key)),
316
+ );
317
+ return Object.keys(rest).length > 0 ? rest : undefined;
318
+ }
319
+
320
+ /**
321
+ * Flattens a template into readable field names and text values.
322
+ *
323
+ * @param {object} template
324
+ * @returns {Map.<string, string>}
325
+ */
326
+ function readableFields(template) {
327
+ const fields = new Map();
328
+ const put = (field, value) => {
329
+ if (![undefined, null, ''].includes(value)) {
330
+ fields.set(field, typeof value === 'string' ? value : JSON.stringify(value));
331
+ }
332
+ };
333
+ const clean = normalizeNewlines(template);
334
+ put('Category', clean.category);
335
+ put('Variable format', clean.parameter_format ?? 'POSITIONAL');
336
+ const components = clean.components ?? [];
337
+ for (const component of components) {
338
+ addComponentFields(component, put);
339
+ }
340
+ return fields;
341
+ }
342
+
343
+ const PART_KEYS = new Set(['type', 'format', 'text', 'example']);
344
+ const HEADER_EXAMPLE_KEYS = new Set(['header_text', 'header_handle', 'header_text_named_params']);
345
+ const BODY_EXAMPLE_KEYS = new Set(['body_text', 'body_text_named_params']);
346
+
347
+ /**
348
+ * @param {object} component
349
+ * @param {(field: string, value: any) => void} put
350
+ * @returns {void}
351
+ */
352
+ function addComponentFields(component, put) {
353
+ switch (component.type) {
354
+ case 'HEADER': {
355
+ put('Header type', component.format);
356
+ put('Header text', component.text);
357
+ put('Header example', listText(component.example?.header_text));
358
+ put('Header media example', listText(component.example?.header_handle));
359
+ put('Header named examples', component.example?.header_text_named_params);
360
+ put('Header – other settings', otherSettings(component, PART_KEYS));
361
+ put(
362
+ 'Header example – other settings',
363
+ otherSettings(component.example, HEADER_EXAMPLE_KEYS),
364
+ );
365
+ break;
366
+ }
367
+ case 'BODY': {
368
+ const rows = component.example?.body_text ?? [];
369
+ put('Body text', component.text);
370
+ put('Body examples', rows.length > 1 ? JSON.stringify(rows) : listText(rows[0]));
371
+ put('Body named examples', component.example?.body_text_named_params);
372
+ put('Body – other settings', otherSettings(component, PART_KEYS));
373
+ put(
374
+ 'Body example – other settings',
375
+ otherSettings(component.example, BODY_EXAMPLE_KEYS),
376
+ );
377
+ break;
378
+ }
379
+ case 'FOOTER': {
380
+ put('Footer text', component.text);
381
+ put('Footer – other settings', otherSettings(component, PART_KEYS));
382
+ break;
383
+ }
384
+ case 'BUTTONS': {
385
+ const buttons = component.buttons ?? [];
386
+ for (const [index, button] of buttons.entries()) {
387
+ const label = `Button ${index + 1} (${button.type})`;
388
+ put(`${label} – text`, button.text);
389
+ put(`${label} – URL`, button.url);
390
+ put(`${label} – URL example`, listText(button.example));
391
+ put(`${label} – phone number`, button.phone_number);
392
+ put(`${label} – other settings`, otherSettings(button, KNOWN_BUTTON_KEYS));
393
+ }
394
+ break;
395
+ }
396
+ default: {
397
+ put(`${component.type} (other part)`, component);
398
+ }
399
+ }
400
+ }
package/lib/config.js ADDED
@@ -0,0 +1,280 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseEnv } from 'node:util';
4
+ import { UsageError } from './errors.js';
5
+
6
+ export const CONFIG_FILE = '.wabadevrc.json';
7
+ export const DEFAULT_GRAPH_VERSION = 'v23.0';
8
+ export const DEFAULT_TEMPLATES_DIR = 'templates';
9
+
10
+ /**
11
+ * Removes a leading UTF-8 byte-order mark, which Windows editors and PowerShell 5.1 write.
12
+ *
13
+ * @param {string} text
14
+ * @returns {string}
15
+ */
16
+ export function stripBom(text) {
17
+ return text.replace(/^\u{FEFF}/u, '');
18
+ }
19
+
20
+ /**
21
+ * `JSON.parse` that tolerates a leading UTF-8 byte-order mark.
22
+ *
23
+ * @param {string} text
24
+ * @returns {any}
25
+ */
26
+ export function parseJson(text) {
27
+ return JSON.parse(stripBom(text));
28
+ }
29
+
30
+ /**
31
+ * @typedef {object} WabaEntry
32
+ * @property {string} wabaId - WhatsApp Business Account ID.
33
+ * @property {string} tokenEnv - Name of the environment variable that holds the access token.
34
+ */
35
+
36
+ /**
37
+ * @typedef {object} Config
38
+ * @property {string} graphVersion - Graph API version, e.g. `v23.0`.
39
+ * @property {string} templatesDir - Absolute path of the template folder.
40
+ * @property {Object.<string, WabaEntry[]>} stages - Stage name to its WABAs.
41
+ * @property {string[]} warnings - Config problems that were fixed automatically (shown as warnings).
42
+ */
43
+
44
+ /**
45
+ * Loads `.env` from the project root into `process.env`. Variables that are already set win.
46
+ *
47
+ * @param {string} cwd - Project root.
48
+ * @param {NodeJS.ProcessEnv} [environment] - Environment to fill (default `process.env`).
49
+ * @returns {string[]} Names of the variables that were set from the file.
50
+ */
51
+ export function loadDotenvFile(cwd, environment = process.env) {
52
+ const file = path.join(cwd, '.env');
53
+ if (!existsSync(file)) {
54
+ return [];
55
+ }
56
+ const parsed = parseEnv(stripBom(readFileSync(file, 'utf8')));
57
+ const loaded = [];
58
+ for (const [key, value] of Object.entries(parsed)) {
59
+ if (environment[key] !== undefined) {
60
+ continue;
61
+ }
62
+
63
+ environment[key] = value;
64
+ loaded.push(key);
65
+ }
66
+ return loaded;
67
+ }
68
+
69
+ /**
70
+ * Reads and validates `.wabadevrc.json`.
71
+ *
72
+ * @param {string} cwd - Project root.
73
+ * @returns {Config}
74
+ */
75
+ export function loadConfig(cwd) {
76
+ const file = path.join(cwd, CONFIG_FILE);
77
+ if (!existsSync(file)) {
78
+ throw new UsageError(`No ${CONFIG_FILE} found in ${cwd}. See the README for its format.`);
79
+ }
80
+ let raw;
81
+ try {
82
+ raw = parseJson(readFileSync(file, 'utf8'));
83
+ } catch (ex) {
84
+ throw new UsageError(`${CONFIG_FILE} is not valid JSON: ${ex.message}`);
85
+ }
86
+ return validateConfig(raw, cwd);
87
+ }
88
+
89
+ /**
90
+ * @param {any} raw - Parsed config file.
91
+ * @param {string} cwd - Project root, used to resolve `templatesDir`.
92
+ * @returns {Config}
93
+ */
94
+ export function validateConfig(raw, cwd) {
95
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
96
+ throw new UsageError(`${CONFIG_FILE} must contain a JSON object.`);
97
+ }
98
+ const graphVersion = raw.graphVersion ?? DEFAULT_GRAPH_VERSION;
99
+ if (typeof graphVersion !== 'string' || !/^v\d+\.\d+$/.test(graphVersion)) {
100
+ throw new UsageError(`${CONFIG_FILE}: graphVersion must look like "v23.0".`);
101
+ }
102
+ const templatesFolder = raw.templatesDir ?? DEFAULT_TEMPLATES_DIR;
103
+ if (typeof templatesFolder !== 'string' || templatesFolder === '') {
104
+ throw new UsageError(`${CONFIG_FILE}: templatesDir must be a non-empty string.`);
105
+ }
106
+ if (!raw.stages || typeof raw.stages !== 'object' || Array.isArray(raw.stages)) {
107
+ throw new UsageError(`${CONFIG_FILE}: "stages" must be an object of stage name to WABAs.`);
108
+ }
109
+ const stages = {};
110
+ const warnings = [];
111
+ for (const [stage, entries] of Object.entries(raw.stages)) {
112
+ if (!Array.isArray(entries) || entries.length === 0) {
113
+ throw new UsageError(`${CONFIG_FILE}: stage "${stage}" needs at least one WABA entry.`);
114
+ }
115
+ stages[stage] = entries.map((entry, index) => {
116
+ const where = `stage "${stage}", entry ${index + 1}`;
117
+ if (!entry || typeof entry.wabaId !== 'string' || !/^\d+$/.test(entry.wabaId)) {
118
+ throw new UsageError(`${CONFIG_FILE}: ${where}: wabaId must be a numeric string.`);
119
+ }
120
+ if (typeof entry.tokenEnv !== 'string' || !/^[A-Za-z_]\w*$/.test(entry.tokenEnv)) {
121
+ throw new UsageError(
122
+ `${CONFIG_FILE}: ${where}: tokenEnv must be an environment variable name.`,
123
+ );
124
+ }
125
+ return { wabaId: entry.wabaId, tokenEnv: entry.tokenEnv };
126
+ });
127
+ stages[stage] = dropDuplicates(stage, stages[stage], warnings);
128
+ }
129
+ return { graphVersion, templatesDir: path.resolve(cwd, templatesFolder), stages, warnings };
130
+ }
131
+
132
+ /**
133
+ * Keeps the first entry of a WABA listed twice in one stage, so it is deployed only once.
134
+ *
135
+ * @param {string} stage
136
+ * @param {WabaEntry[]} entries
137
+ * @param {string[]} warnings - Receives one message per dropped entry.
138
+ * @returns {WabaEntry[]}
139
+ */
140
+ function dropDuplicates(stage, entries, warnings) {
141
+ const kept = new Map();
142
+ for (const entry of entries) {
143
+ const first = kept.get(entry.wabaId);
144
+ if (first) {
145
+ warnings.push(
146
+ `${CONFIG_FILE}: stage "${stage}" lists WABA ${entry.wabaId} more than once; it is used once (tokenEnv ${first.tokenEnv}).`,
147
+ );
148
+ } else {
149
+ kept.set(entry.wabaId, entry);
150
+ }
151
+ }
152
+ return kept.values().toArray();
153
+ }
154
+
155
+ /**
156
+ * @param {Config} config
157
+ * @param {string} name - Stage name.
158
+ * @returns {WabaEntry[]}
159
+ */
160
+ export function getStage(config, name) {
161
+ const entries = config.stages[name];
162
+ if (!entries) {
163
+ const known = Object.keys(config.stages).join(', ');
164
+ throw new UsageError(`Unknown stage "${name}". Stages in ${CONFIG_FILE}: ${known}.`);
165
+ }
166
+ return entries;
167
+ }
168
+
169
+ /**
170
+ * A WABA entry together with the stage it was found in.
171
+ *
172
+ * @typedef {object} StageWaba
173
+ * @property {string} stage - Stage name (several names joined when the WABA is in more stages).
174
+ * @property {string[]} stages - All stages the WABA was found in.
175
+ * @property {WabaEntry} entry
176
+ */
177
+
178
+ /**
179
+ * Finds a WABA in the config without a stage. A WABA listed in several stages is fine as long as
180
+ * all of them use the same token variable.
181
+ *
182
+ * @param {Config} config
183
+ * @param {string} wabaId
184
+ * @param {string} hint - What to do when the WABA is ambiguous, for the error message.
185
+ * @returns {StageWaba}
186
+ */
187
+ function locateWaba(config, wabaId, hint) {
188
+ const matches = Object.entries(config.stages).flatMap(([stage, entries]) =>
189
+ entries.filter((entry) => entry.wabaId === wabaId).map((entry) => ({ stage, entry })),
190
+ );
191
+ if (matches.length === 0) {
192
+ throw new UsageError(`WABA ${wabaId} is not in ${CONFIG_FILE}.`);
193
+ }
194
+ const stages = matches.map((match) => match.stage).join(', ');
195
+ const tokens = new Set(matches.map((match) => match.entry.tokenEnv));
196
+ if (tokens.size > 1) {
197
+ throw new UsageError(
198
+ `WABA ${wabaId} is in stages ${stages} with different tokens; ${hint}.`,
199
+ );
200
+ }
201
+ return { stage: stages, stages: matches.map((match) => match.stage), entry: matches[0].entry };
202
+ }
203
+
204
+ /**
205
+ * Picks the one source WABA: from `--from`, `--from-waba` or both.
206
+ *
207
+ * @param {Config} config
208
+ * @param {string} [stage] - `--from`.
209
+ * @param {string} [wabaId] - `--from-waba`; required when the stage has several WABAs.
210
+ * @returns {StageWaba}
211
+ */
212
+ export function pickSourceWaba(config, stage, wabaId) {
213
+ if (!stage) {
214
+ if (!wabaId) {
215
+ throw new UsageError('Missing --from or --from-waba.');
216
+ }
217
+ return locateWaba(config, wabaId, 'add --from <stage>');
218
+ }
219
+ const entries = getStage(config, stage);
220
+ if (wabaId) {
221
+ const entry = entries.find((candidate) => candidate.wabaId === wabaId);
222
+ if (!entry) {
223
+ throw new UsageError(`WABA ${wabaId} is not part of stage "${stage}".`);
224
+ }
225
+ return { stage, stages: [stage], entry };
226
+ }
227
+ if (entries.length > 1) {
228
+ const ids = entries.map((entry) => entry.wabaId).join(', ');
229
+ throw new UsageError(
230
+ `Stage "${stage}" has several WABAs (${ids}); pick one with --from-waba.`,
231
+ );
232
+ }
233
+ return { stage, stages: [stage], entry: entries[0] };
234
+ }
235
+
236
+ /**
237
+ * The target WABAs: all of a stage (`--to`), the ones named with `--to-waba`, or the named ones
238
+ * within a stage (both).
239
+ *
240
+ * @param {Config} config
241
+ * @param {string} [stage] - `--to`.
242
+ * @param {string[]} [wabaIds] - `--to-waba` values.
243
+ * @param {string} [hint] - Advice when a WABA is in several stages with different tokens.
244
+ * @returns {StageWaba[]}
245
+ */
246
+ export function pickTargetWabas(config, stage, wabaIds = [], hint = 'add --to <stage>') {
247
+ const wanted = [...new Set(wabaIds)];
248
+ if (!stage) {
249
+ if (wanted.length === 0) {
250
+ throw new UsageError('Missing --to or --to-waba.');
251
+ }
252
+ return wanted.map((wabaId) => locateWaba(config, wabaId, hint));
253
+ }
254
+ const entries = getStage(config, stage);
255
+ const known = new Set(entries.map((entry) => entry.wabaId));
256
+ const unknown = wanted.filter((wabaId) => !known.has(wabaId));
257
+ if (unknown.length > 0) {
258
+ throw new UsageError(`WABA ${unknown.join(', ')} is not part of stage "${stage}".`);
259
+ }
260
+ const selected =
261
+ wanted.length === 0 ? entries : entries.filter((entry) => wanted.includes(entry.wabaId));
262
+ return selected.map((entry) => ({ stage, stages: [stage], entry }));
263
+ }
264
+
265
+ /**
266
+ * Reads the token of a WABA entry from the environment.
267
+ *
268
+ * @param {WabaEntry} entry
269
+ * @param {NodeJS.ProcessEnv} [environment]
270
+ * @returns {string}
271
+ */
272
+ export function resolveToken(entry, environment = process.env) {
273
+ const token = environment[entry.tokenEnv];
274
+ if (!token) {
275
+ throw new UsageError(
276
+ `Environment variable ${entry.tokenEnv} (token for WABA ${entry.wabaId}) is not set.`,
277
+ );
278
+ }
279
+ return token;
280
+ }