@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.
- package/LICENSE +202 -0
- package/README.md +105 -2
- package/docs/bring-your-own-app.md +391 -0
- package/package.json +66 -4
- package/src/core.js +20 -0
- package/src/credentials.js +53 -0
- package/src/errors.js +29 -0
- package/src/hash.js +30 -0
- package/src/http.js +148 -0
- package/src/index.js +103 -0
- package/src/money.js +25 -0
- package/src/oauth.js +34 -0
- package/src/ops.js +49 -0
- package/src/platform.js +56 -0
- package/src/platforms/amazon-ads.js +218 -0
- package/src/platforms/apple-ads.js +236 -0
- package/src/platforms/applovin-ads.js +182 -0
- package/src/platforms/google-ads.js +435 -0
- package/src/platforms/index.js +21 -0
- package/src/platforms/linkedin-ads.js +297 -0
- package/src/platforms/meta.js +518 -0
- package/src/platforms/microsoft-ads.js +381 -0
- package/src/platforms/openai-ads.js +246 -0
- package/src/platforms/outbrain-ads.js +128 -0
- package/src/platforms/pinterest-ads.js +271 -0
- package/src/platforms/reddit-ads.js +259 -0
- package/src/platforms/snapchat-ads.js +276 -0
- package/src/platforms/taboola-ads.js +57 -0
- package/src/platforms/tiktok-ads.js +348 -0
- package/src/platforms/trade-desk.js +111 -0
- package/src/platforms/x-ads.js +274 -0
- package/src/safety.js +96 -0
- package/src/tools.js +81 -0
- package/src/zip.js +47 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { definePlatform, row, dateRange } from '../platform.js';
|
|
2
|
+
import { AdsError } from '../errors.js';
|
|
3
|
+
import { assertBornPaused, gateStatus, requireConfirm, gateDelete, checkLength, STATUS } from '../safety.js';
|
|
4
|
+
import { toMajor } from '../money.js';
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
const BASE = 'https://api.outbrain.com/amplify/v0.1';
|
|
8
|
+
|
|
9
|
+
export default definePlatform({
|
|
10
|
+
id: 'outbrain_ads',
|
|
11
|
+
label: 'Outbrain',
|
|
12
|
+
money: 'major',
|
|
13
|
+
credentials: [
|
|
14
|
+
{ name: 'token', required: true, env: 'OUTBRAIN_TOKEN', desc: 'Amplify API token (valid 30 days; a password or email change revokes it).' },
|
|
15
|
+
],
|
|
16
|
+
baseUrl: BASE,
|
|
17
|
+
authHeaders: (c) => ({ 'OB-TOKEN-V1': c.token }),
|
|
18
|
+
parseError: (status, body) => {
|
|
19
|
+
const message = body?.message ?? body?.error ?? (Array.isArray(body) ? body.map((e) => e.message).join('; ') : undefined);
|
|
20
|
+
if (status === 429) return { kind: 'rate_limit', message };
|
|
21
|
+
return message ? { message } : null;
|
|
22
|
+
},
|
|
23
|
+
notes: [
|
|
24
|
+
'accountId is the marketer id (listAccounts).',
|
|
25
|
+
'Campaigns are created disabled and are archived, not deleted. Every budget change needs confirm.',
|
|
26
|
+
'Campaign targeting language is mandatory and lives inside targeting.',
|
|
27
|
+
'Reporting data lags 10-30 minutes.',
|
|
28
|
+
],
|
|
29
|
+
setup: {
|
|
30
|
+
app: 'No developer app: request Amplify API access from Outbrain, then generate a token on the Amplify API Token page (or GET /login with basic auth, limited to 2 per hour).',
|
|
31
|
+
scopes: ['(token, no scopes)'],
|
|
32
|
+
review: 'Outbrain enables API access on request.',
|
|
33
|
+
hosted: { connect: 'own', note: 'Outbrain issues API tokens per account.' },
|
|
34
|
+
docs: 'https://amplifyv01.docs.apiary.io/',
|
|
35
|
+
},
|
|
36
|
+
ops: {
|
|
37
|
+
listAccounts: { run: async (ctx, a) => ({ items: ((await ctx.request({ path: '/marketers' })).marketers ?? []).map((m) => row(m, { id: m.id, name: m.name, enabled: m.enabled }, a)) }) },
|
|
38
|
+
listCampaigns: {
|
|
39
|
+
params: { accountId: { required: true, desc: 'Marketer id.' }, includeArchived: { type: 'boolean' } },
|
|
40
|
+
run: async (ctx, a) => {
|
|
41
|
+
const r = await ctx.request({ path: `/marketers/${a.accountId}/campaigns`, query: { includeArchived: !!a.includeArchived, limit: 50, offset: a.cursor ?? 0 } });
|
|
42
|
+
const next = (Number(a.cursor ?? 0) + 50) < (r.totalCount ?? 0) ? String(Number(a.cursor ?? 0) + 50) : null;
|
|
43
|
+
return { items: (r.campaigns ?? []).map((c) => row(c, { id: c.id, name: c.name, status: c.enabled ? STATUS.ACTIVE : STATUS.PAUSED, archived: c.archived, cpc: c.cpc, budgetId: c.budget?.id, onAir: c.liveStatus?.campaignOnAir }, a)), next };
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
getCampaign: {
|
|
47
|
+
params: { id: { required: true } },
|
|
48
|
+
run: async (ctx, a) => { const c = await ctx.request({ path: `/campaigns/${a.id}` }); return row(c, { id: c.id, name: c.name, status: c.enabled ? STATUS.ACTIVE : STATUS.PAUSED, archived: c.archived, cpc: c.cpc, budget: c.budget, onAir: c.liveStatus?.campaignOnAir, onAirReason: c.liveStatus?.onAirReason }, a); },
|
|
49
|
+
},
|
|
50
|
+
createCampaign: {
|
|
51
|
+
params: {
|
|
52
|
+
accountId: { required: true }, name: { required: true }, cpc: { type: 'number', required: true }, objective: { type: 'string', enum: ['Traffic', 'Awareness'] },
|
|
53
|
+
budgetId: { type: 'string', desc: 'Existing budget, or give dailyBudget/lifetimeBudget to create one.' }, dailyBudget: {}, lifetimeBudget: {}, language: { type: 'string', desc: 'Default "en".' },
|
|
54
|
+
},
|
|
55
|
+
run: async (ctx, a) => {
|
|
56
|
+
assertBornPaused(a, 'campaign');
|
|
57
|
+
checkLength('name', a.name, 100);
|
|
58
|
+
let budgetId = a.budgetId; let createdBudget;
|
|
59
|
+
if (!budgetId) {
|
|
60
|
+
if (a.dailyBudget == null && a.lifetimeBudget == null) throw new AdsError('validation', 'Give budgetId, dailyBudget or lifetimeBudget.', { field: 'budgetId' });
|
|
61
|
+
const b = await ctx.request({ method: 'POST', path: `/marketers/${a.accountId}/budgets`, json: {
|
|
62
|
+
name: `${a.name} budget`.slice(0, 100), amount: toMajor(a.dailyBudget ?? a.lifetimeBudget), startDate: new Date().toISOString().slice(0, 10), runForever: true,
|
|
63
|
+
type: a.dailyBudget != null ? 'DAILY' : 'CAMPAIGN', pacing: a.dailyBudget != null ? 'SPEND_ASAP' : 'AUTOMATIC' } });
|
|
64
|
+
budgetId = b.id; createdBudget = b.id;
|
|
65
|
+
}
|
|
66
|
+
let c;
|
|
67
|
+
try {
|
|
68
|
+
c = await ctx.request({ method: 'POST', path: '/campaigns', json: { name: a.name, budgetId, enabled: false, cpc: toMajor(a.cpc, 'cpc'), objective: a.objective ?? 'Traffic', targeting: { language: a.language ?? 'en' }, ...(a.fields ?? {}) } });
|
|
69
|
+
} catch (e) {
|
|
70
|
+
if (createdBudget) await ctx.request({ method: 'DELETE', path: `/budgets/${createdBudget}` }).catch(() => {});
|
|
71
|
+
throw e;
|
|
72
|
+
}
|
|
73
|
+
if (c.enabled) await ctx.request({ method: 'PUT', path: `/campaigns/${c.id}`, json: { enabled: false } });
|
|
74
|
+
return { id: c.id, status: STATUS.PAUSED, budgetId };
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
listAds: {
|
|
78
|
+
params: { campaignId: { required: true } },
|
|
79
|
+
run: async (ctx, a) => ({ items: ((await ctx.request({ path: `/campaigns/${a.campaignId}/promotedLinks`, query: { limit: 500 } })).promotedLinks ?? []).map((l) => row(l, { id: l.id, text: l.text, url: l.url, status: l.enabled ? STATUS.ACTIVE : STATUS.PAUSED, approval: l.approvalStatus?.status, onAir: l.onAirStatus?.onAir }, a)) }),
|
|
80
|
+
},
|
|
81
|
+
createAd: {
|
|
82
|
+
params: { campaignId: { required: true }, url: { type: 'string', required: true }, text: { type: 'string', desc: 'Title (crawled from the page when omitted).' }, imageUrl: { type: 'string' } },
|
|
83
|
+
run: async (ctx, a) => {
|
|
84
|
+
assertBornPaused(a, 'promoted link');
|
|
85
|
+
const l = await ctx.request({ method: 'POST', path: `/campaigns/${a.campaignId}/promotedLinks`, json: { url: a.url, enabled: false, ...(a.text ? { text: a.text } : {}), ...(a.imageUrl ? { imageMetadata: { url: a.imageUrl } } : {}) } });
|
|
86
|
+
return { id: l.id, status: STATUS.PAUSED, approval: l.approvalStatus?.status };
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
setStatus: {
|
|
90
|
+
params: { id: { required: true }, level: { desc: 'campaign (default) or ad (promoted link).' }, status: { required: true } },
|
|
91
|
+
run: async (ctx, a) => {
|
|
92
|
+
const status = gateStatus(a);
|
|
93
|
+
if (status === STATUS.ARCHIVED) return ctx.platform.ops.deleteObject.run(ctx, { ...a, level: 'campaign' });
|
|
94
|
+
await ctx.request({ method: 'PUT', path: a.level === 'ad' ? `/promotedLinks/${a.id}` : `/campaigns/${a.id}`, json: { enabled: status === STATUS.ACTIVE } });
|
|
95
|
+
return { id: a.id, status };
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
setBudget: {
|
|
99
|
+
params: { id: { required: true, desc: 'Budget id (campaign.budgetId).' }, amount: { required: true } },
|
|
100
|
+
run: async (ctx, a) => {
|
|
101
|
+
const cur = await ctx.request({ path: `/budgets/${a.id}` });
|
|
102
|
+
requireConfirm(a, `Changing budget "${cur.name}" from ${cur.amount} to ${a.amount}`);
|
|
103
|
+
await ctx.request({ method: 'PUT', path: `/budgets/${a.id}`, json: { amount: toMajor(a.amount) } });
|
|
104
|
+
return { id: a.id, amount: toMajor(a.amount), previous: cur.amount };
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
deleteObject: {
|
|
108
|
+
params: { id: { required: true }, level: { required: true, desc: 'campaign (archived; Outbrain has no delete).' }, confirm: {}, confirmName: {}, confirmChildren: {} },
|
|
109
|
+
run: async (ctx, a) => {
|
|
110
|
+
if (a.level !== 'campaign') throw new AdsError('unsupported', 'Outbrain can archive campaigns; promoted links can only be paused.');
|
|
111
|
+
const c = await ctx.request({ path: `/campaigns/${a.id}` });
|
|
112
|
+
const links = (await ctx.request({ path: `/campaigns/${a.id}/promotedLinks`, query: { limit: 500 } })).promotedLinks ?? [];
|
|
113
|
+
gateDelete(a, { what: 'campaign', name: c.name, children: [{ label: 'promoted links', count: links.length }], live: !!c.enabled, spend: c.liveStatus?.amountSpent, note: 'Outbrain archives campaigns (there is no delete).' });
|
|
114
|
+
await ctx.request({ method: 'PUT', path: `/campaigns/${a.id}`, json: { archived: true } });
|
|
115
|
+
return { id: a.id, status: STATUS.ARCHIVED };
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
report: {
|
|
119
|
+
params: { accountId: { required: true }, since: {}, until: {}, daily: { type: 'boolean', desc: 'Rows per day instead of per campaign.' }, campaignId: {} },
|
|
120
|
+
run: async (ctx, a) => {
|
|
121
|
+
const { since, until } = dateRange(a);
|
|
122
|
+
const path = a.daily ? `/reports/marketers/${a.accountId}/periodic` : `/reports/marketers/${a.accountId}/campaigns`;
|
|
123
|
+
const r = await ctx.request({ path, query: { from: since, to: until, ...(a.daily ? { breakdown: 'daily' } : { limit: 500 }), campaignId: a.campaignId } });
|
|
124
|
+
return { rows: (r.results ?? []).map((x) => ({ ...(x.metadata ?? {}), ...(x.metrics ?? {}) })), summary: r.summary };
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
});
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
|
|
2
|
+
import { AdsError } from '../errors.js';
|
|
3
|
+
import { assertBornPaused, gateStatus, gateBudget, gateDelete, checkLength, STATUS } from '../safety.js';
|
|
4
|
+
import { toMicros, fromMicros } from '../money.js';
|
|
5
|
+
import { oauth2Refresh } from '../oauth.js';
|
|
6
|
+
import { hashEmail } from '../hash.js';
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
const TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
|
|
10
|
+
const OBJECTIVES = ['AWARENESS', 'CONSIDERATION', 'VIDEO_COMPLETION', 'APP_INSTALL', 'SALES', 'LEADS', 'CTV_CONSIDERATION', 'WEB_CONVERSION', 'CATALOG_SALES'];
|
|
11
|
+
const BILLING = { CONSIDERATION: ['CLICKTHROUGH'], CATALOG_SALES: ['CLICKTHROUGH', 'IMPRESSION'] };
|
|
12
|
+
const billingFor = (objective) => BILLING[objective] ?? ['IMPRESSION'];
|
|
13
|
+
const PATH = { campaign: 'campaigns', adGroup: 'ad_groups', ad: 'ads' };
|
|
14
|
+
|
|
15
|
+
function parseError(status, body) {
|
|
16
|
+
const message = body?.message;
|
|
17
|
+
if (status === 403 && /Trial access/i.test(message ?? '')) return { kind: 'permission', message, userMessage: 'Pinterest: your app is on Trial access, which cannot do this. Apply for Standard access.' };
|
|
18
|
+
if (status === 403 && /review/i.test(message ?? '')) return { kind: 'refused', message, userMessage: `Pinterest is reviewing this ad account. ${message}` };
|
|
19
|
+
if (Number(body?.code) === 2781) return { kind: 'refused', message, userMessage: 'Pinterest: this Pin was created under Trial access and is sandboxed (never publicly visible); create a new Pin with Standard access.' };
|
|
20
|
+
if (status >= 500) return { kind: 'vendor', message, userMessage: `Pinterest server error; the write may have applied, read it back before retrying. ${message ?? ''}`.trim() };
|
|
21
|
+
return message ? { message, code: body?.code } : null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Batch writes answer HTTP 200 with per-item exceptions; any exception fails the call. */
|
|
25
|
+
function batchData(r) {
|
|
26
|
+
const items = r?.items ?? [];
|
|
27
|
+
const bad = items.filter((i) => i.exceptions && (Array.isArray(i.exceptions) ? i.exceptions.length : Object.keys(i.exceptions).length));
|
|
28
|
+
if (bad.length) {
|
|
29
|
+
const ex = [].concat(bad[0].exceptions);
|
|
30
|
+
throw new AdsError('validation', `Pinterest refused: ${ex.map((e) => e.message ?? JSON.stringify(e)).join('; ')}`, { code: ex[0]?.code });
|
|
31
|
+
}
|
|
32
|
+
return items.map((i) => i.data);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default definePlatform({
|
|
36
|
+
id: 'pinterest_ads',
|
|
37
|
+
label: 'Pinterest Ads',
|
|
38
|
+
money: 'micros',
|
|
39
|
+
credentials: [
|
|
40
|
+
{ name: 'accessToken', required: 'unlessRefresh', env: 'PINTEREST_ADS_ACCESS_TOKEN', desc: 'Token with ads:read and ads:write.' },
|
|
41
|
+
{ name: 'refreshToken', env: 'PINTEREST_ADS_REFRESH_TOKEN' },
|
|
42
|
+
{ name: 'clientId', env: 'PINTEREST_ADS_CLIENT_ID' },
|
|
43
|
+
{ name: 'clientSecret', env: 'PINTEREST_ADS_CLIENT_SECRET' },
|
|
44
|
+
],
|
|
45
|
+
baseUrl: 'https://api.pinterest.com/v5',
|
|
46
|
+
authHeaders: (c) => ({ authorization: `Bearer ${c.accessToken}` }),
|
|
47
|
+
refresh: (c, ctx) => (c.clientId && c.clientSecret ? oauth2Refresh(ctx, c, { tokenUrl: TOKEN_URL, basicAuth: true }) : null),
|
|
48
|
+
parseError,
|
|
49
|
+
notes: [
|
|
50
|
+
'An ad promotes an existing Pin (pinId): publish the Pin first.',
|
|
51
|
+
'There is no delete: deleteObject archives (effectively permanent) and does not cascade.',
|
|
52
|
+
'Every ad group needs a bid and GEO (or LOCATION) targeting.',
|
|
53
|
+
'Under Trial access, objects are sandboxed and invisible to the public; apply for Standard access before running real ads.',
|
|
54
|
+
],
|
|
55
|
+
setup: {
|
|
56
|
+
app: 'A Pinterest app at developers.pinterest.com, created from a business account, with your redirect URI.',
|
|
57
|
+
scopes: ['ads:read', 'ads:write'],
|
|
58
|
+
review: 'New apps start on Trial access (sandboxed Pins, low write quota). Apply for Standard access with a demo of your integration.',
|
|
59
|
+
hosted: { connect: 'app', note: 'Hosted Hermoso connects with one click where supported, with no developer app of your own.' },
|
|
60
|
+
docs: 'https://developers.pinterest.com/docs/api/v5/',
|
|
61
|
+
},
|
|
62
|
+
ops: {
|
|
63
|
+
listAccounts: {
|
|
64
|
+
run: async (ctx, a) => {
|
|
65
|
+
const items = []; let bookmark;
|
|
66
|
+
for (let i = 0; i < 4; i++) {
|
|
67
|
+
const r = await ctx.request({ path: '/ad_accounts', query: { page_size: 250, include_shared_accounts: true, bookmark } });
|
|
68
|
+
items.push(...(r.items ?? []).map((x) => row(x, { id: x.id, name: x.name, currency: x.currency, country: x.country, owner: x.owner?.username }, a)));
|
|
69
|
+
bookmark = r.bookmark; if (!bookmark) break;
|
|
70
|
+
}
|
|
71
|
+
return { items };
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
listCampaigns: {
|
|
75
|
+
params: { accountId: { required: true } },
|
|
76
|
+
run: async (ctx, a) => {
|
|
77
|
+
const r = await ctx.request({ path: `/ad_accounts/${a.accountId}/campaigns`, query: { entity_statuses: 'ACTIVE,PAUSED,ARCHIVED,DRAFT', page_size: Math.min(a.limit ?? 250, 250), order: 'DESCENDING', bookmark: a.cursor } });
|
|
78
|
+
return { items: (r.items ?? []).map((c) => row(c, { id: c.id, name: c.name, status: c.status, summaryStatus: c.summary_status, objective: c.objective_type, dailyCap: fromMicros(c.daily_spend_cap), lifetimeCap: fromMicros(c.lifetime_spend_cap) }, a)), next: r.bookmark ?? null };
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
getCampaign: {
|
|
82
|
+
params: { accountId: { required: true }, id: { required: true } },
|
|
83
|
+
run: async (ctx, a) => { const c = await ctx.request({ path: `/ad_accounts/${a.accountId}/campaigns/${a.id}` }); return row(c, { id: c.id, name: c.name, status: c.status, objective: c.objective_type, dailyCap: fromMicros(c.daily_spend_cap), lifetimeCap: fromMicros(c.lifetime_spend_cap) }, a); },
|
|
84
|
+
},
|
|
85
|
+
createCampaign: {
|
|
86
|
+
params: {
|
|
87
|
+
accountId: { required: true }, name: { required: true }, objective: { type: 'string', enum: OBJECTIVES, required: true },
|
|
88
|
+
dailyBudget: { desc: 'Daily spend cap.' }, lifetimeBudget: { desc: 'Lifetime spend cap (needs endTime).' }, endTime: { type: 'string', desc: 'ISO date-time.' },
|
|
89
|
+
},
|
|
90
|
+
run: async (ctx, a) => {
|
|
91
|
+
assertBornPaused(a, 'campaign');
|
|
92
|
+
checkLength('name', a.name, 255);
|
|
93
|
+
if (a.dailyBudget != null && a.lifetimeBudget != null) throw new AdsError('validation', 'Give a daily OR a lifetime cap, not both.', { field: 'dailyBudget' });
|
|
94
|
+
if (a.lifetimeBudget != null && !a.endTime) throw new AdsError('validation', 'A lifetime cap needs endTime.', { field: 'endTime' });
|
|
95
|
+
const c = { name: a.name, objective_type: a.objective, status: 'PAUSED',
|
|
96
|
+
...(a.dailyBudget != null ? { daily_spend_cap: toMicros(a.dailyBudget, 'dailyBudget') } : {}),
|
|
97
|
+
...(a.lifetimeBudget != null ? { lifetime_spend_cap: toMicros(a.lifetimeBudget, 'lifetimeBudget') } : {}),
|
|
98
|
+
...(a.endTime ? { end_time: Math.floor(Date.parse(a.endTime) / 1000) } : {}), ...(a.fields ?? {}) };
|
|
99
|
+
const [d] = batchData(await ctx.request({ method: 'POST', path: `/ad_accounts/${a.accountId}/campaigns`, json: [c] }));
|
|
100
|
+
return { id: d?.id, status: STATUS.PAUSED };
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
listAdGroups: {
|
|
104
|
+
params: { accountId: { required: true }, campaignId: {} },
|
|
105
|
+
run: async (ctx, a) => {
|
|
106
|
+
const r = await ctx.request({ path: `/ad_accounts/${a.accountId}/ad_groups`, query: { entity_statuses: 'ACTIVE,PAUSED,ARCHIVED,DRAFT', page_size: 250, campaign_ids: a.campaignId, bookmark: a.cursor } });
|
|
107
|
+
return { items: (r.items ?? []).map((g) => row(g, { id: g.id, name: g.name, status: g.status, campaignId: g.campaign_id, budget: fromMicros(g.budget_in_micro_currency), bid: fromMicros(g.bid_in_micro_currency), billableEvent: g.billable_event }, a)), next: r.bookmark ?? null };
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
createAdGroup: {
|
|
111
|
+
params: {
|
|
112
|
+
accountId: { required: true }, campaignId: { required: true }, name: { required: true }, bid: { type: 'number', required: true, desc: 'Required: Pinterest has no safe default bid.' },
|
|
113
|
+
countries: { type: 'array', desc: 'Two-letter codes for GEO targeting.' }, targetingSpec: { type: 'object', desc: 'Full targeting_spec (must contain GEO or LOCATION).' },
|
|
114
|
+
dailyBudget: { desc: 'Only when the campaign does not optimise budget (CBO).' }, billableEvent: { type: 'string' }, placementGroup: { type: 'string', enum: ['ALL', 'SEARCH', 'BROWSE', 'OTHER'] },
|
|
115
|
+
},
|
|
116
|
+
run: async (ctx, a) => {
|
|
117
|
+
assertBornPaused(a, 'ad group');
|
|
118
|
+
checkLength('name', a.name, 255);
|
|
119
|
+
const targeting = a.targetingSpec ?? (a.countries?.length ? { GEO: a.countries } : null);
|
|
120
|
+
if (!targeting?.GEO && !targeting?.LOCATION) throw new AdsError('validation', 'Ad groups need GEO targeting: countries: ["US"] or a targetingSpec with GEO/LOCATION.', { field: 'countries' });
|
|
121
|
+
const camp = await ctx.request({ path: `/ad_accounts/${a.accountId}/campaigns/${a.campaignId}` });
|
|
122
|
+
const allowed = billingFor(camp.objective_type);
|
|
123
|
+
const billable = a.billableEvent ?? allowed[0];
|
|
124
|
+
if (!allowed.includes(billable)) throw new AdsError('validation', `${camp.objective_type} campaigns bill on ${allowed.join(' or ')}.`, { field: 'billableEvent' });
|
|
125
|
+
const cbo = camp.is_campaign_budget_optimization !== false && a.dailyBudget == null;
|
|
126
|
+
const g = { name: a.name, campaign_id: a.campaignId, status: 'PAUSED', billable_event: billable, bid_in_micro_currency: toMicros(a.bid, 'bid'),
|
|
127
|
+
targeting_spec: targeting, placement_group: a.placementGroup ?? 'ALL',
|
|
128
|
+
...(cbo ? { budget_type: 'CBO_ADGROUP' } : { budget_type: 'DAILY', budget_in_micro_currency: toMicros(a.dailyBudget, 'dailyBudget') }), ...(a.fields ?? {}) };
|
|
129
|
+
const [d] = batchData(await ctx.request({ method: 'POST', path: `/ad_accounts/${a.accountId}/ad_groups`, json: [g] }));
|
|
130
|
+
return { id: d?.id, status: STATUS.PAUSED };
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
updateAdGroup: {
|
|
134
|
+
params: { accountId: { required: true }, id: { required: true }, name: {}, bid: { type: 'number' }, targetingSpec: { type: 'object' } },
|
|
135
|
+
run: async (ctx, a) => {
|
|
136
|
+
if (a.status) throw new AdsError('validation', 'Use setStatus to change status.', { field: 'status' });
|
|
137
|
+
const g = { id: a.id, ...(a.name ? { name: a.name } : {}), ...(a.targetingSpec ? { targeting_spec: a.targetingSpec } : {}), ...(a.fields ?? {}) };
|
|
138
|
+
if (a.bid != null) {
|
|
139
|
+
const [cur] = (await ctx.request({ path: `/ad_accounts/${a.accountId}/ad_groups`, query: { ad_group_ids: a.id } })).items ?? [];
|
|
140
|
+
g.bid_in_micro_currency = toMicros(a.bid, 'bid');
|
|
141
|
+
if (cur?.status === 'ACTIVE') gateBudget({ ...a, amount: a.bid }, fromMicros(cur.bid_in_micro_currency));
|
|
142
|
+
}
|
|
143
|
+
const [d] = batchData(await ctx.request({ method: 'PATCH', path: `/ad_accounts/${a.accountId}/ad_groups`, json: [g] }));
|
|
144
|
+
return { id: a.id, adGroup: d };
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
listAds: {
|
|
148
|
+
params: { accountId: { required: true }, campaignId: {}, adGroupId: {} },
|
|
149
|
+
run: async (ctx, a) => {
|
|
150
|
+
const r = await ctx.request({ path: `/ad_accounts/${a.accountId}/ads`, query: { entity_statuses: 'ACTIVE,PAUSED,ARCHIVED,DRAFT', page_size: 250, campaign_ids: a.campaignId, ad_group_ids: a.adGroupId, bookmark: a.cursor } });
|
|
151
|
+
return { items: (r.items ?? []).map((x) => row(x, { id: x.id, name: x.name, status: x.status, adGroupId: x.ad_group_id, pinId: x.pin_id, review: x.review_status, rejected: x.rejected_reasons, pinDeleted: x.is_pin_deleted }, a)), next: r.bookmark ?? null };
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
createAd: {
|
|
155
|
+
params: { accountId: { required: true }, adGroupId: { required: true }, pinId: { type: 'string', required: true }, name: {}, destinationUrl: { type: 'string' }, creativeType: { type: 'string', desc: 'Default REGULAR.' } },
|
|
156
|
+
run: async (ctx, a) => {
|
|
157
|
+
assertBornPaused(a, 'ad');
|
|
158
|
+
checkLength('name', a.name, 255);
|
|
159
|
+
checkLength('destinationUrl', a.destinationUrl, 2048);
|
|
160
|
+
if (!/^\d+$/.test(String(a.pinId))) throw new AdsError('validation', 'pinId must be a numeric Pin id.', { field: 'pinId' });
|
|
161
|
+
const [d] = batchData(await ctx.request({ method: 'POST', path: `/ad_accounts/${a.accountId}/ads`, json: [{ ad_group_id: a.adGroupId, pin_id: String(a.pinId), status: 'PAUSED', creative_type: a.creativeType ?? 'REGULAR', ...(a.name ? { name: a.name } : {}), ...(a.destinationUrl ? { destination_url: a.destinationUrl } : {}), ...(a.fields ?? {}) }] }));
|
|
162
|
+
return { id: d?.id, status: STATUS.PAUSED };
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
listAudiences: {
|
|
166
|
+
params: { accountId: { required: true } },
|
|
167
|
+
run: async (ctx, a) => {
|
|
168
|
+
const r = await ctx.request({ path: `/ad_accounts/${a.accountId}/audiences`, query: { page_size: 250, order: 'DESCENDING', bookmark: a.cursor } });
|
|
169
|
+
return { items: (r.items ?? []).map((x) => row(x, { id: x.id, name: x.name, type: x.audience_type, size: x.size, status: x.status }, a)), next: r.bookmark ?? null };
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
createAudience: {
|
|
173
|
+
params: {
|
|
174
|
+
accountId: { required: true }, name: { required: true }, kind: { type: 'string', enum: ['customer_list', 'actalike', 'visitor', 'engagement'], required: true },
|
|
175
|
+
emails: { type: 'array', desc: 'customer_list: hashed here (SHA-256, lowercase).' }, seedIds: { type: 'array', desc: 'actalike: seed audience ids.' },
|
|
176
|
+
country: { type: 'string', desc: 'actalike: US, CA or GB.' }, percentage: { type: 'number', desc: 'actalike: 1-10.' }, rule: { type: 'object', desc: 'visitor/engagement: Pinterest rule object.' },
|
|
177
|
+
},
|
|
178
|
+
run: async (ctx, a) => {
|
|
179
|
+
let rule = a.rule ?? {};
|
|
180
|
+
let type = { customer_list: 'CUSTOMER_LIST', actalike: 'ACTALIKE', visitor: 'VISITOR', engagement: 'ENGAGEMENT' }[a.kind];
|
|
181
|
+
if (a.kind === 'customer_list') {
|
|
182
|
+
const records = (a.emails ?? []).map(hashEmail).filter(Boolean);
|
|
183
|
+
if (!records.length) throw new AdsError('validation', 'A customer list needs emails.', { field: 'emails' });
|
|
184
|
+
const list = await ctx.request({ method: 'POST', path: `/ad_accounts/${a.accountId}/customer_lists`, json: { name: a.name, list_type: 'EMAIL', records: records.join(',') } });
|
|
185
|
+
rule = { customer_list_id: list.id };
|
|
186
|
+
} else if (a.kind === 'actalike') {
|
|
187
|
+
if (!a.seedIds?.length) throw new AdsError('validation', 'An actalike needs seedIds.', { field: 'seedIds' });
|
|
188
|
+
rule = { seed_id: a.seedIds, country: a.country ?? 'US', percentage: a.percentage ?? 5 };
|
|
189
|
+
if (!['US', 'CA', 'GB'].includes(rule.country)) throw new AdsError('validation', 'Actalike country must be US, CA or GB.', { field: 'country' });
|
|
190
|
+
}
|
|
191
|
+
const r = await ctx.request({ method: 'POST', path: `/ad_accounts/${a.accountId}/audiences`, json: { name: a.name, audience_type: type, rule, ...(a.fields ?? {}) } });
|
|
192
|
+
return { id: r.id, ...(a.kind === 'customer_list' ? { note: 'A list needs about 100 matched people before it delivers.' } : {}) };
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
setStatus: {
|
|
196
|
+
params: { accountId: { required: true }, id: { required: true }, level: {}, status: { required: true } },
|
|
197
|
+
run: async (ctx, a) => {
|
|
198
|
+
const status = gateStatus(a);
|
|
199
|
+
if (status === STATUS.ARCHIVED) return ctx.platform.ops.deleteObject.run(ctx, a);
|
|
200
|
+
const path = PATH[pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform)];
|
|
201
|
+
batchData(await ctx.request({ method: 'PATCH', path: `/ad_accounts/${a.accountId}/${path}`, json: [{ id: a.id, status }] }));
|
|
202
|
+
return { id: a.id, status };
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
setBudget: {
|
|
206
|
+
params: { accountId: { required: true }, id: { required: true }, level: { desc: 'campaign (spend cap, default) or adGroup.' }, amount: { required: true } },
|
|
207
|
+
run: async (ctx, a) => {
|
|
208
|
+
const level = a.level ?? 'campaign';
|
|
209
|
+
if (level === 'campaign') {
|
|
210
|
+
const c = await ctx.request({ path: `/ad_accounts/${a.accountId}/campaigns/${a.id}` });
|
|
211
|
+
const field = c.lifetime_spend_cap != null && c.daily_spend_cap == null ? 'lifetime_spend_cap' : 'daily_spend_cap';
|
|
212
|
+
gateBudget(a, fromMicros(c[field]));
|
|
213
|
+
batchData(await ctx.request({ method: 'PATCH', path: `/ad_accounts/${a.accountId}/campaigns`, json: [{ id: a.id, [field]: toMicros(a.amount) }] }));
|
|
214
|
+
return { id: a.id, [field === 'daily_spend_cap' ? 'dailyCap' : 'lifetimeCap']: Number(a.amount) };
|
|
215
|
+
}
|
|
216
|
+
const [g] = (await ctx.request({ path: `/ad_accounts/${a.accountId}/ad_groups`, query: { ad_group_ids: a.id } })).items ?? [];
|
|
217
|
+
if (!g) throw new AdsError('not_found', `Ad group ${a.id} not found.`);
|
|
218
|
+
if (g.budget_type === 'CBO_ADGROUP') throw new AdsError('validation', 'This ad group\'s budget is optimised at the campaign; change the campaign instead.', { field: 'level' });
|
|
219
|
+
gateBudget(a, fromMicros(g.budget_in_micro_currency));
|
|
220
|
+
batchData(await ctx.request({ method: 'PATCH', path: `/ad_accounts/${a.accountId}/ad_groups`, json: [{ id: a.id, budget_in_micro_currency: toMicros(a.amount) }] }));
|
|
221
|
+
return { id: a.id, budget: Number(a.amount) };
|
|
222
|
+
},
|
|
223
|
+
},
|
|
224
|
+
deleteObject: {
|
|
225
|
+
params: { accountId: { required: true }, id: { required: true }, level: { required: true }, confirm: {}, confirmName: {}, confirmChildren: {} },
|
|
226
|
+
run: async (ctx, a) => {
|
|
227
|
+
const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
|
|
228
|
+
const children = [];
|
|
229
|
+
let cur;
|
|
230
|
+
if (level === 'campaign') {
|
|
231
|
+
cur = await ctx.request({ path: `/ad_accounts/${a.accountId}/campaigns/${a.id}` });
|
|
232
|
+
children.push({ label: 'ad groups', count: ((await ctx.request({ path: `/ad_accounts/${a.accountId}/ad_groups`, query: { campaign_ids: a.id, entity_statuses: 'ACTIVE,PAUSED,DRAFT' } })).items ?? []).length });
|
|
233
|
+
} else if (level === 'adGroup') {
|
|
234
|
+
cur = ((await ctx.request({ path: `/ad_accounts/${a.accountId}/ad_groups`, query: { ad_group_ids: a.id } })).items ?? [])[0];
|
|
235
|
+
children.push({ label: 'ads', count: ((await ctx.request({ path: `/ad_accounts/${a.accountId}/ads`, query: { ad_group_ids: a.id, entity_statuses: 'ACTIVE,PAUSED,DRAFT' } })).items ?? []).length });
|
|
236
|
+
}
|
|
237
|
+
gateDelete(a, { what: level, name: cur?.name, children, live: cur?.status === 'ACTIVE', note: 'Pinterest archives instead of deleting; children are left in place.' });
|
|
238
|
+
batchData(await ctx.request({ method: 'PATCH', path: `/ad_accounts/${a.accountId}/${PATH[level]}`, json: [{ id: a.id, status: 'ARCHIVED' }] }));
|
|
239
|
+
return { id: a.id, status: STATUS.ARCHIVED };
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
report: {
|
|
243
|
+
params: {
|
|
244
|
+
accountId: { required: true }, since: {}, until: {}, level: { type: 'string', enum: ['account', 'campaign', 'adGroup', 'ad'], desc: 'Default account.' },
|
|
245
|
+
ids: { type: 'array', desc: 'Required below account level (Pinterest has no "all" form).' }, granularity: { type: 'string', enum: ['TOTAL', 'DAY', 'HOUR', 'WEEK', 'MONTH'] }, columns: { type: 'array' },
|
|
246
|
+
},
|
|
247
|
+
run: async (ctx, a) => {
|
|
248
|
+
const { since, until } = dateRange(a);
|
|
249
|
+
const level = a.level ?? 'account';
|
|
250
|
+
const seg = { account: '', campaign: '/campaigns', adGroup: '/ad_groups', ad: '/ads' }[level];
|
|
251
|
+
const idKey = { campaign: 'campaign_ids', adGroup: 'ad_group_ids', ad: 'ad_ids' }[level];
|
|
252
|
+
if (seg == null) throw new AdsError('validation', 'Unknown level', { field: 'level' });
|
|
253
|
+
if (idKey && !a.ids?.length) throw new AdsError('validation', `A ${level} report needs ids (up to 250).`, { field: 'ids' });
|
|
254
|
+
const r = await ctx.request({ path: `/ad_accounts/${a.accountId}${seg}/analytics`, query: {
|
|
255
|
+
start_date: since, end_date: until, granularity: a.granularity ?? 'TOTAL',
|
|
256
|
+
columns: (a.columns ?? ['SPEND_IN_DOLLAR', 'PAID_IMPRESSION', 'CLICKTHROUGH_1', 'CTR', 'ECPC_IN_DOLLAR', 'TOTAL_CONVERSIONS']).join(','),
|
|
257
|
+
...(idKey ? { [idKey]: a.ids.join(',') } : {}) } });
|
|
258
|
+
return { rows: Array.isArray(r) ? r : (r.items ?? []) };
|
|
259
|
+
},
|
|
260
|
+
},
|
|
261
|
+
searchTargeting: {
|
|
262
|
+
params: { accountId: { required: true }, type: { required: true, desc: 'Pinterest targeting type: interests, geo, gender, age_bucket, location, locale, keywords...' }, query: { required: true } },
|
|
263
|
+
run: async (ctx, a) => {
|
|
264
|
+
const r = await ctx.request({ path: `/resources/targeting/${a.type}`, query: { ad_account_id: a.accountId } });
|
|
265
|
+
const list = Array.isArray(r) ? r : (r.items ?? Object.entries(r).map(([id, name]) => ({ id, name })));
|
|
266
|
+
const q = String(a.query).toLowerCase();
|
|
267
|
+
return { items: list.filter((x) => String(x.name ?? x.id).toLowerCase().includes(q)).slice(0, a.limit ?? 50).map((x) => ({ id: x.id, name: x.name ?? x.id })) };
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
});
|