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/LICENSE +21 -0
- package/README.md +746 -2
- package/bin/waba.js +4 -0
- package/lib/cli.js +407 -0
- package/lib/commands.js +790 -0
- package/lib/compare.js +400 -0
- package/lib/config.js +280 -0
- package/lib/csv.js +397 -0
- package/lib/errors.js +54 -0
- package/lib/files.js +112 -0
- package/lib/graph.js +187 -0
- package/lib/index.js +21 -0
- package/lib/normalize.js +278 -0
- package/lib/plan.js +110 -0
- package/lib/report.js +229 -0
- package/package.json +64 -5
package/lib/graph.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
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
|
+
*/
|
|
8
|
+
export const TEMPLATE_FIELDS = 'id,name,language,category,status,parameter_format,components';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Fields for a template overview (no components): enough to pick templates and spot overwrites.
|
|
12
|
+
*/
|
|
13
|
+
export const SUMMARY_FIELDS = 'id,name,language,category,status';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {object} GraphClient
|
|
17
|
+
* @property {(wabaId: string, fields?: string) => Promise.<object[]>} listTemplates - All templates,
|
|
18
|
+
* all pages.
|
|
19
|
+
* @property {(wabaId: string, body: object) => Promise.<object>} createTemplate
|
|
20
|
+
* @property {(templateId: string, body: object) => Promise.<object>} updateTemplate
|
|
21
|
+
* @property {(wabaId: string, name: string, templateId: string) => Promise.<object>} deleteTemplate
|
|
22
|
+
* @property {(wabaId: string, fields?: string) => Promise.<object>} getWaba
|
|
23
|
+
* @property {(wabaId: string) => Promise.<object[]>} probeTemplates - First page, one template.
|
|
24
|
+
* @property {() => Promise.<object>} debugToken - Meta's description of this token.
|
|
25
|
+
* @property {(wabaId: string) => Promise.<object[]>} listPhoneNumbers - Sender phone numbers.
|
|
26
|
+
* @property {(businessId: string) => Promise.<object[]>} listBusinessWabas - WABAs a business
|
|
27
|
+
* portfolio owns or has access to as a client.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Meta access tokens start with "EAA"; Meta sometimes repeats a rejected token in its error text.
|
|
32
|
+
*/
|
|
33
|
+
const TOKEN_PATTERN = /EAA[\w-]{16,}/g;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Removes the access token (and anything that looks like a Meta token) from text that may be shown
|
|
37
|
+
* or logged, e.g. Meta's own error messages.
|
|
38
|
+
*
|
|
39
|
+
* @param {string|undefined} text
|
|
40
|
+
* @param {string} token
|
|
41
|
+
* @returns {string|undefined}
|
|
42
|
+
*/
|
|
43
|
+
export function redact(text, token) {
|
|
44
|
+
if (typeof text !== 'string') {
|
|
45
|
+
return text;
|
|
46
|
+
}
|
|
47
|
+
let withoutToken = text;
|
|
48
|
+
if (token && new RegExp(`^${TOKEN_PATTERN.source}$`).test(token)) {
|
|
49
|
+
// A real Meta token is removed wherever it appears, also when Meta repeats it back to back.
|
|
50
|
+
withoutToken = text.split(token).join('[token removed]');
|
|
51
|
+
} else if (token) {
|
|
52
|
+
// Anything else (e.g. a short value pasted by mistake) only as a whole word, so it cannot cut
|
|
53
|
+
// letters out of Meta's text.
|
|
54
|
+
const escaped = token.replaceAll(/[$()*+.?[\\\]^{|}]/g, String.raw`\$&`);
|
|
55
|
+
withoutToken = text.replaceAll(
|
|
56
|
+
new RegExp(String.raw`(?<![\w-])${escaped}(?![\w-])`, 'g'),
|
|
57
|
+
'[token removed]',
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
return withoutToken.replaceAll(TOKEN_PATTERN, '[token removed]');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Thin Graph API client for one access token. The token is sent as a bearer header only.
|
|
65
|
+
*
|
|
66
|
+
* @param {object} options
|
|
67
|
+
* @param {string} options.token - Access token.
|
|
68
|
+
* @param {string} options.version - Graph version, e.g. `v23.0`.
|
|
69
|
+
* @param {typeof fetch} [options.fetchImpl] - Injected `fetch` (tests).
|
|
70
|
+
* @param {string} [options.baseUrl]
|
|
71
|
+
* @returns {GraphClient}
|
|
72
|
+
*/
|
|
73
|
+
export function createGraphClient({ token, version, fetchImpl = fetch, baseUrl = GRAPH_BASE_URL }) {
|
|
74
|
+
const root = `${baseUrl}/${version}/`;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* @param {string} method
|
|
78
|
+
* @param {string} urlOrPath - Path below the version root, or an absolute paging URL.
|
|
79
|
+
* @param {object} [options]
|
|
80
|
+
* @param {Object.<string, string>} [options.query]
|
|
81
|
+
* @param {object} [options.body]
|
|
82
|
+
* @returns {Promise.<any>}
|
|
83
|
+
*/
|
|
84
|
+
async function request(method, urlOrPath, { query, body } = {}) {
|
|
85
|
+
const url = new URL(urlOrPath, root);
|
|
86
|
+
if (url.origin !== new URL(root).origin) {
|
|
87
|
+
// Never send the token to another host (e.g. an unexpected paging URL).
|
|
88
|
+
throw new GraphError({ httpStatus: 0, message: `Refusing request to ${url.origin}` });
|
|
89
|
+
}
|
|
90
|
+
const parameters = Object.entries(query ?? {});
|
|
91
|
+
for (const [key, value] of parameters) {
|
|
92
|
+
url.searchParams.set(key, value);
|
|
93
|
+
}
|
|
94
|
+
const response = await fetchImpl(url, {
|
|
95
|
+
method,
|
|
96
|
+
headers: {
|
|
97
|
+
Authorization: `Bearer ${token}`,
|
|
98
|
+
...(body && { 'Content-Type': 'application/json' }),
|
|
99
|
+
},
|
|
100
|
+
...(body && { body: JSON.stringify(body) }),
|
|
101
|
+
});
|
|
102
|
+
const text = await response.text();
|
|
103
|
+
let data = {};
|
|
104
|
+
if (text) {
|
|
105
|
+
try {
|
|
106
|
+
data = JSON.parse(text);
|
|
107
|
+
} catch {
|
|
108
|
+
data = { raw: text };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (!response.ok || data.error) {
|
|
112
|
+
const error = data.error ?? {};
|
|
113
|
+
throw new GraphError({
|
|
114
|
+
httpStatus: response.status,
|
|
115
|
+
message: redact(error.message ?? `HTTP ${response.status}`, token),
|
|
116
|
+
code: error.code,
|
|
117
|
+
subcode: error.error_subcode,
|
|
118
|
+
userTitle: redact(error.error_user_title, token),
|
|
119
|
+
userMessage: redact(error.error_user_msg, token),
|
|
120
|
+
traceId: error.fbtrace_id,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return data;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Reads every page of a list edge.
|
|
128
|
+
*
|
|
129
|
+
* @param {string} path
|
|
130
|
+
* @param {string} fields
|
|
131
|
+
* @returns {Promise.<object[]>}
|
|
132
|
+
*/
|
|
133
|
+
async function listAll(path, fields) {
|
|
134
|
+
const items = [];
|
|
135
|
+
let page = await request('GET', path, { query: { fields, limit: '100' } });
|
|
136
|
+
items.push(...(page.data ?? []));
|
|
137
|
+
while (page.paging?.next) {
|
|
138
|
+
page = await request('GET', page.paging.next);
|
|
139
|
+
items.push(...(page.data ?? []));
|
|
140
|
+
}
|
|
141
|
+
return items;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
listTemplates(wabaId, fields = TEMPLATE_FIELDS) {
|
|
146
|
+
return listAll(`${encodeURIComponent(wabaId)}/message_templates`, fields);
|
|
147
|
+
},
|
|
148
|
+
async debugToken() {
|
|
149
|
+
const response = await request('GET', 'debug_token', { query: { input_token: token } });
|
|
150
|
+
return response.data ?? {};
|
|
151
|
+
},
|
|
152
|
+
async listBusinessWabas(businessId) {
|
|
153
|
+
const id = encodeURIComponent(businessId);
|
|
154
|
+
const [owned, client] = await Promise.all([
|
|
155
|
+
listAll(`${id}/owned_whatsapp_business_accounts`, 'id,name'),
|
|
156
|
+
listAll(`${id}/client_whatsapp_business_accounts`, 'id,name'),
|
|
157
|
+
]);
|
|
158
|
+
return [...owned, ...client];
|
|
159
|
+
},
|
|
160
|
+
listPhoneNumbers(wabaId) {
|
|
161
|
+
return listAll(
|
|
162
|
+
`${encodeURIComponent(wabaId)}/phone_numbers`,
|
|
163
|
+
'id,display_phone_number,verified_name',
|
|
164
|
+
);
|
|
165
|
+
},
|
|
166
|
+
createTemplate(wabaId, body) {
|
|
167
|
+
return request('POST', `${encodeURIComponent(wabaId)}/message_templates`, { body });
|
|
168
|
+
},
|
|
169
|
+
updateTemplate(templateId, body) {
|
|
170
|
+
return request('POST', encodeURIComponent(templateId), { body });
|
|
171
|
+
},
|
|
172
|
+
deleteTemplate(wabaId, name, templateId) {
|
|
173
|
+
return request('DELETE', `${encodeURIComponent(wabaId)}/message_templates`, {
|
|
174
|
+
query: { name, hsm_id: templateId },
|
|
175
|
+
});
|
|
176
|
+
},
|
|
177
|
+
getWaba(wabaId, fields = 'id,name') {
|
|
178
|
+
return request('GET', encodeURIComponent(wabaId), { query: { fields } });
|
|
179
|
+
},
|
|
180
|
+
async probeTemplates(wabaId) {
|
|
181
|
+
const page = await request('GET', `${encodeURIComponent(wabaId)}/message_templates`, {
|
|
182
|
+
query: { fields: 'id,name', limit: '1' },
|
|
183
|
+
});
|
|
184
|
+
return page.data ?? [];
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
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 { GraphError, UsageError } from './errors.js';
|
|
20
|
+
export { createGraphClient } from './graph.js';
|
|
21
|
+
export { formatReport } from './report.js';
|
package/lib/normalize.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Statuses in which Meta accepts an edit of an existing template.
|
|
3
|
+
*/
|
|
4
|
+
export const EDITABLE_STATUSES = new Set(['APPROVED', 'REJECTED', 'PAUSED']);
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Note for Meta's sample templates, which Meta adds to new WABAs and refuses to edit or delete
|
|
8
|
+
* (error #100/2388094, checked 2026-11).
|
|
9
|
+
*/
|
|
10
|
+
export const META_SAMPLE_NOTE =
|
|
11
|
+
"Meta's sample template — Meta does not allow editing or deleting it";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Whether a live template is one of Meta's sample templates (`hello_world`, `jaspers_market_*`).
|
|
15
|
+
*
|
|
16
|
+
* @param {{name: string}} template
|
|
17
|
+
* @returns {boolean}
|
|
18
|
+
*/
|
|
19
|
+
export function isMetaSampleTemplate(template) {
|
|
20
|
+
return /^(?:hello_world|jaspers_market_\w+)$/.test(template.name);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const MEDIA_HEADER_FORMATS = new Set(['IMAGE', 'VIDEO', 'DOCUMENT']);
|
|
24
|
+
const SAFE_SEGMENT = /^[A-Za-z0-9_]+$/;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {object} Template
|
|
28
|
+
* @property {string} name
|
|
29
|
+
* @property {string} language
|
|
30
|
+
* @property {string} [category]
|
|
31
|
+
* @property {string} [parameter_format]
|
|
32
|
+
* @property {object[]} components
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Returns a copy with object keys sorted at every level (stable files and comparisons).
|
|
37
|
+
*
|
|
38
|
+
* @param {any} value
|
|
39
|
+
* @returns {any}
|
|
40
|
+
*/
|
|
41
|
+
export function sortKeys(value) {
|
|
42
|
+
if (Array.isArray(value)) {
|
|
43
|
+
return value.map(sortKeys);
|
|
44
|
+
}
|
|
45
|
+
if (value && typeof value === 'object') {
|
|
46
|
+
return Object.fromEntries(
|
|
47
|
+
Object.keys(value)
|
|
48
|
+
.toSorted((a, b) => a.localeCompare(b))
|
|
49
|
+
.map((key) => [key, sortKeys(value[key])]),
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Keeps only the fields that define a template and drops read-only ones (id, status, …).
|
|
57
|
+
* Files, CSV rows and live templates all pass through here before they are compared.
|
|
58
|
+
*
|
|
59
|
+
* @param {object} template - Template from a file, a CSV row or the Graph API.
|
|
60
|
+
* @returns {Template}
|
|
61
|
+
*/
|
|
62
|
+
export function normalizeTemplate(template) {
|
|
63
|
+
const normalized = {
|
|
64
|
+
name: template.name,
|
|
65
|
+
language: template.language,
|
|
66
|
+
components: template.components ?? [],
|
|
67
|
+
};
|
|
68
|
+
if (template.category) {
|
|
69
|
+
normalized.category = String(template.category).toUpperCase();
|
|
70
|
+
}
|
|
71
|
+
if (template.parameter_format) {
|
|
72
|
+
normalized.parameter_format = String(template.parameter_format).toUpperCase();
|
|
73
|
+
}
|
|
74
|
+
return sortKeys(normalized);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @param {{name: string, language: string}} template
|
|
79
|
+
* @returns {string}
|
|
80
|
+
*/
|
|
81
|
+
export function templateKey(template) {
|
|
82
|
+
return `${template.name}::${template.language}`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Throws when a name or language could not safely be used as a file or folder name.
|
|
87
|
+
*
|
|
88
|
+
* @param {{name: string, language: string}} template
|
|
89
|
+
* @returns {void}
|
|
90
|
+
*/
|
|
91
|
+
export function assertSafeIdentity(template) {
|
|
92
|
+
const fields = Object.entries({ name: template.name, language: template.language });
|
|
93
|
+
for (const [field, value] of fields) {
|
|
94
|
+
if (typeof value !== 'string' || !SAFE_SEGMENT.test(value)) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`Template ${field} "${value}" may only contain letters, digits and underscores.`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The part of a template that deploy compares. Category is left out on purpose: Meta refuses
|
|
104
|
+
* category edits on approved templates and re-categorizes templates itself.
|
|
105
|
+
*
|
|
106
|
+
* @param {Template} template
|
|
107
|
+
* @returns {string}
|
|
108
|
+
*/
|
|
109
|
+
export function comparableContent(template) {
|
|
110
|
+
return JSON.stringify(
|
|
111
|
+
sortKeys(
|
|
112
|
+
normalizeNewlines({
|
|
113
|
+
components: template.components ?? [],
|
|
114
|
+
parameter_format: template.parameter_format ?? 'POSITIONAL',
|
|
115
|
+
}),
|
|
116
|
+
),
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Copy with `\r\n` and `\r` turned into `\n` in every string, so line endings never count as a change.
|
|
122
|
+
*
|
|
123
|
+
* @param {any} value
|
|
124
|
+
* @returns {any}
|
|
125
|
+
*/
|
|
126
|
+
export function normalizeNewlines(value) {
|
|
127
|
+
if (typeof value === 'string') {
|
|
128
|
+
return value.replaceAll(/\r\n?/g, '\n');
|
|
129
|
+
}
|
|
130
|
+
if (Array.isArray(value)) {
|
|
131
|
+
return value.map(normalizeNewlines);
|
|
132
|
+
}
|
|
133
|
+
if (value && typeof value === 'object') {
|
|
134
|
+
return Object.fromEntries(
|
|
135
|
+
Object.entries(value).map(([key, item]) => [key, normalizeNewlines(item)]),
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Why a template is out of scope for this version, or `undefined` when it is supported.
|
|
143
|
+
*
|
|
144
|
+
* @param {Template} template
|
|
145
|
+
* @returns {string|undefined}
|
|
146
|
+
*/
|
|
147
|
+
export function unsupportedReason(template) {
|
|
148
|
+
if (template.category === 'AUTHENTICATION') {
|
|
149
|
+
return 'authentication (OTP) templates are not supported yet';
|
|
150
|
+
}
|
|
151
|
+
const components = template.components ?? [];
|
|
152
|
+
for (const component of components) {
|
|
153
|
+
const type = String(component.type ?? '').toUpperCase();
|
|
154
|
+
if (type === 'CAROUSEL') {
|
|
155
|
+
return 'carousel templates are not supported yet';
|
|
156
|
+
}
|
|
157
|
+
if (type === 'HEADER' && MEDIA_HEADER_FORMATS.has(String(component.format).toUpperCase())) {
|
|
158
|
+
return 'media headers (image, video, document) are not supported yet';
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Request body for creating a template.
|
|
166
|
+
*
|
|
167
|
+
* @param {Template} template
|
|
168
|
+
* @returns {object}
|
|
169
|
+
*/
|
|
170
|
+
export function toCreateBody(template) {
|
|
171
|
+
return {
|
|
172
|
+
name: template.name,
|
|
173
|
+
language: template.language,
|
|
174
|
+
category: template.category,
|
|
175
|
+
components: template.components,
|
|
176
|
+
...(template.parameter_format && { parameter_format: template.parameter_format }),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Request body for editing a template. Category is never sent (see `comparableContent`).
|
|
182
|
+
*
|
|
183
|
+
* @param {Template} template
|
|
184
|
+
* @returns {object}
|
|
185
|
+
*/
|
|
186
|
+
export function toUpdateBody(template) {
|
|
187
|
+
return {
|
|
188
|
+
components: template.components,
|
|
189
|
+
...(template.parameter_format && { parameter_format: template.parameter_format }),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const COMPONENT_ORDER = ['HEADER', 'BODY', 'FOOTER', 'BUTTONS'];
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Replaces the given component types of `base` with those of `source` (removing them when
|
|
197
|
+
* `source` has none) and keeps all other components. Used for CSV rows: the sheet defines only the
|
|
198
|
+
* parts it has columns for.
|
|
199
|
+
*
|
|
200
|
+
* @param {Template} base - Existing template (file or live).
|
|
201
|
+
* @param {Template} source - Template whose listed parts win.
|
|
202
|
+
* @param {string[]} parts - Component types from `source`, e.g. `['BODY', 'FOOTER']`; buttons per
|
|
203
|
+
* type as `BUTTON:QUICK_REPLY`, `BUTTON:URL`, `BUTTON:PHONE_NUMBER` (other button types are kept).
|
|
204
|
+
* @returns {Template}
|
|
205
|
+
*/
|
|
206
|
+
export function mergeParts(base, source, parts) {
|
|
207
|
+
const owned = new Set(parts);
|
|
208
|
+
const ownedButtons = new Set(
|
|
209
|
+
parts.filter((part) => part.startsWith('BUTTON:')).map((part) => part.slice(7)),
|
|
210
|
+
);
|
|
211
|
+
const kept = (base.components ?? []).filter(
|
|
212
|
+
(component) => !owned.has(component.type) && component.type !== 'BUTTONS',
|
|
213
|
+
);
|
|
214
|
+
const taken = source.components.filter(
|
|
215
|
+
(component) => owned.has(component.type) && component.type !== 'BUTTONS',
|
|
216
|
+
);
|
|
217
|
+
const buttons = mergeButtons(
|
|
218
|
+
buttonsOf(base).filter((button) => !ownedButtons.has(button.type)),
|
|
219
|
+
buttonsOf(source).filter((button) => ownedButtons.has(button.type)),
|
|
220
|
+
);
|
|
221
|
+
const components = [
|
|
222
|
+
...kept,
|
|
223
|
+
...taken,
|
|
224
|
+
...(buttons.length > 0 ? [{ type: 'BUTTONS', buttons }] : []),
|
|
225
|
+
].toSorted((a, b) => componentRank(a) - componentRank(b));
|
|
226
|
+
return normalizeTemplate({
|
|
227
|
+
...base,
|
|
228
|
+
components,
|
|
229
|
+
parameter_format: source.parameter_format ?? base.parameter_format,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Replaces the BODY of `base` with the BODY of `bodySource` and keeps header, footer and buttons.
|
|
235
|
+
*
|
|
236
|
+
* @param {Template} base - Existing template (file or live).
|
|
237
|
+
* @param {Template} bodySource - Template whose BODY wins.
|
|
238
|
+
* @returns {Template}
|
|
239
|
+
*/
|
|
240
|
+
export function mergeBody(base, bodySource) {
|
|
241
|
+
return mergeParts(base, bodySource, ['BODY']);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* @param {Template} template
|
|
246
|
+
* @returns {object[]} Its buttons (none without a BUTTONS component).
|
|
247
|
+
*/
|
|
248
|
+
function buttonsOf(template) {
|
|
249
|
+
return (
|
|
250
|
+
(template.components ?? []).find((component) => component.type === 'BUTTONS')?.buttons ?? []
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Kept and new buttons in one list; quick replies first, so they stay grouped as Meta requires.
|
|
256
|
+
*
|
|
257
|
+
* @param {object[]} kept
|
|
258
|
+
* @param {object[]} taken
|
|
259
|
+
* @returns {object[]}
|
|
260
|
+
*/
|
|
261
|
+
function mergeButtons(kept, taken) {
|
|
262
|
+
const all = [...kept, ...taken];
|
|
263
|
+
return [
|
|
264
|
+
...all.filter((button) => button.type === 'QUICK_REPLY'),
|
|
265
|
+
...all.filter((button) => button.type !== 'QUICK_REPLY'),
|
|
266
|
+
];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Position of a component (header, body, footer, buttons); unknown types go last.
|
|
271
|
+
*
|
|
272
|
+
* @param {{type: string}} component
|
|
273
|
+
* @returns {number}
|
|
274
|
+
*/
|
|
275
|
+
function componentRank(component) {
|
|
276
|
+
const index = COMPONENT_ORDER.indexOf(component.type);
|
|
277
|
+
return index === -1 ? COMPONENT_ORDER.length : index;
|
|
278
|
+
}
|
package/lib/plan.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import {
|
|
2
|
+
EDITABLE_STATUSES,
|
|
3
|
+
META_SAMPLE_NOTE,
|
|
4
|
+
comparableContent,
|
|
5
|
+
isMetaSampleTemplate,
|
|
6
|
+
mergeParts,
|
|
7
|
+
normalizeTemplate,
|
|
8
|
+
templateKey,
|
|
9
|
+
toCreateBody,
|
|
10
|
+
toUpdateBody,
|
|
11
|
+
unsupportedReason,
|
|
12
|
+
} from './normalize.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @typedef {object} SourceTemplate
|
|
16
|
+
* @property {import('./normalize.js').Template} template - Normalized template.
|
|
17
|
+
* @property {string[]} [parts] - CSV row: only these component types are authoritative.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @typedef {object} PlannedAction
|
|
22
|
+
* @property {'create'|'update'|'unchanged'|'blocked'|'skipped'|'extra'|'delete'} action
|
|
23
|
+
* @property {string} name
|
|
24
|
+
* @property {string} language
|
|
25
|
+
* @property {string} [status] - Live status in the target before deploying.
|
|
26
|
+
* @property {string} [templateId] - Live template ID in the target.
|
|
27
|
+
* @property {object} [body] - Request body for create/update.
|
|
28
|
+
* @property {string} [note] - Why blocked/skipped, or a category difference.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Decides what to do per template for one target WABA. Pure: no I/O.
|
|
33
|
+
*
|
|
34
|
+
* @param {object} input
|
|
35
|
+
* @param {SourceTemplate[]} input.source - What should be in the target.
|
|
36
|
+
* @param {object[]} input.target - Live templates of the target WABA (raw Graph objects).
|
|
37
|
+
* @param {boolean} [input.fullSet] - Source is the complete set, so target-only templates count
|
|
38
|
+
* as `extra` (and `delete` with prune).
|
|
39
|
+
* @param {boolean} [input.prune] - Turn `extra` into `delete`.
|
|
40
|
+
* @returns {PlannedAction[]}
|
|
41
|
+
*/
|
|
42
|
+
export function planDeploy({ source, target, fullSet = false, prune = false }) {
|
|
43
|
+
const live = new Map(target.map((template) => [templateKey(template), template]));
|
|
44
|
+
const actions = [];
|
|
45
|
+
const sourceKeys = new Set();
|
|
46
|
+
for (const { template, parts } of source) {
|
|
47
|
+
const key = templateKey(template);
|
|
48
|
+
sourceKeys.add(key);
|
|
49
|
+
const base = { name: template.name, language: template.language };
|
|
50
|
+
const existing = live.get(key);
|
|
51
|
+
const reason =
|
|
52
|
+
unsupportedReason(template) ??
|
|
53
|
+
(existing ? unsupportedReason(normalizeTemplate(existing)) : undefined);
|
|
54
|
+
if (reason) {
|
|
55
|
+
actions.push({ ...base, action: 'skipped', note: reason, status: existing?.status });
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (!existing) {
|
|
59
|
+
actions.push({ ...base, action: 'create', body: toCreateBody(template) });
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const current = normalizeTemplate(existing);
|
|
63
|
+
const desired = parts ? mergeParts(current, template, parts) : template;
|
|
64
|
+
const known = { ...base, status: existing.status, templateId: existing.id };
|
|
65
|
+
const categoryNote =
|
|
66
|
+
template.category && current.category && template.category !== current.category
|
|
67
|
+
? `category ${current.category} in target, ${template.category} in source (not changed)`
|
|
68
|
+
: undefined;
|
|
69
|
+
if (comparableContent(desired) === comparableContent(current)) {
|
|
70
|
+
actions.push({ ...known, action: 'unchanged', note: categoryNote });
|
|
71
|
+
} else if (isMetaSampleTemplate(existing)) {
|
|
72
|
+
actions.push({ ...known, action: 'skipped', note: META_SAMPLE_NOTE });
|
|
73
|
+
} else if (EDITABLE_STATUSES.has(existing.status)) {
|
|
74
|
+
actions.push({
|
|
75
|
+
...known,
|
|
76
|
+
action: 'update',
|
|
77
|
+
body: toUpdateBody(desired),
|
|
78
|
+
note: categoryNote,
|
|
79
|
+
});
|
|
80
|
+
} else {
|
|
81
|
+
actions.push({
|
|
82
|
+
...known,
|
|
83
|
+
action: 'blocked',
|
|
84
|
+
note: `status ${existing.status} cannot be edited`,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (fullSet) {
|
|
89
|
+
for (const [key, existing] of live) {
|
|
90
|
+
if (sourceKeys.has(key)) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Never delete what this tool cannot recreate (media, OTP, carousel), nor Meta's
|
|
95
|
+
// samples, which Meta refuses to delete.
|
|
96
|
+
const reason =
|
|
97
|
+
unsupportedReason(normalizeTemplate(existing)) ??
|
|
98
|
+
(isMetaSampleTemplate(existing) ? META_SAMPLE_NOTE : undefined);
|
|
99
|
+
actions.push({
|
|
100
|
+
name: existing.name,
|
|
101
|
+
language: existing.language,
|
|
102
|
+
status: existing.status,
|
|
103
|
+
templateId: existing.id,
|
|
104
|
+
action: prune && !reason ? 'delete' : 'extra',
|
|
105
|
+
...(reason && { note: `kept: ${reason}` }),
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return actions;
|
|
110
|
+
}
|