@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,435 @@
1
+ import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
2
+ import { AdsError } from '../errors.js';
3
+ import { assertBornPaused, gateStatus, gateBudget, gateDelete, checkLength, requireConfirm, STATUS } from '../safety.js';
4
+ import { toMicros, fromMicros } from '../money.js';
5
+ import { oauth2Refresh } from '../oauth.js';
6
+
7
+
8
+ const VERSION = 'v26';
9
+ const TOKEN_URL = 'https://oauth2.googleapis.com/token';
10
+
11
+ /** Ids go into GAQL strings, so anything that is not purely digits is refused, never escaped. */
12
+ function digits(v, field = 'id') {
13
+ const s = String(v ?? '').replace(/-/g, '');
14
+ if (!/^\d+$/.test(s)) throw new AdsError('validation', `${field} must be a numeric id (got "${v}")`, { field });
15
+ return s;
16
+ }
17
+ const cid = (a) => digits(a.accountId, 'accountId');
18
+
19
+ const REPORT_FROM = new Set(['campaign', 'ad_group', 'ad_group_ad', 'keyword_view', 'campaign_budget', 'age_range_view', 'gender_view',
20
+ 'geographic_view', 'search_term_view', 'ad_group_criterion', 'campaign_criterion', 'conversion_action', 'user_list', 'asset',
21
+ 'campaign_asset', 'ad_group_asset', 'location_view', 'customer', 'bidding_strategy', 'change_event', 'change_status',
22
+ 'landing_page_view', 'click_view', 'asset_group', 'asset_group_asset', 'label', 'recommendation']);
23
+ const LANGUAGES = { en: 1000, de: 1001, fr: 1002, es: 1003, it: 1004, ja: 1005, da: 1009, nl: 1010, fi: 1011, ko: 1012, no: 1013, pt: 1014, sv: 1015, zh: 1017, ar: 1019, pl: 1030, ru: 1031, tr: 1037, hi: 1023 };
24
+
25
+ function parseError(status, body) {
26
+ const e = body?.error ?? body?.[0]?.error;
27
+ if (!e) return null;
28
+ const errs = (e.details ?? []).flatMap((d) => d.errors ?? []);
29
+ const first = errs[0];
30
+ const codeEnum = first ? Object.values(first.errorCode ?? {})[0] : undefined;
31
+ const msg = errs.length
32
+ ? errs.slice(0, 5).map((x) => `${x.message}${x.location?.fieldPathElements ? ` (${x.location.fieldPathElements.map((f) => f.fieldName).join('.')})` : ''}`).join('; ')
33
+ : e.message;
34
+ const code = codeEnum ?? e.status;
35
+ const out = { code, message: msg };
36
+ if (e.status === 'RESOURCE_EXHAUSTED' || /RESOURCE_(TEMPORARILY_)?EXHAUSTED|EXCESSIVE_/.test(String(codeEnum))) return { ...out, kind: 'rate_limit' };
37
+ if (e.status === 'UNAUTHENTICATED') return { ...out, kind: 'auth' };
38
+ if (codeEnum === 'CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION' || codeEnum === 'DEVELOPER_TOKEN_NOT_APPROVED') {
39
+ return { ...out, kind: 'permission', userMessage: `Google Ads: your developer app is not approved for production (Basic or Standard access) yet. ${msg}` };
40
+ }
41
+ if (['INCOMPLETE_SIGNUP', 'CUSTOMER_NOT_ENABLED', 'NOT_ADS_USER'].includes(codeEnum)) {
42
+ return { ...out, kind: 'refused', userMessage: `Google Ads: this account cannot run ads yet (${codeEnum}); finish its setup and billing at ads.google.com. ${msg}` };
43
+ }
44
+ if (e.status === 'PERMISSION_DENIED') return { ...out, kind: 'permission' };
45
+ if (e.status === 'NOT_FOUND') return { ...out, kind: 'not_found' };
46
+ if (e.status === 'INVALID_ARGUMENT') return { ...out, kind: 'validation' };
47
+ return out;
48
+ }
49
+
50
+ async function search(ctx, accountId, query, max = 2000) {
51
+ const rows = [];
52
+ let pageToken;
53
+ do {
54
+ const r = await ctx.request({ method: 'POST', path: `/customers/${accountId}/googleAds:search`, json: { query, ...(pageToken ? { pageToken } : {}) } });
55
+ rows.push(...(r.results ?? []));
56
+ pageToken = r.nextPageToken;
57
+ } while (pageToken && rows.length < max);
58
+ return rows.slice(0, max);
59
+ }
60
+
61
+ const mutate = (ctx, accountId, resource, operations, validateOnly) =>
62
+ ctx.request({ method: 'POST', path: `/customers/${accountId}/${resource}:mutate`, json: { operations, ...(validateOnly ? { validateOnly: true } : {}) } });
63
+
64
+ /** updateMask must list LEAF paths; a parent path is refused with FIELD_HAS_SUBFIELDS. */
65
+ export function leafMask(obj) {
66
+ const walk = (o, prefix) => Object.entries(o).flatMap(([k, v]) => {
67
+ if (k === 'resourceName') return [];
68
+ const snake = k.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase());
69
+ const path = prefix ? `${prefix}.${snake}` : snake;
70
+ return v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length ? walk(v, path) : [path];
71
+ });
72
+ return walk(obj, '').join(',');
73
+ }
74
+
75
+ function biddingFields(strategy = 'MANUAL_CPC', a) {
76
+ switch (strategy) {
77
+ case 'MANUAL_CPC': return { manualCpc: { enhancedCpcEnabled: false } };
78
+ case 'MAXIMIZE_CLICKS': return { targetSpend: a.maxCpc != null ? { cpcBidCeilingMicros: String(toMicros(a.maxCpc, 'maxCpc')) } : {} };
79
+ case 'MAXIMIZE_CONVERSIONS': case 'TARGET_CPA':
80
+ return { maximizeConversions: a.targetCpa != null ? { targetCpaMicros: String(toMicros(a.targetCpa, 'targetCpa')) } : {} };
81
+ case 'MAXIMIZE_CONVERSION_VALUE': case 'TARGET_ROAS':
82
+ return { maximizeConversionValue: a.targetRoas != null ? { targetRoas: Number(a.targetRoas) } : {} };
83
+ default: throw new AdsError('validation', 'biddingStrategy must be MANUAL_CPC, MAXIMIZE_CLICKS, MAXIMIZE_CONVERSIONS, TARGET_CPA, MAXIMIZE_CONVERSION_VALUE or TARGET_ROAS', { field: 'biddingStrategy' });
84
+ }
85
+ }
86
+
87
+ const statusOut = (s) => ({ ENABLED: STATUS.ACTIVE, PAUSED: STATUS.PAUSED, REMOVED: 'REMOVED' }[s] ?? s);
88
+
89
+ export default definePlatform({
90
+ id: 'google_ads',
91
+ label: 'Google Ads',
92
+ money: 'micros',
93
+ credentials: [
94
+ { name: 'clientId', required: true, env: 'GOOGLE_ADS_CLIENT_ID', desc: 'OAuth client id of your Google Cloud project.' },
95
+ { name: 'clientSecret', required: true, env: 'GOOGLE_ADS_CLIENT_SECRET' },
96
+ { name: 'refreshToken', required: true, env: 'GOOGLE_ADS_REFRESH_TOKEN', desc: 'From an OAuth consent with the adwords scope and access_type=offline.' },
97
+ { name: 'developerToken', env: 'GOOGLE_ADS_DEVELOPER_TOKEN', desc: 'Developer token from your manager account (sent when set).' },
98
+ { name: 'loginCustomerId', env: 'GOOGLE_ADS_LOGIN_CUSTOMER_ID', desc: 'Manager account id, only when acting on a client through a manager.' },
99
+ { name: 'apiVersion', env: 'GOOGLE_ADS_API_VERSION', desc: `Default ${VERSION}.` },
100
+ ],
101
+ baseUrl: (c) => `https://googleads.googleapis.com/${c.apiVersion || VERSION}`,
102
+ authHeaders: (c) => ({
103
+ authorization: `Bearer ${c.accessToken}`,
104
+ ...(c.developerToken ? { 'developer-token': c.developerToken } : {}),
105
+ ...(c.loginCustomerId ? { 'login-customer-id': String(c.loginCustomerId).replace(/\D/g, '') } : {}),
106
+ }),
107
+ refresh: (c, ctx) => oauth2Refresh(ctx, c, { tokenUrl: TOKEN_URL }),
108
+ parseError,
109
+ notes: [
110
+ 'Account ids are digits only (dashes are stripped).',
111
+ 'Campaign creation is one atomic mutate: budget, campaign and targeting succeed or fail together.',
112
+ 'Pass validateOnly: true to any create to have Google check it without creating anything.',
113
+ 'Removing a campaign also removes its budget when nothing else uses it.',
114
+ ],
115
+ setup: {
116
+ app: 'A Google Cloud project with the Google Ads API enabled, an OAuth client (web or desktop), and a developer token from a Google Ads manager account (API Center).',
117
+ scopes: ['https://www.googleapis.com/auth/adwords'],
118
+ review: 'The adwords scope is sensitive: an external OAuth app needs Google verification. The developer token starts at Test access (test accounts only); apply for Basic, then Standard access for production accounts and higher quotas.',
119
+ hosted: { connect: 'app', note: 'Hosted Hermoso connects with one click where supported, with no developer app of your own.' },
120
+ docs: 'https://developers.google.com/google-ads/api/docs/start',
121
+ },
122
+ ops: {
123
+ listAccounts: {
124
+ run: async (ctx, a) => {
125
+ const r = await ctx.request({ path: '/customers:listAccessibleCustomers' });
126
+ const ids = (r.resourceNames ?? []).map((n) => n.split('/')[1]).slice(0, 50);
127
+ const items = [];
128
+ for (const id of ids) {
129
+ try {
130
+ const [c] = await search(ctx, id, 'SELECT customer.id, customer.descriptive_name, customer.currency_code, customer.manager, customer.test_account FROM customer LIMIT 1', 1);
131
+ items.push(row(c, { id, name: c?.customer?.descriptiveName, currency: c?.customer?.currencyCode, manager: c?.customer?.manager, test: c?.customer?.testAccount }, a));
132
+ } catch (e) {
133
+ items.push({ id, error: e.message });
134
+ }
135
+ }
136
+ return { items };
137
+ },
138
+ },
139
+ listCampaigns: {
140
+ params: { accountId: { required: true }, since: {}, until: {}, includeRemoved: { type: 'boolean' } },
141
+ run: async (ctx, a) => {
142
+ const { since, until } = dateRange(a);
143
+ const rows = await search(ctx, cid(a), `SELECT campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign_budget.amount_micros, customer.currency_code, metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions FROM campaign WHERE segments.date BETWEEN '${since}' AND '${until}'${a.includeRemoved ? '' : " AND campaign.status != 'REMOVED'"}`, a.limit ?? 2000);
144
+ return { items: rows.map((r) => row(r, { id: r.campaign.id, name: r.campaign.name, status: statusOut(r.campaign.status), channel: r.campaign.advertisingChannelType,
145
+ dailyBudget: fromMicros(r.campaignBudget?.amountMicros), currency: r.customer?.currencyCode,
146
+ impressions: Number(r.metrics?.impressions ?? 0), clicks: Number(r.metrics?.clicks ?? 0), cost: fromMicros(r.metrics?.costMicros ?? 0), conversions: Number(r.metrics?.conversions ?? 0) }, a)), range: { since, until } };
147
+ },
148
+ },
149
+ getCampaign: {
150
+ params: { accountId: { required: true }, id: { required: true } },
151
+ run: async (ctx, a) => {
152
+ const [r] = await search(ctx, cid(a), `SELECT campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign.bidding_strategy_type, campaign.start_date_time, campaign.end_date_time, campaign_budget.amount_micros, campaign_budget.resource_name FROM campaign WHERE campaign.id = ${digits(a.id)}`, 1);
153
+ if (!r) throw new AdsError('not_found', `Campaign ${a.id} not found in account ${a.accountId}.`);
154
+ return row(r, { id: r.campaign.id, name: r.campaign.name, status: statusOut(r.campaign.status), channel: r.campaign.advertisingChannelType, bidding: r.campaign.biddingStrategyType, dailyBudget: fromMicros(r.campaignBudget?.amountMicros), start: r.campaign.startDateTime, end: r.campaign.endDateTime }, a);
155
+ },
156
+ },
157
+ createCampaign: {
158
+ params: {
159
+ accountId: { required: true }, name: { required: true }, dailyBudget: { required: true },
160
+ channel: { type: 'string', enum: ['SEARCH', 'DISPLAY'], desc: 'Default SEARCH.' },
161
+ biddingStrategy: { type: 'string', desc: 'MANUAL_CPC (default), MAXIMIZE_CLICKS, MAXIMIZE_CONVERSIONS, TARGET_CPA, MAXIMIZE_CONVERSION_VALUE, TARGET_ROAS.' },
162
+ maxCpc: { type: 'number' }, targetCpa: { type: 'number' }, targetRoas: { type: 'number' },
163
+ locations: { type: 'array', desc: 'Geo target constant ids (from searchTargeting type "locations").' },
164
+ languages: { type: 'array', desc: 'Language codes (en, de...) or language constant ids.' },
165
+ searchPartners: { type: 'boolean' }, startDate: { type: 'string', desc: 'YYYY-MM-DD' }, endDate: { type: 'string', desc: 'YYYY-MM-DD' },
166
+ validateOnly: { type: 'boolean', desc: 'Check without creating.' },
167
+ },
168
+ run: async (ctx, a) => {
169
+ assertBornPaused(a, 'campaign');
170
+ const id = cid(a);
171
+ const channel = a.channel ?? 'SEARCH';
172
+ const budgetRn = `customers/${id}/campaignBudgets/-1`;
173
+ const campRn = `customers/${id}/campaigns/-2`;
174
+ const campaign = {
175
+ resourceName: campRn, name: a.name, status: 'PAUSED', advertisingChannelType: channel, campaignBudget: budgetRn,
176
+ containsEuPoliticalAdvertising: a.euPolitical ? 'CONTAINS_EU_POLITICAL_ADVERTISING' : 'DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING',
177
+ networkSettings: channel === 'SEARCH'
178
+ ? { targetGoogleSearch: true, targetSearchNetwork: !!a.searchPartners, targetContentNetwork: false, targetPartnerSearchNetwork: false }
179
+ : { targetGoogleSearch: false, targetSearchNetwork: false, targetContentNetwork: true, targetPartnerSearchNetwork: false },
180
+ ...biddingFields(a.biddingStrategy, a),
181
+ ...(a.startDate ? { startDateTime: `${a.startDate} 00:00:00` } : {}),
182
+ ...(a.endDate ? { endDateTime: `${a.endDate} 23:59:59` } : {}),
183
+ ...(a.fields ?? {}),
184
+ };
185
+ const ops = [
186
+ { campaignBudgetOperation: { create: { resourceName: budgetRn, name: `${a.name} budget ${Date.now()}`, amountMicros: String(toMicros(a.dailyBudget, 'dailyBudget')), deliveryMethod: 'STANDARD', explicitlyShared: false } } },
187
+ { campaignOperation: { create: campaign } },
188
+ ];
189
+ for (const loc of a.locations ?? []) ops.push({ campaignCriterionOperation: { create: { campaign: campRn, location: { geoTargetConstant: `geoTargetConstants/${digits(loc, 'locations')}` } } } });
190
+ for (const lang of a.languages ?? []) {
191
+ const lid = LANGUAGES[String(lang).toLowerCase()] ?? digits(lang, 'languages');
192
+ ops.push({ campaignCriterionOperation: { create: { campaign: campRn, language: { languageConstant: `languageConstants/${lid}` } } } });
193
+ }
194
+ const r = await ctx.request({ method: 'POST', path: `/customers/${id}/googleAds:mutate`, json: { mutateOperations: ops, ...(a.validateOnly ? { validateOnly: true } : {}) } });
195
+ if (a.validateOnly) return { validated: true };
196
+ const rn = (r.mutateOperationResponses ?? []).find((x) => x.campaignResult)?.campaignResult?.resourceName;
197
+ const newId = rn?.split('/').pop();
198
+ const out = { id: newId, resourceName: rn, status: STATUS.PAUSED };
199
+ if (!(a.locations ?? []).length) out.warning = 'No locations given: Google serves this campaign in every country. Add locations before activating.';
200
+ return out;
201
+ },
202
+ },
203
+ updateCampaign: {
204
+ params: { accountId: { required: true }, id: { required: true }, name: {}, endDate: { type: 'string', desc: 'YYYY-MM-DD' }, biddingStrategy: { type: 'string' }, maxCpc: { type: 'number' }, targetCpa: { type: 'number' }, targetRoas: { type: 'number' } },
205
+ run: async (ctx, a) => {
206
+ if (a.status != null) throw new AdsError('validation', 'Use setStatus to change status.', { field: 'status' });
207
+ const id = cid(a);
208
+ const oid = digits(a.id);
209
+ const update = { resourceName: `customers/${id}/campaigns/${oid}`, ...(a.name ? { name: a.name } : {}), ...(a.endDate ? { endDateTime: `${a.endDate} 23:59:59` } : {}), ...(a.fields ?? {}) };
210
+ if (a.biddingStrategy) {
211
+ const [c] = await search(ctx, id, `SELECT campaign.status FROM campaign WHERE campaign.id = ${oid}`, 1);
212
+ if (c?.campaign?.status !== 'PAUSED') requireConfirm(a, 'Changing bidding on a live campaign');
213
+ Object.assign(update, biddingFields(a.biddingStrategy, a));
214
+ }
215
+ const mask = leafMask(update);
216
+ if (!mask) throw new AdsError('validation', 'Nothing to update.', { field: 'name' });
217
+ await mutate(ctx, id, 'campaigns', [{ update, updateMask: mask }], a.validateOnly);
218
+ return { id: oid, updated: mask.split(',') };
219
+ },
220
+ },
221
+ listAdGroups: {
222
+ params: { accountId: { required: true }, campaignId: {} },
223
+ run: async (ctx, a) => {
224
+ const where = a.campaignId ? ` AND campaign.id = ${digits(a.campaignId, 'campaignId')}` : '';
225
+ const rows = await search(ctx, cid(a), `SELECT ad_group.id, ad_group.name, ad_group.status, ad_group.type, ad_group.cpc_bid_micros, campaign.id FROM ad_group WHERE ad_group.status != 'REMOVED'${where}`, a.limit ?? 2000);
226
+ return { items: rows.map((r) => row(r, { id: r.adGroup.id, name: r.adGroup.name, status: statusOut(r.adGroup.status), type: r.adGroup.type, cpcBid: fromMicros(r.adGroup.cpcBidMicros), campaignId: r.campaign?.id }, a)) };
227
+ },
228
+ },
229
+ createAdGroup: {
230
+ params: {
231
+ accountId: { required: true }, campaignId: { required: true }, name: { required: true }, cpcBid: { type: 'number' },
232
+ keywords: { type: 'array', desc: 'Optional [{text, matchType: EXACT|PHRASE|BROAD}] (or strings, PHRASE).' }, validateOnly: { type: 'boolean' },
233
+ },
234
+ run: async (ctx, a) => {
235
+ assertBornPaused(a, 'ad group');
236
+ const id = cid(a);
237
+ const camp = digits(a.campaignId, 'campaignId');
238
+ checkLength('name', a.name, 255);
239
+ const [c] = await search(ctx, id, `SELECT campaign.advertising_channel_type FROM campaign WHERE campaign.id = ${camp}`, 1);
240
+ if (!c) throw new AdsError('not_found', `Campaign ${camp} not found.`);
241
+ const type = c.campaign.advertisingChannelType === 'DISPLAY' ? 'DISPLAY_STANDARD' : 'SEARCH_STANDARD';
242
+ const agRn = `customers/${id}/adGroups/-1`;
243
+ const ops = [{ adGroupOperation: { create: { resourceName: agRn, campaign: `customers/${id}/campaigns/${camp}`, name: a.name, status: 'PAUSED', type,
244
+ ...(a.cpcBid != null ? { cpcBidMicros: String(toMicros(a.cpcBid, 'cpcBid')) } : {}), ...(a.fields ?? {}) } } }];
245
+ const kws = (a.keywords ?? []).map((k) => (typeof k === 'string' ? { text: k } : k));
246
+ if (kws.length > 1000) throw new AdsError('validation', 'At most 1000 keywords per call.', { field: 'keywords' });
247
+ for (const k of kws) {
248
+ checkLength('keyword', k.text, 80);
249
+ if (k.text.trim().split(/\s+/).length > 10) throw new AdsError('validation', `Keyword "${k.text}" has more than 10 words.`, { field: 'keywords' });
250
+ ops.push({ adGroupCriterionOperation: { create: { adGroup: agRn, status: 'ENABLED', keyword: { text: k.text, matchType: k.matchType ?? 'PHRASE' } } } });
251
+ }
252
+ const r = await ctx.request({ method: 'POST', path: `/customers/${id}/googleAds:mutate`, json: { mutateOperations: ops, ...(a.validateOnly ? { validateOnly: true } : {}) } });
253
+ if (a.validateOnly) return { validated: true };
254
+ const rn = (r.mutateOperationResponses ?? []).find((x) => x.adGroupResult)?.adGroupResult?.resourceName;
255
+ return { id: rn?.split('/').pop(), resourceName: rn, status: STATUS.PAUSED, keywords: kws.length };
256
+ },
257
+ },
258
+ listAds: {
259
+ params: { accountId: { required: true }, adGroupId: {}, campaignId: {} },
260
+ run: async (ctx, a) => {
261
+ const where = a.adGroupId ? ` AND ad_group.id = ${digits(a.adGroupId, 'adGroupId')}` : a.campaignId ? ` AND campaign.id = ${digits(a.campaignId, 'campaignId')}` : '';
262
+ const rows = await search(ctx, cid(a), `SELECT ad_group_ad.ad.id, ad_group_ad.ad.name, ad_group_ad.ad.type, ad_group_ad.status, ad_group_ad.ad.final_urls, ad_group_ad.policy_summary.approval_status, ad_group.id FROM ad_group_ad WHERE ad_group_ad.status != 'REMOVED'${where}`, a.limit ?? 2000);
263
+ return { items: rows.map((r) => row(r, { id: r.adGroupAd.ad.id, name: r.adGroupAd.ad.name, type: r.adGroupAd.ad.type, status: statusOut(r.adGroupAd.status), adGroupId: r.adGroup?.id, finalUrls: r.adGroupAd.ad.finalUrls, approval: r.adGroupAd.policySummary?.approvalStatus }, a)) };
264
+ },
265
+ },
266
+ createAd: {
267
+ params: {
268
+ accountId: { required: true }, adGroupId: { required: true }, finalUrl: { type: 'string', required: true },
269
+ headlines: { type: 'array', required: true, desc: 'Responsive search ad: 3-15 headlines, 30 characters each.' },
270
+ descriptions: { type: 'array', required: true, desc: '2-4 descriptions, 90 characters each.' },
271
+ path1: { type: 'string' }, path2: { type: 'string' }, validateOnly: { type: 'boolean' },
272
+ },
273
+ run: async (ctx, a) => {
274
+ assertBornPaused(a, 'ad');
275
+ const id = cid(a);
276
+ if (a.headlines.length < 3 || a.headlines.length > 15) throw new AdsError('validation', 'A responsive search ad needs 3 to 15 headlines.', { field: 'headlines' });
277
+ if (a.descriptions.length < 2 || a.descriptions.length > 4) throw new AdsError('validation', 'A responsive search ad needs 2 to 4 descriptions.', { field: 'descriptions' });
278
+ const asText = (x) => (typeof x === 'string' ? { text: x } : x);
279
+ a.headlines.map(asText).forEach((h, i) => checkLength(`headlines[${i}]`, h.text, 30));
280
+ a.descriptions.map(asText).forEach((d, i) => checkLength(`descriptions[${i}]`, d.text, 90));
281
+ checkLength('path1', a.path1, 15); checkLength('path2', a.path2, 15);
282
+ if (a.path2 && !a.path1) throw new AdsError('validation', 'path2 needs path1.', { field: 'path2' });
283
+ const r = await mutate(ctx, id, 'adGroupAds', [{ create: {
284
+ adGroup: `customers/${id}/adGroups/${digits(a.adGroupId, 'adGroupId')}`, status: 'PAUSED',
285
+ ad: { finalUrls: [a.finalUrl], responsiveSearchAd: { headlines: a.headlines.map(asText), descriptions: a.descriptions.map(asText), path1: a.path1, path2: a.path2 }, ...(a.fields ?? {}) },
286
+ } }], a.validateOnly);
287
+ if (a.validateOnly) return { validated: true };
288
+ const rn = r.results?.[0]?.resourceName;
289
+ return { id: rn?.split('~').pop(), resourceName: rn, status: STATUS.PAUSED };
290
+ },
291
+ },
292
+ uploadAsset: {
293
+ params: { accountId: { required: true }, url: { type: 'string', desc: 'Public image URL.' }, youtubeVideoId: { type: 'string', desc: 'Or a YouTube video id.' }, name: { type: 'string' } },
294
+ run: async (ctx, a) => {
295
+ const id = cid(a);
296
+ let asset;
297
+ if (a.youtubeVideoId) {
298
+ asset = { name: a.name ?? `YouTube ${a.youtubeVideoId}`, type: 'YOUTUBE_VIDEO', youtubeVideoAsset: { youtubeVideoId: a.youtubeVideoId } };
299
+ } else {
300
+ if (!a.url) throw new AdsError('validation', 'Give url (image) or youtubeVideoId.', { field: 'url' });
301
+ const res = await (ctx.publicFetch ?? ctx.fetch)(a.url);
302
+ if (!res.ok) throw new AdsError('validation', `Could not download ${a.url} (HTTP ${res.status})`, { field: 'url' });
303
+ const buf = Buffer.from(await res.arrayBuffer());
304
+ if (buf.length > 5 * 1024 * 1024) throw new AdsError('validation', 'Google Ads images must be 5 MB or smaller.', { field: 'url' });
305
+ asset = { name: a.name ?? `Image ${Date.now()}`, type: 'IMAGE', imageAsset: { data: buf.toString('base64') } };
306
+ }
307
+ checkLength('name', asset.name, 128);
308
+ const r = await mutate(ctx, id, 'assets', [{ create: asset }]);
309
+ const rn = r.results?.[0]?.resourceName;
310
+ return { id: rn?.split('/').pop(), resourceName: rn };
311
+ },
312
+ },
313
+ listAudiences: {
314
+ params: { accountId: { required: true } },
315
+ run: async (ctx, a) => {
316
+ const rows = await search(ctx, cid(a), 'SELECT user_list.id, user_list.name, user_list.type, user_list.size_for_search, user_list.size_for_display, user_list.membership_status FROM user_list', a.limit ?? 2000);
317
+ return { items: rows.map((r) => row(r, { id: r.userList.id, name: r.userList.name, type: r.userList.type, sizeSearch: r.userList.sizeForSearch, sizeDisplay: r.userList.sizeForDisplay, status: r.userList.membershipStatus }, a)) };
318
+ },
319
+ },
320
+ createAudience: {
321
+ params: { accountId: { required: true }, name: { required: true }, urlContains: { type: 'string', required: true, desc: 'Website visitors whose URL contains this text.' }, lifespanDays: { type: 'number', desc: '1-540, default 30.' } },
322
+ run: async (ctx, a) => {
323
+ checkLength('name', a.name, 255);
324
+ const days = a.lifespanDays ?? 30;
325
+ if (days < 1 || days > 540) throw new AdsError('validation', 'lifespanDays must be 1-540.', { field: 'lifespanDays' });
326
+ const r = await mutate(ctx, cid(a), 'userLists', [{ create: {
327
+ name: a.name, membershipStatus: 'OPEN', membershipLifeSpan: days,
328
+ ruleBasedUserList: { prepopulationStatus: 'REQUESTED', flexibleRuleUserList: { inclusiveRuleOperator: 'OR', inclusiveOperands: [{ lookbackWindowDays: days,
329
+ rule: { ruleItemGroups: [{ ruleItems: [{ name: 'url__', stringRuleItem: { operator: 'CONTAINS', value: a.urlContains } }] }] } }] } },
330
+ } }]);
331
+ const rn = r.results?.[0]?.resourceName;
332
+ return { id: rn?.split('/').pop(), resourceName: rn, note: 'Customer-list (Customer Match) uploads go through Google\'s Data Manager API, which is not covered here.' };
333
+ },
334
+ },
335
+ setStatus: {
336
+ params: { accountId: { required: true }, id: { required: true }, level: {}, adGroupId: { desc: 'Required for level "ad".' }, status: { required: true } },
337
+ run: async (ctx, a) => {
338
+ const status = gateStatus(a);
339
+ if (status === STATUS.ARCHIVED) throw new AdsError('validation', 'Google Ads has no archive; use deleteObject to remove.', { field: 'status' });
340
+ const id = cid(a);
341
+ const level = pickLevel(a, { campaign: 'campaigns', adGroup: 'adGroups', ad: 'adGroupAds' }, ctx.platform);
342
+ const rn = level === 'adGroupAds' ? `customers/${id}/adGroupAds/${digits(a.adGroupId, 'adGroupId')}~${digits(a.id)}` : `customers/${id}/${level}/${digits(a.id)}`;
343
+ await mutate(ctx, id, level, [{ update: { resourceName: rn, status: status === STATUS.ACTIVE ? 'ENABLED' : 'PAUSED' }, updateMask: 'status' }]);
344
+ return { id: a.id, status };
345
+ },
346
+ },
347
+ setBudget: {
348
+ params: { accountId: { required: true }, id: { required: true, desc: 'Campaign id.' }, amount: { required: true } },
349
+ run: async (ctx, a) => {
350
+ const id = cid(a);
351
+ const [r] = await search(ctx, id, `SELECT campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.explicitly_shared, campaign_budget.reference_count FROM campaign WHERE campaign.id = ${digits(a.id)}`, 1);
352
+ if (!r) throw new AdsError('not_found', `Campaign ${a.id} not found.`);
353
+ gateBudget(a, fromMicros(r.campaignBudget.amountMicros));
354
+ const note = r.campaignBudget.explicitlyShared ? `This budget is shared by ${r.campaignBudget.referenceCount} campaigns; all of them change.` : undefined;
355
+ await mutate(ctx, id, 'campaignBudgets', [{ update: { resourceName: r.campaignBudget.resourceName, amountMicros: String(toMicros(a.amount)) }, updateMask: 'amount_micros' }]);
356
+ return { id: a.id, dailyBudget: Number(a.amount), previous: fromMicros(r.campaignBudget.amountMicros), ...(note ? { note } : {}) };
357
+ },
358
+ },
359
+ deleteObject: {
360
+ params: { accountId: { required: true }, id: { required: true }, level: { required: true }, adGroupId: { desc: 'Required for level "ad".' }, confirm: {}, confirmName: {}, confirmChildren: {} },
361
+ run: async (ctx, a) => {
362
+ const id = cid(a);
363
+ const oid = digits(a.id);
364
+ const radius = { what: a.level, children: [] };
365
+ let rn; let resource; let budget;
366
+ if (a.level === 'campaign') {
367
+ const [c] = await search(ctx, id, `SELECT campaign.name, campaign.status, metrics.cost_micros, campaign_budget.resource_name, campaign_budget.explicitly_shared, campaign_budget.reference_count FROM campaign WHERE campaign.id = ${oid}`, 1);
368
+ if (!c) throw new AdsError('not_found', `Campaign ${oid} not found.`);
369
+ const groups = await search(ctx, id, `SELECT ad_group.id FROM ad_group WHERE campaign.id = ${oid} AND ad_group.status != 'REMOVED'`);
370
+ Object.assign(radius, { name: c.campaign.name, live: c.campaign.status === 'ENABLED', spend: fromMicros(c.metrics?.costMicros ?? 0) });
371
+ radius.children.push({ label: 'ad groups', count: groups.length });
372
+ rn = `customers/${id}/campaigns/${oid}`; resource = 'campaigns';
373
+ if (!c.campaignBudget.explicitlyShared && Number(c.campaignBudget.referenceCount ?? 1) <= 1) budget = c.campaignBudget.resourceName;
374
+ } else if (a.level === 'adGroup') {
375
+ const [g] = await search(ctx, id, `SELECT ad_group.name, ad_group.status FROM ad_group WHERE ad_group.id = ${oid}`, 1);
376
+ if (!g) throw new AdsError('not_found', `Ad group ${oid} not found.`);
377
+ const ads = await search(ctx, id, `SELECT ad_group_ad.ad.id FROM ad_group_ad WHERE ad_group.id = ${oid} AND ad_group_ad.status != 'REMOVED'`);
378
+ Object.assign(radius, { name: g.adGroup.name, live: g.adGroup.status === 'ENABLED' });
379
+ radius.children.push({ label: 'ads', count: ads.length });
380
+ rn = `customers/${id}/adGroups/${oid}`; resource = 'adGroups';
381
+ } else if (a.level === 'ad') {
382
+ rn = `customers/${id}/adGroupAds/${digits(a.adGroupId, 'adGroupId')}~${oid}`; resource = 'adGroupAds';
383
+ } else {
384
+ throw new AdsError('validation', 'level must be campaign, adGroup or ad', { field: 'level' });
385
+ }
386
+ gateDelete(a, radius);
387
+ await mutate(ctx, id, resource, [{ remove: rn }]);
388
+ if (budget) await mutate(ctx, id, 'campaignBudgets', [{ remove: budget }]).catch(() => {});
389
+ return { removed: rn, ...(budget ? { budgetRemoved: budget } : {}) };
390
+ },
391
+ },
392
+ report: {
393
+ params: {
394
+ accountId: { required: true }, query: { type: 'string', desc: 'Optional GAQL SELECT ... FROM <resource> ...' },
395
+ level: { type: 'string', enum: ['campaign', 'ad_group', 'ad_group_ad', 'keyword_view', 'search_term_view'], desc: 'Default campaign (ignored with query).' },
396
+ since: {}, until: {},
397
+ },
398
+ run: async (ctx, a) => {
399
+ let q = a.query;
400
+ if (q) {
401
+ const m = /^\s*SELECT\s[\s\S]+?\sFROM\s+([a-z_]+)/i.exec(q);
402
+ if (!m) throw new AdsError('validation', 'query must be a GAQL SELECT ... FROM ...', { field: 'query' });
403
+ if (!REPORT_FROM.has(m[1].toLowerCase())) throw new AdsError('validation', `FROM ${m[1]} is not an allowed report resource.`, { field: 'query' });
404
+ } else {
405
+ const { since, until } = dateRange(a);
406
+ const level = a.level ?? 'campaign';
407
+ const dims = { campaign: 'campaign.id, campaign.name', ad_group: 'campaign.name, ad_group.id, ad_group.name', ad_group_ad: 'ad_group.name, ad_group_ad.ad.id, ad_group_ad.ad.name',
408
+ keyword_view: 'ad_group.name, ad_group_criterion.keyword.text, ad_group_criterion.keyword.match_type', search_term_view: 'search_term_view.search_term, campaign.name' }[level];
409
+ if (!dims) throw new AdsError('validation', 'Unknown level', { field: 'level' });
410
+ q = `SELECT ${dims}, metrics.impressions, metrics.clicks, metrics.ctr, metrics.average_cpc, metrics.cost_micros, metrics.conversions, metrics.conversions_value FROM ${level} WHERE segments.date BETWEEN '${since}' AND '${until}'`;
411
+ }
412
+ const rows = await search(ctx, cid(a), q, a.limit ?? 2000);
413
+ return { rows, query: q };
414
+ },
415
+ },
416
+ searchTargeting: {
417
+ params: { type: { required: true, enum: ['locations', 'keywords', 'languages'] }, query: { required: true }, accountId: { desc: 'Required for keywords.' }, countryCode: { type: 'string' } },
418
+ run: async (ctx, a) => {
419
+ if (a.type === 'languages') {
420
+ const q = String(a.query).toLowerCase();
421
+ return { items: Object.entries(LANGUAGES).filter(([k]) => k.startsWith(q) || q === '*').map(([code, id]) => ({ id: String(id), code })) };
422
+ }
423
+ if (a.type === 'locations') {
424
+ const r = await ctx.request({ method: 'POST', path: '/geoTargetConstants:suggest', json: { locale: 'en', ...(a.countryCode ? { countryCode: a.countryCode } : {}), locationNames: { names: [a.query] } } });
425
+ return { items: (r.geoTargetConstantSuggestions ?? []).map((s) => ({ id: s.geoTargetConstant?.id, name: s.geoTargetConstant?.canonicalName ?? s.geoTargetConstant?.name, type: s.geoTargetConstant?.targetType, countryCode: s.geoTargetConstant?.countryCode, reach: s.reach })) };
426
+ }
427
+ if (a.type === 'keywords') {
428
+ const r = await ctx.request({ method: 'POST', path: `/customers/${cid(a)}:generateKeywordIdeas`, json: { keywordPlanNetwork: 'GOOGLE_SEARCH', includeAdultKeywords: false, pageSize: Math.min(a.limit ?? 50, 200), keywordSeed: { keywords: [a.query] }, language: 'languageConstants/1000' } });
429
+ return { items: (r.results ?? []).map((k) => ({ keyword: k.text, avgMonthlySearches: Number(k.keywordIdeaMetrics?.avgMonthlySearches ?? 0), competition: k.keywordIdeaMetrics?.competition, lowBid: fromMicros(k.keywordIdeaMetrics?.lowTopOfPageBidMicros), highBid: fromMicros(k.keywordIdeaMetrics?.highTopOfPageBidMicros) })) };
430
+ }
431
+ throw new AdsError('validation', 'type must be locations, keywords or languages', { field: 'type' });
432
+ },
433
+ },
434
+ },
435
+ });
@@ -0,0 +1,21 @@
1
+ import meta from './meta.js';
2
+ import googleAds from './google-ads.js';
3
+ import microsoftAds from './microsoft-ads.js';
4
+ import linkedinAds from './linkedin-ads.js';
5
+ import tiktokAds from './tiktok-ads.js';
6
+ import redditAds from './reddit-ads.js';
7
+ import pinterestAds from './pinterest-ads.js';
8
+ import snapchatAds from './snapchat-ads.js';
9
+ import xAds from './x-ads.js';
10
+ import openaiAds from './openai-ads.js';
11
+ import appleAds from './apple-ads.js';
12
+ import amazonAds from './amazon-ads.js';
13
+ import applovinAds from './applovin-ads.js';
14
+ import outbrainAds from './outbrain-ads.js';
15
+ import taboolaAds from './taboola-ads.js';
16
+ import tradeDesk from './trade-desk.js';
17
+
18
+ export const PLATFORMS = Object.freeze(Object.fromEntries([
19
+ meta, googleAds, microsoftAds, linkedinAds, tiktokAds, redditAds, pinterestAds, snapchatAds,
20
+ xAds, openaiAds, appleAds, amazonAds, applovinAds, outbrainAds, taboolaAds, tradeDesk,
21
+ ].map((p) => [p.id, p])));