@metricraven/cli 0.0.0-stage → 0.2.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/README.md +82 -2
- package/dist/api.js +77 -0
- package/dist/args.js +160 -0
- package/dist/commands.js +1391 -0
- package/dist/completion.js +69 -0
- package/dist/config.js +48 -0
- package/dist/format.js +67 -0
- package/dist/index.js +177 -0
- package/dist/prompt.js +48 -0
- package/dist/range.js +138 -0
- package/package.json +30 -4
package/dist/commands.js
ADDED
|
@@ -0,0 +1,1391 @@
|
|
|
1
|
+
import { ApiError, createClient } from "./api.js";
|
|
2
|
+
import { UsageError, buildFilters, positiveInt, rangeParams } from "./args.js";
|
|
3
|
+
import { customRange, validTimeZone } from "./range.js";
|
|
4
|
+
import { completionScript } from "./completion.js";
|
|
5
|
+
import { configPath, deleteConfigToken, readConfig, resolveSettings, updateConfig } from "./config.js";
|
|
6
|
+
import { bold, change, date, dim, duration, money, num, pct, section, table, truncate } from "./format.js";
|
|
7
|
+
import { interactive, prompt, promptHidden, readStdin } from "./prompt.js";
|
|
8
|
+
export const TOKENS_URL = "https://metricraven.com/app/api";
|
|
9
|
+
const out = (s) => process.stdout.write(`${s}\n`);
|
|
10
|
+
const printJson = (data) => out(JSON.stringify(data));
|
|
11
|
+
/**
|
|
12
|
+
* --fields: the API's ?fields= selection (comma-separated dot paths, period always kept). The
|
|
13
|
+
* answer is then only part of a report, so it is printed as JSON instead of the usual tables.
|
|
14
|
+
*/
|
|
15
|
+
export function selectFields(flags, params) {
|
|
16
|
+
if (flags.fields === undefined)
|
|
17
|
+
return false;
|
|
18
|
+
const fields = flags.fields.trim();
|
|
19
|
+
if (!fields)
|
|
20
|
+
throw new UsageError("--fields needs comma-separated dot paths, e.g. --fields overview.current,series.date.");
|
|
21
|
+
params.set("fields", fields);
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
/** Runs a parsed command. Returns the exit code. */
|
|
25
|
+
export async function run(command, flags) {
|
|
26
|
+
const [group, sub, ...rest] = command;
|
|
27
|
+
if (group === "completion") {
|
|
28
|
+
out(completionScript(sub ?? ""));
|
|
29
|
+
return 0;
|
|
30
|
+
}
|
|
31
|
+
if (group === "login")
|
|
32
|
+
return login(flags);
|
|
33
|
+
if (group === "logout") {
|
|
34
|
+
await deleteConfigToken();
|
|
35
|
+
out(`Logged out. Removed the token from ${configPath()}.`);
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
const config = await readConfig();
|
|
39
|
+
const settings = resolveSettings(flags, process.env, config);
|
|
40
|
+
if (!settings.token)
|
|
41
|
+
throw new UsageError(`Not logged in. Run \`metricraven login\`, or set METRICRAVEN_TOKEN (create a token at ${TOKENS_URL}).`);
|
|
42
|
+
const client = createClient({ apiBase: settings.apiBase, token: settings.token, verbose: flags.verbose });
|
|
43
|
+
const ctx = { flags, client, site: () => pickSite(client, settings.site, flags) };
|
|
44
|
+
switch (group) {
|
|
45
|
+
case "whoami":
|
|
46
|
+
return whoami(ctx);
|
|
47
|
+
case "account":
|
|
48
|
+
if (!sub || sub === "get")
|
|
49
|
+
return whoami(ctx);
|
|
50
|
+
if (sub === "update")
|
|
51
|
+
return updateAccount(ctx);
|
|
52
|
+
break;
|
|
53
|
+
case "tokens":
|
|
54
|
+
return tokens(ctx, sub, rest);
|
|
55
|
+
case "payments":
|
|
56
|
+
if (sub === "delete")
|
|
57
|
+
return deletePayments(ctx);
|
|
58
|
+
break;
|
|
59
|
+
case "use":
|
|
60
|
+
return useSite(ctx, sub);
|
|
61
|
+
case "websites":
|
|
62
|
+
case "sites":
|
|
63
|
+
if (sub === "create")
|
|
64
|
+
return createWebsite(ctx);
|
|
65
|
+
if (sub === "keys")
|
|
66
|
+
return siteKeys(ctx, rest[0], rest.slice(1));
|
|
67
|
+
if (!sub || sub === "list")
|
|
68
|
+
return listWebsites(ctx);
|
|
69
|
+
if (sub === "get")
|
|
70
|
+
return getWebsite(ctx, rest[0]);
|
|
71
|
+
if (sub === "update")
|
|
72
|
+
return updateWebsite(ctx, rest[0]);
|
|
73
|
+
if (sub === "delete")
|
|
74
|
+
return deleteWebsiteCommand(ctx, rest[0]);
|
|
75
|
+
break;
|
|
76
|
+
case "analytics":
|
|
77
|
+
return analytics(ctx, sub, rest);
|
|
78
|
+
case "realtime":
|
|
79
|
+
case "live":
|
|
80
|
+
return realtime(ctx);
|
|
81
|
+
case "visitors":
|
|
82
|
+
if (!sub || sub === "list")
|
|
83
|
+
return listVisitors(ctx);
|
|
84
|
+
if (sub === "get")
|
|
85
|
+
return getVisitor(ctx, rest[0]);
|
|
86
|
+
break;
|
|
87
|
+
case "funnels":
|
|
88
|
+
if (!sub || sub === "list")
|
|
89
|
+
return listFunnels(ctx);
|
|
90
|
+
break;
|
|
91
|
+
case "goals":
|
|
92
|
+
if (sub === "delete-events")
|
|
93
|
+
return deleteGoalEvents(ctx);
|
|
94
|
+
return goals(ctx, sub, rest);
|
|
95
|
+
case "notes":
|
|
96
|
+
if (!sub || sub === "list")
|
|
97
|
+
return listNotes(ctx);
|
|
98
|
+
if (sub === "add")
|
|
99
|
+
return addNote(ctx);
|
|
100
|
+
break;
|
|
101
|
+
case "mentions":
|
|
102
|
+
if (!sub || sub === "list")
|
|
103
|
+
return listMentions(ctx);
|
|
104
|
+
break;
|
|
105
|
+
case "ai-visibility":
|
|
106
|
+
case "ai":
|
|
107
|
+
if (!sub || sub === "summary")
|
|
108
|
+
return aiVisibility(ctx);
|
|
109
|
+
break;
|
|
110
|
+
case "alerts":
|
|
111
|
+
return alerts(ctx, sub, rest);
|
|
112
|
+
case "members":
|
|
113
|
+
case "team":
|
|
114
|
+
return members(ctx, sub, rest);
|
|
115
|
+
case "bots":
|
|
116
|
+
return bots(ctx, sub, rest);
|
|
117
|
+
case "proxy":
|
|
118
|
+
return managedProxy(ctx, sub, rest);
|
|
119
|
+
}
|
|
120
|
+
throw new UsageError(`Unknown command "${command.join(" ")}". Run \`metricraven --help\`.`);
|
|
121
|
+
}
|
|
122
|
+
async function login(flags) {
|
|
123
|
+
let token = flags.token?.trim();
|
|
124
|
+
if (!token) {
|
|
125
|
+
if (process.stdin.isTTY) {
|
|
126
|
+
out(`Create an access token at ${bold(TOKENS_URL)} (Settings → API & MCP), then paste it here.`);
|
|
127
|
+
token = await promptHidden("Token: ");
|
|
128
|
+
}
|
|
129
|
+
else
|
|
130
|
+
token = await readStdin();
|
|
131
|
+
}
|
|
132
|
+
if (!token)
|
|
133
|
+
throw new UsageError("No token given.");
|
|
134
|
+
if (!token.startsWith("mr_"))
|
|
135
|
+
throw new UsageError(`That doesn't look like an account token (they start with mr_). Create one at ${TOKENS_URL}.`);
|
|
136
|
+
const config = await readConfig();
|
|
137
|
+
const apiBase = resolveSettings({}, process.env, config).apiBase;
|
|
138
|
+
const account = await createClient({ apiBase, token, verbose: flags.verbose })
|
|
139
|
+
.get("/account")
|
|
140
|
+
.catch((error) => {
|
|
141
|
+
if (error instanceof ApiError && error.status === 401)
|
|
142
|
+
throw new ApiError(`That token was not accepted (deleted, mistyped or for another server). Create a new one at ${TOKENS_URL}.`, 401);
|
|
143
|
+
throw error;
|
|
144
|
+
});
|
|
145
|
+
await updateConfig({ token });
|
|
146
|
+
if (flags.json)
|
|
147
|
+
printJson(account);
|
|
148
|
+
else
|
|
149
|
+
out(`Logged in as ${bold(account.user.email)} with token "${account.token.name}" (${scopes(account.token.scopes)}). Saved to ${configPath()}.`);
|
|
150
|
+
return 0;
|
|
151
|
+
}
|
|
152
|
+
const scopes = (s) => ["read reports", s.includes("visitors") ? "visitor details" : null, s.includes("write") ? "write" : null].filter(Boolean).join(", ");
|
|
153
|
+
async function whoami({ flags, client }) {
|
|
154
|
+
const account = await client.get("/account");
|
|
155
|
+
if (flags.json)
|
|
156
|
+
return printJson(account), 0;
|
|
157
|
+
out(`${bold(account.user.email)}${account.user.name ? ` (${account.user.name})` : ""}`);
|
|
158
|
+
out(`Token: ${account.token.name}`);
|
|
159
|
+
out(`Access: ${scopes(account.token.scopes)}`);
|
|
160
|
+
out(`Websites: ${account.token.siteIds === null ? "all" : account.token.siteIds.join(", ")}`);
|
|
161
|
+
return 0;
|
|
162
|
+
}
|
|
163
|
+
async function websites(client) {
|
|
164
|
+
return (await client.get("/websites")).websites;
|
|
165
|
+
}
|
|
166
|
+
/** The website for a report: --site, METRICRAVEN_SITE or the saved default; otherwise the only one, or a prompt. */
|
|
167
|
+
async function pickSite(client, configured, flags) {
|
|
168
|
+
if (configured)
|
|
169
|
+
return configured;
|
|
170
|
+
const list = await websites(client);
|
|
171
|
+
if (list.length === 1)
|
|
172
|
+
return list[0].id;
|
|
173
|
+
if (!list.length)
|
|
174
|
+
throw new UsageError("This token can't see any websites. Add one with `metricraven websites create`.");
|
|
175
|
+
if (!interactive() || flags.json)
|
|
176
|
+
throw new UsageError(`Choose a website with --site <id> or \`metricraven use <id>\`. This token can use ${list.length}: run \`metricraven websites list\`.`);
|
|
177
|
+
list.forEach((w, i) => out(`${String(i + 1).padStart(2)}. ${w.name} ${dim(`${w.domains.join(", ")} · ${w.id}`)}`));
|
|
178
|
+
const answer = await prompt("Website number: ");
|
|
179
|
+
const chosen = list[Number(answer) - 1];
|
|
180
|
+
if (!chosen)
|
|
181
|
+
throw new UsageError("No website chosen.");
|
|
182
|
+
out(dim(`Tip: \`metricraven use ${chosen.id}\` makes it the default.`));
|
|
183
|
+
return chosen.id;
|
|
184
|
+
}
|
|
185
|
+
async function listWebsites({ flags, client }) {
|
|
186
|
+
const list = await websites(client);
|
|
187
|
+
if (flags.json)
|
|
188
|
+
return printJson({ websites: list }), 0;
|
|
189
|
+
if (!list.length)
|
|
190
|
+
return out("No websites yet. Add one with `metricraven websites create --name <name> --domain <domain>`."), 0;
|
|
191
|
+
const current = resolveSettings(flags, process.env, await readConfig()).site;
|
|
192
|
+
out(table(["", "Name", "Domains", "ID"], list.map((w) => [w.id === current ? "*" : "", w.name, w.domains.join(", "), w.id])));
|
|
193
|
+
return 0;
|
|
194
|
+
}
|
|
195
|
+
async function createWebsite({ flags, client }) {
|
|
196
|
+
if (!flags.name || !flags.domain)
|
|
197
|
+
throw new UsageError("Use: metricraven websites create --name <name> --domain <example.com>");
|
|
198
|
+
const data = await needs("write", client.post("/websites", { name: flags.name, domain: flags.domain }));
|
|
199
|
+
const script = `<script defer src="https://metricraven.com/js/script.js" data-site-id="${data.website.id}"></script>`;
|
|
200
|
+
if (flags.json)
|
|
201
|
+
return printJson({ ...data, trackingScript: script }), 0;
|
|
202
|
+
out(`Created ${bold(data.website.name)} (${data.website.domains.join(", ")}).`);
|
|
203
|
+
out(`Website ID: ${data.website.id}`);
|
|
204
|
+
out(`Secret key: ${data.secretKey}`);
|
|
205
|
+
out(dim("The secret key is shown once. Keep it on your server (server events, payments, reports)."));
|
|
206
|
+
out(`\nAdd this to the <head> of every page:\n${script}`);
|
|
207
|
+
return 0;
|
|
208
|
+
}
|
|
209
|
+
async function useSite({ flags, client }, id) {
|
|
210
|
+
if (!id)
|
|
211
|
+
throw new UsageError("Use: metricraven use <website_id> (see `metricraven websites list`).");
|
|
212
|
+
const site = (await websites(client)).find((w) => w.id === id);
|
|
213
|
+
if (!site)
|
|
214
|
+
throw new UsageError(`No website "${id}" for this token. Run \`metricraven websites list\`.`);
|
|
215
|
+
await updateConfig({ site: id });
|
|
216
|
+
if (flags.json)
|
|
217
|
+
printJson({ site: id });
|
|
218
|
+
else
|
|
219
|
+
out(`Default website: ${bold(site.name)} (${id}).`);
|
|
220
|
+
return 0;
|
|
221
|
+
}
|
|
222
|
+
const REPORTS = ["traffic", "revenue", "conversions", "insights", "search", "crawlers", "ads", "meta-ads"];
|
|
223
|
+
async function analytics(ctx, sub, rest) {
|
|
224
|
+
const { flags, client } = ctx;
|
|
225
|
+
if (!sub)
|
|
226
|
+
throw new UsageError(`Use: metricraven analytics <${[...REPORTS, "breakdown", "goal"].join("|")}>`);
|
|
227
|
+
const params = rangeParams(flags);
|
|
228
|
+
if (sub === "breakdown") {
|
|
229
|
+
const dimension = rest[0];
|
|
230
|
+
if (!dimension)
|
|
231
|
+
throw new UsageError("Use: metricraven analytics breakdown <dimension>, e.g. country, referrer, page, utmSource.");
|
|
232
|
+
params.set("dimension", dimension);
|
|
233
|
+
if (flags.sort)
|
|
234
|
+
params.set("sort", flags.sort);
|
|
235
|
+
if (flags.q)
|
|
236
|
+
params.set("q", flags.q);
|
|
237
|
+
const limit = positiveInt(flags.limit, "limit", 100);
|
|
238
|
+
if (limit !== undefined)
|
|
239
|
+
params.set("limit", String(Math.max(1, limit)));
|
|
240
|
+
const offset = positiveInt(flags.offset, "offset", 1_000_000);
|
|
241
|
+
if (offset !== undefined)
|
|
242
|
+
params.set("offset", String(offset));
|
|
243
|
+
}
|
|
244
|
+
else if (sub === "goal") {
|
|
245
|
+
if (!rest[0])
|
|
246
|
+
throw new UsageError("Use: metricraven analytics goal <name>");
|
|
247
|
+
params.set("name", rest[0]);
|
|
248
|
+
}
|
|
249
|
+
else if (sub === "meta-ads" && rest[0]) {
|
|
250
|
+
if (!["campaign", "adset", "ad"].includes(rest[0]))
|
|
251
|
+
throw new UsageError("Use: metricraven analytics meta-ads [campaign|adset|ad]");
|
|
252
|
+
params.set("level", rest[0]);
|
|
253
|
+
}
|
|
254
|
+
else if (sub === "ads") {
|
|
255
|
+
if (rest[0] && !["campaign", "adgroup", "adset", "ad"].includes(rest[0]))
|
|
256
|
+
throw new UsageError("Use: metricraven analytics ads [campaign|adgroup|ad] [--provider all|meta|google]");
|
|
257
|
+
if (rest[0])
|
|
258
|
+
params.set("level", rest[0]);
|
|
259
|
+
if (flags.provider) {
|
|
260
|
+
if (!["all", "meta", "google", "tiktok"].includes(flags.provider))
|
|
261
|
+
throw new UsageError("Use --provider all, meta or google.");
|
|
262
|
+
params.set("provider", flags.provider);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
else if (!REPORTS.includes(sub)) {
|
|
266
|
+
throw new UsageError(`Unknown report "${sub}". Use ${[...REPORTS, "breakdown", "goal"].join(", ")}.`);
|
|
267
|
+
}
|
|
268
|
+
params.set("site", await ctx.site());
|
|
269
|
+
const selected = selectFields(flags, params);
|
|
270
|
+
const path = sub === "breakdown" ? "/stats/breakdown" : sub === "goal" ? "/stats/goal" : `/stats/${sub}`;
|
|
271
|
+
const data = await client.get(path, params);
|
|
272
|
+
if (flags.json || selected)
|
|
273
|
+
return printJson(data), 0;
|
|
274
|
+
const render = RENDER[sub];
|
|
275
|
+
out(render ? render(data) : JSON.stringify(data, null, 2));
|
|
276
|
+
return 0;
|
|
277
|
+
}
|
|
278
|
+
const NETWORKS = { meta: "Meta Ads", google: "Google Ads", tiktok: "TikTok Ads" };
|
|
279
|
+
/** analytics ads and analytics meta-ads (the same response shape). */
|
|
280
|
+
function renderAds(d) {
|
|
281
|
+
if (!d.configured)
|
|
282
|
+
return d.reason === "no_account"
|
|
283
|
+
? "An ad network is connected but no ad account is chosen yet. Pick one in Settings → Integrations."
|
|
284
|
+
: "No ad network is connected for this website. Connect Meta Ads or Google Ads in the dashboard: https://metricraven.com/docs/meta-ads";
|
|
285
|
+
const cur = d.period?.currency ?? "USD";
|
|
286
|
+
const t = d.totals;
|
|
287
|
+
const roas = (v) => (v === null || v === undefined ? "–" : `${num(v, 2)}x`);
|
|
288
|
+
const combined = (d.accounts?.length ?? 0) > 1;
|
|
289
|
+
const label = d.level === "ad" ? "Ad" : d.level === "adset" || d.level === "adgroup" ? (d.provider === "meta" ? "Ad set" : "Ad group") : "Campaign";
|
|
290
|
+
return [
|
|
291
|
+
...(d.accounts ?? []).map((a) => dim(`${NETWORKS[a.provider] ?? a.provider}: ${a.name}${d.sample ? " · sample data" : ""} · days ${a.days.from} → ${a.days.to} (${a.timeZone})`)),
|
|
292
|
+
`${combined ? "All networks: s" : "S"}pend ${money(t.spend, cur)} · revenue ${money(t.revenue, cur)} · ROAS ${roas(t.roas)} · ${num(t.customers)} customers · cost per customer ${t.costPerCustomer === null ? "–" : money(t.costPerCustomer, cur)} · assisted ${money(t.assistedRevenue ?? 0, cur)}`,
|
|
293
|
+
...(d.accounts ?? []).flatMap((a) => [
|
|
294
|
+
a.sync.error ? dim(`${NETWORKS[a.provider] ?? a.provider} sync: ${a.sync.error}`) : "",
|
|
295
|
+
a.unconvertedSpend ? dim(`${money(a.unconvertedSpend, a.currency)} of ${NETWORKS[a.provider] ?? a.provider} spend has no exchange rate yet and is left out.`) : "",
|
|
296
|
+
]),
|
|
297
|
+
section(`${label}s`, d.rows?.length
|
|
298
|
+
? table([label, ...(combined ? ["Network"] : []), "Spend", "Link clicks", "Ad visitors", "Customers", "Revenue", "ROAS", "Cost/customer", "Assisted"], d.rows.slice(0, 15).map((r) => [
|
|
299
|
+
truncate(r.name, 40),
|
|
300
|
+
...(combined ? [(NETWORKS[r.provider ?? ""] ?? r.provider ?? "").replace(" Ads", "")] : []),
|
|
301
|
+
money(r.spend, cur),
|
|
302
|
+
num(r.linkClicks),
|
|
303
|
+
num(r.visitors),
|
|
304
|
+
num(r.customers),
|
|
305
|
+
money(r.revenue, cur),
|
|
306
|
+
roas(r.roas),
|
|
307
|
+
r.costPerCustomer === null ? "–" : money(r.costPerCustomer, cur),
|
|
308
|
+
money(r.assistedRevenue ?? 0, cur),
|
|
309
|
+
]), ["left", ...(combined ? ["left"] : []), "right", "right", "right", "right", "right", "right", "right", "right"])
|
|
310
|
+
: dim("No ad spend or attributed visits in this period.")),
|
|
311
|
+
...(d.accounts ?? [])
|
|
312
|
+
.filter((a) => a.unattributed.visitors || a.unattributed.revenue)
|
|
313
|
+
.map((a) => dim(`${a.unattributed.label}: ${num(a.unattributed.visitors)} visitors, ${num(a.unattributed.customers)} customers, ${money(a.unattributed.revenue, cur)} revenue. Not in the totals or ROAS.`)),
|
|
314
|
+
]
|
|
315
|
+
.filter(Boolean)
|
|
316
|
+
.join("\n");
|
|
317
|
+
}
|
|
318
|
+
function periodLine(p) {
|
|
319
|
+
if (!p?.from || !p.to)
|
|
320
|
+
return "";
|
|
321
|
+
const zone = p.timeZone && p.timeZone !== "UTC" ? ` ${p.timeZone}` : " UTC";
|
|
322
|
+
return dim(`${p.allTime ? "All time: " : ""}${date(p.from)} → ${date(p.to)}${zone}`);
|
|
323
|
+
}
|
|
324
|
+
const rowsTable = (rows, label, currency, limit = 5) => rows?.length
|
|
325
|
+
? table([label, "Visitors", "Revenue"], rows.slice(0, limit).map((r) => [truncate(r.name), num(r.visitors), r.revenue === undefined ? "–" : money(r.revenue, currency)]), ["left", "right", "right"])
|
|
326
|
+
: dim("No data.");
|
|
327
|
+
const RENDER = {
|
|
328
|
+
traffic(d) {
|
|
329
|
+
const c = d.overview.current;
|
|
330
|
+
const ch = d.overview.change;
|
|
331
|
+
const cur = d.period.currency ?? "USD";
|
|
332
|
+
const metric = (label, value, key, lowerIsBetter = false) => [label, value, change(ch[key], { lowerIsBetter })];
|
|
333
|
+
return [
|
|
334
|
+
periodLine(d.period),
|
|
335
|
+
table(["Metric", "Value", "vs previous"], [
|
|
336
|
+
metric("Visitors", num(c.visitors), "visitors"),
|
|
337
|
+
metric("Pageviews", num(c.pageviews), "pageviews"),
|
|
338
|
+
metric("Visits", num(c.sessions), "sessions"),
|
|
339
|
+
metric("Bounce rate", pct(c.bounceRate, 0), "bounceRate", true),
|
|
340
|
+
metric("Visit duration", duration(c.avgSessionDuration), "avgSessionDuration"),
|
|
341
|
+
metric("Revenue", money(c.revenue, cur), "revenue"),
|
|
342
|
+
metric("Conversion rate", pct(c.conversionRate, 2), "conversionRate"),
|
|
343
|
+
metric("Revenue / visitor", money(c.revenuePerVisitor, cur), "revenuePerVisitor"),
|
|
344
|
+
], ["left", "right", "right"]),
|
|
345
|
+
section("Top channels", rowsTable(d.channels, "Channel", cur)),
|
|
346
|
+
section("Top pages", rowsTable(d.pages, "Page", cur)),
|
|
347
|
+
section("Top countries", rowsTable(d.countries, "Country", cur)),
|
|
348
|
+
].join("\n");
|
|
349
|
+
},
|
|
350
|
+
breakdown(d) {
|
|
351
|
+
if (!d.rows.length)
|
|
352
|
+
return dim("No data.");
|
|
353
|
+
return [
|
|
354
|
+
table([d.dimension, "Visitors", "Pageviews", "Revenue"], d.rows.map((r) => [truncate(r.name, 60), num(r.visitors), num(r.pageviews), money(r.revenue)]), ["left", "right", "right", "right"]),
|
|
355
|
+
dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`),
|
|
356
|
+
].join("\n");
|
|
357
|
+
},
|
|
358
|
+
revenue(d) {
|
|
359
|
+
const c = d.overview.current;
|
|
360
|
+
const ch = d.overview.change;
|
|
361
|
+
const cur = d.period.currency ?? "USD";
|
|
362
|
+
return [
|
|
363
|
+
periodLine(d.period),
|
|
364
|
+
table(["Metric", "Value", "vs previous"], [
|
|
365
|
+
["Revenue", money(c.revenue, cur), change(ch.revenue)],
|
|
366
|
+
["New revenue", money(c.newRevenue, cur), change(ch.newRevenue)],
|
|
367
|
+
["Renewal revenue", money(c.renewalRevenue, cur), change(ch.renewalRevenue)],
|
|
368
|
+
["New payments", num(c.newPayments), change(ch.newPayments)],
|
|
369
|
+
["Renewals", num(c.renewals), change(ch.renewals)],
|
|
370
|
+
["Paying customers", num(c.payingCustomers), change(ch.payingCustomers)],
|
|
371
|
+
["Refunds", `${num(c.refunds)} (${money(c.refundedAmount, cur)})`, ""],
|
|
372
|
+
], ["left", "right", "right"]),
|
|
373
|
+
section("Revenue by channel (first touch)", d.byChannel?.length
|
|
374
|
+
? table(["Channel", "Revenue", "New", "Renewals"], d.byChannel.slice(0, 8).map((r) => [r.name, money(r.revenue, cur), num(r.newPayments), num(r.renewals)]), ["left", "right", "right", "right"])
|
|
375
|
+
: dim("No payments.")),
|
|
376
|
+
d.ltv ? section("Lifetime value", `${num(d.ltv.customers)} customers · average ${money(d.ltv.average, cur)}`) : "",
|
|
377
|
+
].join("\n");
|
|
378
|
+
},
|
|
379
|
+
conversions(d) {
|
|
380
|
+
// Hidden goals (Settings → Goals) stay out of the table, like the dashboard; --json has them all.
|
|
381
|
+
const shown = d.goals.filter((g) => !g.hidden);
|
|
382
|
+
const hidden = d.goals.length - shown.length;
|
|
383
|
+
return [
|
|
384
|
+
periodLine(d.period),
|
|
385
|
+
section("Goals", shown.length
|
|
386
|
+
? table(["Goal", "Visitors", "Completions", "Rate"], shown.map((g) => [truncate(goalText(g)), num(g.visitors), num(g.events), pct(g.rate, 2)]), ["left", "right", "right", "right"])
|
|
387
|
+
: dim("No goals in this period.")),
|
|
388
|
+
hidden ? dim(`${num(hidden)} hidden goal${hidden === 1 ? "" : "s"} not shown (see --json or \`metricraven goals list\`).`) : "",
|
|
389
|
+
d.funnel?.length
|
|
390
|
+
? section("Funnel", table(["Step", "Visitors", "From start"], d.funnel.map((s) => [s.displayName || s.step, num(s.visitors), pct(s.fromStart, 0)]), ["left", "right", "right"]))
|
|
391
|
+
: "",
|
|
392
|
+
]
|
|
393
|
+
.filter(Boolean)
|
|
394
|
+
.join("\n");
|
|
395
|
+
},
|
|
396
|
+
insights(d) {
|
|
397
|
+
const o = d.overview;
|
|
398
|
+
const cur = d.period.currency ?? "USD";
|
|
399
|
+
return [
|
|
400
|
+
periodLine(d.period),
|
|
401
|
+
`${num(o.visitors)} visitors · ${num(o.payingVisitors)} paying (${pct(o.purchaseRate, 2)}) · ${num(o.customers)} customers · ${money(o.revenue, cur)}`,
|
|
402
|
+
d.timing
|
|
403
|
+
? `Time to first purchase: median ${num(d.timing.medianDays, 1)} days, ${num(d.timing.medianVisits)} visits · ${pct(d.timing.firstVisitPercent, 0)} buy on the first visit`
|
|
404
|
+
: "",
|
|
405
|
+
d.revenueMix?.sources?.length
|
|
406
|
+
? section("Revenue by source", table(["Source", "Revenue"], d.revenueMix.sources.slice(0, 6).map((s) => [s.name, money(s.revenue, cur)]), ["left", "right"]))
|
|
407
|
+
: "",
|
|
408
|
+
d.sourceChanges?.length
|
|
409
|
+
? section("Source changes (visitors)", table(["Source", "Now", "Before", "Change"], d.sourceChanges.slice(0, 6).map((s) => [s.name, num(s.current), num(s.previous), change(s.percent)]), ["left", "right", "right", "right"]))
|
|
410
|
+
: "",
|
|
411
|
+
]
|
|
412
|
+
.filter(Boolean)
|
|
413
|
+
.join("\n");
|
|
414
|
+
},
|
|
415
|
+
search(d) {
|
|
416
|
+
if (!d.configured)
|
|
417
|
+
return `Search Console isn't connected for this website (${d.reason?.replace(/_/g, " ") ?? "not configured"}). Connect it in the dashboard: https://metricraven.com/docs/search-console`;
|
|
418
|
+
const t = d.totals;
|
|
419
|
+
return [
|
|
420
|
+
periodLine(d.period),
|
|
421
|
+
`${num(t.clicks)} clicks · ${num(t.impressions)} impressions · CTR ${pct(t.ctr * (t.ctr <= 1 ? 100 : 1), 1)} · position ${num(t.position, 1)}`,
|
|
422
|
+
section("Top queries", d.queries?.length
|
|
423
|
+
? table(["Query", "Clicks", "Impressions", "Position", "Revenue"], d.queries.slice(0, 10).map((q) => [truncate(q.query), num(q.clicks), num(q.impressions), num(q.position, 1), money(q.revenue)]), ["left", "right", "right", "right", "right"])
|
|
424
|
+
: dim("No queries.")),
|
|
425
|
+
].join("\n");
|
|
426
|
+
},
|
|
427
|
+
ads: (d) => renderAds(d),
|
|
428
|
+
"meta-ads": (d) => renderAds(d),
|
|
429
|
+
crawlers(d) {
|
|
430
|
+
return [
|
|
431
|
+
periodLine(d.period),
|
|
432
|
+
`${num(d.total)} bot and AI crawler requests${d.byType.length ? ` · ${d.byType.map((t) => `${t.name} ${num(t.requests)}`).join(" · ")}` : ""}`,
|
|
433
|
+
d.byBot.length
|
|
434
|
+
? section("Crawlers", table(["Crawler", "Provider", "Purpose", "Requests", "Pages", "Last seen"], d.byBot.slice(0, 15).map((b) => [b.bot, b.provider ?? "–", b.type, num(b.requests), num(b.pages), date(b.lastSeenAt)]), ["left", "left", "left", "right", "right", "left"]))
|
|
435
|
+
: dim("No crawler requests in this period."),
|
|
436
|
+
].join("\n");
|
|
437
|
+
},
|
|
438
|
+
goal(d) {
|
|
439
|
+
const t = d.totals;
|
|
440
|
+
return [
|
|
441
|
+
periodLine(d.period),
|
|
442
|
+
`${bold(goalText(d))}${d.hidden ? dim(" (hidden)") : ""}: ${num(t.events)} completions by ${num(t.people)} visitors · ${pct(t.rate, 2)} of ${num(t.visitors)} visitors`,
|
|
443
|
+
d.description ? dim(d.description) : "",
|
|
444
|
+
d.sources.length
|
|
445
|
+
? section("Sources", table(["Source", "Visitors"], d.sources.slice(0, 10).map((s) => [s.name, num(s.visitors)]), ["left", "right"]))
|
|
446
|
+
: "",
|
|
447
|
+
...d.properties.slice(0, 5).map((p) => section(`Property: ${p.key}`, table(["Value", "Completions"], p.values.slice(0, 10).map((v) => [truncate(v.value), num(v.events)]), ["left", "right"]))),
|
|
448
|
+
]
|
|
449
|
+
.filter(Boolean)
|
|
450
|
+
.join("\n");
|
|
451
|
+
},
|
|
452
|
+
};
|
|
453
|
+
async function realtime(ctx) {
|
|
454
|
+
const params = new URLSearchParams({ site: await ctx.site() });
|
|
455
|
+
const selected = selectFields(ctx.flags, params);
|
|
456
|
+
const d = await ctx.client.get("/stats/live", params);
|
|
457
|
+
if (ctx.flags.json || selected)
|
|
458
|
+
return printJson(d), 0;
|
|
459
|
+
out(`${bold(num(d.visitorsNow))} visitor${d.visitorsNow === 1 ? "" : "s"} online now`);
|
|
460
|
+
if (d.visitors.length)
|
|
461
|
+
out(table(["Visitor", "Page", "Source", "Location", "Device", "Last seen"], d.visitors.slice(0, 25).map((v) => [
|
|
462
|
+
v.name ?? v.visitorId.slice(0, 8),
|
|
463
|
+
truncate(v.path ?? "–", 40),
|
|
464
|
+
v.source ?? "–",
|
|
465
|
+
[v.city, v.country].filter(Boolean).join(", ") || "–",
|
|
466
|
+
v.deviceType ?? "–",
|
|
467
|
+
date(v.lastSeenAt),
|
|
468
|
+
])));
|
|
469
|
+
return 0;
|
|
470
|
+
}
|
|
471
|
+
async function listVisitors(ctx) {
|
|
472
|
+
const { flags } = ctx;
|
|
473
|
+
const params = rangeParams(flags);
|
|
474
|
+
if (flags.q)
|
|
475
|
+
params.set("q", flags.q);
|
|
476
|
+
if (flags.payment)
|
|
477
|
+
params.set("payment", flags.payment);
|
|
478
|
+
visitorSearchParams(flags, params);
|
|
479
|
+
if (flags.sort)
|
|
480
|
+
params.set("sort", flags.sort);
|
|
481
|
+
const limit = positiveInt(flags.limit, "limit", 100);
|
|
482
|
+
if (limit !== undefined)
|
|
483
|
+
params.set("limit", String(Math.max(1, limit)));
|
|
484
|
+
const offset = positiveInt(flags.offset, "offset", 1_000_000);
|
|
485
|
+
if (offset !== undefined)
|
|
486
|
+
params.set("offset", String(offset));
|
|
487
|
+
params.set("site", await ctx.site());
|
|
488
|
+
const selected = selectFields(flags, params);
|
|
489
|
+
const d = await ctx.client.get("/stats/visitors", params).catch((e) => needs("visitors", Promise.reject(e)));
|
|
490
|
+
if (flags.json || selected)
|
|
491
|
+
return printJson(d), 0;
|
|
492
|
+
if (!d.rows.length)
|
|
493
|
+
return out(dim("No visitors match.")), 0;
|
|
494
|
+
out(periodLine(d.period));
|
|
495
|
+
out(table(["Visitor", "Paid", "Pageviews", "Source", "Country", "Last seen"], d.rows.map((r) => [r.name ?? r.email ?? r.visitorId, r.paid ? "yes" : "", num(r.pageviews), r.source ?? "–", r.country ?? "–", date(r.lastPageviewAt)]), ["left", "left", "right", "left", "left", "left"]));
|
|
496
|
+
out(dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`));
|
|
497
|
+
return 0;
|
|
498
|
+
}
|
|
499
|
+
async function getVisitor(ctx, id) {
|
|
500
|
+
if (!id)
|
|
501
|
+
throw new UsageError("Use: metricraven visitors get <visitor_id>");
|
|
502
|
+
const params = new URLSearchParams({ site: await ctx.site() });
|
|
503
|
+
const d = await ctx.client.get(`/visitors/${encodeURIComponent(id)}`, params).catch((e) => needs("visitors", Promise.reject(e)));
|
|
504
|
+
if (ctx.flags.json)
|
|
505
|
+
return printJson(d), 0;
|
|
506
|
+
const s = d.summary;
|
|
507
|
+
out(bold(d.user?.name ?? d.user?.email ?? d.visitorId));
|
|
508
|
+
out(`${num(s.visits)} visits · ${num(s.pageviews)} pageviews · ${num(s.events)} goals · ${duration(s.timeOnSite)} on site · spent ${money(s.spent)}`);
|
|
509
|
+
if (s.firstTouch)
|
|
510
|
+
out(`First touch: ${s.firstTouch.channel ?? "–"} / ${s.firstTouch.source ?? "–"} → ${s.firstTouch.landingPage ?? "–"}`);
|
|
511
|
+
out(dim(`${date(s.firstSeenAt)} → ${date(s.lastSeenAt)}`));
|
|
512
|
+
out(section("Timeline", table(["When", "Type", "Detail"], d.timeline.slice(-50).map((t) => [date(t.at), t.type, truncate(t.path ?? t.name ?? (t.amount !== undefined ? money(t.amount) : ""), 60)]))));
|
|
513
|
+
return 0;
|
|
514
|
+
}
|
|
515
|
+
async function listFunnels(ctx) {
|
|
516
|
+
const d = await ctx.client.get("/funnels", new URLSearchParams({ site: await ctx.site() }));
|
|
517
|
+
if (ctx.flags.json)
|
|
518
|
+
return printJson(d), 0;
|
|
519
|
+
if (!d.funnels.length)
|
|
520
|
+
return out(dim("No saved funnels.")), 0;
|
|
521
|
+
out(table(["Funnel", "Steps", "ID"], d.funnels.map((f) => [f.name, truncate(f.steps, 70), f.id])));
|
|
522
|
+
return 0;
|
|
523
|
+
}
|
|
524
|
+
/** Notes take calendar days; the period becomes from/to dates in the chosen zone. */
|
|
525
|
+
function noteDays(flags) {
|
|
526
|
+
const params = new URLSearchParams();
|
|
527
|
+
if (flags.from || flags.to) {
|
|
528
|
+
if (flags.from)
|
|
529
|
+
params.set("from", flags.from);
|
|
530
|
+
if (flags.to)
|
|
531
|
+
params.set("to", flags.to);
|
|
532
|
+
return params;
|
|
533
|
+
}
|
|
534
|
+
if (flags.period === "all")
|
|
535
|
+
return params;
|
|
536
|
+
const range = rangeParams({ ...flags, filter: undefined });
|
|
537
|
+
const zone = range.get("timezone") ?? "UTC";
|
|
538
|
+
const from = range.get("from");
|
|
539
|
+
const to = range.get("to");
|
|
540
|
+
if (from)
|
|
541
|
+
params.set("from", new Intl.DateTimeFormat("en-CA", { timeZone: zone }).format(new Date(from)));
|
|
542
|
+
if (to)
|
|
543
|
+
params.set("to", new Intl.DateTimeFormat("en-CA", { timeZone: zone }).format(new Date(to)));
|
|
544
|
+
return params;
|
|
545
|
+
}
|
|
546
|
+
async function listNotes(ctx) {
|
|
547
|
+
const params = noteDays(ctx.flags);
|
|
548
|
+
params.set("site", await ctx.site());
|
|
549
|
+
const d = await ctx.client.get("/notes", params);
|
|
550
|
+
if (ctx.flags.json)
|
|
551
|
+
return printJson(d), 0;
|
|
552
|
+
if (!d.notes.length)
|
|
553
|
+
return out(dim("No notes in this period.")), 0;
|
|
554
|
+
out(table(["Date", "Note"], d.notes.map((n) => [n.date, n.text])));
|
|
555
|
+
return 0;
|
|
556
|
+
}
|
|
557
|
+
async function addNote(ctx) {
|
|
558
|
+
const { flags } = ctx;
|
|
559
|
+
if (!flags.text)
|
|
560
|
+
throw new UsageError("Use: metricraven notes add --text <text> [--date YYYY-MM-DD]");
|
|
561
|
+
const day = flags.date ?? new Intl.DateTimeFormat("en-CA", { timeZone: flags.timezone || "UTC" }).format(new Date());
|
|
562
|
+
const site = await ctx.site();
|
|
563
|
+
const note = await needs("write", ctx.client.post("/notes", { date: day, text: flags.text }, new URLSearchParams({ site })));
|
|
564
|
+
if (flags.json)
|
|
565
|
+
return printJson(note), 0;
|
|
566
|
+
out(`Added a note on ${note.date}: ${note.text}`);
|
|
567
|
+
return 0;
|
|
568
|
+
}
|
|
569
|
+
/** Stored X and Reddit mentions in the period (newest first). Reads only; never starts a search. */
|
|
570
|
+
async function listMentions(ctx) {
|
|
571
|
+
const { flags } = ctx;
|
|
572
|
+
const params = rangeParams({ ...flags, filter: undefined });
|
|
573
|
+
if (flags.platform) {
|
|
574
|
+
if (flags.platform !== "x" && flags.platform !== "reddit")
|
|
575
|
+
throw new UsageError("--platform must be x or reddit.");
|
|
576
|
+
params.set("platform", flags.platform);
|
|
577
|
+
}
|
|
578
|
+
if (flags.q)
|
|
579
|
+
params.set("q", flags.q);
|
|
580
|
+
const limit = positiveInt(flags.limit, "limit", 1000);
|
|
581
|
+
const offset = positiveInt(flags.offset, "offset", 1_000_000);
|
|
582
|
+
if (limit !== undefined)
|
|
583
|
+
params.set("limit", String(Math.max(1, limit)));
|
|
584
|
+
if (offset !== undefined)
|
|
585
|
+
params.set("offset", String(offset));
|
|
586
|
+
params.set("site", await ctx.site());
|
|
587
|
+
const d = await ctx.client.get("/stats/mentions", params);
|
|
588
|
+
if (flags.json)
|
|
589
|
+
return printJson(d), 0;
|
|
590
|
+
if (d.meta.locked)
|
|
591
|
+
return out(d.meta.message ?? "X and Reddit mentions need the Growth plan."), 0;
|
|
592
|
+
if (!d.data.length)
|
|
593
|
+
return out(dim("No mentions in this period.")), 0;
|
|
594
|
+
const where = (m) => (m.platform === "x" ? `X @${m.author.username}` : `r/${m.subreddit ?? "?"} u/${m.author.username}`);
|
|
595
|
+
const stats = (m) => m.platform === "x"
|
|
596
|
+
? `${num(m.engagement.likes)} likes · ${num(m.engagement.reposts)} reposts`
|
|
597
|
+
: `${num(m.engagement.score)} pts · ${num(m.engagement.comments)} comments`;
|
|
598
|
+
const body = (m) => truncate(`${m.title ? `${m.title}: ` : ""}${m.text}`.replace(/\s+/g, " ").trim(), 70);
|
|
599
|
+
out(table(["Date", "Where", "Post", "Engagement"], d.data.map((m) => [date(m.timestamp), where(m), body(m), stats(m)])));
|
|
600
|
+
if (d.pagination.hasMore)
|
|
601
|
+
out(dim(`Showing ${d.pagination.offset + 1}–${d.pagination.offset + d.data.length} of ${d.pagination.total}. Use --offset for more.`));
|
|
602
|
+
return 0;
|
|
603
|
+
}
|
|
604
|
+
/** AI visibility from the latest weekly check (Growth). Reads only; never starts a check. */
|
|
605
|
+
async function aiVisibility(ctx) {
|
|
606
|
+
const params = rangeParams({ ...ctx.flags, filter: undefined, period: ctx.flags.period ?? "90d" });
|
|
607
|
+
params.set("site", await ctx.site());
|
|
608
|
+
// --filter model:is:claude, mention:is:not_mentioned, citedDomain:is_not:example.com …
|
|
609
|
+
const filters = buildFilters(ctx.flags.filter);
|
|
610
|
+
if (filters.length)
|
|
611
|
+
params.set("filters", JSON.stringify(filters));
|
|
612
|
+
const d = await ctx.client.get("/stats/ai-visibility", params);
|
|
613
|
+
if (ctx.flags.json)
|
|
614
|
+
return printJson(d), 0;
|
|
615
|
+
if (d.meta.locked)
|
|
616
|
+
return out(d.meta.message ?? "AI visibility needs the Growth plan."), 0;
|
|
617
|
+
const s = d.latestRun?.summary;
|
|
618
|
+
if (!s)
|
|
619
|
+
return out(dim("No AI visibility checks yet. Add prompts in the dashboard's AI visibility tab.")), 0;
|
|
620
|
+
const pct = (n) => `${Math.round(n * 100)}%`;
|
|
621
|
+
const pos = (n) => (n === null ? "—" : `#${n.toFixed(1)}`);
|
|
622
|
+
out(`${d.meta.brand}${d.meta.sample ? " (sample data)" : ""} · latest check ${d.latestRun?.completedAt ? date(d.latestRun.completedAt) : "—"}`);
|
|
623
|
+
out(`Visibility ${Math.round(s.visibilityScore)} · mentioned in ${pct(s.presenceRate)} · avg position ${pos(s.avgPosition)} · named first ${pct(s.topPositionRate)} · pages cited ${pct(s.citedRate)}`);
|
|
624
|
+
if (d.trend.length > 1)
|
|
625
|
+
out(dim(`Trend: ${d.trend.map((t) => Math.round(t.summary.visibilityScore)).join(" → ")}`));
|
|
626
|
+
out("");
|
|
627
|
+
out(table(["Assistant", "Score", "Mentioned", "Position"], d.models.filter((m) => m.summary).map((m) => [m.summary.noAnswer ? `${m.name} (no AI answer for ${m.summary.noAnswer})` : m.name, String(Math.round(m.summary.visibilityScore)), pct(m.summary.presenceRate), pos(m.summary.avgPosition)])));
|
|
628
|
+
out("");
|
|
629
|
+
out(table(["#", "Brand", "Score", "Mentioned", "Assistants"], d.competitors.slice(0, 10).map((c) => [String(c.rank), c.isYou ? `${c.name} (you)` : c.name, String(Math.round(c.visibilityScore)), pct(c.presenceRate), String(c.models)])));
|
|
630
|
+
if (d.credits)
|
|
631
|
+
out(dim(`Credits: ${num(d.credits.used)} of ${num(d.credits.allowance)} used, resets ${date(d.credits.resetsAt)}`));
|
|
632
|
+
return 0;
|
|
633
|
+
}
|
|
634
|
+
/** "Signup started (signup_started)" when the goal has a display name, else the raw name. */
|
|
635
|
+
const goalText = (g) => g.displayName && g.displayName !== g.name ? `${g.displayName} (${g.name})` : g.name;
|
|
636
|
+
/** `metricraven goals …`: how goals are shown (display name, colour, description, hidden). */
|
|
637
|
+
async function goals(ctx, sub, rest) {
|
|
638
|
+
const { flags, client } = ctx;
|
|
639
|
+
const site = await ctx.site();
|
|
640
|
+
const params = () => new URLSearchParams({ site });
|
|
641
|
+
const colorText = (hex, colors) => (hex ? (colors.find((c) => c.color === hex)?.label ?? hex) : "–");
|
|
642
|
+
const goalArg = () => {
|
|
643
|
+
if (!rest[0])
|
|
644
|
+
throw new UsageError(`Use: metricraven goals ${sub} <goal> (the raw goal name, as tracked).`);
|
|
645
|
+
return rest[0];
|
|
646
|
+
};
|
|
647
|
+
switch (sub ?? "list") {
|
|
648
|
+
case "list": {
|
|
649
|
+
const p = params();
|
|
650
|
+
if (rest[0])
|
|
651
|
+
p.set("goal", rest[0]);
|
|
652
|
+
const d = await client.get("/goals/customizations", p);
|
|
653
|
+
if (flags.json)
|
|
654
|
+
return printJson(d), 0;
|
|
655
|
+
if (!d.customizations.length)
|
|
656
|
+
return out(dim("No goal customisations yet. Use `metricraven goals set <goal> --name <label>`.")), 0;
|
|
657
|
+
out(table(["Goal", "Display name", "Colour", "Hidden", "Description"], d.customizations.map((c) => [c.goal, c.displayName ?? "–", colorText(c.color, d.colors), c.hidden ? "yes" : "no", c.description ? truncate(c.description, 50) : "–"])));
|
|
658
|
+
return 0;
|
|
659
|
+
}
|
|
660
|
+
case "colors":
|
|
661
|
+
case "colours": {
|
|
662
|
+
const d = await client.get("/goals/customizations", params());
|
|
663
|
+
if (flags.json)
|
|
664
|
+
return printJson(d.colors), 0;
|
|
665
|
+
out(table(["Colour", "Hex", "Family"], d.colors.map((c) => [c.label, c.color, c.family])));
|
|
666
|
+
return 0;
|
|
667
|
+
}
|
|
668
|
+
case "set": {
|
|
669
|
+
const goal = goalArg();
|
|
670
|
+
if (flags.hidden && flags.visible)
|
|
671
|
+
throw new UsageError("Use --hidden or --visible, not both.");
|
|
672
|
+
const body = { goal };
|
|
673
|
+
if (flags.name !== undefined)
|
|
674
|
+
body.displayName = flags.name || null;
|
|
675
|
+
if (flags.description !== undefined)
|
|
676
|
+
body.description = flags.description || null;
|
|
677
|
+
if (flags.color !== undefined) {
|
|
678
|
+
if (!flags.color)
|
|
679
|
+
body.color = null;
|
|
680
|
+
else if (flags.color.startsWith("#"))
|
|
681
|
+
body.color = flags.color.toLowerCase();
|
|
682
|
+
else {
|
|
683
|
+
const { colors } = await client.get("/goals/customizations", params());
|
|
684
|
+
const match = colors.find((c) => c.label.toLowerCase() === flags.color.toLowerCase());
|
|
685
|
+
if (!match)
|
|
686
|
+
throw new UsageError(`Unknown colour "${flags.color}". Use one of: ${colors.map((c) => c.label).join(", ")} (or a hex from \`metricraven goals colors\`).`);
|
|
687
|
+
body.color = match.color;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
if (flags.hidden)
|
|
691
|
+
body.hidden = true;
|
|
692
|
+
if (flags.visible)
|
|
693
|
+
body.hidden = false;
|
|
694
|
+
if (Object.keys(body).length === 1)
|
|
695
|
+
throw new UsageError("Nothing to change. Use --name, --color, --description, --hidden or --visible.");
|
|
696
|
+
const d = await needs("write", client.put("/goals/customizations", body, params()));
|
|
697
|
+
if (flags.json)
|
|
698
|
+
return printJson(d), 0;
|
|
699
|
+
const c = d.customization;
|
|
700
|
+
out(`Saved ${bold(goalText({ name: c.goal, displayName: c.displayName }))}: colour ${colorText(c.color, d.colors)}, ${c.hidden ? "hidden" : "visible"}.`);
|
|
701
|
+
return 0;
|
|
702
|
+
}
|
|
703
|
+
case "reset": {
|
|
704
|
+
const goal = goalArg();
|
|
705
|
+
const p = params();
|
|
706
|
+
p.set("goal", goal);
|
|
707
|
+
const d = await needs("write", client.del("/goals/customizations", p));
|
|
708
|
+
if (flags.json)
|
|
709
|
+
return printJson(d), 0;
|
|
710
|
+
out(`Reset ${goal}: raw name, default colour, visible.`);
|
|
711
|
+
return 0;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
throw new UsageError(`Unknown command "goals ${sub}". Use list, set, reset or colors.`);
|
|
715
|
+
}
|
|
716
|
+
const triggerText = (t) => (t.type === "goal" ? `goal ${t.goalName}` : t.type === "payment" ? "any payment" : "new customer");
|
|
717
|
+
/** `metricraven alerts …`: conversion alerts on the website (list/get/create/update/delete/history). */
|
|
718
|
+
async function alerts(ctx, sub, rest) {
|
|
719
|
+
const { flags, client } = ctx;
|
|
720
|
+
const site = await ctx.site();
|
|
721
|
+
const params = () => new URLSearchParams({ site });
|
|
722
|
+
const alertPath = (id) => {
|
|
723
|
+
if (!id)
|
|
724
|
+
throw new UsageError(`Use: metricraven alerts ${sub} <alert_id> (IDs from \`metricraven alerts list\`).`);
|
|
725
|
+
return `/alerts/${encodeURIComponent(id)}`;
|
|
726
|
+
};
|
|
727
|
+
switch (sub ?? "list") {
|
|
728
|
+
case "list": {
|
|
729
|
+
const d = await client.get("/alerts", params());
|
|
730
|
+
if (flags.json)
|
|
731
|
+
return printJson(d), 0;
|
|
732
|
+
if (!d.data.length) {
|
|
733
|
+
out(dim("No alerts yet. Create one with `metricraven alerts create --goal <name>`."));
|
|
734
|
+
if (d.goals.length)
|
|
735
|
+
out(dim(`Tracked goals: ${d.goals.slice(0, 12).join(", ")}`));
|
|
736
|
+
return 0;
|
|
737
|
+
}
|
|
738
|
+
out(table(["Alert", "Trigger", "On", "Recipients", "Today", "Total", "ID"], d.data.map((a) => [a.name, triggerText(a.trigger), a.isEnabled ? "yes" : "no", String(a.recipients.length), num(a.dailyCount), num(a.triggerCount), a.id])));
|
|
739
|
+
return 0;
|
|
740
|
+
}
|
|
741
|
+
case "get": {
|
|
742
|
+
const d = await client.get(alertPath(rest[0]), params());
|
|
743
|
+
if (flags.json)
|
|
744
|
+
return printJson(d), 0;
|
|
745
|
+
const a = d.data[0];
|
|
746
|
+
out(bold(a.name));
|
|
747
|
+
out(`Trigger: ${triggerText(a.trigger)} · ${a.isEnabled ? "enabled" : "disabled"}`);
|
|
748
|
+
out(`Recipients: ${a.recipients.map((r) => r.email).join(", ") || "none"}`);
|
|
749
|
+
if (a.template.subject)
|
|
750
|
+
out(`Subject: ${a.template.subject}`);
|
|
751
|
+
if (a.template.message)
|
|
752
|
+
out(`Message: ${truncate(a.template.message, 200)}`);
|
|
753
|
+
out(`Triggered: ${num(a.dailyCount)} today · ${num(a.monthlyCount)} this month · ${num(a.triggerCount)} total`);
|
|
754
|
+
if (a.lastTriggeredAt)
|
|
755
|
+
out(dim(`Last triggered ${date(a.lastTriggeredAt)}`));
|
|
756
|
+
if (a.lastError)
|
|
757
|
+
out(`Last error: ${a.lastError}`);
|
|
758
|
+
return 0;
|
|
759
|
+
}
|
|
760
|
+
case "create": {
|
|
761
|
+
const type = flags.trigger ?? "goal";
|
|
762
|
+
if (!["goal", "payment", "new_customer"].includes(type))
|
|
763
|
+
throw new UsageError("--trigger must be goal, payment or new_customer.");
|
|
764
|
+
let goal = flags.goal;
|
|
765
|
+
if (type === "goal" && !goal) {
|
|
766
|
+
if (!interactive() || flags.json)
|
|
767
|
+
throw new UsageError("Use: metricraven alerts create --goal <name> (or --trigger payment|new_customer).");
|
|
768
|
+
goal = await prompt("Goal name: ");
|
|
769
|
+
}
|
|
770
|
+
const body = {
|
|
771
|
+
name: flags.name,
|
|
772
|
+
trigger: type === "goal" ? { type, goalName: goal } : { type },
|
|
773
|
+
template: flags.subject || flags.message ? { subject: flags.subject, message: flags.message } : undefined,
|
|
774
|
+
notify: flags.notify,
|
|
775
|
+
isEnabled: flags.disabled ? false : undefined,
|
|
776
|
+
};
|
|
777
|
+
const d = await needs("write", client.post("/alerts", body, params()));
|
|
778
|
+
if (flags.json)
|
|
779
|
+
return printJson(d), 0;
|
|
780
|
+
const a = d.data[0];
|
|
781
|
+
out(`Created "${a.name}" (${triggerText(a.trigger)}), ${a.isEnabled ? "enabled" : "disabled"}, emailing ${a.recipients.map((r) => r.email).join(", ") || "nobody yet"}. ID ${a.id}`);
|
|
782
|
+
return 0;
|
|
783
|
+
}
|
|
784
|
+
case "update": {
|
|
785
|
+
if (flags.enabled && flags.disabled)
|
|
786
|
+
throw new UsageError("Use --enabled or --disabled, not both.");
|
|
787
|
+
const body = {
|
|
788
|
+
name: flags.name,
|
|
789
|
+
trigger: flags.goal ? { type: "goal", goalName: flags.goal } : undefined,
|
|
790
|
+
isEnabled: flags.enabled ? true : flags.disabled ? false : undefined,
|
|
791
|
+
};
|
|
792
|
+
if (Object.values(body).every((v) => v === undefined))
|
|
793
|
+
throw new UsageError("Nothing to change. Use --name, --goal, --enabled or --disabled.");
|
|
794
|
+
const d = await needs("write", client.patch(alertPath(rest[0]), body, params()));
|
|
795
|
+
if (flags.json)
|
|
796
|
+
return printJson(d), 0;
|
|
797
|
+
const a = d.data[0];
|
|
798
|
+
out(`Updated "${a.name}" (${triggerText(a.trigger)}), ${a.isEnabled ? "enabled" : "disabled"}.`);
|
|
799
|
+
return 0;
|
|
800
|
+
}
|
|
801
|
+
case "delete": {
|
|
802
|
+
const path = alertPath(rest[0]);
|
|
803
|
+
if (!flags.yes) {
|
|
804
|
+
if (!interactive())
|
|
805
|
+
throw new UsageError("Add --yes to delete without a prompt.");
|
|
806
|
+
const answer = await prompt(`Delete alert ${rest[0]}? Its history is kept. [y/N] `);
|
|
807
|
+
if (!/^y(es)?$/i.test(answer))
|
|
808
|
+
return out("Kept."), 0;
|
|
809
|
+
}
|
|
810
|
+
const d = await needs("write", client.del(path, params()));
|
|
811
|
+
if (flags.json)
|
|
812
|
+
return printJson(d), 0;
|
|
813
|
+
out(`Deleted alert ${d.data.id}.`);
|
|
814
|
+
return 0;
|
|
815
|
+
}
|
|
816
|
+
case "history": {
|
|
817
|
+
const p = params();
|
|
818
|
+
if (flags.alert)
|
|
819
|
+
p.set("alertId", flags.alert);
|
|
820
|
+
const limit = positiveInt(flags.limit, "limit", 100);
|
|
821
|
+
if (limit)
|
|
822
|
+
p.set("limit", String(limit));
|
|
823
|
+
const d = await client.get("/alerts/history", p);
|
|
824
|
+
if (flags.json)
|
|
825
|
+
return printJson(d), 0;
|
|
826
|
+
if (!d.data.length)
|
|
827
|
+
return out(dim("No alert emails yet.")), 0;
|
|
828
|
+
out(table(["When", "Alert", "Goal", "Email", "Conversions", "Status"], d.data.map((l) => [date(l.triggeredAt), l.alertName, l.goalName, l.kind === "digest" ? "summary" : "instant", num(l.conversions), l.error ? `${l.status}: ${truncate(l.error, 40)}` : l.status])));
|
|
829
|
+
out(dim(`${num(d.counts.sent)} sent · ${num(d.counts.failed)} failed · ${num(d.counts.total)} total`));
|
|
830
|
+
return 0;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
throw new UsageError(`Unknown command "alerts ${sub}". Use list, get, create, update, delete or history.`);
|
|
834
|
+
}
|
|
835
|
+
/** `metricraven members …`: the website's team (list/invite/role/remove/revoke). Ownership transfer stays in the dashboard. */
|
|
836
|
+
async function members(ctx, sub, rest) {
|
|
837
|
+
const { flags, client } = ctx;
|
|
838
|
+
const site = await ctx.site();
|
|
839
|
+
const params = () => new URLSearchParams({ site });
|
|
840
|
+
const role = () => {
|
|
841
|
+
if (flags.role !== "admin" && flags.role !== "viewer")
|
|
842
|
+
throw new UsageError("Add --role admin or --role viewer.");
|
|
843
|
+
return flags.role;
|
|
844
|
+
};
|
|
845
|
+
const id = (what) => {
|
|
846
|
+
if (!rest[0])
|
|
847
|
+
throw new UsageError(`Use: metricraven members ${sub} <${what}> (IDs from \`metricraven members list --json\`).`);
|
|
848
|
+
return encodeURIComponent(rest[0]);
|
|
849
|
+
};
|
|
850
|
+
switch (sub ?? "list") {
|
|
851
|
+
case "list": {
|
|
852
|
+
const d = await client.get("/members", params());
|
|
853
|
+
if (flags.json)
|
|
854
|
+
return printJson(d), 0;
|
|
855
|
+
out(table(["Member", "Name", "Role", "ID"], d.data.members.map((m) => [m.you ? `${m.email} (you)` : m.email, m.name ?? "", m.role, m.id])));
|
|
856
|
+
if (d.data.invites.length) {
|
|
857
|
+
out(section("Pending invitations", table(["Email", "Role", "Expires", "ID"], d.data.invites.map((i) => [i.email, i.role, i.expired ? "expired" : date(i.expiresAt), i.id]))));
|
|
858
|
+
}
|
|
859
|
+
const seats = d.data.seats;
|
|
860
|
+
if (seats)
|
|
861
|
+
out(dim(`${num(seats.used)}${seats.limit === null ? "" : ` of ${num(seats.limit)}`} ${seats.used === 1 && seats.limit === null ? "seat" : "seats"} used on the plan`));
|
|
862
|
+
return 0;
|
|
863
|
+
}
|
|
864
|
+
case "invite": {
|
|
865
|
+
const email = rest[0];
|
|
866
|
+
if (!email)
|
|
867
|
+
throw new UsageError("Use: metricraven members invite <email> --role admin|viewer");
|
|
868
|
+
const d = await needs("write", client.post("/members", { email, role: role() }, params()));
|
|
869
|
+
if (flags.json)
|
|
870
|
+
return printJson(d), 0;
|
|
871
|
+
out(`Invited ${d.data.invite.email} as ${d.data.invite.role}. ${d.data.emailSent ? "The invitation was emailed." : "The email couldn't be sent; share this link:"}`);
|
|
872
|
+
if (!d.data.emailSent)
|
|
873
|
+
out(d.data.url);
|
|
874
|
+
out(dim(`The link works for 7 days, until ${date(d.data.invite.expiresAt)}.`));
|
|
875
|
+
return 0;
|
|
876
|
+
}
|
|
877
|
+
case "role": {
|
|
878
|
+
const path = `/members/${id("user_id")}`;
|
|
879
|
+
const r = role();
|
|
880
|
+
await needs("write", client.patch(path, { role: r }, params()));
|
|
881
|
+
if (flags.json)
|
|
882
|
+
return printJson({ status: "success" }), 0;
|
|
883
|
+
out(`Changed ${rest[0]} to ${r}.`);
|
|
884
|
+
return 0;
|
|
885
|
+
}
|
|
886
|
+
case "remove": {
|
|
887
|
+
const path = `/members/${id("user_id")}`;
|
|
888
|
+
if (!flags.yes) {
|
|
889
|
+
if (!interactive())
|
|
890
|
+
throw new UsageError("Add --yes to remove without a prompt.");
|
|
891
|
+
const answer = await prompt(`Remove member ${rest[0]}? They lose access at once. [y/N] `);
|
|
892
|
+
if (!/^y(es)?$/i.test(answer))
|
|
893
|
+
return out("Kept."), 0;
|
|
894
|
+
}
|
|
895
|
+
await needs("write", client.del(path, params()));
|
|
896
|
+
if (flags.json)
|
|
897
|
+
return printJson({ status: "success" }), 0;
|
|
898
|
+
out(`Removed ${rest[0]}.`);
|
|
899
|
+
return 0;
|
|
900
|
+
}
|
|
901
|
+
case "revoke": {
|
|
902
|
+
await needs("write", client.del(`/members/invites/${id("invite_id")}`, params()));
|
|
903
|
+
if (flags.json)
|
|
904
|
+
return printJson({ status: "success" }), 0;
|
|
905
|
+
out(`Revoked invitation ${rest[0]}.`);
|
|
906
|
+
return 0;
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
throw new UsageError(`Unknown command "members ${sub}". Use list, invite, role, remove or revoke.`);
|
|
910
|
+
}
|
|
911
|
+
function printBotSettings(d) {
|
|
912
|
+
const list = (v) => (v.length ? v.join(", ") : "none");
|
|
913
|
+
out(`Excluded companies: ${list(d.settings.excludedCompanies)}`);
|
|
914
|
+
out(`Excluded agents: ${list(d.settings.excludedAgents)}`);
|
|
915
|
+
out(`Bot token: ${d.token.hasToken ? `${d.token.hint ?? "set"}${d.token.lastUsedAt ? `, last used ${date(d.token.lastUsedAt)}` : ", not used yet"}` : "none (create one in Settings → Tracking & install)"}`);
|
|
916
|
+
out(`Require bot token: ${d.settings.rejectWithoutToken ? "yes" : "no"}`);
|
|
917
|
+
}
|
|
918
|
+
/** `metricraven bots …`: bot traffic settings (exclusions, token enforcement) and the bot request allowance. */
|
|
919
|
+
async function bots(ctx, sub, rest) {
|
|
920
|
+
const { flags, client } = ctx;
|
|
921
|
+
const site = await ctx.site();
|
|
922
|
+
const params = () => new URLSearchParams({ site });
|
|
923
|
+
switch (sub ?? "settings") {
|
|
924
|
+
case "settings": {
|
|
925
|
+
const d = await client.get("/bot-traffic/settings", params());
|
|
926
|
+
if (flags.json)
|
|
927
|
+
return printJson(d), 0;
|
|
928
|
+
printBotSettings(d.data);
|
|
929
|
+
const rows = d.data.catalog.map((c) => {
|
|
930
|
+
const excluded = c.agents.filter((a) => a.excluded).map((a) => a.agent);
|
|
931
|
+
return [c.company, c.status, c.status === "partial" ? excluded.join(", ") : c.agents.map((a) => a.agent).join(", ")];
|
|
932
|
+
});
|
|
933
|
+
out(section("Known crawlers", table(["Company", "Status", "Agents"], rows.map((r) => [r[0], r[1], truncate(r[2], 60)]))));
|
|
934
|
+
return 0;
|
|
935
|
+
}
|
|
936
|
+
case "usage": {
|
|
937
|
+
const d = await client.get("/bot-traffic/usage", params());
|
|
938
|
+
if (flags.json)
|
|
939
|
+
return printJson(d), 0;
|
|
940
|
+
const u = d.data;
|
|
941
|
+
out(`${bold(num(u.usage))}${u.allowance === null ? " bot requests (no limit)" : ` of ${num(u.allowance)} bot requests (${pct(u.percentUsed ?? 0)})`}`);
|
|
942
|
+
if (u.paused)
|
|
943
|
+
out(`Bot tracking is paused until ${date(u.resetAt)}${u.dropped ? `; ${num(u.dropped)} requests not recorded` : ""}.`);
|
|
944
|
+
else
|
|
945
|
+
out(dim(`Resets ${date(u.resetAt)}.${u.enforced || u.allowance === null ? "" : " The allowance isn't enforced on this account yet."}`));
|
|
946
|
+
if (u.websites.length)
|
|
947
|
+
out(section("By website", table(["Website", "Requests"], u.websites.map((w) => [w.name, num(w.requests)]))));
|
|
948
|
+
return 0;
|
|
949
|
+
}
|
|
950
|
+
case "exclude":
|
|
951
|
+
case "include": {
|
|
952
|
+
if (!rest.length)
|
|
953
|
+
throw new UsageError(`Use: metricraven bots ${sub} <name…> [--company] (names from \`metricraven bots settings\`).`);
|
|
954
|
+
const key = `${sub === "exclude" ? "disable" : "enable"}${flags.company ? "Companies" : "Agents"}`;
|
|
955
|
+
const d = await needs("write", client.patch("/bot-traffic/settings", { [key]: rest }, params()));
|
|
956
|
+
if (flags.json)
|
|
957
|
+
return printJson(d), 0;
|
|
958
|
+
const what = flags.company ? (rest.length === 1 ? "company" : "companies") : rest.length === 1 ? "agent" : "agents";
|
|
959
|
+
out(d.changed ? `${sub === "exclude" ? "Excluded" : "Included"} ${what} ${rest.join(", ")}. This applies to new crawl events.` : "Nothing changed.");
|
|
960
|
+
printBotSettings(d.data);
|
|
961
|
+
return 0;
|
|
962
|
+
}
|
|
963
|
+
case "require-token": {
|
|
964
|
+
const value = rest[0];
|
|
965
|
+
if (value !== "on" && value !== "off")
|
|
966
|
+
throw new UsageError("Use: metricraven bots require-token on|off");
|
|
967
|
+
const d = await needs("write", client.patch("/bot-traffic/settings", { rejectWithoutToken: value === "on" }, params()));
|
|
968
|
+
if (flags.json)
|
|
969
|
+
return printJson(d), 0;
|
|
970
|
+
out(value === "on" ? "Crawl events without the bot token are now refused." : "Crawl events sent with the secret key are accepted again.");
|
|
971
|
+
return 0;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
throw new UsageError(`Unknown command "bots ${sub}". Use settings, usage, exclude, include or require-token.`);
|
|
975
|
+
}
|
|
976
|
+
const PROXY_STATUS = {
|
|
977
|
+
pending_dns: "Waiting for DNS",
|
|
978
|
+
issuing_certificate: "Issuing certificate",
|
|
979
|
+
active: "Active",
|
|
980
|
+
error: "Needs attention",
|
|
981
|
+
};
|
|
982
|
+
function printProxy(d) {
|
|
983
|
+
const p = d.proxy;
|
|
984
|
+
if (!p) {
|
|
985
|
+
if (!d.available)
|
|
986
|
+
return out("The managed proxy isn't available on this server.");
|
|
987
|
+
out(`No managed proxy. Enable one with \`metricraven proxy enable a.<your-domain>\`; it CNAMEs to ${d.target}.`);
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
out(`${bold(p.hostname)} ${PROXY_STATUS[p.status] ?? p.status}${p.checkedAt ? dim(` (checked ${date(p.checkedAt)})`) : ""}`);
|
|
991
|
+
if (p.error)
|
|
992
|
+
out(p.error);
|
|
993
|
+
if (p.status !== "active")
|
|
994
|
+
out(section("Add this DNS record", table(["Type", "Name / Host", "Value", ""], p.records.map((r) => [r.type, r.name, r.value, r.required ? "" : "only if the CNAME doesn't verify"]))));
|
|
995
|
+
else
|
|
996
|
+
out(section("Script tag", p.snippet));
|
|
997
|
+
}
|
|
998
|
+
/** `metricraven proxy …`: the managed proxy subdomain (one CNAME; MetricRaven serves the script there). */
|
|
999
|
+
async function managedProxy(ctx, sub, rest) {
|
|
1000
|
+
const { flags, client } = ctx;
|
|
1001
|
+
const site = await ctx.site();
|
|
1002
|
+
const params = () => new URLSearchParams({ site });
|
|
1003
|
+
const done = (d) => {
|
|
1004
|
+
if (flags.json)
|
|
1005
|
+
printJson(d);
|
|
1006
|
+
else
|
|
1007
|
+
printProxy(d.data);
|
|
1008
|
+
return 0;
|
|
1009
|
+
};
|
|
1010
|
+
switch (sub ?? "status") {
|
|
1011
|
+
case "status":
|
|
1012
|
+
return done(await client.get("/managed-proxy", params()));
|
|
1013
|
+
case "enable": {
|
|
1014
|
+
if (!rest[0])
|
|
1015
|
+
throw new UsageError("Use: metricraven proxy enable <subdomain>, e.g. a.example.com");
|
|
1016
|
+
return done(await needs("write", client.post("/managed-proxy", { hostname: rest[0] }, params())));
|
|
1017
|
+
}
|
|
1018
|
+
case "check":
|
|
1019
|
+
return done(await needs("write", client.post("/managed-proxy/check", {}, params())));
|
|
1020
|
+
case "remove": {
|
|
1021
|
+
if (!flags.yes) {
|
|
1022
|
+
if (!interactive())
|
|
1023
|
+
throw new UsageError("Add --yes to remove without a prompt.");
|
|
1024
|
+
const answer = await prompt("Remove the managed proxy? The script stops loading from that subdomain at once. [y/N] ");
|
|
1025
|
+
if (!/^y(es)?$/i.test(answer))
|
|
1026
|
+
return out("Kept."), 0;
|
|
1027
|
+
}
|
|
1028
|
+
const d = await needs("write", client.del("/managed-proxy", params()));
|
|
1029
|
+
if (flags.json)
|
|
1030
|
+
return printJson(d), 0;
|
|
1031
|
+
out("Removed. Delete the DNS record and point your script tag back at metricraven.com.");
|
|
1032
|
+
return 0;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
throw new UsageError(`Unknown command "proxy ${sub}". Use status, enable, check or remove.`);
|
|
1036
|
+
}
|
|
1037
|
+
// ---------------------------------------------------------------------------------------------
|
|
1038
|
+
// Account profile, websites get/update/delete, access tokens, data deletion, visitor search
|
|
1039
|
+
/** Destructive commands ask first; --yes skips the question (and is required without a terminal). */
|
|
1040
|
+
async function confirmOrStop(flags, question) {
|
|
1041
|
+
if (flags.yes)
|
|
1042
|
+
return true;
|
|
1043
|
+
if (!interactive() || flags.json)
|
|
1044
|
+
throw new UsageError("Add --yes to do this without a prompt.");
|
|
1045
|
+
const answer = await prompt(`${question} [y/N] `);
|
|
1046
|
+
if (/^y(es)?$/i.test(answer))
|
|
1047
|
+
return true;
|
|
1048
|
+
out("Nothing changed.");
|
|
1049
|
+
return false;
|
|
1050
|
+
}
|
|
1051
|
+
async function updateAccount({ flags, client }) {
|
|
1052
|
+
if (flags.name === undefined)
|
|
1053
|
+
throw new UsageError('Use: metricraven account update --name "Your name" (pass "" to clear).');
|
|
1054
|
+
const account = await needs("write", client.patch("/account", { name: flags.name.trim() || null }));
|
|
1055
|
+
if (flags.json)
|
|
1056
|
+
return printJson(account), 0;
|
|
1057
|
+
out(`Name: ${account.user.name ?? dim("(none)")} · ${account.user.email}`);
|
|
1058
|
+
return 0;
|
|
1059
|
+
}
|
|
1060
|
+
async function websiteId(ctx, id) {
|
|
1061
|
+
return id ?? (await ctx.site());
|
|
1062
|
+
}
|
|
1063
|
+
async function getWebsite(ctx, id) {
|
|
1064
|
+
const siteId = await websiteId(ctx, id);
|
|
1065
|
+
const d = await ctx.client.get(`/websites/${encodeURIComponent(siteId)}`);
|
|
1066
|
+
if (ctx.flags.json)
|
|
1067
|
+
return printJson(d), 0;
|
|
1068
|
+
const w = d.website;
|
|
1069
|
+
out(bold(w.name));
|
|
1070
|
+
out(`ID: ${w.id}`);
|
|
1071
|
+
out(`Domains: ${w.domains.join(", ") || "–"}`);
|
|
1072
|
+
if (w.appIds.length)
|
|
1073
|
+
out(`Apps: ${w.appIds.join(", ")}`);
|
|
1074
|
+
out(`Your role: ${w.role}`);
|
|
1075
|
+
if (w.createdAt)
|
|
1076
|
+
out(dim(`Created ${date(w.createdAt)}`));
|
|
1077
|
+
return 0;
|
|
1078
|
+
}
|
|
1079
|
+
async function updateWebsite(ctx, id) {
|
|
1080
|
+
const { flags, client } = ctx;
|
|
1081
|
+
const body = {};
|
|
1082
|
+
if (flags.name !== undefined)
|
|
1083
|
+
body.name = flags.name.trim();
|
|
1084
|
+
if (flags.domain !== undefined)
|
|
1085
|
+
body.domains = flags.domain.split(",").map((d) => d.trim()).filter(Boolean);
|
|
1086
|
+
if (!body.name && !body.domains?.length)
|
|
1087
|
+
throw new UsageError("Use: metricraven websites update [<website_id>] --name <name> and/or --domain example.com[,other.com] (replaces the domains).");
|
|
1088
|
+
const siteId = await websiteId(ctx, id);
|
|
1089
|
+
const d = await needs("write", client.patch(`/websites/${encodeURIComponent(siteId)}`, body));
|
|
1090
|
+
if (flags.json)
|
|
1091
|
+
return printJson(d), 0;
|
|
1092
|
+
out(`Updated ${bold(d.website.name)} (${d.website.domains.join(", ")}).`);
|
|
1093
|
+
return 0;
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Deleting a website asks for the same confirmation as the dashboard: type its domain. --yes is
|
|
1097
|
+
* not enough; without a terminal, pass the domain with --domain to confirm.
|
|
1098
|
+
*/
|
|
1099
|
+
async function deleteWebsiteCommand(ctx, id) {
|
|
1100
|
+
const { flags, client } = ctx;
|
|
1101
|
+
if (!id)
|
|
1102
|
+
throw new UsageError("Use: metricraven websites delete <website_id> (the ID is required here; see `metricraven websites list`).");
|
|
1103
|
+
const { website } = await client.get(`/websites/${encodeURIComponent(id)}`);
|
|
1104
|
+
if (website.role !== "owner")
|
|
1105
|
+
throw new UsageError(`Only the owner can delete ${website.name}; your role is ${website.role}.`);
|
|
1106
|
+
const expected = website.domains[0] ?? website.name;
|
|
1107
|
+
let typed = flags.domain?.trim();
|
|
1108
|
+
if (!typed) {
|
|
1109
|
+
if (!interactive() || flags.json)
|
|
1110
|
+
throw new UsageError(`Deleting a website needs confirmation: add --domain ${expected} (the website's domain).`);
|
|
1111
|
+
out(`This permanently deletes ${bold(website.name)} and all of its data: pageviews, goals, payments, visitors, funnels, alerts and integrations.`);
|
|
1112
|
+
typed = await prompt(`Type ${expected} to confirm: `);
|
|
1113
|
+
}
|
|
1114
|
+
if (typed.toLowerCase() !== expected.toLowerCase()) {
|
|
1115
|
+
out("That doesn't match. Nothing was deleted.");
|
|
1116
|
+
return 1;
|
|
1117
|
+
}
|
|
1118
|
+
const d = await needs("write", client.del(`/websites/${encodeURIComponent(id)}`, new URLSearchParams({ confirm: typed })));
|
|
1119
|
+
if (flags.json)
|
|
1120
|
+
return printJson(d), 0;
|
|
1121
|
+
const total = Object.values(d.deleted).reduce((a, b) => a + b, 0);
|
|
1122
|
+
out(`Deleted ${website.name} (${d.id}) and ${num(total)} stored records.`);
|
|
1123
|
+
const config = await readConfig();
|
|
1124
|
+
if (config.site === d.id) {
|
|
1125
|
+
await updateConfig({ site: undefined });
|
|
1126
|
+
out(dim("It was your default website; run `metricraven use <id>` to pick another."));
|
|
1127
|
+
}
|
|
1128
|
+
return 0;
|
|
1129
|
+
}
|
|
1130
|
+
async function tokens(ctx, sub, rest) {
|
|
1131
|
+
const { flags, client } = ctx;
|
|
1132
|
+
switch (sub ?? "list") {
|
|
1133
|
+
case "list": {
|
|
1134
|
+
const d = await client.get("/tokens");
|
|
1135
|
+
if (flags.json)
|
|
1136
|
+
return printJson(d), 0;
|
|
1137
|
+
if (!d.tokens.length)
|
|
1138
|
+
return out(dim("No tokens.")), 0;
|
|
1139
|
+
out(table(["", "Name", "Token", "Access", "Websites", "Last used", "ID"], d.tokens.map((t) => [
|
|
1140
|
+
t.current ? "*" : "",
|
|
1141
|
+
t.name,
|
|
1142
|
+
t.hint,
|
|
1143
|
+
scopes(t.scopes),
|
|
1144
|
+
t.siteIds === null ? "all" : t.siteIds.join(", "),
|
|
1145
|
+
t.lastUsedAt ? date(t.lastUsedAt) : "never",
|
|
1146
|
+
t.id,
|
|
1147
|
+
])));
|
|
1148
|
+
out(dim("* = the token this CLI is using"));
|
|
1149
|
+
return 0;
|
|
1150
|
+
}
|
|
1151
|
+
case "create": {
|
|
1152
|
+
const name = flags.name?.trim();
|
|
1153
|
+
if (!name)
|
|
1154
|
+
throw new UsageError("Use: metricraven tokens create --name <label> [--scopes read,visitors,write] [--sites <id,id>]");
|
|
1155
|
+
const requested = (flags.scopes ?? "read").split(",").map((s) => s.trim()).filter(Boolean);
|
|
1156
|
+
const unknown = requested.filter((s) => !["read", "visitors", "write"].includes(s));
|
|
1157
|
+
if (unknown.length)
|
|
1158
|
+
throw new UsageError(`Unknown scope ${unknown.join(", ")}. Use read, visitors and/or write.`);
|
|
1159
|
+
const body = { name, scopes: requested };
|
|
1160
|
+
if (flags.sites !== undefined)
|
|
1161
|
+
body.siteIds = flags.sites === "all" ? null : flags.sites.split(",").map((s) => s.trim()).filter(Boolean);
|
|
1162
|
+
const d = await needs("write", client.post("/tokens", body));
|
|
1163
|
+
if (flags.json)
|
|
1164
|
+
return printJson(d), 0;
|
|
1165
|
+
out(`Created "${d.token.name}" (${scopes(d.token.scopes)}; websites: ${d.token.siteIds === null ? "all" : d.token.siteIds.join(", ")}).`);
|
|
1166
|
+
out(`Token: ${d.value}`);
|
|
1167
|
+
out(dim("Shown once. Store it somewhere safe, e.g. METRICRAVEN_TOKEN in your CI secrets."));
|
|
1168
|
+
return 0;
|
|
1169
|
+
}
|
|
1170
|
+
case "delete":
|
|
1171
|
+
case "revoke": {
|
|
1172
|
+
const id = rest[0];
|
|
1173
|
+
if (!id)
|
|
1174
|
+
throw new UsageError("Use: metricraven tokens delete <token_id> (IDs from `metricraven tokens list`).");
|
|
1175
|
+
const list = await client.get("/tokens");
|
|
1176
|
+
const target = list.tokens.find((t) => t.id === id);
|
|
1177
|
+
if (!target)
|
|
1178
|
+
throw new UsageError(`No token "${id}". Run \`metricraven tokens list\`.`);
|
|
1179
|
+
const warning = target.current ? " This is the token the CLI is using; you'll need to log in again." : "";
|
|
1180
|
+
if (!(await confirmOrStop(flags, `Delete token "${target.name}" (${target.hint})? It stops working at once.${warning}`)))
|
|
1181
|
+
return 0;
|
|
1182
|
+
const d = await needs("write", client.del(`/tokens/${encodeURIComponent(id)}`));
|
|
1183
|
+
if (flags.json)
|
|
1184
|
+
return printJson(d), 0;
|
|
1185
|
+
out(`Deleted token "${target.name}".`);
|
|
1186
|
+
if (d.current)
|
|
1187
|
+
out(dim("That was this CLI's token. Run `metricraven login` with another one."));
|
|
1188
|
+
return 0;
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
throw new UsageError(`Unknown command "tokens ${sub}". Use list, create or delete.`);
|
|
1192
|
+
}
|
|
1193
|
+
/** --from/--to (calendar days in --timezone) as the API's startAt/endAt. */
|
|
1194
|
+
function deletionRange(flags, params) {
|
|
1195
|
+
if (!flags.from && !flags.to)
|
|
1196
|
+
return;
|
|
1197
|
+
if (!flags.from || !flags.to)
|
|
1198
|
+
throw new UsageError("Use --from and --to together (YYYY-MM-DD, inclusive).");
|
|
1199
|
+
const zone = validTimeZone(flags.timezone);
|
|
1200
|
+
if (!zone)
|
|
1201
|
+
throw new UsageError(`Unknown timezone "${flags.timezone}".`);
|
|
1202
|
+
const range = customRange(flags.from, flags.to, zone);
|
|
1203
|
+
if (!range)
|
|
1204
|
+
throw new UsageError("--from and --to must be real dates like 2026-10-01, with --from on or before --to.");
|
|
1205
|
+
params.set("startAt", range.from.toISOString());
|
|
1206
|
+
params.set("endAt", range.to.toISOString());
|
|
1207
|
+
}
|
|
1208
|
+
const plural = (what, n) => (n === 1 ? what.replace(/s$/, "") : what);
|
|
1209
|
+
/** Counts first (dry run), asks, then deletes. */
|
|
1210
|
+
async function deleteWithCount(ctx, path, params, what) {
|
|
1211
|
+
const { flags, client } = ctx;
|
|
1212
|
+
params.set("site", await ctx.site());
|
|
1213
|
+
const preview = await needs("write", client.del(path, new URLSearchParams([...params, ["dry_run", "1"]])));
|
|
1214
|
+
if (flags["dry-run"]) {
|
|
1215
|
+
if (flags.json)
|
|
1216
|
+
return printJson(preview), 0;
|
|
1217
|
+
return out(`${num(preview.matched)} ${plural(what, preview.matched)} would be deleted.`), 0;
|
|
1218
|
+
}
|
|
1219
|
+
if (!preview.matched) {
|
|
1220
|
+
if (flags.json)
|
|
1221
|
+
return printJson(preview), 0;
|
|
1222
|
+
return out(`No ${what} match. Nothing to delete.`), 0;
|
|
1223
|
+
}
|
|
1224
|
+
if (!(await confirmOrStop(flags, `Permanently delete ${num(preview.matched)} ${plural(what, preview.matched)}? Reports change at once.`)))
|
|
1225
|
+
return 0;
|
|
1226
|
+
const d = await needs("write", client.del(path, params));
|
|
1227
|
+
if (flags.json)
|
|
1228
|
+
return printJson(d), 0;
|
|
1229
|
+
out(`Deleted ${num(d.deleted)} ${plural(what, d.deleted)}.`);
|
|
1230
|
+
return 0;
|
|
1231
|
+
}
|
|
1232
|
+
async function deletePayments(ctx) {
|
|
1233
|
+
const { flags } = ctx;
|
|
1234
|
+
const params = new URLSearchParams();
|
|
1235
|
+
if (flags.transaction)
|
|
1236
|
+
params.set("transaction_id", flags.transaction);
|
|
1237
|
+
if (flags.visitor)
|
|
1238
|
+
params.set("visitor_id", flags.visitor);
|
|
1239
|
+
if (flags.user)
|
|
1240
|
+
params.set("user_id", flags.user);
|
|
1241
|
+
if (!flags.transaction)
|
|
1242
|
+
deletionRange(flags, params);
|
|
1243
|
+
if (![...params].length)
|
|
1244
|
+
throw new UsageError("Use: metricraven payments delete --transaction <id> | --visitor <id> | --user <id> [--from --to] | --from <day> --to <day>");
|
|
1245
|
+
return deleteWithCount(ctx, "/payments", params, "payments");
|
|
1246
|
+
}
|
|
1247
|
+
async function deleteGoalEvents(ctx) {
|
|
1248
|
+
const { flags } = ctx;
|
|
1249
|
+
const params = new URLSearchParams();
|
|
1250
|
+
if (flags.goal)
|
|
1251
|
+
params.set("name", flags.goal);
|
|
1252
|
+
if (flags.visitor)
|
|
1253
|
+
params.set("visitor_id", flags.visitor);
|
|
1254
|
+
if (flags.user)
|
|
1255
|
+
params.set("user_id", flags.user);
|
|
1256
|
+
deletionRange(flags, params);
|
|
1257
|
+
if (![...params].length)
|
|
1258
|
+
throw new UsageError("Use: metricraven goals delete-events --goal <name> | --visitor <id> | --user <id> [--from --to] | --from <day> --to <day>");
|
|
1259
|
+
return deleteWithCount(ctx, "/events", params, "goal events");
|
|
1260
|
+
}
|
|
1261
|
+
/** visitors list search flags, sent as the explorer's shortcut parameters. */
|
|
1262
|
+
function visitorSearchParams(flags, params) {
|
|
1263
|
+
const map = [
|
|
1264
|
+
["page", "visitedPage"],
|
|
1265
|
+
["page-contains", "visitedPageContains"],
|
|
1266
|
+
["goal", "completedGoal"],
|
|
1267
|
+
["referrer", "referrer"],
|
|
1268
|
+
["channel", "channel"],
|
|
1269
|
+
["source", "source"],
|
|
1270
|
+
["utm-source", "utm_source"],
|
|
1271
|
+
["utm-medium", "utm_medium"],
|
|
1272
|
+
["utm-campaign", "utm_campaign"],
|
|
1273
|
+
["country", "country"],
|
|
1274
|
+
["device", "device"],
|
|
1275
|
+
["browser", "browser"],
|
|
1276
|
+
["os", "os"],
|
|
1277
|
+
];
|
|
1278
|
+
for (const [flag, param] of map) {
|
|
1279
|
+
const value = flags[flag];
|
|
1280
|
+
if (typeof value === "string" && value.trim())
|
|
1281
|
+
params.set(param, value.trim());
|
|
1282
|
+
}
|
|
1283
|
+
const gt = positiveInt(flags["visits-gt"], "visits-gt", 100_000);
|
|
1284
|
+
if (gt !== undefined)
|
|
1285
|
+
params.set("visits_gt", String(gt));
|
|
1286
|
+
const lt = positiveInt(flags["visits-lt"], "visits-lt", 100_000);
|
|
1287
|
+
if (lt !== undefined)
|
|
1288
|
+
params.set("visits_lt", String(lt));
|
|
1289
|
+
}
|
|
1290
|
+
const GRACES = ["none", "24h", "7d"];
|
|
1291
|
+
async function siteKeys(ctx, sub, rest) {
|
|
1292
|
+
const { flags, client } = ctx;
|
|
1293
|
+
const site = await ctx.site();
|
|
1294
|
+
const params = () => new URLSearchParams({ site });
|
|
1295
|
+
const keyPath = (id, suffix = "") => {
|
|
1296
|
+
if (!id)
|
|
1297
|
+
throw new UsageError(`Use: metricraven websites keys ${sub} <key_id> (IDs from \`metricraven websites keys list\`; "default" for the default key).`);
|
|
1298
|
+
return `/site/keys/${encodeURIComponent(id)}${suffix}`;
|
|
1299
|
+
};
|
|
1300
|
+
const confirm = async (question) => {
|
|
1301
|
+
if (flags.yes)
|
|
1302
|
+
return true;
|
|
1303
|
+
if (!interactive() || flags.json)
|
|
1304
|
+
throw new UsageError("Add --yes to do this without a prompt.");
|
|
1305
|
+
return /^y(es)?$/i.test(await prompt(`${question} [y/N] `));
|
|
1306
|
+
};
|
|
1307
|
+
const showSecret = (key, secretKey) => {
|
|
1308
|
+
out(`Secret key for "${key.name}" (${key.id}): ${secretKey}`);
|
|
1309
|
+
out(dim("Shown once. Keep it on your server, never in browser code."));
|
|
1310
|
+
};
|
|
1311
|
+
switch (sub ?? "list") {
|
|
1312
|
+
case "list": {
|
|
1313
|
+
const d = await needs("write", client.get("/site/keys", params()));
|
|
1314
|
+
if (flags.json)
|
|
1315
|
+
return printJson(d), 0;
|
|
1316
|
+
out(table(["Name", "Key", "Created", "Last used", "ID"], [
|
|
1317
|
+
...d.keys.map((k) => [k.default ? `${k.name} (default)` : k.name, k.hint ?? "ana_sec_…", k.createdAt ? date(k.createdAt) : "–", k.lastUsedAt ? date(k.lastUsedAt) : "never", k.id]),
|
|
1318
|
+
...d.previous.map((k) => [`${k.name}, previous`, k.hint ?? "ana_sec_…", `until ${date(k.expiresAt)}`, k.lastUsedAt ? date(k.lastUsedAt) : "never", k.keyId]),
|
|
1319
|
+
]));
|
|
1320
|
+
out(dim(`${d.keys.length - 1} of ${d.maxNamedKeys} named keys.`));
|
|
1321
|
+
return 0;
|
|
1322
|
+
}
|
|
1323
|
+
case "create": {
|
|
1324
|
+
const name = flags.name ?? rest[0];
|
|
1325
|
+
if (!name)
|
|
1326
|
+
throw new UsageError("Use: metricraven websites keys create --name <label>");
|
|
1327
|
+
const d = await needs("write", client.post("/site/keys", { name }, params()));
|
|
1328
|
+
if (flags.json)
|
|
1329
|
+
return printJson(d), 0;
|
|
1330
|
+
showSecret(d.key, d.secretKey);
|
|
1331
|
+
return 0;
|
|
1332
|
+
}
|
|
1333
|
+
case "rename": {
|
|
1334
|
+
const path = keyPath(rest[0]);
|
|
1335
|
+
if (!flags.name)
|
|
1336
|
+
throw new UsageError("Use: metricraven websites keys rename <key_id> --name <label>");
|
|
1337
|
+
const d = await needs("write", client.patch(path, { name: flags.name }, params()));
|
|
1338
|
+
if (flags.json)
|
|
1339
|
+
return printJson(d), 0;
|
|
1340
|
+
out(`Renamed ${d.key.id} to "${d.key.name}".`);
|
|
1341
|
+
return 0;
|
|
1342
|
+
}
|
|
1343
|
+
case "revoke":
|
|
1344
|
+
case "delete": {
|
|
1345
|
+
const path = keyPath(rest[0]);
|
|
1346
|
+
if (!(await confirm(`Revoke key ${rest[0]}? Servers using it fail with 401 at once.`)))
|
|
1347
|
+
return out("Kept."), 0;
|
|
1348
|
+
const d = await needs("write", client.del(path, params()));
|
|
1349
|
+
if (flags.json)
|
|
1350
|
+
return printJson(d), 0;
|
|
1351
|
+
out(`Revoked key ${d.id}.`);
|
|
1352
|
+
return 0;
|
|
1353
|
+
}
|
|
1354
|
+
case "roll":
|
|
1355
|
+
case "rotate": {
|
|
1356
|
+
const path = keyPath(rest[0], "/roll");
|
|
1357
|
+
const grace = flags.grace ?? "none";
|
|
1358
|
+
if (!GRACES.includes(grace))
|
|
1359
|
+
throw new UsageError("--grace must be none, 24h or 7d.");
|
|
1360
|
+
const keep = grace === "none" ? "stops working at once" : `keeps working for ${grace}`;
|
|
1361
|
+
if (!(await confirm(`Roll key ${rest[0]}? Its current value ${keep}.`)))
|
|
1362
|
+
return out("Kept."), 0;
|
|
1363
|
+
const d = await needs("write", client.post(path, { grace }, params()));
|
|
1364
|
+
if (flags.json)
|
|
1365
|
+
return printJson(d), 0;
|
|
1366
|
+
showSecret(d.key, d.secretKey);
|
|
1367
|
+
return 0;
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
throw new UsageError(`Unknown command "websites keys ${sub}". Use list, create, rename, revoke or roll.`);
|
|
1371
|
+
}
|
|
1372
|
+
/** The API answers 401 for a missing scope too; name the access the command needs. */
|
|
1373
|
+
async function needs(access, request) {
|
|
1374
|
+
try {
|
|
1375
|
+
return await request;
|
|
1376
|
+
}
|
|
1377
|
+
catch (error) {
|
|
1378
|
+
if (error instanceof ApiError && error.status === 401) {
|
|
1379
|
+
const label = access === "visitors" ? "Visitor details" : "Write";
|
|
1380
|
+
throw new ApiError(`This needs a token with ${label} access. Create one at ${TOKENS_URL} and run \`metricraven login\`. (Also check the token can use this website.)`, 401, error.code);
|
|
1381
|
+
}
|
|
1382
|
+
throw error;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
export function errorMessage(error) {
|
|
1386
|
+
if (error instanceof UsageError || error instanceof ApiError)
|
|
1387
|
+
return error.message;
|
|
1388
|
+
if (error instanceof Error && error.message === "canceled")
|
|
1389
|
+
return "Canceled.";
|
|
1390
|
+
return `Unexpected error: ${error?.message ?? String(error)}`;
|
|
1391
|
+
}
|