waba-devtools 0.0.0-stage → 0.2.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/errors.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Error for wrong command-line usage or an invalid project setup (exit code 2).
3
+ */
4
+ export class UsageError extends Error {
5
+ /**
6
+ * @param {string} message - What is wrong and how to fix it.
7
+ * @param {string} [code] - Stable machine-readable reason (e.g. `BUSINESS_ID_REQUIRED`), so callers
8
+ * such as the desktop app can show their own wording.
9
+ */
10
+ constructor(message, code) {
11
+ super(message);
12
+ this.name = 'UsageError';
13
+ if (code) {
14
+ this.code = code;
15
+ }
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Error returned by Meta's Graph API. Carries Meta's own codes and messages, never the token.
21
+ */
22
+ export class GraphError extends Error {
23
+ /**
24
+ * @param {object} details
25
+ * @param {number} details.httpStatus - HTTP status of the response.
26
+ * @param {string} details.message - Meta's error message.
27
+ * @param {number} [details.code] - Meta's error code.
28
+ * @param {number} [details.subcode] - Meta's error subcode.
29
+ * @param {string} [details.userTitle] - Meta's `error_user_title`.
30
+ * @param {string} [details.userMessage] - Meta's `error_user_msg`.
31
+ * @param {string} [details.traceId] - Meta's `fbtrace_id`.
32
+ * @param {number} [details.regainAccessMinutes] - Meta's `estimated_time_to_regain_access` from
33
+ * the `X-Business-Use-Case-Usage` header, when a throttled response carried it.
34
+ */
35
+ constructor({
36
+ httpStatus,
37
+ message,
38
+ code,
39
+ subcode,
40
+ userTitle,
41
+ userMessage,
42
+ traceId,
43
+ regainAccessMinutes,
44
+ }) {
45
+ super(message);
46
+ this.name = 'GraphError';
47
+ this.httpStatus = httpStatus;
48
+ this.code = code;
49
+ this.subcode = subcode;
50
+ this.userTitle = userTitle;
51
+ this.userMessage = userMessage;
52
+ this.traceId = traceId;
53
+ if (regainAccessMinutes !== undefined) {
54
+ this.regainAccessMinutes = regainAccessMinutes;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * One-line description with Meta's codes, for reports.
60
+ *
61
+ * @returns {string}
62
+ */
63
+ describe() {
64
+ const codes = [this.code, this.subcode].filter((value) => value !== undefined).join('/');
65
+ const detail = this.userMessage ? ` — ${this.userMessage}` : '';
66
+ return `${codes ? `(#${codes}) ` : ''}${this.message}${detail}`;
67
+ }
68
+ }
package/lib/files.js ADDED
@@ -0,0 +1,112 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { parseJson } from './config.js';
5
+ import { UsageError } from './errors.js';
6
+ import { assertSafeIdentity, normalizeTemplate, templateKey } from './normalize.js';
7
+
8
+ /**
9
+ * Path of a template file: `<directory>/<name>/<language>.json`.
10
+ *
11
+ * @param {string} directory - Templates folder.
12
+ * @param {{name: string, language: string}} template
13
+ * @returns {string}
14
+ */
15
+ export function templatePath(directory, template) {
16
+ assertSafeIdentity(template);
17
+ return path.join(directory, template.name, `${template.language}.json`);
18
+ }
19
+
20
+ /**
21
+ * Stable file content: sorted keys, 4-space indent, LF, final newline.
22
+ *
23
+ * @param {object} template - Normalized template.
24
+ * @returns {string}
25
+ */
26
+ export function serializeTemplate(template) {
27
+ return `${JSON.stringify(template, undefined, 4)}\n`;
28
+ }
29
+
30
+ /**
31
+ * Reads one template file, or `undefined` when it does not exist.
32
+ *
33
+ * @param {string} directory
34
+ * @param {{name: string, language: string}} identity
35
+ * @returns {Promise.<import('./normalize.js').Template | undefined>}
36
+ */
37
+ export async function readTemplateFile(directory, identity) {
38
+ const file = templatePath(directory, identity);
39
+ return existsSync(file)
40
+ ? normalizeTemplate(parseJson(await readFile(file, 'utf8')))
41
+ : undefined;
42
+ }
43
+
44
+ /**
45
+ * Writes a template file.
46
+ *
47
+ * @param {string} directory
48
+ * @param {import('./normalize.js').Template} template - Normalized template.
49
+ * @returns {Promise.<'created' | 'updated' | 'unchanged'>}
50
+ */
51
+ export async function writeTemplateFile(directory, template) {
52
+ const file = templatePath(directory, template);
53
+ const content = serializeTemplate(template);
54
+ let previous;
55
+ if (existsSync(file)) {
56
+ previous = await readFile(file, 'utf8');
57
+ if (previous === content) {
58
+ return 'unchanged';
59
+ }
60
+ }
61
+ await mkdir(path.dirname(file), { recursive: true });
62
+ await writeFile(file, content, 'utf8');
63
+ return previous === undefined ? 'created' : 'updated';
64
+ }
65
+
66
+ /**
67
+ * Reads all templates below `directory`. File and folder names must match the content.
68
+ *
69
+ * @param {string} directory
70
+ * @returns {Promise.<import('./normalize.js').Template[]>}
71
+ */
72
+ export async function readTemplateDirectory(directory) {
73
+ if (!existsSync(directory)) {
74
+ throw new UsageError(
75
+ `Templates folder ${directory} does not exist. Run "waba retrieve" first.`,
76
+ );
77
+ }
78
+ const templates = [];
79
+ const folders = await readdir(directory, { withFileTypes: true });
80
+ for (const folder of folders) {
81
+ if (!folder.isDirectory()) {
82
+ continue;
83
+ }
84
+ const folderPath = path.join(directory, folder.name);
85
+ const files = await readdir(folderPath, { withFileTypes: true });
86
+ for (const file of files) {
87
+ if (!file.isFile() || !file.name.endsWith('.json')) {
88
+ continue;
89
+ }
90
+ const relative = `${folder.name}/${file.name}`;
91
+ let parsed;
92
+ try {
93
+ parsed = parseJson(await readFile(path.join(folderPath, file.name), 'utf8'));
94
+ } catch (ex) {
95
+ throw new UsageError(`${relative} is not valid JSON: ${ex.message}`);
96
+ }
97
+ const template = normalizeTemplate(parsed);
98
+ if (
99
+ template.name !== folder.name ||
100
+ `${template.language}.json` !== file.name ||
101
+ !template.category
102
+ ) {
103
+ throw new UsageError(
104
+ `${relative} must contain name "${folder.name}", the language of its file ` +
105
+ `name and a category.`,
106
+ );
107
+ }
108
+ templates.push(template);
109
+ }
110
+ }
111
+ return templates.toSorted((a, b) => templateKey(a).localeCompare(templateKey(b)));
112
+ }
package/lib/graph.js ADDED
@@ -0,0 +1,264 @@
1
+ import { GraphError } from './errors.js';
2
+
3
+ export const GRAPH_BASE_URL = 'https://graph.facebook.com';
4
+
5
+ /**
6
+ * Fields requested when listing templates, so normalization always sees the same shape.
7
+ * `last_updated_time` only feeds the hourly write budget of `deploy`; normalization drops it, so it
8
+ * is never compared or written to template files.
9
+ */
10
+ export const TEMPLATE_FIELDS =
11
+ 'id,name,language,category,status,parameter_format,components,last_updated_time';
12
+
13
+ /**
14
+ * Fields for a template overview (no components): enough to pick templates and spot overwrites.
15
+ */
16
+ export const SUMMARY_FIELDS = 'id,name,language,category,status';
17
+
18
+ /**
19
+ * @typedef {object} GraphClient
20
+ * @property {(wabaId: string, fields?: string) => Promise.<object[]>} listTemplates - All templates,
21
+ * all pages.
22
+ * @property {(wabaId: string, body: object) => Promise.<object>} createTemplate
23
+ * @property {(templateId: string, body: object) => Promise.<object>} updateTemplate
24
+ * @property {(wabaId: string, name: string, templateId: string) => Promise.<object>} deleteTemplate
25
+ * @property {(wabaId: string, fields?: string) => Promise.<object>} getWaba
26
+ * @property {(wabaId: string) => Promise.<object[]>} probeTemplates - First page, one template.
27
+ * @property {() => Promise.<object>} debugToken - Meta's description of this token.
28
+ * @property {(wabaId: string) => Promise.<object[]>} listPhoneNumbers - Sender phone numbers.
29
+ * @property {(businessId: string) => Promise.<object[]>} listBusinessWabas - WABAs a business
30
+ * portfolio owns or has access to as a client.
31
+ * @property {() => UsageInfo|undefined} usage - Highest `X-Business-Use-Case-Usage` values seen in
32
+ * this client's responses so far (`undefined` when Meta sent none).
33
+ */
34
+
35
+ /**
36
+ * Meta access tokens start with "EAA"; Meta sometimes repeats a rejected token in its error text.
37
+ */
38
+ const TOKEN_PATTERN = /EAA[\w-]{16,}/g;
39
+
40
+ /**
41
+ * Removes the access token (and anything that looks like a Meta token) from text that may be shown
42
+ * or logged, e.g. Meta's own error messages.
43
+ *
44
+ * @param {string|undefined} text
45
+ * @param {string} token
46
+ * @returns {string|undefined}
47
+ */
48
+ export function redact(text, token) {
49
+ if (typeof text !== 'string') {
50
+ return text;
51
+ }
52
+ let withoutToken = text;
53
+ if (token && new RegExp(`^${TOKEN_PATTERN.source}$`).test(token)) {
54
+ // A real Meta token is removed wherever it appears, also when Meta repeats it back to back.
55
+ withoutToken = text.split(token).join('[token removed]');
56
+ } else if (token) {
57
+ // Anything else (e.g. a short value pasted by mistake) only as a whole word, so it cannot cut
58
+ // letters out of Meta's text.
59
+ const escaped = token.replaceAll(/[$()*+.?[\\\]^{|}]/g, String.raw`\$&`);
60
+ withoutToken = text.replaceAll(
61
+ new RegExp(String.raw`(?<![\w-])${escaped}(?![\w-])`, 'g'),
62
+ '[token removed]',
63
+ );
64
+ }
65
+ return withoutToken.replaceAll(TOKEN_PATTERN, '[token removed]');
66
+ }
67
+
68
+ /**
69
+ * @typedef {object} UsageInfo
70
+ * @property {number} callCount - `call_count`, percent of the hourly allowance used.
71
+ * @property {number} totalCputime - `total_cputime`, percent.
72
+ * @property {number} totalTime - `total_time`, percent.
73
+ * @property {number} regainAccessMinutes - `estimated_time_to_regain_access` (0 = not throttled).
74
+ */
75
+
76
+ const USAGE_FIELDS = [
77
+ ['callCount', 'call_count'],
78
+ ['totalCputime', 'total_cputime'],
79
+ ['totalTime', 'total_time'],
80
+ ['regainAccessMinutes', 'estimated_time_to_regain_access'],
81
+ ];
82
+
83
+ /**
84
+ * Highest of each value in two usage readings.
85
+ *
86
+ * @param {UsageInfo|undefined} a
87
+ * @param {UsageInfo|undefined} b
88
+ * @returns {UsageInfo|undefined}
89
+ */
90
+ export function maxUsage(a, b) {
91
+ return a && b
92
+ ? Object.fromEntries(USAGE_FIELDS.map(([key]) => [key, Math.max(a[key], b[key])]))
93
+ : (a ?? b);
94
+ }
95
+
96
+ /**
97
+ * Meta's business use case usage from the `X-Business-Use-Case-Usage` header of a response: the
98
+ * highest value of each field over all its entries, or `undefined` when the header is missing.
99
+ *
100
+ * @param {Headers|undefined} headers
101
+ * @returns {UsageInfo|undefined}
102
+ */
103
+ export function parseUsage(headers) {
104
+ const raw = headers?.get?.('x-business-use-case-usage');
105
+ if (!raw) {
106
+ return;
107
+ }
108
+ let usage;
109
+ try {
110
+ usage = JSON.parse(raw);
111
+ } catch {
112
+ return;
113
+ }
114
+ const entries = Object.values(usage ?? {})
115
+ .flat()
116
+ .filter((entry) => entry && typeof entry === 'object');
117
+ if (entries.length === 0) {
118
+ return;
119
+ }
120
+ return Object.fromEntries(
121
+ USAGE_FIELDS.map(([key, field]) => [
122
+ key,
123
+ Math.max(0, ...entries.map((entry) => Number(entry[field])).filter(Number.isFinite)),
124
+ ]),
125
+ );
126
+ }
127
+
128
+ /**
129
+ * Thin Graph API client for one access token. The token is sent as a bearer header only.
130
+ *
131
+ * @param {object} options
132
+ * @param {string} options.token - Access token.
133
+ * @param {string} options.version - Graph version, e.g. `v23.0`.
134
+ * @param {typeof fetch} [options.fetchImpl] - Injected `fetch` (tests).
135
+ * @param {string} [options.baseUrl]
136
+ * @returns {GraphClient}
137
+ */
138
+ export function createGraphClient({ token, version, fetchImpl = fetch, baseUrl = GRAPH_BASE_URL }) {
139
+ const root = `${baseUrl}/${version}/`;
140
+ /**
141
+ * Highest usage seen in this client's responses.
142
+ *
143
+ * @type {UsageInfo|undefined}
144
+ */
145
+ let peakUsage;
146
+
147
+ /**
148
+ * @param {string} method
149
+ * @param {string} urlOrPath - Path below the version root, or an absolute paging URL.
150
+ * @param {object} [options]
151
+ * @param {Object.<string, string>} [options.query]
152
+ * @param {object} [options.body]
153
+ * @returns {Promise.<any>}
154
+ */
155
+ async function request(method, urlOrPath, { query, body } = {}) {
156
+ const url = new URL(urlOrPath, root);
157
+ if (url.origin !== new URL(root).origin) {
158
+ // Never send the token to another host (e.g. an unexpected paging URL).
159
+ throw new GraphError({ httpStatus: 0, message: `Refusing request to ${url.origin}` });
160
+ }
161
+ const parameters = Object.entries(query ?? {});
162
+ for (const [key, value] of parameters) {
163
+ url.searchParams.set(key, value);
164
+ }
165
+ const response = await fetchImpl(url, {
166
+ method,
167
+ headers: {
168
+ Authorization: `Bearer ${token}`,
169
+ ...(body && { 'Content-Type': 'application/json' }),
170
+ },
171
+ ...(body && { body: JSON.stringify(body) }),
172
+ });
173
+ const usage = parseUsage(response.headers);
174
+ peakUsage = maxUsage(peakUsage, usage);
175
+ const text = await response.text();
176
+ let data = {};
177
+ if (text) {
178
+ try {
179
+ data = JSON.parse(text);
180
+ } catch {
181
+ data = { raw: text };
182
+ }
183
+ }
184
+ if (!response.ok || data.error) {
185
+ const error = data.error ?? {};
186
+ throw new GraphError({
187
+ httpStatus: response.status,
188
+ message: redact(error.message ?? `HTTP ${response.status}`, token),
189
+ code: error.code,
190
+ subcode: error.error_subcode,
191
+ userTitle: redact(error.error_user_title, token),
192
+ userMessage: redact(error.error_user_msg, token),
193
+ traceId: error.fbtrace_id,
194
+ regainAccessMinutes: usage?.regainAccessMinutes || undefined,
195
+ });
196
+ }
197
+ return data;
198
+ }
199
+
200
+ /**
201
+ * Reads every page of a list edge.
202
+ *
203
+ * @param {string} path
204
+ * @param {string} fields
205
+ * @returns {Promise.<object[]>}
206
+ */
207
+ async function listAll(path, fields) {
208
+ const items = [];
209
+ let page = await request('GET', path, { query: { fields, limit: '100' } });
210
+ items.push(...(page.data ?? []));
211
+ while (page.paging?.next) {
212
+ page = await request('GET', page.paging.next);
213
+ items.push(...(page.data ?? []));
214
+ }
215
+ return items;
216
+ }
217
+
218
+ return {
219
+ usage() {
220
+ return peakUsage && { ...peakUsage };
221
+ },
222
+ listTemplates(wabaId, fields = TEMPLATE_FIELDS) {
223
+ return listAll(`${encodeURIComponent(wabaId)}/message_templates`, fields);
224
+ },
225
+ async debugToken() {
226
+ const response = await request('GET', 'debug_token', { query: { input_token: token } });
227
+ return response.data ?? {};
228
+ },
229
+ async listBusinessWabas(businessId) {
230
+ const id = encodeURIComponent(businessId);
231
+ const [owned, client] = await Promise.all([
232
+ listAll(`${id}/owned_whatsapp_business_accounts`, 'id,name'),
233
+ listAll(`${id}/client_whatsapp_business_accounts`, 'id,name'),
234
+ ]);
235
+ return [...owned, ...client];
236
+ },
237
+ listPhoneNumbers(wabaId) {
238
+ return listAll(
239
+ `${encodeURIComponent(wabaId)}/phone_numbers`,
240
+ 'id,display_phone_number,verified_name',
241
+ );
242
+ },
243
+ createTemplate(wabaId, body) {
244
+ return request('POST', `${encodeURIComponent(wabaId)}/message_templates`, { body });
245
+ },
246
+ updateTemplate(templateId, body) {
247
+ return request('POST', encodeURIComponent(templateId), { body });
248
+ },
249
+ deleteTemplate(wabaId, name, templateId) {
250
+ return request('DELETE', `${encodeURIComponent(wabaId)}/message_templates`, {
251
+ query: { name, hsm_id: templateId },
252
+ });
253
+ },
254
+ getWaba(wabaId, fields = 'id,name') {
255
+ return request('GET', encodeURIComponent(wabaId), { query: { fields } });
256
+ },
257
+ async probeTemplates(wabaId) {
258
+ const page = await request('GET', `${encodeURIComponent(wabaId)}/message_templates`, {
259
+ query: { fields: 'id,name', limit: '1' },
260
+ });
261
+ return page.data ?? [];
262
+ },
263
+ };
264
+ }
package/lib/index.js ADDED
@@ -0,0 +1,29 @@
1
+ export {
2
+ check,
3
+ createBackup,
4
+ deploy,
5
+ discoverWabas,
6
+ importCsv,
7
+ listTemplates,
8
+ retrieve,
9
+ } from './commands.js';
10
+ export { compareBackups, compareWabas, compareWithLive, fieldChanges } from './compare.js';
11
+ export {
12
+ CONFIG_FILE,
13
+ loadConfig,
14
+ loadDotenvFile,
15
+ parseJson,
16
+ stripBom,
17
+ validateConfig,
18
+ } from './config.js';
19
+ export {
20
+ DEFAULT_LIMIT_PERCENT,
21
+ META_CREATES_PER_HOUR,
22
+ planBatches,
23
+ writeBudget,
24
+ writesPerHour,
25
+ } from './budget.js';
26
+ export { templatesToCsv } from './csv.js';
27
+ export { GraphError, UsageError } from './errors.js';
28
+ export { createGraphClient } from './graph.js';
29
+ export { formatReport } from './report.js';