@hermoso/ads 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,274 @@
1
+ import { createHmac, randomBytes } from 'node:crypto';
2
+ import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
3
+ import { AdsError } from '../errors.js';
4
+ import { assertBornPaused, gateStatus, gateBudget, gateDelete, STATUS } from '../safety.js';
5
+ import { toMicros, fromMicros } from '../money.js';
6
+ import { hashEmail } from '../hash.js';
7
+
8
+
9
+ const VERSION = '12';
10
+ const PROD = `https://ads-api.x.com/${VERSION}`;
11
+ const SANDBOX = `https://ads-api-sandbox.twitter.com/${VERSION}`;
12
+ const OBJECTIVES = ['APP_ENGAGEMENTS', 'APP_INSTALLS', 'ENGAGEMENTS', 'FOLLOWERS', 'PREROLL_VIEWS', 'REACH', 'VIDEO_VIEWS', 'WEBSITE_CLICKS'];
13
+ const ENTITY = { campaign: 'campaigns', adGroup: 'line_items', ad: 'promoted_tweets' };
14
+
15
+ /** RFC 3986 percent-encoding (encodeURIComponent leaves !*()' bare, OAuth 1.0a does not). */
16
+ export const pct = (v) => encodeURIComponent(String(v)).replace(/[!*()']/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
17
+
18
+ /** Build the exact URL that will be both signed and sent. */
19
+ export function xUrl(base, path, params = {}) {
20
+ const q = Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== '').map(([k, v]) => `${pct(k)}=${pct(Array.isArray(v) ? v.join(',') : v)}`).join('&');
21
+ return `${base}${path}${q ? `?${q}` : ''}`;
22
+ }
23
+
24
+ /** OAuth 1.0a HMAC-SHA1 Authorization header for method + url (query params included in the signature). */
25
+ export function oauth1Header({ method, url, consumerKey, consumerSecret, token, tokenSecret, nonce, timestamp }) {
26
+ const u = new URL(url);
27
+ const oauth = {
28
+ oauth_consumer_key: consumerKey, oauth_nonce: nonce ?? randomBytes(16).toString('hex'), oauth_signature_method: 'HMAC-SHA1',
29
+ oauth_timestamp: String(timestamp ?? Math.floor(Date.now() / 1000)), oauth_version: '1.0', ...(token ? { oauth_token: token } : {}),
30
+ };
31
+ const params = Object.entries(oauth).map(([k, v]) => [pct(k), pct(v)]);
32
+ if (u.search.length > 1) {
33
+ for (const part of u.search.slice(1).split('&')) {
34
+ const [k, v = ''] = part.split('=');
35
+ params.push([pct(decodeURIComponent(k)), pct(decodeURIComponent(v))]);
36
+ }
37
+ }
38
+ params.sort((x, y) => (x[0] === y[0] ? (x[1] < y[1] ? -1 : 1) : x[0] < y[0] ? -1 : 1));
39
+ const paramString = params.map(([k, v]) => `${k}=${v}`).join('&');
40
+ const baseUrl = `${u.protocol}//${u.host}${u.pathname}`;
41
+ const base = `${method.toUpperCase()}&${pct(baseUrl)}&${pct(paramString)}`;
42
+ const key = `${pct(consumerSecret)}&${pct(tokenSecret ?? '')}`;
43
+ const sig = createHmac('sha1', key).update(base).digest('base64');
44
+ return 'OAuth ' + Object.entries({ ...oauth, oauth_signature: sig }).sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => `${pct(k)}="${pct(v)}"`).join(', ');
45
+ }
46
+
47
+ function parseError(status, body) {
48
+ const e = body?.errors?.[0];
49
+ if (!e) return null;
50
+ const code = e.code;
51
+ const message = e.message;
52
+ if (code === 'UNAUTHORIZED_CLIENT_APPLICATION') return { kind: 'permission', code, message, userMessage: 'X: your developer app has not been granted Ads API access.' };
53
+ if (code === 'UNAUTHORIZED_ACCESS') return { kind: 'auth', code, message, userMessage: 'X rejected the OAuth 1.0a signature (usually an encoding mismatch or wrong token secret).' };
54
+ if (code === 'INSUFFICIENT_USER_AUTHORIZED_PERMISSION') return { kind: 'auth', code, message };
55
+ if (/FUNDING_INSTRUMENT/.test(code ?? '')) return { kind: 'refused', code, message, userMessage: `X: billing is not ready on this ad account (${code}). ${message}` };
56
+ if (code === 'ACCOUNT_LOCKED_OUT' || code === 'CURRENT_USER_SUSPENDED') return { kind: 'refused', code, message, userMessage: `X has locked this account (${code}); reconnecting cannot fix it.` };
57
+ return { code, message };
58
+ }
59
+
60
+ const strip = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== null && v !== ''));
61
+
62
+ export default definePlatform({
63
+ id: 'x_ads',
64
+ label: 'X Ads',
65
+ money: 'micros',
66
+ credentials: [
67
+ { name: 'consumerKey', required: true, env: 'X_ADS_CONSUMER_KEY', desc: 'API key of your developer app (with Ads API access).' },
68
+ { name: 'consumerSecret', required: true, env: 'X_ADS_CONSUMER_SECRET' },
69
+ { name: 'accessToken', required: true, env: 'X_ADS_ACCESS_TOKEN', desc: 'OAuth 1.0a user access token.' },
70
+ { name: 'accessTokenSecret', required: true, env: 'X_ADS_ACCESS_TOKEN_SECRET' },
71
+ { name: 'sandbox', env: 'X_ADS_SANDBOX', desc: '"true" for the sandbox host.' },
72
+ ],
73
+ baseUrl: (c) => (c.sandbox === 'true' || c.sandbox === true ? SANDBOX : PROD),
74
+ authHeaders: (c, req) => ({ authorization: oauth1Header({ method: req.method ?? 'GET', url: req.url, consumerKey: c.consumerKey, consumerSecret: c.consumerSecret, token: c.accessToken, tokenSecret: c.accessTokenSecret }) }),
75
+ parseError,
76
+ notes: [
77
+ 'A campaign needs a funding instrument; createCampaign lists the usable ones when none is given.',
78
+ 'Delivery needs BOTH the campaign and the line item active. Promoted posts cannot be paused: pause the line item.',
79
+ 'X silently ignores changes to immutable fields (objective, product type); updates read back and report what did not change.',
80
+ 'Report windows must fall on whole UTC hours; empty stats mean "no data or wrong id", never zero.',
81
+ ],
82
+ setup: {
83
+ app: 'An app in the X developer portal with Ads API access approved for it, and OAuth 1.0a user authentication enabled with your callback URL.',
84
+ scopes: ['(OAuth 1.0a has no scopes: access comes from the app\'s Ads API approval and the user\'s role on the ad account)'],
85
+ review: 'Ads API access is applied for per developer app and reviewed by X. Each advertiser then authorizes your app (three-legged OAuth 1.0a) and needs a role on the ad account.',
86
+ hosted: { connect: 'app', note: 'Hosted Hermoso connects with one click where supported, with no developer app of your own.' },
87
+ docs: 'https://docs.x.com/x-ads-api',
88
+ },
89
+ ops: {
90
+ listAccounts: {
91
+ run: async (ctx, a) => {
92
+ const r = await call(ctx, 'GET', '/accounts', { count: 200 });
93
+ return { items: (r.data ?? []).filter((x) => !x.deleted).map((x) => row(x, { id: x.id, name: x.name, status: x.approval_status, timezone: x.timezone, currency: x.currency }, a)) };
94
+ },
95
+ },
96
+ listCampaigns: {
97
+ params: { accountId: { required: true } },
98
+ run: async (ctx, a) => {
99
+ const r = await call(ctx, 'GET', `/accounts/${a.accountId}/campaigns`, { count: Math.min(a.limit ?? 200, 200), cursor: a.cursor });
100
+ return { items: (r.data ?? []).filter((x) => !x.deleted).map((c) => row(c, { id: c.id, name: c.name, status: c.entity_status, dailyBudget: fromMicros(c.daily_budget_amount_local_micro), totalBudget: fromMicros(c.total_budget_amount_local_micro), fundingInstrumentId: c.funding_instrument_id }, a)), next: r.next_cursor ?? null };
101
+ },
102
+ },
103
+ getCampaign: {
104
+ params: { accountId: { required: true }, id: { required: true } },
105
+ run: async (ctx, a) => { const c = (await call(ctx, 'GET', `/accounts/${a.accountId}/campaigns/${a.id}`)).data; return row(c, { id: c.id, name: c.name, status: c.entity_status, dailyBudget: fromMicros(c.daily_budget_amount_local_micro), totalBudget: fromMicros(c.total_budget_amount_local_micro) }, a); },
106
+ },
107
+ createCampaign: {
108
+ params: { accountId: { required: true }, name: { required: true }, fundingInstrumentId: { type: 'string', desc: 'Required; omit to list the usable ones.' }, dailyBudget: {}, lifetimeBudget: {} },
109
+ run: async (ctx, a) => {
110
+ assertBornPaused(a, 'campaign');
111
+ if (!a.fundingInstrumentId) {
112
+ const f = await call(ctx, 'GET', `/accounts/${a.accountId}/funding_instruments`, { count: 200 });
113
+ const usable = (f.data ?? []).filter((x) => x.able_to_fund && !x.cancelled && !x.deleted).map((x) => ({ id: x.id, type: x.type, currency: x.currency, description: x.description }));
114
+ throw new AdsError('validation', usable.length ? `A campaign needs fundingInstrumentId. Usable: ${usable.map((u) => `${u.id} (${u.type})`).join(', ')}` : 'This ad account has no usable funding instrument; add billing in X Ads first.', { field: 'fundingInstrumentId', hint: { fundingInstruments: usable } });
115
+ }
116
+ if (String(a.name).trim().length < 3) throw new AdsError('validation', 'Campaign name needs at least 3 characters.', { field: 'name' });
117
+ const r = await call(ctx, 'POST', `/accounts/${a.accountId}/campaigns`, strip({ name: a.name, funding_instrument_id: a.fundingInstrumentId, entity_status: 'PAUSED',
118
+ daily_budget_amount_local_micro: a.dailyBudget != null ? toMicros(a.dailyBudget, 'dailyBudget') : undefined,
119
+ total_budget_amount_local_micro: a.lifetimeBudget != null ? toMicros(a.lifetimeBudget, 'lifetimeBudget') : undefined, ...(a.fields ?? {}) }));
120
+ return { id: r.data?.id, status: STATUS.PAUSED };
121
+ },
122
+ },
123
+ listAdGroups: {
124
+ params: { accountId: { required: true }, campaignId: {} },
125
+ run: async (ctx, a) => {
126
+ const r = await call(ctx, 'GET', `/accounts/${a.accountId}/line_items`, { count: 200, campaign_ids: a.campaignId, cursor: a.cursor });
127
+ return { items: (r.data ?? []).filter((x) => !x.deleted).map((l) => row(l, { id: l.id, name: l.name, status: l.entity_status, campaignId: l.campaign_id, objective: l.objective, bid: fromMicros(l.bid_amount_local_micro), bidStrategy: l.bid_strategy }, a)), next: r.next_cursor ?? null };
128
+ },
129
+ },
130
+ createAdGroup: {
131
+ params: {
132
+ accountId: { required: true }, campaignId: { required: true }, name: { required: true }, objective: { type: 'string', enum: OBJECTIVES, required: true },
133
+ bid: { type: 'number', desc: 'Needed for MAX / TARGET bid strategies.' }, bidStrategy: { type: 'string', enum: ['AUTO', 'MAX', 'TARGET'], desc: 'Default AUTO.' },
134
+ placements: { type: 'array', desc: 'Default ["ALL_ON_TWITTER"].' }, goal: { type: 'string' }, startTime: { type: 'string' }, endTime: { type: 'string' }, lifetimeBudget: {},
135
+ },
136
+ run: async (ctx, a) => {
137
+ assertBornPaused(a, 'line item');
138
+ if (!OBJECTIVES.includes(a.objective)) throw new AdsError('validation', `objective must be one of ${OBJECTIVES.join(', ')}`, { field: 'objective' });
139
+ const strategy = a.bidStrategy ?? 'AUTO';
140
+ if (strategy !== 'AUTO' && a.bid == null) throw new AdsError('validation', `${strategy} bidding needs bid.`, { field: 'bid' });
141
+ const r = await call(ctx, 'POST', `/accounts/${a.accountId}/line_items`, strip({
142
+ campaign_id: a.campaignId, name: a.name, objective: a.objective, product_type: a.objective === 'FOLLOWERS' ? 'PROMOTED_ACCOUNT' : 'PROMOTED_TWEETS',
143
+ placements: a.placements ?? ['ALL_ON_TWITTER'], entity_status: 'PAUSED', bid_strategy: strategy, goal: a.goal,
144
+ bid_amount_local_micro: strategy !== 'AUTO' ? toMicros(a.bid, 'bid') : undefined,
145
+ start_time: a.startTime ?? new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'), end_time: a.endTime,
146
+ total_budget_amount_local_micro: a.lifetimeBudget != null ? toMicros(a.lifetimeBudget, 'lifetimeBudget') : undefined, ...(a.fields ?? {}),
147
+ }));
148
+ return { id: r.data?.id, status: STATUS.PAUSED, note: 'No targeting criteria means unrestricted delivery; add targeting before activating.' };
149
+ },
150
+ },
151
+ updateAdGroup: {
152
+ params: { accountId: { required: true }, id: { required: true }, name: {}, bid: { type: 'number' }, endTime: { type: 'string' } },
153
+ run: async (ctx, a) => {
154
+ for (const k of ['objective', 'product_type']) if (a.fields?.[k]) throw new AdsError('validation', `X does not allow changing ${k} on an existing line item.`, { field: k });
155
+ const before = (await call(ctx, 'GET', `/accounts/${a.accountId}/line_items/${a.id}`)).data;
156
+ const params = strip({ name: a.name, end_time: a.endTime, ...(a.fields ?? {}) });
157
+ if (a.bid != null) {
158
+ params.bid_amount_local_micro = toMicros(a.bid, 'bid');
159
+ if (before.entity_status !== 'PAUSED') gateBudget({ ...a, amount: a.bid }, fromMicros(before.bid_amount_local_micro));
160
+ }
161
+ await call(ctx, 'PUT', `/accounts/${a.accountId}/line_items/${a.id}`, params);
162
+ const after = (await call(ctx, 'GET', `/accounts/${a.accountId}/line_items/${a.id}`)).data;
163
+ const unchanged = Object.keys(params).filter((k) => after[k] !== undefined && String(after[k]) === String(before[k]) && String(params[k]) !== String(before[k]));
164
+ return { id: a.id, lineItem: after, ...(unchanged.length ? { unchanged, warning: `X accepted but did not apply: ${unchanged.join(', ')}` } : {}) };
165
+ },
166
+ },
167
+ listAds: {
168
+ params: { accountId: { required: true }, adGroupId: { desc: 'Line item id.' } },
169
+ run: async (ctx, a) => {
170
+ const r = await call(ctx, 'GET', `/accounts/${a.accountId}/promoted_tweets`, { count: 200, line_item_ids: a.adGroupId, cursor: a.cursor });
171
+ return { items: (r.data ?? []).filter((x) => !x.deleted).map((p) => row(p, { id: p.id, postId: p.tweet_id, adGroupId: p.line_item_id, status: p.entity_status, approval: p.approval_status }, a)), next: r.next_cursor ?? null };
172
+ },
173
+ },
174
+ createAd: {
175
+ params: { accountId: { required: true }, adGroupId: { required: true, desc: 'Line item id.' }, postIds: { type: 'array', required: true, desc: 'Existing post ids to promote.' } },
176
+ run: async (ctx, a) => {
177
+ const ids = a.postIds.map((x) => String(x).replace(/\D/g, ''));
178
+ const li = (await call(ctx, 'GET', `/accounts/${a.accountId}/line_items/${a.adGroupId}`)).data;
179
+ if (li?.entity_status === 'ACTIVE') {
180
+ const camp = (await call(ctx, 'GET', `/accounts/${a.accountId}/campaigns/${li.campaign_id}`)).data;
181
+ if (camp?.entity_status === 'ACTIVE' && a.confirm !== true) throw new AdsError('confirm_required', 'This line item and its campaign are live, so a promoted post starts spending at once. Repeat with confirm: true.');
182
+ }
183
+ const r = await call(ctx, 'POST', `/accounts/${a.accountId}/promoted_tweets`, { line_item_id: a.adGroupId, tweet_ids: ids.join(',') });
184
+ return { items: (r.data ?? []).map((p) => ({ id: p.id, postId: p.tweet_id, approval: p.approval_status })) };
185
+ },
186
+ },
187
+ listAudiences: {
188
+ params: { accountId: { required: true } },
189
+ run: async (ctx, a) => {
190
+ const r = await call(ctx, 'GET', `/accounts/${a.accountId}/custom_audiences`, { count: 1000, cursor: a.cursor });
191
+ return { items: (r.data ?? []).filter((x) => !x.deleted).map((x) => row(x, { id: x.id, name: x.name, size: x.audience_size, targetable: x.targetable, reasonsNotTargetable: x.reasons_not_targetable }, a)), next: r.next_cursor ?? null };
192
+ },
193
+ },
194
+ createAudience: {
195
+ params: { accountId: { required: true }, name: { required: true }, description: { type: 'string' }, emails: { type: 'array', desc: 'Hashed here (SHA-256, trimmed + lowercased).' } },
196
+ run: async (ctx, a) => {
197
+ const r = await call(ctx, 'POST', `/accounts/${a.accountId}/custom_audiences`, strip({ name: a.name, description: a.description }));
198
+ const id = r.data?.id;
199
+ const users = (a.emails ?? []).map(hashEmail).filter(Boolean).map((h) => ({ email: [h] }));
200
+ let result;
201
+ if (users.length) {
202
+ if (users.length > 2500) throw new AdsError('validation', 'At most 2500 users per call.', { field: 'emails' });
203
+ const c = await ctx.creds();
204
+ const url = xUrl(baseOf(c), `/accounts/${a.accountId}/custom_audiences/${id}/users`);
205
+ result = await ctx.request({ method: 'POST', url, json: [{ operation_type: 'Update', params: { users } }] });
206
+ }
207
+ return { id, ...(result ? { received: result.data?.total_count, matched: result.data?.success_count } : {}), note: 'An audience takes up to 48 hours to build and needs 100+ matched users to be targetable.' };
208
+ },
209
+ },
210
+ setStatus: {
211
+ params: { accountId: { required: true }, id: { required: true }, level: {}, status: { required: true } },
212
+ run: async (ctx, a) => {
213
+ const status = gateStatus(a);
214
+ const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
215
+ if (level === 'ad') throw new AdsError('validation', 'X cannot pause a promoted post; pause its line item instead.', { field: 'level' });
216
+ if (status === STATUS.ARCHIVED) throw new AdsError('validation', 'X has no archive status; use deleteObject.', { field: 'status' });
217
+ await call(ctx, 'PUT', `/accounts/${a.accountId}/${ENTITY[level]}/${a.id}`, { entity_status: status });
218
+ return { id: a.id, status, ...(status === STATUS.ACTIVE ? { note: 'Delivery needs both the campaign and the line item ACTIVE.' } : {}) };
219
+ },
220
+ },
221
+ setBudget: {
222
+ params: { accountId: { required: true }, id: { required: true, desc: 'Campaign id.' }, amount: { required: true }, kind: { type: 'string', enum: ['daily', 'total'] } },
223
+ run: async (ctx, a) => {
224
+ const cur = (await call(ctx, 'GET', `/accounts/${a.accountId}/campaigns/${a.id}`)).data;
225
+ const field = a.kind === 'total' ? 'total_budget_amount_local_micro' : 'daily_budget_amount_local_micro';
226
+ gateBudget(a, fromMicros(cur[field]));
227
+ await call(ctx, 'PUT', `/accounts/${a.accountId}/campaigns/${a.id}`, { [field]: toMicros(a.amount) });
228
+ return { id: a.id, [a.kind === 'total' ? 'totalBudget' : 'dailyBudget']: Number(a.amount) };
229
+ },
230
+ },
231
+ deleteObject: {
232
+ params: { accountId: { required: true }, id: { required: true }, level: { required: true }, confirm: {}, confirmName: {}, confirmChildren: {} },
233
+ run: async (ctx, a) => {
234
+ const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
235
+ const cur = (await call(ctx, 'GET', `/accounts/${a.accountId}/${ENTITY[level]}/${a.id}`)).data;
236
+ const children = [];
237
+ if (level === 'campaign') children.push({ label: 'line items', count: ((await call(ctx, 'GET', `/accounts/${a.accountId}/line_items`, { campaign_ids: a.id, count: 200 })).data ?? []).filter((x) => !x.deleted).length });
238
+ if (level === 'adGroup') children.push({ label: 'promoted posts', count: ((await call(ctx, 'GET', `/accounts/${a.accountId}/promoted_tweets`, { line_item_ids: a.id, count: 200 })).data ?? []).filter((x) => !x.deleted).length });
239
+ gateDelete(a, { what: level, name: cur?.name, children, live: cur?.entity_status === 'ACTIVE' });
240
+ await call(ctx, 'DELETE', `/accounts/${a.accountId}/${ENTITY[level]}/${a.id}`);
241
+ return { id: a.id, deleted: true };
242
+ },
243
+ },
244
+ report: {
245
+ params: {
246
+ accountId: { required: true }, ids: { type: 'array', required: true, desc: 'Up to 20 entity ids.' }, entity: { type: 'string', desc: 'CAMPAIGN (default), LINE_ITEM, PROMOTED_TWEET, ACCOUNT, FUNDING_INSTRUMENT.' },
247
+ since: {}, until: {}, granularity: { type: 'string', enum: ['HOUR', 'DAY', 'TOTAL'] }, metricGroups: { type: 'array', desc: 'Default ENGAGEMENT, BILLING.' },
248
+ },
249
+ run: async (ctx, a) => {
250
+ if (a.ids.length > 20) throw new AdsError('validation', 'At most 20 ids per stats call.', { field: 'ids' });
251
+ const { since, until } = dateRange(a);
252
+ const end = new Date(Date.parse(`${until}T00:00:00Z`) + 86400000).toISOString().replace('.000Z', 'Z');
253
+ const r = await call(ctx, 'GET', `/stats/accounts/${a.accountId}`, { entity: a.entity ?? 'CAMPAIGN', entity_ids: a.ids.join(','), start_time: `${since}T00:00:00Z`, end_time: end, granularity: a.granularity ?? 'TOTAL', placement: 'ALL_ON_TWITTER', metric_groups: (a.metricGroups ?? ['ENGAGEMENT', 'BILLING']).join(',') });
254
+ const rows = (r.data ?? []).map((d) => ({ id: d.id, metrics: d.id_data?.[0]?.metrics ?? {}, spend: (d.id_data?.[0]?.metrics?.billed_charge_local_micro ?? []).reduce((s, v) => s + (v ?? 0), 0) / 1e6 }));
255
+ return { rows, note: 'All-null metrics mean no data OR an id not on this account; they are not zeros.' };
256
+ },
257
+ },
258
+ searchTargeting: {
259
+ params: { type: { required: true, enum: ['locations', 'interests', 'languages', 'platforms', 'devices', 'conversations'] }, query: { required: true }, locationType: { type: 'string', enum: ['COUNTRIES', 'REGIONS', 'METROS', 'CITIES', 'POSTAL_CODES'] } },
260
+ run: async (ctx, a) => {
261
+ const r = await call(ctx, 'GET', `/targeting_criteria/${a.type}`, a.type === 'locations' ? { q: a.query, location_type: a.locationType, count: 200 } : { count: 1000 });
262
+ const q = String(a.query).toLowerCase();
263
+ const list = (r.data ?? []).filter((x) => a.type === 'locations' || String(x.name).toLowerCase().includes(q));
264
+ return { items: list.slice(0, a.limit ?? 50).map((x) => ({ id: x.targeting_value, name: x.name, type: x.targeting_type ?? x.location_type })) };
265
+ },
266
+ },
267
+ },
268
+ });
269
+
270
+ const baseOf = (c) => (c.sandbox === 'true' || c.sandbox === true ? SANDBOX : PROD);
271
+ async function call(ctx, method, path, params) {
272
+ const c = await ctx.creds();
273
+ return ctx.request({ method, url: xUrl(baseOf(c), path, params) });
274
+ }
package/src/safety.js ADDED
@@ -0,0 +1,96 @@
1
+ import { AdsError } from './errors.js';
2
+
3
+
4
+ export const STATUS = Object.freeze({ ACTIVE: 'ACTIVE', PAUSED: 'PAUSED', ARCHIVED: 'ARCHIVED' });
5
+
6
+ export function normalizeStatus(s) {
7
+ const v = String(s ?? '').trim().toUpperCase();
8
+ if (['ACTIVE', 'ENABLE', 'ENABLED', 'ON', 'RUNNING', 'LIVE'].includes(v)) return STATUS.ACTIVE;
9
+ if (['PAUSED', 'PAUSE', 'DISABLE', 'DISABLED', 'OFF', 'STOPPED'].includes(v)) return STATUS.PAUSED;
10
+ if (['ARCHIVED', 'ARCHIVE'].includes(v)) return STATUS.ARCHIVED;
11
+ throw new AdsError('validation', `status must be ACTIVE, PAUSED or ARCHIVED (got "${s}")`, { field: 'status' });
12
+ }
13
+
14
+ /** Refuse a create that asks to start live. Returns nothing; throws when refused. */
15
+ export function assertBornPaused(args, what = 'object') {
16
+ if (args?.status == null) return;
17
+ const s = normalizeStatus(args.status);
18
+ if (s === STATUS.ACTIVE) {
19
+ throw new AdsError('refused',
20
+ `A new ${what} is always created paused so nothing spends by accident. Create it, check it, then call setStatus with status ACTIVE and confirm: true.`,
21
+ { field: 'status' });
22
+ }
23
+ }
24
+
25
+ export function requireConfirm(args, action) {
26
+ if (args?.confirm === true) return;
27
+ throw new AdsError('confirm_required',
28
+ `${action} can spend money or cannot be undone. Check with the account owner, then repeat the call with confirm: true.`);
29
+ }
30
+
31
+ /** setStatus: activation needs confirm; pausing and archiving-by-pause never do. */
32
+ export function gateStatus(args) {
33
+ const status = normalizeStatus(args?.status);
34
+ if (status === STATUS.ACTIVE) requireConfirm(args, 'Turning this on');
35
+ return status;
36
+ }
37
+
38
+ /**
39
+ * setBudget: raising (or setting when the current value is unknown) needs confirm;
40
+ * lowering is free. `current` is in the same plain units as `amount`, or null when unknown.
41
+ */
42
+ export function gateBudget(args, current = null) {
43
+ const amount = Number(args?.amount);
44
+ if (current != null && Number.isFinite(Number(current)) && amount <= Number(current)) return;
45
+ requireConfirm(args, current == null ? 'Changing a budget' : `Raising the budget from ${current} to ${amount}`);
46
+ }
47
+
48
+ /**
49
+ * Delete/archive blast-radius gate.
50
+ * radius = { what, name, children: [{ label, count }], live, spend }
51
+ * Every delete needs confirm: true. A "heavy" target (it still has children, it is live, or it
52
+ * has spent money) also needs the caller to echo its exact name (confirmName) and the total
53
+ * number of child objects (confirmChildren). Echoing forces whoever is driving to have actually
54
+ * looked at what goes, which a bare boolean never does.
55
+ */
56
+ export function gateDelete(args, radius = {}) {
57
+ const what = radius.what ?? 'object';
58
+ requireConfirm(args, `Deleting this ${what}`);
59
+ const kids = (radius.children ?? []).filter((c) => c.count > 0);
60
+ const total = kids.reduce((n, c) => n + c.count, 0);
61
+ const heavy = total > 0 || radius.live || Number(radius.spend) > 0;
62
+ if (!heavy) return;
63
+ const parts = [];
64
+ if (kids.length) parts.push(kids.map((c) => `${c.count} ${c.label}`).join(', ') + ' underneath');
65
+ if (radius.live) parts.push('it is live');
66
+ if (Number(radius.spend) > 0) parts.push(`it has spent ${radius.spend}`);
67
+ const nameOk = radius.name == null || args.confirmName === radius.name;
68
+ const countOk = Number(args.confirmChildren ?? 0) === total;
69
+ if (!nameOk || !countOk) {
70
+ throw new AdsError('confirm_required',
71
+ `This ${what}${radius.name ? ` ("${radius.name}")` : ''} is not empty: ${parts.join('; ')}. ` +
72
+ `To delete it anyway repeat with confirm: true, confirmName: ${radius.name != null ? JSON.stringify(radius.name) : '(not needed)'} and confirmChildren: ${total}.` +
73
+ (radius.note ? ` ${radius.note}` : ''),
74
+ { hint: { name: radius.name, children: total, live: !!radius.live } });
75
+ }
76
+ }
77
+
78
+ /** Refuse-never-truncate. */
79
+ export function checkLength(field, value, max) {
80
+ if (value == null) return value;
81
+ const s = String(value);
82
+ const length = [...s].length;
83
+ if (length > max) {
84
+ throw new AdsError('validation',
85
+ `${field} is ${length} characters; this platform allows ${max}. Shorten it (nothing was sent or truncated).`,
86
+ { field, max, length });
87
+ }
88
+ return s;
89
+ }
90
+
91
+ export function requireArgs(args, names, op) {
92
+ const missing = names.filter((n) => args?.[n] == null || args[n] === '');
93
+ if (missing.length) {
94
+ throw new AdsError('validation', `${op} needs ${missing.join(', ')}`, { field: missing[0] });
95
+ }
96
+ }
package/src/tools.js ADDED
@@ -0,0 +1,81 @@
1
+ import { createAds, PLATFORMS } from './index.js';
2
+ import { envCredentialStore, layeredCredentialStore } from './credentials.js';
3
+ import { defaultCredentialStore } from './core.js';
4
+
5
+ const JSON_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'object', 'array']);
6
+ const snake = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, (_, a, b) => `${a}_${b}`).replace(/[^a-zA-Z0-9]+/g, '_').toLowerCase();
7
+
8
+ function paramSchema(p = {}) {
9
+ const s = { type: JSON_TYPES.has(p.type) ? p.type : 'string' };
10
+ if (p.desc || p.description) s.description = p.desc || p.description;
11
+ if (Array.isArray(p.enum)) s.enum = p.enum;
12
+ if (s.type === 'array') s.items = p.items && typeof p.items === 'object' ? p.items : {};
13
+ return s;
14
+ }
15
+
16
+ /** The gate for one operation: activating, any budget change and deletes need a yes; everything else does not. */
17
+ export function adsGate(op) {
18
+ return (a = {}) => {
19
+ if (op === 'setStatus') return /^(active|enabled?|on|live|running|resume)$/i.test(String(a.status || '')) ? { kind: 'spend' } : null;
20
+ if (op === 'setBudget') return { kind: 'spend' };
21
+ if (op === 'deleteObject') return { kind: 'delete' };
22
+ if ((op === 'updateCampaign' || op === 'updateAdGroup') && Object.keys(a).some((k) => /budget|bid/i.test(k) && a[k] != null && a[k] !== '')) return { kind: 'spend' };
23
+ if ((op === 'updateCampaign' || op === 'updateAdGroup') && /^(active|enabled?)$/i.test(String(a.status || ''))) return { kind: 'spend' };
24
+ return null;
25
+ };
26
+ }
27
+
28
+ /**
29
+ * getTools(options) → the ads tools. `options` go to createAds (account, credentials, fetch, hooks, platforms). The
30
+ * client is built on first use; listing the tools needs no credentials and makes no network call.
31
+ *
32
+ * Credentials: without `options.credentials`, each platform's environment variables (META_ACCESS_TOKEN, ...; see
33
+ * list_ad_platforms) are read first and @hermoso/core's credential store second, the same order as the standalone
34
+ * ads MCP server, so `list_ad_platforms` and the calls themselves agree on what is connected.
35
+ */
36
+ export function getTools(options = {}) {
37
+ const credentials = options.credentials ?? layeredCredentialStore(envCredentialStore(Object.values(PLATFORMS), options.env || process.env), defaultCredentialStore());
38
+ const account = options.account ?? 'default';
39
+ const opts = { ...options, credentials };
40
+ let client;
41
+ const ads = () => (client ||= createAds(opts));
42
+ const catalog = createAds({ ...opts }).describe();
43
+ const tools = [{
44
+ name: 'list_ad_platforms', group: 'ads', core: true,
45
+ description: 'The ad platforms this install can manage, which operations each supports and which credentials each needs (and whether they are set).',
46
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
47
+ annotations: { readOnlyHint: true, openWorldHint: false },
48
+ run: async () => {
49
+ const out = [];
50
+ const env = options.env || process.env;
51
+ for (const p of catalog) {
52
+ const missing = [];
53
+ for (const c of p.credentials || []) if (c.required && !(c.env && env[c.env])) missing.push(c.name);
54
+ let stored = null;
55
+ try { stored = await credentials.get(account, PLATFORMS[p.id]?.provider ?? p.id); } catch { stored = null; }
56
+ const lacking = (p.credentials || []).filter((c) => c.required === true && (stored?.[c.name] == null || stored[c.name] === '')).map((c) => c.name);
57
+ out.push({ id: p.id, label: p.label, connected: !!stored && !lacking.length, operations: Object.keys(p.ops || {}), credentials: (p.credentials || []).map((c) => ({ name: c.name, required: !!c.required, env: c.env || null })), envMissing: missing, notes: p.notes || [] });
58
+ }
59
+ return { platforms: out };
60
+ },
61
+ summarize: (r) => r.platforms.map((p) => `${p.id} (${p.label}): ${p.connected ? 'connected' : 'not connected'}, ${p.operations.length} operations${!p.connected && p.envMissing.length ? `; needs ${p.envMissing.join(', ')} (env or the credential store)` : ''}`).join('\n'),
62
+ }];
63
+ for (const p of catalog) {
64
+ for (const [op, d] of Object.entries(p.ops || {})) {
65
+ const params = d.params || {};
66
+ const properties = Object.fromEntries(Object.entries(params).map(([k, v]) => [k, paramSchema(v)]));
67
+ const required = Object.entries(params).filter(([, v]) => v.required).map(([k]) => k);
68
+ const write = !!d.write;
69
+ tools.push({
70
+ name: `${p.id}_${snake(op)}`,
71
+ group: 'ads',
72
+ description: `${p.label}: ${d.summary}`,
73
+ inputSchema: { type: 'object', properties, ...(required.length ? { required } : {}) },
74
+ annotations: { readOnlyHint: !write, destructiveHint: op === 'deleteObject', openWorldHint: true },
75
+ gate: adsGate(op),
76
+ run: (a) => ads().run(p.id, op, a),
77
+ });
78
+ }
79
+ }
80
+ return tools;
81
+ }
package/src/zip.js ADDED
@@ -0,0 +1,47 @@
1
+ import { inflateRawSync, gunzipSync } from 'node:zlib';
2
+
3
+ /** Return the first file inside a ZIP archive as a Buffer (stored or deflated entries). */
4
+ export function unzipFirst(buf) {
5
+ let eocd = -1;
6
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
7
+ if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
8
+ }
9
+ if (eocd < 0) throw new Error('not a zip archive');
10
+ const cdOffset = buf.readUInt32LE(eocd + 16);
11
+ if (buf.readUInt32LE(cdOffset) !== 0x02014b50) throw new Error('bad zip central directory');
12
+ const method = buf.readUInt16LE(cdOffset + 10);
13
+ const compSize = buf.readUInt32LE(cdOffset + 20);
14
+ const localOffset = buf.readUInt32LE(cdOffset + 42);
15
+ const nameLen = buf.readUInt16LE(localOffset + 26);
16
+ const extraLen = buf.readUInt16LE(localOffset + 28);
17
+ const start = localOffset + 30 + nameLen + extraLen;
18
+ const data = buf.subarray(start, start + compSize);
19
+ if (method === 0) return Buffer.from(data);
20
+ if (method === 8) return inflateRawSync(data);
21
+ throw new Error(`unsupported zip compression method ${method}`);
22
+ }
23
+
24
+ /** Decompress by magic bytes: gzip (1f 8b), zip (PK), or pass through. */
25
+ export function decompress(buf) {
26
+ if (buf[0] === 0x1f && buf[1] === 0x8b) return gunzipSync(buf);
27
+ if (buf[0] === 0x50 && buf[1] === 0x4b) return unzipFirst(buf);
28
+ return buf;
29
+ }
30
+
31
+ /** Minimal CSV parser (quotes, escaped quotes, CRLF). */
32
+ export function parseCsv(text) {
33
+ const rows = []; let rowv = []; let field = ''; let q = false;
34
+ for (let i = 0; i < text.length; i++) {
35
+ const c = text[i];
36
+ if (q) {
37
+ if (c === '"') { if (text[i + 1] === '"') { field += '"'; i++; } else q = false; } else field += c;
38
+ } else if (c === '"') q = true;
39
+ else if (c === ',') { rowv.push(field); field = ''; }
40
+ else if (c === '\n' || c === '\r') {
41
+ if (c === '\r' && text[i + 1] === '\n') i++;
42
+ rowv.push(field); rows.push(rowv); rowv = []; field = '';
43
+ } else field += c;
44
+ }
45
+ if (field !== '' || rowv.length) { rowv.push(field); rows.push(rowv); }
46
+ return rows;
47
+ }