@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,236 @@
1
+ import { createPrivateKey, createPublicKey, sign as cryptoSign, generateKeyPairSync } from 'node:crypto';
2
+ import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
3
+ import { AdsError } from '../errors.js';
4
+ import { assertBornPaused, gateStatus, gateBudget, gateDelete, checkLength, STATUS } from '../safety.js';
5
+ import { toMajor } from '../money.js';
6
+
7
+
8
+ const BASE = 'https://api.ads.apple.com/v1';
9
+ const TOKEN_URL = 'https://appleid.apple.com/auth/oauth2/token';
10
+ const PATH = { campaign: 'campaigns', adGroup: 'adgroups', ad: 'ads' };
11
+ const b64url = (b) => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
12
+
13
+ /** The client-secret JWT. The signature MUST be raw R||S (64 bytes); DER gets "invalid_client". */
14
+ export function clientSecretJwt({ clientId, teamId, keyId, privateKey, ttlSeconds = 1800, now = Math.floor(Date.now() / 1000) }) {
15
+ const header = b64url(JSON.stringify({ alg: 'ES256', kid: keyId }));
16
+ const payload = b64url(JSON.stringify({ sub: clientId, aud: 'https://appleid.apple.com', iat: now, exp: now + ttlSeconds, iss: teamId }));
17
+ const key = createPrivateKey(String(privateKey).replace(/\\n/g, '\n'));
18
+ const sig = cryptoSign('sha256', Buffer.from(`${header}.${payload}`), { key, dsaEncoding: 'ieee-p1363' });
19
+ return `${header}.${payload}.${b64url(sig)}`;
20
+ }
21
+
22
+ /** Generate the key pair a user uploads to Apple Ads (public half) and keeps (private half). */
23
+ export function generateAppleKeyPair() {
24
+ const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
25
+ return { privateKey: privateKey.export({ type: 'sec1', format: 'pem' }), publicKey: publicKey.export({ type: 'spki', format: 'pem' }) };
26
+ }
27
+ export { createPublicKey };
28
+
29
+ const tokenCache = new Map();
30
+ async function token(c, ctx) {
31
+ const hit = tokenCache.get(c.clientId);
32
+ if (hit && hit.exp > Date.now()) return hit.token;
33
+ const jwt = clientSecretJwt(c);
34
+ const params = new URLSearchParams({ grant_type: 'client_credentials', client_id: c.clientId, client_secret: jwt, scope: 'searchadsorg' });
35
+ const res = await ctx.fetch(`${TOKEN_URL}?${params}`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' }, body: params.toString() });
36
+ const j = await res.json().catch(() => ({}));
37
+ if (!res.ok || !j.access_token) throw new AdsError('auth', `Apple refused the API credentials (${j.error ?? res.status}). Check clientId, teamId, keyId and that the uploaded public key matches the private key.`, { platform: 'apple_ads' });
38
+ tokenCache.set(c.clientId, { token: j.access_token, exp: Date.now() + (Number(j.expires_in ?? 3600) - 300) * 1000 });
39
+ if (tokenCache.size > 200) tokenCache.delete(tokenCache.keys().next().value);
40
+ return j.access_token;
41
+ }
42
+ export const _clearAppleTokens = () => tokenCache.clear();
43
+
44
+ function parseError(status, body) {
45
+ const e = body?.error;
46
+ const details = (e?.details ?? e?.errors ?? []).map((d) => `${d.message}${d.messageCode ?? d.code ? ` [${d.messageCode ?? d.code}]` : ''}`).join('; ');
47
+ const message = details || (typeof e === 'string' ? e : e?.message);
48
+ if (/CAMPAIGN_TARGET_CPA_MUST_BE_NULL/.test(message ?? '')) return { kind: 'validation', message, userMessage: 'Apple Ads: a manual CPT campaign takes its bid on the ad group, not the campaign.' };
49
+ if (/CAN_NOT_DELETE_DPP_CREATIVE_AD/.test(message ?? '')) return { kind: 'refused', message, userMessage: 'Apple Ads cannot delete a default-product-page ad: pause it, or delete its ad group.' };
50
+ if (status === 403) return { kind: 'permission', message, userMessage: `Apple Ads: the API user lacks a role on this ad account. ${message ?? ''}`.trim() };
51
+ return message ? { message } : null;
52
+ }
53
+
54
+ const money = (amount, currency) => ({ amount: toMajor(amount).toFixed(2), currency });
55
+ const query = (ctx, a, entity, filters = []) => req(ctx, a, 'POST', `/${entity}/query`, { filters, pagination: { offset: Number(a.cursor ?? 0), pageSize: Math.min(a.limit ?? 1000, 1000) } });
56
+ const eq = (field, value) => ({ field, operator: 'EQUALS', value: String(value) });
57
+ function req(ctx, a, method, path, json) {
58
+ return ctx.creds().then((c) => {
59
+ const account = a.accountId ?? c.accountId;
60
+ if (!account) throw new AdsError('validation', 'Apple Ads calls need accountId (from listAccounts).', { field: 'accountId' });
61
+ return ctx.request({ method, path, json, headers: { 'X-AP-Context': `adAccountId=${account}` } })
62
+ .then((b) => (b && typeof b === 'object' && !('data' in b) && 'result' in b ? { ...b, data: b.result } : b));
63
+ });
64
+ }
65
+
66
+ export default definePlatform({
67
+ id: 'apple_ads',
68
+ label: 'Apple Ads',
69
+ money: 'major',
70
+ credentials: [
71
+ { name: 'clientId', required: true, env: 'APPLE_ADS_CLIENT_ID' },
72
+ { name: 'teamId', required: true, env: 'APPLE_ADS_TEAM_ID' },
73
+ { name: 'keyId', required: true, env: 'APPLE_ADS_KEY_ID' },
74
+ { name: 'privateKey', required: true, env: 'APPLE_ADS_PRIVATE_KEY', desc: 'EC P-256 private key PEM (its public half is uploaded in Apple Ads).' },
75
+ { name: 'accountId', env: 'APPLE_ADS_ORG_ID', desc: 'Default ad account (org) id.' },
76
+ ],
77
+ baseUrl: BASE,
78
+ authHeaders: async (c, _req, ctx) => ({ authorization: `Bearer ${await token(c, ctx)}` }),
79
+ parseError,
80
+ notes: [
81
+ 'Everything is created PAUSED; enabling needs confirm.',
82
+ 'Manual CPT bids go on the ad group, not the campaign.',
83
+ 'Ad group startTime is sent always (Apple requires it in practice).',
84
+ 'Lists are POST <entity>/query with filters + pagination; arrays in updates replace the whole list (send every country).',
85
+ ],
86
+ setup: {
87
+ app: 'No developer app: in Apple Ads, invite a user with an API role (API Account Manager), sign in as that user, and under Account Settings > API upload the public key of an EC P-256 key pair to get clientId, teamId and keyId.',
88
+ scopes: ['searchadsorg'],
89
+ review: 'None beyond the API role. Only a user holding an API role sees the API settings (an Account Admin does not).',
90
+ hosted: { connect: 'own', note: 'Apple Ads issues API credentials per organization.' },
91
+ docs: 'https://developer.apple.com/documentation/apple_ads',
92
+ },
93
+ ops: {
94
+ listAccounts: {
95
+ run: async (ctx, a) => {
96
+ const r = await ctx.request({ path: '/acls' });
97
+ const list = r.data ?? r.result?.acls ?? r.result ?? [];
98
+ return { items: list.map((x) => { const acct = x.adAccount ?? x; return row(x, { id: String(acct.id ?? acct.orgId), name: acct.name ?? acct.orgName, roles: x.roles, currency: acct.currency ?? x.currency }, a); }) };
99
+ },
100
+ },
101
+ listCampaigns: {
102
+ params: { accountId: {} },
103
+ run: async (ctx, a) => {
104
+ const r = await query(ctx, a, 'campaigns');
105
+ return { items: (r.data ?? r.result ?? []).map((c) => row(c, { id: String(c.id), name: c.name, status: c.status, servingStatus: c.servingStatus, dailyBudget: c.dailyBudget?.value?.amount ?? c.dailyBudget?.amount, currency: c.dailyBudget?.value?.currency ?? c.dailyBudget?.currency, countries: c.countriesOrRegions ?? c.targeting?.countryOrRegion?.include }, a)) };
106
+ },
107
+ },
108
+ getCampaign: {
109
+ params: { accountId: {}, id: { required: true } },
110
+ run: async (ctx, a) => { const r = await req(ctx, a, 'GET', `/campaigns/${a.id}`); const c = r.data ?? r.result; return row(c, { id: String(c.id), name: c.name, status: c.status, servingStatus: c.servingStatus, dailyBudget: c.dailyBudget?.value?.amount ?? c.dailyBudget?.amount }, a); },
111
+ },
112
+ createCampaign: {
113
+ params: {
114
+ accountId: {}, name: { required: true }, appId: { type: 'string', required: true, desc: 'App Store app id (adamId) to promote.' },
115
+ countries: { type: 'array', required: true, desc: 'ISO-3166 alpha-2 codes.' }, dailyBudget: { required: true }, currency: { type: 'string', required: true },
116
+ placement: { type: 'string', desc: 'APPSTORE_SEARCH_RESULTS (default), APPSTORE_SEARCH_TAB, APPSTORE_TODAY_TAB, APPSTORE_PRODUCT_PAGES.' },
117
+ },
118
+ run: async (ctx, a) => {
119
+ assertBornPaused(a, 'campaign');
120
+ checkLength('name', a.name, 200);
121
+ if (!/^[A-Z]{3}$/.test(a.currency)) throw new AdsError('validation', 'currency must be an ISO 4217 code like USD.', { field: 'currency' });
122
+ for (const c of a.countries) if (!/^[A-Z]{2}$/.test(c)) throw new AdsError('validation', `"${c}" is not an ISO alpha-2 country code.`, { field: 'countries' });
123
+ const c = await ctx.creds();
124
+ const body = { adAccountId: Number(a.accountId ?? c.accountId), name: a.name, billingEvent: 'TAPS', promotedObjectType: 'APPSTORE_APP', promotedObjectId: Number(a.appId),
125
+ dailyBudget: { value: money(a.dailyBudget, a.currency) }, status: 'PAUSED',
126
+ targeting: { supplySource: { include: ['APPSTORE'] }, supplyPlacement: { include: [a.placement ?? 'APPSTORE_SEARCH_RESULTS'] }, countryOrRegion: { include: a.countries } },
127
+ bidStrategy: { bidStrategyType: 'MANUAL_CPT', bidStrategyGoal: 'TAP' }, ...(a.fields ?? {}) };
128
+ const r = await req(ctx, a, 'POST', '/campaigns', body);
129
+ const d = r.data ?? r.result;
130
+ return { id: String(d?.id), status: STATUS.PAUSED };
131
+ },
132
+ },
133
+ listAdGroups: {
134
+ params: { accountId: {}, campaignId: {} },
135
+ run: async (ctx, a) => {
136
+ const r = await query(ctx, a, 'adgroups', a.campaignId ? [eq('campaignId', a.campaignId)] : []);
137
+ return { items: (r.data ?? r.result ?? []).map((g) => row(g, { id: String(g.id), name: g.name, status: g.status, campaignId: String(g.campaignId), bid: g.bidStrategy?.bid?.amount ?? g.defaultBidAmount?.amount }, a)) };
138
+ },
139
+ },
140
+ createAdGroup: {
141
+ params: { accountId: {}, campaignId: { required: true }, name: { required: true }, bid: { type: 'number', required: true, desc: 'Max cost per tap.' }, currency: { type: 'string', required: true }, keywords: { type: 'array', desc: 'Optional [{text, matchType: EXACT|BROAD}] (strings are EXACT).' }, automatedKeywords: { type: 'boolean' } },
142
+ run: async (ctx, a) => {
143
+ assertBornPaused(a, 'ad group');
144
+ checkLength('name', a.name, 200);
145
+ const startTime = new Date().toISOString().replace('Z', '').slice(0, 23);
146
+ const r = await req(ctx, a, 'POST', '/adgroups', { campaignId: Number(a.campaignId), name: a.name, pricingModel: 'CPT', startTime, status: 'PAUSED', automatedKeywordsOptIn: !!a.automatedKeywords,
147
+ bidStrategy: { bidStrategyType: 'MANUAL_CPT', bidStrategyGoal: 'TAP', bid: money(a.bid, a.currency) }, ...(a.fields ?? {}) });
148
+ const id = String((r.data ?? r.result)?.id);
149
+ const kws = (a.keywords ?? []).map((k) => (typeof k === 'string' ? { text: k } : k));
150
+ if (kws.length > 1000) throw new AdsError('validation', 'At most 1000 keywords per call.', { field: 'keywords' });
151
+ for (const k of kws) await req(ctx, a, 'POST', '/keywords', { adGroupId: Number(id), text: k.text, matchType: k.matchType ?? 'EXACT', ...(k.bid != null ? { bid: money(k.bid, a.currency) } : {}) });
152
+ return { id, status: STATUS.PAUSED, keywords: kws.length };
153
+ },
154
+ },
155
+ listAds: {
156
+ params: { accountId: {}, adGroupId: {} },
157
+ run: async (ctx, a) => {
158
+ const r = await query(ctx, a, 'ads', a.adGroupId ? [eq('adGroupId', a.adGroupId)] : []);
159
+ return { items: (r.data ?? r.result ?? []).map((x) => row(x, { id: String(x.id), name: x.name, status: x.status, adGroupId: String(x.adGroupId), creativeId: String(x.creativeId) }, a)) };
160
+ },
161
+ },
162
+ createCreative: {
163
+ params: { accountId: {}, name: { required: true }, appId: { type: 'string', required: true }, productPageId: { type: 'string', desc: 'Custom product page id; omit for the default page.' } },
164
+ run: async (ctx, a) => {
165
+ const custom = !!a.productPageId;
166
+ const r = await req(ctx, a, 'POST', '/creatives', { name: a.name, creativeType: custom ? 'CUSTOM_PRODUCT_PAGE' : 'DEFAULT_PRODUCT_PAGE', destination: { destinationType: 'APP_STORE_PRODUCT_PAGE', parameters: { adamId: String(a.appId), ...(custom ? { productPageId: a.productPageId } : {}) } }, creativeSpec: {} });
167
+ const d = r.data ?? r.result;
168
+ return { id: String(d?.id), systemStatus: d?.systemStatus };
169
+ },
170
+ },
171
+ createAd: {
172
+ params: { accountId: {}, adGroupId: { required: true }, creativeId: { type: 'string', required: true }, name: { required: true } },
173
+ run: async (ctx, a) => {
174
+ assertBornPaused(a, 'ad');
175
+ const r = await req(ctx, a, 'POST', '/ads', { adGroupId: Number(a.adGroupId), creativeId: Number(a.creativeId), name: a.name, status: 'PAUSED' });
176
+ return { id: String((r.data ?? r.result)?.id), status: STATUS.PAUSED, note: 'Ads serve only on the Search tab placement; Search results campaigns need no ad.' };
177
+ },
178
+ },
179
+ setStatus: {
180
+ params: { accountId: {}, id: { required: true }, level: {}, status: { required: true } },
181
+ run: async (ctx, a) => {
182
+ const status = gateStatus(a);
183
+ if (status === STATUS.ARCHIVED) throw new AdsError('validation', 'Apple Ads has no archive; use deleteObject.', { field: 'status' });
184
+ const path = PATH[pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform)];
185
+ await req(ctx, a, 'PUT', `/${path}/${a.id}`, { status: status === STATUS.ACTIVE ? 'ENABLED' : 'PAUSED' });
186
+ return { id: String(a.id), status };
187
+ },
188
+ },
189
+ setBudget: {
190
+ params: { accountId: {}, id: { required: true, desc: 'Campaign id.' }, amount: { required: true } },
191
+ run: async (ctx, a) => {
192
+ const c = (await req(ctx, a, 'GET', `/campaigns/${a.id}`)).data ?? {};
193
+ const cur = c.dailyBudget?.value ?? c.dailyBudget ?? c.dailyBudgetAmount;
194
+ gateBudget(a, cur?.amount != null ? Number(cur.amount) : null);
195
+ await req(ctx, a, 'PUT', `/campaigns/${a.id}`, { dailyBudget: { value: money(a.amount, cur?.currency ?? 'USD') } });
196
+ return { id: String(a.id), dailyBudget: toMajor(a.amount), currency: cur?.currency };
197
+ },
198
+ },
199
+ deleteObject: {
200
+ params: { accountId: {}, id: { required: true }, level: { required: true }, confirm: {}, confirmName: {}, confirmChildren: {} },
201
+ run: async (ctx, a) => {
202
+ const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
203
+ const cur = (await req(ctx, a, 'GET', `/${PATH[level]}/${a.id}`)).data ?? {};
204
+ const children = [];
205
+ if (level === 'campaign') children.push({ label: 'ad groups', count: ((await query(ctx, a, 'adgroups', [eq('campaignId', a.id)])).data ?? []).length });
206
+ if (level === 'adGroup') children.push({ label: 'ads', count: ((await query(ctx, a, 'ads', [eq('adGroupId', a.id)])).data ?? []).length });
207
+ gateDelete(a, { what: level, name: cur.name, children, live: cur.status === 'ENABLED', note: 'Apple deletes cannot be undone.' });
208
+ await req(ctx, a, 'DELETE', `/${PATH[level]}/${a.id}`);
209
+ return { id: String(a.id), deleted: true };
210
+ },
211
+ },
212
+ report: {
213
+ params: { accountId: {}, level: { type: 'string', enum: ['campaigns', 'adgroups', 'keywords', 'searchterms', 'ads'], desc: 'Default campaigns.' }, campaignId: { desc: 'Required below campaign level.' }, since: {}, until: {}, granularity: { type: 'string', enum: ['HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY'] } },
214
+ run: async (ctx, a) => {
215
+ const { since, until } = dateRange(a);
216
+ const level = a.level ?? 'campaigns';
217
+ if (level !== 'campaigns' && !a.campaignId) throw new AdsError('validation', `A ${level} report needs campaignId.`, { field: 'campaignId' });
218
+ const r = await req(ctx, a, 'POST', `/reports/apps/${level}/query`, {
219
+ timeRange: { start: since, end: until, timeZone: 'ORTZ', ...(a.granularity ? { granularity: a.granularity } : {}) },
220
+ ...(a.campaignId ? { filters: [eq('campaignId', a.campaignId)] } : {}),
221
+ pagination: { offset: 0, limit: Math.min(a.limit ?? 1000, 5000) }, options: { includeRows: ['GRAND_TOTAL'] },
222
+ });
223
+ return { rows: r.data?.reportingDataResponse?.row ?? r.data?.row ?? r.data ?? [], totals: r.data?.reportingDataResponse?.grandTotals };
224
+ },
225
+ },
226
+ searchTargeting: {
227
+ params: { accountId: {}, type: { required: true, enum: ['locations'] }, query: { required: true }, countryCode: { type: 'string' } },
228
+ run: async (ctx, a) => {
229
+ if (String(a.query).length < 2 && a.query !== '*') throw new AdsError('validation', 'query needs at least 2 characters.', { field: 'query' });
230
+ const c = await ctx.creds();
231
+ const r = await ctx.request({ path: '/search/geo', query: { supplySource: 'APPSTORE', query: a.query, countrycode: a.countryCode, limit: a.limit ?? 50 }, headers: { 'X-AP-Context': `adAccountId=${a.accountId ?? c.accountId ?? ''}` } });
232
+ return { items: (r.data ?? []).map((x) => ({ id: x.id, name: x.displayName ?? x.name, type: x.entity, countryCode: x.countryCode })) };
233
+ },
234
+ },
235
+ },
236
+ });
@@ -0,0 +1,182 @@
1
+ import { definePlatform, row, dateRange } from '../platform.js';
2
+ import { AdsError } from '../errors.js';
3
+ import { assertBornPaused, gateStatus, requireConfirm, checkLength, STATUS } from '../safety.js';
4
+
5
+
6
+ const MANAGE = 'https://api.ads.axon.ai/manage/v1';
7
+ const REPORT = 'https://r.applovin.com';
8
+ const WEB_GOALS = ['CPE', 'CPP', 'CHK_ROAS'];
9
+ const APP_GOALS = ['CPI', 'CPE', 'CPP', 'AD_ROAS', 'CHK_ROAS', 'BLD_ROAS'];
10
+
11
+ const budget = new Map();
12
+ function guard(key) {
13
+ const b = budget.get(key) ?? { errors: [], lockedUntil: 0 };
14
+ const now = Date.now();
15
+ b.errors = b.errors.filter((t) => now - t < 5 * 60000);
16
+ budget.set(key, b);
17
+ if (b.lockedUntil > now) throw new AdsError('rate_limit', `AppLovin has locked this account's API until ${new Date(b.lockedUntil).toISOString()}; nothing was sent.`);
18
+ if (b.errors.length >= 20) throw new AdsError('rate_limit', 'Too many AppLovin errors in the last 5 minutes; refusing locally so AppLovin does not lock the account for 24 hours. Fix the request first.');
19
+ return b;
20
+ }
21
+ export const _resetAppLovinBudget = () => budget.clear();
22
+
23
+ async function call(ctx, opts, keyName = 'campaignKey') {
24
+ const c = await ctx.creds();
25
+ const key = c[keyName];
26
+ if (!key) throw new AdsError('not_connected', keyName === 'campaignKey' ? 'Campaign management needs the AppLovin Campaign Management key (AppLovin enables it per account on request).' : 'Reporting needs the AppLovin Reporting key.', { platform: 'applovin_ads' });
27
+ const b = guard(key);
28
+ try {
29
+ return await ctx.request(opts);
30
+ } catch (e) {
31
+ if (e.code === '100007') b.lockedUntil = Date.now() + 24 * 3600000;
32
+ else if (e.kind !== 'vendor' || e.status) b.errors.push(Date.now());
33
+ throw e;
34
+ }
35
+ }
36
+ const manage = (ctx, method, path, { query, json } = {}) => ctx.creds().then((c) => call(ctx, { method, base: MANAGE, path, query: { account_id: c.accountId, ...(query ?? {}) }, json }));
37
+
38
+ function parseError(status, body, headers) {
39
+ const code = headers?.get?.('x-al-error-code') ?? undefined;
40
+ const message = headers?.get?.('x-al-error-message') ?? body?.error ?? body?.message ?? (typeof body === 'string' ? body : undefined);
41
+ if (status === 429 && code === '100007') return { kind: 'rate_limit', code, message, userMessage: 'AppLovin has blocked this account\'s API for 24 hours after too many failed requests.' };
42
+ if (status === 403) return { kind: 'permission', code, message, userMessage: `AppLovin: this account is not enabled for that setting or API. ${message ?? ''}`.trim() };
43
+ return { code, message };
44
+ }
45
+
46
+ export default definePlatform({
47
+ id: 'applovin_ads',
48
+ label: 'AppLovin',
49
+ money: 'major',
50
+ credentials: [
51
+ { name: 'campaignKey', env: 'APPLOVIN_CAMPAIGN_KEY', desc: 'Campaign Management API key (enabled per account by AppLovin).' },
52
+ { name: 'reportKey', env: 'APPLOVIN_REPORT_KEY', desc: 'Reporting key (dashboard > Account > Keys).' },
53
+ { name: 'accountId', required: true, env: 'APPLOVIN_ACCOUNT_ID' },
54
+ { name: 'accountType', env: 'APPLOVIN_ACCOUNT_TYPE', desc: 'WEB (default) or APP.' },
55
+ ],
56
+ baseUrl: MANAGE,
57
+ authHeaders: (c, req) => (req.url?.startsWith(MANAGE) && c.campaignKey ? { authorization: c.campaignKey } : {}),
58
+ parseError,
59
+ notes: [
60
+ 'The API has no delete or archive: pause a campaign to stop it.',
61
+ 'AppLovin ignores the status on create; createCampaign reads it back and pauses it if needed.',
62
+ 'Targeting is replaced wholesale on update.',
63
+ 'Never loop retries: 100 errors in 5 minutes lock the account\'s API for 24 hours.',
64
+ ],
65
+ setup: {
66
+ app: 'No developer app: copy keys from the AppLovin dashboard (Account > Keys). Ask AppLovin to enable the Campaign Management API on the account for write access.',
67
+ scopes: ['(keys, no scopes)'],
68
+ review: 'Campaign management is an allowlist beta enabled per account on request; reporting keys are self-serve.',
69
+ hosted: { connect: 'own', note: 'AppLovin issues keys per account, and campaign management is enabled per account on request.' },
70
+ docs: 'https://support.axon.ai/',
71
+ },
72
+ ops: {
73
+ listAccounts: {
74
+ run: async (ctx, a) => {
75
+ const c = await ctx.creds();
76
+ if (c.campaignKey) { const me = await call(ctx, { base: MANAGE, path: '/me' }); return { items: [row(me, { id: String(me.accountId ?? c.accountId), type: me.accountType }, a)] }; }
77
+ return { items: [{ id: String(c.accountId), type: c.accountType ?? 'WEB' }] };
78
+ },
79
+ },
80
+ listCampaigns: {
81
+ run: async (ctx, a) => {
82
+ const r = await manage(ctx, 'GET', '/campaign/list', { query: { page: a.cursor ?? 1, size: Math.min(a.limit ?? 100, 100) } });
83
+ const list = Array.isArray(r) ? r : (r.campaigns ?? r.data ?? []);
84
+ return { items: list.map((c) => row(c, { id: String(c.id), name: c.name, status: c.status, type: c.type, goal: c.goal?.goal_type, dailyBudget: Number(c.budget?.daily_budget_for_all_countries ?? NaN) || undefined }, a)) };
85
+ },
86
+ },
87
+ getCampaign: {
88
+ params: { id: { required: true } },
89
+ run: async (ctx, a) => {
90
+ const r = await manage(ctx, 'GET', '/campaign/list', { query: { ids: String(a.id) } });
91
+ const c = (Array.isArray(r) ? r : (r.campaigns ?? r.data ?? []))[0];
92
+ if (!c) throw new AdsError('not_found', `Campaign ${a.id} not found.`);
93
+ return row(c, { id: String(c.id), name: c.name, status: c.status, type: c.type, budget: c.budget, goal: c.goal, targeting: c.targeting }, a);
94
+ },
95
+ },
96
+ createCampaign: {
97
+ params: {
98
+ name: { required: true }, dailyBudget: { required: true }, countries: { type: 'array', required: true, desc: 'Country codes (lowercase or uppercase).' },
99
+ goalType: { type: 'string', desc: `WEB: ${WEB_GOALS.join(', ')}; APP: ${APP_GOALS.join(', ')}.` }, goalValue: { type: 'number', required: true },
100
+ websiteUrl: { type: 'string', desc: 'Required for WEB campaigns.' }, startDate: { type: 'string', desc: 'YYYY-MM-DD, default tomorrow (UTC).' },
101
+ },
102
+ run: async (ctx, a) => {
103
+ assertBornPaused(a, 'campaign');
104
+ const c = await ctx.creds();
105
+ const type = String(c.accountType ?? 'WEB').toUpperCase();
106
+ const goal = a.goalType ?? (type === 'WEB' ? 'CPP' : 'CPI');
107
+ if (!(type === 'WEB' ? WEB_GOALS : APP_GOALS).includes(goal)) throw new AdsError('validation', `goalType for a ${type} account must be one of ${(type === 'WEB' ? WEB_GOALS : APP_GOALS).join(', ')}.`, { field: 'goalType' });
108
+ if (type === 'WEB' && !a.websiteUrl) throw new AdsError('validation', 'A WEB campaign needs websiteUrl.', { field: 'websiteUrl' });
109
+ const start = a.startDate ?? new Date(Date.now() + 86400000).toISOString().slice(0, 10);
110
+ const body = { name: a.name, type, status: 'PAUSED', targeting: a.countries.map((cc) => ({ country_code: String(cc).toUpperCase() })),
111
+ budget: { daily_budget_for_all_countries: String(a.dailyBudget) }, goal: { goal_type: goal, goal_value_for_all_countries: String(a.goalValue) },
112
+ bidding_strategy: 'AUTO_BIDDING_WITH_CPM_BILLING', start_date: `${start}T00:00:00`, ...(a.websiteUrl ? { website_url: a.websiteUrl } : {}), ...(a.fields ?? {}) };
113
+ const r = await manage(ctx, 'POST', '/campaign/create', { json: body });
114
+ const back = await ctx.platform.ops.getCampaign.run(ctx, { id: r.id });
115
+ if (back.status !== 'PAUSED') await manage(ctx, 'POST', '/campaign/update', { json: { id: String(r.id), type, status: 'PAUSED' } });
116
+ return { id: String(r.id), status: STATUS.PAUSED, ...(back.status !== 'PAUSED' ? { note: `AppLovin created it ${back.status}; it was paused straight away.` } : {}) };
117
+ },
118
+ },
119
+ updateCampaign: {
120
+ params: { id: { required: true }, name: {}, endDate: { type: 'string' }, websiteUrl: { type: 'string' }, countries: { type: 'array', desc: 'Replaces targeting wholesale.' } },
121
+ run: async (ctx, a) => {
122
+ const cur = await ctx.platform.ops.getCampaign.run(ctx, { id: a.id, raw: true });
123
+ const live = cur.status === 'LIVE';
124
+ if (live && (a.countries || a.endDate)) requireConfirm(a, 'Changing targeting or end date on a live campaign');
125
+ const body = { id: String(a.id), type: cur.raw?.type, ...(a.name ? { name: a.name } : {}), ...(a.endDate ? { end_date: `${a.endDate}T00:00:00` } : {}), ...(a.websiteUrl ? { website_url: a.websiteUrl } : {}),
126
+ ...(a.countries ? { targeting: a.countries.map((cc) => ({ country_code: String(cc).toUpperCase() })) } : {}), ...(a.fields ?? {}) };
127
+ await manage(ctx, 'POST', '/campaign/update', { json: body });
128
+ return { id: String(a.id) };
129
+ },
130
+ },
131
+ listAds: {
132
+ params: { campaignId: { required: true } },
133
+ run: async (ctx, a) => {
134
+ const r = await manage(ctx, 'GET', '/creative_set/list_by_campaign_id', { query: { ids: String(a.campaignId) } });
135
+ const list = r.campaigns?.[String(a.campaignId)] ?? [];
136
+ return { items: list.map((s) => row(s, { id: String(s.id), name: s.name, status: s.status, type: s.type }, a)) };
137
+ },
138
+ },
139
+ createCreative: {
140
+ params: { campaignId: { required: true }, name: { required: true }, assetIds: { type: 'array', required: true }, title: { type: 'string', desc: '25 characters.' }, description: { type: 'string', desc: '75 characters.' }, buttonLabel: { type: 'string', desc: '13 characters.' } },
141
+ run: async (ctx, a) => {
142
+ checkLength('title', a.title, 25); checkLength('description', a.description, 75); checkLength('buttonLabel', a.buttonLabel, 13);
143
+ const c = await ctx.creds();
144
+ const brand = a.title || a.description || a.buttonLabel ? { brand_info: { title: a.title, description: a.description, button_label: a.buttonLabel } } : {};
145
+ const r = await manage(ctx, 'POST', '/creative_set/create', { json: { type: String(c.accountType ?? 'WEB').toUpperCase(), name: a.name, campaign_id: String(a.campaignId), status: 'PAUSED', assets: a.assetIds.map((id) => ({ id })), ...brand, ...(a.fields ?? {}) } });
146
+ return { id: String(r.id), status: STATUS.PAUSED };
147
+ },
148
+ },
149
+ setStatus: {
150
+ params: { id: { required: true }, level: { desc: 'campaign (default) or ad (creative set).' }, status: { required: true } },
151
+ run: async (ctx, a) => {
152
+ const status = gateStatus(a);
153
+ if (status === STATUS.ARCHIVED) throw new AdsError('validation', 'AppLovin has no archive; pause instead.', { field: 'status' });
154
+ const c = await ctx.creds();
155
+ const path = a.level === 'ad' ? '/creative_set/update' : '/campaign/update';
156
+ await manage(ctx, 'POST', path, { json: { id: String(a.id), type: String(c.accountType ?? 'WEB').toUpperCase(), status: status === STATUS.ACTIVE ? 'LIVE' : 'PAUSED' } });
157
+ return { id: String(a.id), status };
158
+ },
159
+ },
160
+ setBudget: {
161
+ params: { id: { required: true }, amount: { required: true } },
162
+ run: async (ctx, a) => {
163
+ const cur = await ctx.platform.ops.getCampaign.run(ctx, { id: a.id, raw: true });
164
+ if (cur.status === 'LIVE') requireConfirm(a, 'Changing the budget of a live campaign');
165
+ await manage(ctx, 'POST', '/campaign/update', { json: { id: String(a.id), type: cur.raw?.type, budget: { daily_budget_for_all_countries: String(a.amount) } } });
166
+ return { id: String(a.id), dailyBudget: Number(a.amount) };
167
+ },
168
+ },
169
+ report: {
170
+ params: { since: {}, until: {}, columns: { type: 'array' } },
171
+ run: async (ctx, a) => {
172
+ const c = await ctx.creds();
173
+ const { since, until } = dateRange(a);
174
+ const web = String(c.accountType ?? 'WEB').toUpperCase() === 'WEB';
175
+ const r = await call(ctx, { base: REPORT, path: web ? '/webReport' : '/report', auth: true, query: {
176
+ api_key: c.reportKey, start: since, end: until, format: 'json', report_type: 'advertiser',
177
+ columns: (a.columns ?? ['day', 'campaign', 'impressions', 'clicks', 'cost', 'conversions']).join(','), ...(web ? { attribution_mode: 'click' } : {}), limit: Math.min(a.limit ?? 1000, 10000) } }, 'reportKey');
178
+ return { rows: r.results ?? r ?? [] };
179
+ },
180
+ },
181
+ },
182
+ });