-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·654 lines (624 loc) · 19.7 KB
/
Copy pathcli.js
File metadata and controls
executable file
·654 lines (624 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
#!/usr/bin/env node
"use strict";
const auth = require("./auth.js");
const parseArgs = argv => {
const positionals = [];
const flags = {};
const sets = [];
for (let i = 0; i < argv.length; i++) {
const token = argv[i];
if (!token.startsWith("--")) {
positionals.push(token);
continue;
}
const name = token.slice(2);
const next = argv[i + 1];
const hasValue = next !== undefined && !next.startsWith("--");
if (name === "set" && hasValue) {
sets.push(next);
i++;
continue;
}
if (hasValue) {
flags[name] = next;
i++;
} else {
flags[name] = true;
}
}
return { _: positionals, flags, sets };
};
const setDotPath = (obj, path, value) => {
const parts = path.split(".");
let cursor = obj;
for (let i = 0; i < parts.length - 1; i++) {
if (typeof cursor[parts[i]] !== "object" || cursor[parts[i]] === null) {
cursor[parts[i]] = {};
}
cursor = cursor[parts[i]];
}
cursor[parts[parts.length - 1]] = value;
return obj;
};
const buildBodyFromSets = sets => {
const body = {};
for (const entry of sets) {
const eq = entry.indexOf("=");
if (eq === -1) {
continue;
}
setDotPath(body, entry.slice(0, eq), entry.slice(eq + 1));
}
return body;
};
const buildConversionEvent = ({
type,
customName,
actionSource,
value,
currency,
conversionId,
email,
externalId,
clickId,
ip,
userAgent
}) => {
const hasSignal = email || externalId || clickId || (ip && userAgent);
if (!hasSignal) {
throw new Error(
"Conversion event needs at least one attribution signal (email, external-id, click-id, or ip+user-agent)"
);
}
const user = {};
if (email) {
user.email = auth.hashPII(email);
}
if (externalId) {
user.external_id = auth.hashPII(externalId);
}
if (ip) {
user.ip_address = auth.hashPII(ip);
}
if (userAgent) {
user.user_agent = userAgent;
}
const trackingType = String(type || "").toUpperCase();
const eventType = { tracking_type: trackingType };
if (trackingType === "CUSTOM" && customName) {
eventType.custom_event_name = customName;
}
const event = {
event_at: new Date().toISOString(),
action_source: (actionSource || "WEBSITE").toUpperCase(),
type: eventType,
user
};
if (clickId) {
event.click_id = clickId;
}
const metadata = {};
if (value !== undefined) {
metadata.value = value;
}
if (currency) {
metadata.currency = currency;
}
if (conversionId) {
metadata.conversion_id = conversionId;
}
if (Object.keys(metadata).length) {
event.metadata = metadata;
}
return event;
};
const RedditAdsAPI = require("./api.js");
const crypto = require("node:crypto");
const fs = require("node:fs");
const readline = require("node:readline");
const { spawn } = require("node:child_process");
// Credentials come from flags, then env, then the saved session (persisted at
// login so the stored refresh token can be exchanged without re-passing creds).
const resolveCredentials = (flags, session) => {
const clientId =
flags["client-id"] || process.env.REDDIT_CLIENT_ID || (session && session.client_id);
const clientSecret =
flags.secret || process.env.REDDIT_CLIENT_SECRET || (session && session.client_secret);
if (!clientId || !clientSecret) {
throw new Error(
"Missing credentials: set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET (or pass --client-id/--secret)"
);
}
return { clientId, clientSecret };
};
const resolveAccount = (flags, session) => {
const accountId = flags.account || (session && session.default_account_id);
if (!accountId) {
throw new Error(
"No ad account: pass --account <id> or run `reddit-ads-cli accounts use <id>`"
);
}
return accountId;
};
const print = (data, flags) => {
if (flags.json) {
process.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
return;
}
const payload = data && typeof data === "object" && "data" in data ? data.data : data;
if (Array.isArray(payload)) {
if (payload.length === 0) {
process.stdout.write("(no results)\n");
return;
}
payload.forEach(row => {
if (!row || typeof row !== "object") {
process.stdout.write(`${row}\n`);
return;
}
const id = row.id || row.asset_id || "";
const label = row.name || row.title || row.username || row.headline || row.type || "";
const status = row.configured_status || row.effective_status || row.status || "";
const line = [id, label, status].filter(Boolean).join("\t");
process.stdout.write(`${line || JSON.stringify(row)}\n`);
});
return;
}
process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
};
// Creative assets are wrapped as { result: { id, type, status, media: { permanent_url } } }.
const formatCreatives = data => {
const raw = data && data.data !== undefined ? data.data : data;
const items = (Array.isArray(raw) ? raw : [raw]).filter(Boolean);
if (items.length === 0) {
process.stdout.write("(no results)\n");
return;
}
process.stdout.write(["ID", "TYPE", "STATUS", "MEDIA_URL", "COVER_URL"].join("\t") + "\n");
for (const item of items) {
const asset = item.result || item;
const media = asset.media || {};
const mediaUrl = media.permanent_url || asset.media_url || "";
const coverUrl =
media.cover_url || asset.cover_url || asset.preview_url || asset.thumbnail_url || "";
process.stdout.write(
[asset.id || "", asset.type || "", asset.status || "", mediaUrl, coverUrl].join("\t") +
"\n"
);
}
};
const typedBody = flags => {
const body = {};
const map = {
name: "name",
status: "configured_status",
objective: "objective",
bid: "bid_value",
goal: "goal_value",
pixel: "conversion_pixel_id",
campaign: "campaign_id",
adgroup: "ad_group_id",
start: "start_time",
end: "end_time",
"spend-cap": "spend_cap"
};
for (const [flag, field] of Object.entries(map)) {
if (flags[flag] !== undefined) {
body[field] = flags[flag];
}
}
return body;
};
// list/create are account-scoped; show/edit/pause/resume address the entity by its own id.
const resourceCommands = (resource, getAccount, flags, sets, id) => ({
list: () =>
resource.list(getAccount(), { campaign_id: flags.campaign, ad_group_id: flags.adgroup }),
show: () => resource.get(id()),
create: () =>
resource.create(getAccount(), { ...typedBody(flags), ...buildBodyFromSets(sets) }),
edit: () => resource.update(id(), { ...typedBody(flags), ...buildBodyFromSets(sets) }),
pause: () => resource.update(id(), { configured_status: "PAUSED" }),
resume: () => resource.update(id(), { configured_status: "ACTIVE" })
});
// Reddit has no "list ad accounts" / "list profiles" endpoint; enumerate via businesses.
const listUnderBusinesses = async (api, fetchChildren) => {
const businesses = (await api.businesses()).data || [];
const out = [];
for (const business of businesses) {
const children = (await fetchChildren(business.id)).data || [];
for (const child of children) {
out.push({ ...child, business_id: business.id });
}
}
return { data: out };
};
const dispatch = async ({ group, command, positionals, flags, sets, api, getAccount }) => {
const id = () => positionals[0];
const groups = {
businesses: {
list: () => api.businesses()
},
profiles: {
list: () => listUnderBusinesses(api, businessId => api.businessProfiles(businessId))
},
accounts: {
list: () => listUnderBusinesses(api, businessId => api.businessAdAccounts(businessId)),
show: () => api.accounts.get(id() || getAccount())
},
campaigns: resourceCommands(api.campaigns, getAccount, flags, sets, id),
adgroups: resourceCommands(api.adGroups, getAccount, flags, sets, id),
ads: resourceCommands(api.ads, getAccount, flags, sets, id),
creatives: {
list: () => {
if (!flags.profile) {
throw new Error("creatives list requires --profile <profile_id>");
}
return api.creativeAssets.list(flags.profile);
},
show: () => api.creativeAssets.get(id())
},
pixels: {
list: () => api.pixels.list(getAccount())
}
};
const handler = groups[group] && groups[group][command];
if (!handler) {
throw new Error(`Unknown command: ${group} ${command || ""}`.trim());
}
return handler();
};
// Resolve a date input to an ISO 8601 string. Accepts "now", an ISO/parseable
// date, or a relative offset like "-7d", "+3h" (units: s, m, h, d, w).
// Reddit wants second-precision ISO (YYYY-MM-DDTHH:MM:SSZ), without milliseconds.
const toRedditIso = date => date.toISOString().replace(/\.\d{3}Z$/, "Z");
const resolveDate = (input, now = new Date()) => {
if (input === undefined || input === null || input === "" || input === "now") {
return toRedditIso(now);
}
const relative = String(input).match(/^([+-])(\d+)([smhdw])$/i);
if (relative) {
const sign = relative[1] === "-" ? -1 : 1;
const unitMs = { s: 1e3, m: 60e3, h: 3600e3, d: 86400e3, w: 7 * 86400e3 };
const offset = sign * Number(relative[2]) * unitMs[relative[3].toLowerCase()];
return toRedditIso(new Date(now.getTime() + offset));
}
const date = new Date(input);
if (Number.isNaN(date.getTime())) {
throw new Error(`Invalid date: ${input} (use ISO, "now", or a relative offset like -7d)`);
}
return toRedditIso(date);
};
const LEVEL_FIELD = { campaign: "CAMPAIGN_ID", ad_group: "AD_GROUP_ID", ad: "AD_ID" };
const buildReportBody = (flags, sets) => {
const level = flags.level || "campaign";
const levelField = LEVEL_FIELD[level] || LEVEL_FIELD.campaign;
const fieldsFlag = flags.fields || flags.metrics;
const fields = fieldsFlag
? fieldsFlag.split(",").map(field => field.trim().toUpperCase())
: [
levelField,
"SPEND",
"IMPRESSIONS",
"CLICKS",
"CTR",
"CPC",
"KEY_CONVERSION_TOTAL_COUNT"
];
const breakdowns = flags.breakdowns
? flags.breakdowns.split(",").map(breakdown => breakdown.trim().toUpperCase())
: [levelField];
// Reddit reports require hourly granularity (YYYY-MM-DDTHH:00:00Z).
const floorHour = iso => iso.replace(/T(\d{2}):\d{2}:\d{2}Z$/, "T$1:00:00Z");
return {
starts_at: floorHour(resolveDate(flags.from === undefined ? "-7d" : flags.from)),
ends_at: floorHour(resolveDate(flags.to === undefined ? "now" : flags.to)),
fields,
breakdowns,
...(flags["time-zone"] ? { time_zone_id: flags["time-zone"] } : {}),
...buildBodyFromSets(sets)
};
};
const openBrowser = url => {
const cmd =
process.platform === "darwin"
? "open"
: process.platform === "win32"
? "start"
: "xdg-open";
try {
spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
} catch {
/* user can copy the URL manually */
}
};
const runAuth = async (command, flags) => {
if (command === "logout") {
fs.rmSync(auth.sessionPath(), { force: true });
process.stdout.write("Logged out\n");
return;
}
if (command === "status") {
const s = auth.readSession();
if (!s) {
process.stdout.write("Not logged in\n");
return;
}
process.stdout.write(
`Logged in. Scope: ${s.scope}. Account: ${s.default_account_id || "(none)"}. Expires: ${new Date(s.expires_at).toISOString()}\n`
);
return;
}
const { clientId, clientSecret } = resolveCredentials(flags);
const redirectUri = flags["redirect-uri"] || auth.DEFAULT_REDIRECT_URI;
const scope = flags.scope || auth.DEFAULT_SCOPE;
const state = crypto.randomBytes(8).toString("hex");
const authorizeUrl = auth.buildAuthorizeUrl({ clientId, redirectUri, scope, state });
let code;
if (flags.manual) {
process.stdout.write(
`Open this URL, authorize, then paste the redirect URL here:\n${authorizeUrl}\n`
);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise(resolve =>
rl.question("Paste redirect URL or code: ", resolve)
);
rl.close();
code = auth.parseCodeFromInput(answer, state);
} else {
const port = Number(flags.port) || Number(new URL(redirectUri).port) || 8080;
process.stdout.write(`Opening browser for authorization...\n${authorizeUrl}\n`);
code = await auth.captureCodeViaLoopback({
port,
redirectUri,
state,
onUrl: () => openBrowser(authorizeUrl)
});
}
const token = await auth.exchangeCode({ clientId, clientSecret, code, redirectUri });
auth.writeSession({
access_token: token.access_token,
refresh_token: token.refresh_token,
expires_at: Date.now() + token.expires_in * 1000,
scope: token.scope,
redirect_uri: redirectUri,
// Persisted so later commands can refresh the saved token without re-supplying creds.
client_id: clientId,
client_secret: clientSecret
});
process.stdout.write(
"Login successful. Run `reddit-ads-cli accounts list` to find your account id.\n"
);
};
const runRaw = async (method, rest, flags) => {
const session = auth.readSession();
if (!session) {
throw new Error("Not logged in — run `reddit-ads-cli auth login` first");
}
const { clientId, clientSecret } = resolveCredentials(flags, session);
const { accessToken } = await auth.getValidAccessToken({ session, clientId, clientSecret });
const api = RedditAdsAPI({ accessToken, baseUrl: flags["base-url"] });
const body = flags.body ? JSON.parse(flags.body) : undefined;
const data = await api.request((method || "GET").toUpperCase(), rest[0], { body });
print(data, flags);
};
const USAGE = {
auth: {
desc: "Authenticate and manage the local session",
cmds: {
login: "auth login [--manual] [--redirect-uri URL] [--port N] [--scope CSV]",
status: "auth status",
logout: "auth logout"
}
},
businesses: {
desc: "Businesses you can access",
cmds: { list: "businesses list" }
},
accounts: {
desc: "Ad accounts (use sets the default account)",
cmds: {
list: "accounts list",
show: "accounts show [<ad_account_id>]",
use: "accounts use <ad_account_id>"
}
},
profiles: {
desc: "Reddit ad profiles (publishers of creative assets)",
cmds: { list: "profiles list" }
},
campaigns: {
desc: "Campaigns",
cmds: {
list: "campaigns list",
show: "campaigns show <campaign_id>",
create: "campaigns create --name N --objective O [--goal N --pixel ID ...]",
edit: "campaigns edit <campaign_id> [--name N --status S ...]",
pause: "campaigns pause <campaign_id>",
resume: "campaigns resume <campaign_id>"
}
},
adgroups: {
desc: "Ad groups",
cmds: {
list: "adgroups list [--campaign <campaign_id>]",
show: "adgroups show <ad_group_id>",
create: "adgroups create --campaign <id> --name N [--bid N ...]",
edit: "adgroups edit <ad_group_id> [flags]",
pause: "adgroups pause <ad_group_id>",
resume: "adgroups resume <ad_group_id>"
}
},
ads: {
desc: "Ads",
cmds: {
list: "ads list [--adgroup <ad_group_id>]",
show: "ads show <ad_id>",
create: "ads create --adgroup <id> --name N [flags]",
edit: "ads edit <ad_id> [flags]",
pause: "ads pause <ad_id>",
resume: "ads resume <ad_id>"
}
},
creatives: {
desc: "Creative assets (read-only)",
cmds: {
list: "creatives list --profile <profile_id>",
show: "creatives show <creative_asset_id>"
}
},
reports: {
desc: "Performance reports",
cmds: {
report:
"reports report [--level campaign|ad_group|ad] [--from -7d] [--to now] [--fields A,B] [--breakdowns X,Y]"
}
},
pixels: {
desc: "Conversion pixels",
cmds: { list: "pixels list" }
},
events: {
desc: "Conversion (CAPI) events",
cmds: {
send: "events send --pixel <pixel_id> --type PURCHASE [--value N --currency USD --email E]"
}
},
raw: {
desc: "Call any API endpoint directly",
cmds: { "<METHOD> <path>": "raw GET /me/businesses [--body '<json>']" }
}
};
const printGroupHelp = (group, stream = process.stdout) => {
const usage = USAGE[group];
if (!usage) {
return printHelp(stream);
}
stream.write(`${group} — ${usage.desc}\n\nCommands:\n`);
for (const example of Object.values(usage.cmds)) {
stream.write(` reddit-ads-cli ${example}\n`);
}
stream.write("\nGlobal flags: --account <id>, --json, --client-id, --secret, --base-url\n");
};
const printHelp = (stream = process.stdout) => {
stream.write("reddit-ads-cli <group> <command> [options]\n\nGroups:\n");
for (const [group, usage] of Object.entries(USAGE)) {
stream.write(` ${group.padEnd(11)} ${usage.desc}\n`);
}
stream.write(
"\nGlobal flags: --account <id>, --json, --client-id, --secret, --base-url\n" +
"Run `reddit-ads-cli <group>` to see its commands. See README.md for details.\n"
);
};
const main = async () => {
const argv = process.argv.slice(2);
const { _: positionals, flags, sets } = parseArgs(argv);
const [group, command, ...rest] = positionals;
if (!group || group === "help") {
printHelp();
return;
}
if (!USAGE[group]) {
printHelp(process.stderr);
throw new Error(`Unknown group: ${group}`);
}
if (!command || flags.help) {
printGroupHelp(group);
return;
}
if (group !== "raw" && !USAGE[group].cmds[command]) {
printGroupHelp(group, process.stderr);
throw new Error(`Unknown command: ${group} ${command}`);
}
if (group === "auth") {
await runAuth(command, flags);
return;
}
if (group === "raw") {
await runRaw(command, rest, flags);
return;
}
const session = auth.readSession();
if (!session) {
throw new Error("Not logged in — run `reddit-ads-cli auth login` first");
}
const { clientId, clientSecret } = resolveCredentials(flags, session);
const { accessToken } = await auth.getValidAccessToken({ session, clientId, clientSecret });
const api = RedditAdsAPI({ accessToken, baseUrl: flags["base-url"] });
if (group === "accounts" && command === "use") {
auth.writeSession({ ...session, default_account_id: rest[0] });
process.stdout.write(`Default account set to ${rest[0]}\n`);
return;
}
if (group === "reports" && command === "report") {
print(
await api.reports.run(resolveAccount(flags, session), buildReportBody(flags, sets)),
flags
);
return;
}
if (group === "events" && command === "send") {
if (!flags.pixel) {
throw new Error("events send requires --pixel <pixel_id>");
}
const event = buildConversionEvent({
type: flags.type,
customName: flags["custom-name"],
actionSource: flags["action-source"],
value: flags.value !== undefined ? Number(flags.value) : undefined,
currency: flags.currency,
conversionId: flags["conversion-id"],
email: flags.email,
externalId: flags["external-id"],
clickId: flags["click-id"],
ip: flags.ip,
userAgent: flags["user-agent"]
});
const payload = { events: [event] };
if (flags["test-id"]) {
payload.test_id = flags["test-id"];
}
print(await api.events.send(flags.pixel, payload), flags);
return;
}
let cachedAccount;
const getAccount = () => {
if (cachedAccount === undefined) {
cachedAccount = resolveAccount(flags, session);
}
return cachedAccount;
};
const data = await dispatch({
group,
command,
positionals: rest,
flags,
sets,
api,
getAccount
});
if (!flags.json && group === "creatives") {
formatCreatives(data);
return;
}
print(data, flags);
};
module.exports = {
parseArgs,
setDotPath,
buildBodyFromSets,
buildConversionEvent,
resolveDate,
buildReportBody,
formatCreatives,
resolveCredentials,
resolveAccount,
dispatch,
print,
main
};
if (require.main === module) {
main().catch(err => {
process.stderr.write(`${err.message}\n`);
process.exit(1);
});
}