@metricraven/cli 0.1.0 → 0.2.1

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 CHANGED
@@ -29,6 +29,11 @@ The token is saved to `~/.config/metricraven/config.json` (or `$XDG_CONFIG_HOME/
29
29
  | `login`, `logout`, `whoami` | Save, remove or inspect the access token |
30
30
  | `websites list` | Websites this token can use |
31
31
  | `websites create --name --domain` | Add a website; prints its ID, secret key and tracking script |
32
+ | `websites get [id]`, `websites update [id] [--name] [--domain a.com,b.com]` | One website's settings; rename it or replace its domains (write access, admin) |
33
+ | `websites delete <id>` | Delete a website and all of its data (owner only; you type its domain, or pass `--domain <domain>` in scripts) |
34
+ | `account update --name <name>` | Change your display name (write access) |
35
+ | `tokens list`, `tokens create --name [--scopes read,visitors,write] [--sites id,id\|all]`, `tokens delete <id>` | Manage access tokens; a new token never gets more access than the one you use |
36
+ | `websites keys list\|create --name\|rename <id> --name\|revoke <id>\|roll <id> [--grace none\|24h\|7d]` | Site secret keys: the default key and named keys with last use; revoke and roll ask first (`--yes` to skip). Needs write access, admin |
32
37
  | `use <website_id>` | Set the default website |
33
38
  | `analytics traffic` | Visitors, pageviews, revenue, conversion rate and top sources |
34
39
  | `analytics breakdown <dimension>` | Full table for `channel`, `referrer`, `page`, `utmSource`, `country`, `device`, … |
@@ -38,14 +43,19 @@ The token is saved to `~/.config/metricraven/config.json` (or `$XDG_CONFIG_HOME/
38
43
  | `analytics insights` | What converts and how long buyers take |
39
44
  | `analytics search` | Google Search Console queries |
40
45
  | `analytics crawlers` | AI crawlers and bots |
46
+ | `analytics meta-ads [campaign\|adset\|ad]` | Meta Ads spend, attributed revenue, ROAS and cost per customer |
41
47
  | `realtime` | Visitors online now |
42
48
  | `visitors list`, `visitors get <id>` | Visitors and journeys (token needs visitor details access) |
49
+ | `visitors list --page /pricing --goal signup --visits-gt 2` | Search visitors by visited page (`--page`, `--page-contains`), completed goal, `--referrer`, `--channel`, `--source`, `--utm-source/medium/campaign`, `--country`, `--device`, `--browser`, `--os` and visits in the period (`--visits-gt`, `--visits-lt`) |
50
+ | `payments delete`, `goals delete-events` | Delete payments (`--transaction`, `--visitor`, `--user`, `--from/--to`) or goal events (`--goal`, `--visitor`, `--user`, `--from/--to`); shows the count and asks first (`--yes`, `--dry-run`) |
43
51
  | `funnels list` | Saved funnels |
52
+ | `goals list`, `goals colors` | Goal display settings (display name, colour, description, hidden) and the palette |
53
+ | `goals set <goal> [--name] [--color] [--description] [--hidden\|--visible]`, `goals reset <goal>` | Change how a goal is shown (needs write access, admin) |
44
54
  | `notes list`, `notes add --text [--date]` | Chart notes (adding needs write access) |
45
55
  | `mentions [--platform x\|reddit] [--q text]` | X and Reddit posts mentioning the website (Growth plan) |
46
56
  | `completion bash\|zsh\|fish` | Shell completion script |
47
57
 
48
- Reports cover the last 30 days by default. Use `--period today|yesterday|24h|7d|30d|90d|6m|1y|wtd|mtd|all`, or `--from 2026-10-01 --to 2026-10-31`, with `--timezone Europe/Madrid` for day boundaries. Filter with `--filter dimension:operator:value` (repeatable; operators `is`, `is_not`, `contains`, `not_contains`).
58
+ Reports cover the last 30 days by default. Use `--period today|yesterday|24h|7d|30d|90d|6m|1y|wtd|mtd|all`, or `--from 2026-10-01 --to 2026-10-31`, with `--timezone Europe/Madrid` for day boundaries. `--compare year` (or a `YYYY-MM-DD` start) changes what the change figures compare against; the default is the previous period of equal length. Filter with `--filter dimension:operator:value` (repeatable; operators `is`, `is_not`, `contains`, `not_contains`, and `gt`/`lt` for `visits`, e.g. `-f visits:gt:2`).
49
59
 
50
60
  ```bash
51
61
  metricraven analytics traffic --period 7d
@@ -61,6 +71,13 @@ metricraven analytics traffic -f country:is:US -f device:is:mobile --json | jq .
61
71
  | `METRICRAVEN_SITE` | Default website ID |
62
72
  | `METRICRAVEN_API_BASE` | API origin, default `https://metricraven.com` |
63
73
 
74
+ `--fields` on `analytics`, `realtime` and `visitors list` returns only part of the answer, as JSON (comma-separated dot paths; `period` is always kept):
75
+
76
+ ```sh
77
+ metricraven analytics traffic -p 7d --fields overview.current,series.date,series.visitors
78
+ metricraven analytics breakdown country --fields rows.name,rows.revenue
79
+ ```
80
+
64
81
  Global flags: `--site <id>`, `--json`, `--verbose` (request URLs and status codes on stderr), `--help`, `--version`.
65
82
 
66
83
  Full documentation: https://metricraven.com/docs/cli
package/dist/api.js CHANGED
@@ -50,6 +50,7 @@ export function createClient(opts) {
50
50
  get: (path, params) => request("GET", path, params),
51
51
  post: (path, body, params) => request("POST", path, params, body),
52
52
  patch: (path, body, params) => request("PATCH", path, params, body),
53
+ put: (path, body, params) => request("PUT", path, params, body),
53
54
  del: (path, params) => request("DELETE", path, params),
54
55
  };
55
56
  }
package/dist/args.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { parseArgs } from "node:util";
2
- import { PERIODS, customRange, presetRange, validTimeZone } from "./range.js";
3
- export const FILTER_OPERATORS = ["is", "is_not", "contains", "not_contains"];
2
+ import { PERIODS, compareStartFor, customRange, presetRange, validTimeZone } from "./range.js";
3
+ export const FILTER_OPERATORS = ["is", "is_not", "contains", "not_contains", "gt", "lt"];
4
4
  /** Every flag the CLI understands; commands ignore the ones that don't apply. */
5
5
  const OPTIONS = {
6
6
  json: { type: "boolean" },
7
+ fields: { type: "string" },
7
8
  site: { type: "string" },
8
9
  token: { type: "string" },
9
10
  verbose: { type: "boolean", short: "v" },
@@ -14,6 +15,7 @@ const OPTIONS = {
14
15
  to: { type: "string" },
15
16
  timezone: { type: "string", short: "z" },
16
17
  filter: { type: "string", short: "f", multiple: true },
18
+ compare: { type: "string" },
17
19
  sort: { type: "string" },
18
20
  limit: { type: "string", short: "n" },
19
21
  offset: { type: "string" },
@@ -34,6 +36,37 @@ const OPTIONS = {
34
36
  yes: { type: "boolean", short: "y" },
35
37
  alert: { type: "string" },
36
38
  role: { type: "string" },
39
+ color: { type: "string" },
40
+ description: { type: "string" },
41
+ hidden: { type: "boolean" },
42
+ visible: { type: "boolean" },
43
+ company: { type: "boolean" },
44
+ // analytics ads
45
+ provider: { type: "string" },
46
+ // tokens create
47
+ scopes: { type: "string" },
48
+ sites: { type: "string" },
49
+ // payments delete, goals delete-events
50
+ transaction: { type: "string" },
51
+ visitor: { type: "string" },
52
+ user: { type: "string" },
53
+ "dry-run": { type: "boolean" },
54
+ // visitors list search filters
55
+ page: { type: "string" },
56
+ "page-contains": { type: "string" },
57
+ referrer: { type: "string" },
58
+ channel: { type: "string" },
59
+ source: { type: "string" },
60
+ "utm-source": { type: "string" },
61
+ "utm-medium": { type: "string" },
62
+ "utm-campaign": { type: "string" },
63
+ country: { type: "string" },
64
+ device: { type: "string" },
65
+ browser: { type: "string" },
66
+ os: { type: "string" },
67
+ "visits-gt": { type: "string" },
68
+ "visits-lt": { type: "string" },
69
+ grace: { type: "string" },
37
70
  };
38
71
  export class UsageError extends Error {
39
72
  }
@@ -107,6 +140,14 @@ export function rangeParams(flags, now = new Date()) {
107
140
  const filters = buildFilters(flags.filter);
108
141
  if (filters.length)
109
142
  params.set("filters", JSON.stringify(filters));
143
+ if (flags.compare) {
144
+ const from = params.get("from");
145
+ const start = from ? compareStartFor(flags.compare, new Date(from), zone) : null;
146
+ if (start === undefined)
147
+ throw new UsageError(`--compare must be previous, year, off or a YYYY-MM-DD day before the period starts (got "${flags.compare}").`);
148
+ if (start)
149
+ params.set("compareStart", start.toISOString());
150
+ }
110
151
  return params;
111
152
  }
112
153
  export function positiveInt(value, name, max) {
package/dist/commands.js CHANGED
@@ -1,12 +1,27 @@
1
1
  import { ApiError, createClient } from "./api.js";
2
- import { UsageError, positiveInt, rangeParams } from "./args.js";
2
+ import { UsageError, buildFilters, positiveInt, rangeParams } from "./args.js";
3
+ import { customRange, validTimeZone } from "./range.js";
3
4
  import { completionScript } from "./completion.js";
4
5
  import { configPath, deleteConfigToken, readConfig, resolveSettings, updateConfig } from "./config.js";
5
- import { bold, change, date, dim, duration, money, num, pct, section, table, truncate } from "./format.js";
6
+ import { bold, change, date, dim, duration, money, num, pct, section, table, terminalSafe, truncate } from "./format.js";
6
7
  import { interactive, prompt, promptHidden, readStdin } from "./prompt.js";
7
8
  export const TOKENS_URL = "https://metricraven.com/app/api";
8
- const out = (s) => process.stdout.write(`${s}\n`);
9
+ /** Every line the CLI prints; terminalSafe strips escape sequences that came from report data. */
10
+ const out = (s) => process.stdout.write(`${terminalSafe(s)}\n`);
9
11
  const printJson = (data) => out(JSON.stringify(data));
12
+ /**
13
+ * --fields: the API's ?fields= selection (comma-separated dot paths, period always kept). The
14
+ * answer is then only part of a report, so it is printed as JSON instead of the usual tables.
15
+ */
16
+ export function selectFields(flags, params) {
17
+ if (flags.fields === undefined)
18
+ return false;
19
+ const fields = flags.fields.trim();
20
+ if (!fields)
21
+ throw new UsageError("--fields needs comma-separated dot paths, e.g. --fields overview.current,series.date.");
22
+ params.set("fields", fields);
23
+ return true;
24
+ }
10
25
  /** Runs a parsed command. Returns the exit code. */
11
26
  export async function run(command, flags) {
12
27
  const [group, sub, ...rest] = command;
@@ -30,14 +45,34 @@ export async function run(command, flags) {
30
45
  switch (group) {
31
46
  case "whoami":
32
47
  return whoami(ctx);
48
+ case "account":
49
+ if (!sub || sub === "get")
50
+ return whoami(ctx);
51
+ if (sub === "update")
52
+ return updateAccount(ctx);
53
+ break;
54
+ case "tokens":
55
+ return tokens(ctx, sub, rest);
56
+ case "payments":
57
+ if (sub === "delete")
58
+ return deletePayments(ctx);
59
+ break;
33
60
  case "use":
34
61
  return useSite(ctx, sub);
35
62
  case "websites":
36
63
  case "sites":
37
64
  if (sub === "create")
38
65
  return createWebsite(ctx);
66
+ if (sub === "keys")
67
+ return siteKeys(ctx, rest[0], rest.slice(1));
39
68
  if (!sub || sub === "list")
40
69
  return listWebsites(ctx);
70
+ if (sub === "get")
71
+ return getWebsite(ctx, rest[0]);
72
+ if (sub === "update")
73
+ return updateWebsite(ctx, rest[0]);
74
+ if (sub === "delete")
75
+ return deleteWebsiteCommand(ctx, rest[0]);
41
76
  break;
42
77
  case "analytics":
43
78
  return analytics(ctx, sub, rest);
@@ -54,6 +89,10 @@ export async function run(command, flags) {
54
89
  if (!sub || sub === "list")
55
90
  return listFunnels(ctx);
56
91
  break;
92
+ case "goals":
93
+ if (sub === "delete-events")
94
+ return deleteGoalEvents(ctx);
95
+ return goals(ctx, sub, rest);
57
96
  case "notes":
58
97
  if (!sub || sub === "list")
59
98
  return listNotes(ctx);
@@ -64,11 +103,20 @@ export async function run(command, flags) {
64
103
  if (!sub || sub === "list")
65
104
  return listMentions(ctx);
66
105
  break;
106
+ case "ai-visibility":
107
+ case "ai":
108
+ if (!sub || sub === "summary")
109
+ return aiVisibility(ctx);
110
+ break;
67
111
  case "alerts":
68
112
  return alerts(ctx, sub, rest);
69
113
  case "members":
70
114
  case "team":
71
115
  return members(ctx, sub, rest);
116
+ case "bots":
117
+ return bots(ctx, sub, rest);
118
+ case "proxy":
119
+ return managedProxy(ctx, sub, rest);
72
120
  }
73
121
  throw new UsageError(`Unknown command "${command.join(" ")}". Run \`metricraven --help\`.`);
74
122
  }
@@ -172,7 +220,7 @@ async function useSite({ flags, client }, id) {
172
220
  out(`Default website: ${bold(site.name)} (${id}).`);
173
221
  return 0;
174
222
  }
175
- const REPORTS = ["traffic", "revenue", "conversions", "insights", "search", "crawlers"];
223
+ const REPORTS = ["traffic", "revenue", "conversions", "insights", "search", "crawlers", "ads", "meta-ads"];
176
224
  async function analytics(ctx, sub, rest) {
177
225
  const { flags, client } = ctx;
178
226
  if (!sub)
@@ -199,18 +247,75 @@ async function analytics(ctx, sub, rest) {
199
247
  throw new UsageError("Use: metricraven analytics goal <name>");
200
248
  params.set("name", rest[0]);
201
249
  }
250
+ else if (sub === "meta-ads" && rest[0]) {
251
+ if (!["campaign", "adset", "ad"].includes(rest[0]))
252
+ throw new UsageError("Use: metricraven analytics meta-ads [campaign|adset|ad]");
253
+ params.set("level", rest[0]);
254
+ }
255
+ else if (sub === "ads") {
256
+ if (rest[0] && !["campaign", "adgroup", "adset", "ad"].includes(rest[0]))
257
+ throw new UsageError("Use: metricraven analytics ads [campaign|adgroup|ad] [--provider all|meta|google]");
258
+ if (rest[0])
259
+ params.set("level", rest[0]);
260
+ if (flags.provider) {
261
+ if (!["all", "meta", "google", "tiktok"].includes(flags.provider))
262
+ throw new UsageError("Use --provider all, meta or google.");
263
+ params.set("provider", flags.provider);
264
+ }
265
+ }
202
266
  else if (!REPORTS.includes(sub)) {
203
267
  throw new UsageError(`Unknown report "${sub}". Use ${[...REPORTS, "breakdown", "goal"].join(", ")}.`);
204
268
  }
205
269
  params.set("site", await ctx.site());
270
+ const selected = selectFields(flags, params);
206
271
  const path = sub === "breakdown" ? "/stats/breakdown" : sub === "goal" ? "/stats/goal" : `/stats/${sub}`;
207
272
  const data = await client.get(path, params);
208
- if (flags.json)
273
+ if (flags.json || selected)
209
274
  return printJson(data), 0;
210
275
  const render = RENDER[sub];
211
276
  out(render ? render(data) : JSON.stringify(data, null, 2));
212
277
  return 0;
213
278
  }
279
+ const NETWORKS = { meta: "Meta Ads", google: "Google Ads", tiktok: "TikTok Ads" };
280
+ /** analytics ads and analytics meta-ads (the same response shape). */
281
+ function renderAds(d) {
282
+ if (!d.configured)
283
+ return d.reason === "no_account"
284
+ ? "An ad network is connected but no ad account is chosen yet. Pick one in Settings → Integrations."
285
+ : "No ad network is connected for this website. Connect Meta Ads or Google Ads in the dashboard: https://metricraven.com/docs/meta-ads";
286
+ const cur = d.period?.currency ?? "USD";
287
+ const t = d.totals;
288
+ const roas = (v) => (v === null || v === undefined ? "–" : `${num(v, 2)}x`);
289
+ const combined = (d.accounts?.length ?? 0) > 1;
290
+ const label = d.level === "ad" ? "Ad" : d.level === "adset" || d.level === "adgroup" ? (d.provider === "meta" ? "Ad set" : "Ad group") : "Campaign";
291
+ return [
292
+ ...(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})`)),
293
+ `${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)}`,
294
+ ...(d.accounts ?? []).flatMap((a) => [
295
+ a.sync.error ? dim(`${NETWORKS[a.provider] ?? a.provider} sync: ${a.sync.error}`) : "",
296
+ a.unconvertedSpend ? dim(`${money(a.unconvertedSpend, a.currency)} of ${NETWORKS[a.provider] ?? a.provider} spend has no exchange rate yet and is left out.`) : "",
297
+ ]),
298
+ section(`${label}s`, d.rows?.length
299
+ ? table([label, ...(combined ? ["Network"] : []), "Spend", "Link clicks", "Ad visitors", "Customers", "Revenue", "ROAS", "Cost/customer", "Assisted"], d.rows.slice(0, 15).map((r) => [
300
+ truncate(r.name, 40),
301
+ ...(combined ? [(NETWORKS[r.provider ?? ""] ?? r.provider ?? "").replace(" Ads", "")] : []),
302
+ money(r.spend, cur),
303
+ num(r.linkClicks),
304
+ num(r.visitors),
305
+ num(r.customers),
306
+ money(r.revenue, cur),
307
+ roas(r.roas),
308
+ r.costPerCustomer === null ? "–" : money(r.costPerCustomer, cur),
309
+ money(r.assistedRevenue ?? 0, cur),
310
+ ]), ["left", ...(combined ? ["left"] : []), "right", "right", "right", "right", "right", "right", "right", "right"])
311
+ : dim("No ad spend or attributed visits in this period.")),
312
+ ...(d.accounts ?? [])
313
+ .filter((a) => a.unattributed.visitors || a.unattributed.revenue)
314
+ .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.`)),
315
+ ]
316
+ .filter(Boolean)
317
+ .join("\n");
318
+ }
214
319
  function periodLine(p) {
215
320
  if (!p?.from || !p.to)
216
321
  return "";
@@ -273,15 +378,21 @@ const RENDER = {
273
378
  ].join("\n");
274
379
  },
275
380
  conversions(d) {
381
+ // Hidden goals (Settings → Goals) stay out of the table, like the dashboard; --json has them all.
382
+ const shown = d.goals.filter((g) => !g.hidden);
383
+ const hidden = d.goals.length - shown.length;
276
384
  return [
277
385
  periodLine(d.period),
278
- section("Goals", d.goals.length
279
- ? table(["Goal", "Visitors", "Completions", "Rate"], d.goals.map((g) => [truncate(g.name), num(g.visitors), num(g.events), pct(g.rate, 2)]), ["left", "right", "right", "right"])
386
+ section("Goals", shown.length
387
+ ? 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"])
280
388
  : dim("No goals in this period.")),
389
+ hidden ? dim(`${num(hidden)} hidden goal${hidden === 1 ? "" : "s"} not shown (see --json or \`metricraven goals list\`).`) : "",
281
390
  d.funnel?.length
282
- ? section("Funnel", table(["Step", "Visitors", "From start"], d.funnel.map((s) => [s.step, num(s.visitors), pct(s.fromStart, 0)]), ["left", "right", "right"]))
391
+ ? 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"]))
283
392
  : "",
284
- ].join("\n");
393
+ ]
394
+ .filter(Boolean)
395
+ .join("\n");
285
396
  },
286
397
  insights(d) {
287
398
  const o = d.overview;
@@ -314,6 +425,8 @@ const RENDER = {
314
425
  : dim("No queries.")),
315
426
  ].join("\n");
316
427
  },
428
+ ads: (d) => renderAds(d),
429
+ "meta-ads": (d) => renderAds(d),
317
430
  crawlers(d) {
318
431
  return [
319
432
  periodLine(d.period),
@@ -327,7 +440,8 @@ const RENDER = {
327
440
  const t = d.totals;
328
441
  return [
329
442
  periodLine(d.period),
330
- `${bold(d.name)}: ${num(t.events)} completions by ${num(t.people)} visitors · ${pct(t.rate, 2)} of ${num(t.visitors)} visitors`,
443
+ `${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`,
444
+ d.description ? dim(d.description) : "",
331
445
  d.sources.length
332
446
  ? section("Sources", table(["Source", "Visitors"], d.sources.slice(0, 10).map((s) => [s.name, num(s.visitors)]), ["left", "right"]))
333
447
  : "",
@@ -339,8 +453,9 @@ const RENDER = {
339
453
  };
340
454
  async function realtime(ctx) {
341
455
  const params = new URLSearchParams({ site: await ctx.site() });
456
+ const selected = selectFields(ctx.flags, params);
342
457
  const d = await ctx.client.get("/stats/live", params);
343
- if (ctx.flags.json)
458
+ if (ctx.flags.json || selected)
344
459
  return printJson(d), 0;
345
460
  out(`${bold(num(d.visitorsNow))} visitor${d.visitorsNow === 1 ? "" : "s"} online now`);
346
461
  if (d.visitors.length)
@@ -361,6 +476,7 @@ async function listVisitors(ctx) {
361
476
  params.set("q", flags.q);
362
477
  if (flags.payment)
363
478
  params.set("payment", flags.payment);
479
+ visitorSearchParams(flags, params);
364
480
  if (flags.sort)
365
481
  params.set("sort", flags.sort);
366
482
  const limit = positiveInt(flags.limit, "limit", 100);
@@ -370,8 +486,9 @@ async function listVisitors(ctx) {
370
486
  if (offset !== undefined)
371
487
  params.set("offset", String(offset));
372
488
  params.set("site", await ctx.site());
489
+ const selected = selectFields(flags, params);
373
490
  const d = await ctx.client.get("/stats/visitors", params).catch((e) => needs("visitors", Promise.reject(e)));
374
- if (flags.json)
491
+ if (flags.json || selected)
375
492
  return printJson(d), 0;
376
493
  if (!d.rows.length)
377
494
  return out(dim("No visitors match.")), 0;
@@ -485,6 +602,118 @@ async function listMentions(ctx) {
485
602
  out(dim(`Showing ${d.pagination.offset + 1}–${d.pagination.offset + d.data.length} of ${d.pagination.total}. Use --offset for more.`));
486
603
  return 0;
487
604
  }
605
+ /** AI visibility from the latest weekly check (Growth). Reads only; never starts a check. */
606
+ async function aiVisibility(ctx) {
607
+ const params = rangeParams({ ...ctx.flags, filter: undefined, period: ctx.flags.period ?? "90d" });
608
+ params.set("site", await ctx.site());
609
+ // --filter model:is:claude, mention:is:not_mentioned, citedDomain:is_not:example.com …
610
+ const filters = buildFilters(ctx.flags.filter);
611
+ if (filters.length)
612
+ params.set("filters", JSON.stringify(filters));
613
+ const d = await ctx.client.get("/stats/ai-visibility", params);
614
+ if (ctx.flags.json)
615
+ return printJson(d), 0;
616
+ if (d.meta.locked)
617
+ return out(d.meta.message ?? "AI visibility needs the Growth plan."), 0;
618
+ const s = d.latestRun?.summary;
619
+ if (!s)
620
+ return out(dim("No AI visibility checks yet. Add prompts in the dashboard's AI visibility tab.")), 0;
621
+ const pct = (n) => `${Math.round(n * 100)}%`;
622
+ const pos = (n) => (n === null ? "—" : `#${n.toFixed(1)}`);
623
+ out(`${d.meta.brand}${d.meta.sample ? " (sample data)" : ""} · latest check ${d.latestRun?.completedAt ? date(d.latestRun.completedAt) : "—"}`);
624
+ 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)}`);
625
+ if (d.trend.length > 1)
626
+ out(dim(`Trend: ${d.trend.map((t) => Math.round(t.summary.visibilityScore)).join(" → ")}`));
627
+ out("");
628
+ 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)])));
629
+ out("");
630
+ 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)])));
631
+ if (d.credits)
632
+ out(dim(`Credits: ${num(d.credits.used)} of ${num(d.credits.allowance)} used, resets ${date(d.credits.resetsAt)}`));
633
+ return 0;
634
+ }
635
+ /** "Signup started (signup_started)" when the goal has a display name, else the raw name. */
636
+ const goalText = (g) => g.displayName && g.displayName !== g.name ? `${g.displayName} (${g.name})` : g.name;
637
+ /** `metricraven goals …`: how goals are shown (display name, colour, description, hidden). */
638
+ async function goals(ctx, sub, rest) {
639
+ const { flags, client } = ctx;
640
+ const site = await ctx.site();
641
+ const params = () => new URLSearchParams({ site });
642
+ const colorText = (hex, colors) => (hex ? (colors.find((c) => c.color === hex)?.label ?? hex) : "–");
643
+ const goalArg = () => {
644
+ if (!rest[0])
645
+ throw new UsageError(`Use: metricraven goals ${sub} <goal> (the raw goal name, as tracked).`);
646
+ return rest[0];
647
+ };
648
+ switch (sub ?? "list") {
649
+ case "list": {
650
+ const p = params();
651
+ if (rest[0])
652
+ p.set("goal", rest[0]);
653
+ const d = await client.get("/goals/customizations", p);
654
+ if (flags.json)
655
+ return printJson(d), 0;
656
+ if (!d.customizations.length)
657
+ return out(dim("No goal customisations yet. Use `metricraven goals set <goal> --name <label>`.")), 0;
658
+ 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) : "–"])));
659
+ return 0;
660
+ }
661
+ case "colors":
662
+ case "colours": {
663
+ const d = await client.get("/goals/customizations", params());
664
+ if (flags.json)
665
+ return printJson(d.colors), 0;
666
+ out(table(["Colour", "Hex", "Family"], d.colors.map((c) => [c.label, c.color, c.family])));
667
+ return 0;
668
+ }
669
+ case "set": {
670
+ const goal = goalArg();
671
+ if (flags.hidden && flags.visible)
672
+ throw new UsageError("Use --hidden or --visible, not both.");
673
+ const body = { goal };
674
+ if (flags.name !== undefined)
675
+ body.displayName = flags.name || null;
676
+ if (flags.description !== undefined)
677
+ body.description = flags.description || null;
678
+ if (flags.color !== undefined) {
679
+ if (!flags.color)
680
+ body.color = null;
681
+ else if (flags.color.startsWith("#"))
682
+ body.color = flags.color.toLowerCase();
683
+ else {
684
+ const { colors } = await client.get("/goals/customizations", params());
685
+ const match = colors.find((c) => c.label.toLowerCase() === flags.color.toLowerCase());
686
+ if (!match)
687
+ throw new UsageError(`Unknown colour "${flags.color}". Use one of: ${colors.map((c) => c.label).join(", ")} (or a hex from \`metricraven goals colors\`).`);
688
+ body.color = match.color;
689
+ }
690
+ }
691
+ if (flags.hidden)
692
+ body.hidden = true;
693
+ if (flags.visible)
694
+ body.hidden = false;
695
+ if (Object.keys(body).length === 1)
696
+ throw new UsageError("Nothing to change. Use --name, --color, --description, --hidden or --visible.");
697
+ const d = await needs("write", client.put("/goals/customizations", body, params()));
698
+ if (flags.json)
699
+ return printJson(d), 0;
700
+ const c = d.customization;
701
+ out(`Saved ${bold(goalText({ name: c.goal, displayName: c.displayName }))}: colour ${colorText(c.color, d.colors)}, ${c.hidden ? "hidden" : "visible"}.`);
702
+ return 0;
703
+ }
704
+ case "reset": {
705
+ const goal = goalArg();
706
+ const p = params();
707
+ p.set("goal", goal);
708
+ const d = await needs("write", client.del("/goals/customizations", p));
709
+ if (flags.json)
710
+ return printJson(d), 0;
711
+ out(`Reset ${goal}: raw name, default colour, visible.`);
712
+ return 0;
713
+ }
714
+ }
715
+ throw new UsageError(`Unknown command "goals ${sub}". Use list, set, reset or colors.`);
716
+ }
488
717
  const triggerText = (t) => (t.type === "goal" ? `goal ${t.goalName}` : t.type === "payment" ? "any payment" : "new customer");
489
718
  /** `metricraven alerts …`: conversion alerts on the website (list/get/create/update/delete/history). */
490
719
  async function alerts(ctx, sub, rest) {
@@ -680,6 +909,467 @@ async function members(ctx, sub, rest) {
680
909
  }
681
910
  throw new UsageError(`Unknown command "members ${sub}". Use list, invite, role, remove or revoke.`);
682
911
  }
912
+ function printBotSettings(d) {
913
+ const list = (v) => (v.length ? v.join(", ") : "none");
914
+ out(`Excluded companies: ${list(d.settings.excludedCompanies)}`);
915
+ out(`Excluded agents: ${list(d.settings.excludedAgents)}`);
916
+ 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)"}`);
917
+ out(`Require bot token: ${d.settings.rejectWithoutToken ? "yes" : "no"}`);
918
+ }
919
+ /** `metricraven bots …`: bot traffic settings (exclusions, token enforcement) and the bot request allowance. */
920
+ async function bots(ctx, sub, rest) {
921
+ const { flags, client } = ctx;
922
+ const site = await ctx.site();
923
+ const params = () => new URLSearchParams({ site });
924
+ switch (sub ?? "settings") {
925
+ case "settings": {
926
+ const d = await client.get("/bot-traffic/settings", params());
927
+ if (flags.json)
928
+ return printJson(d), 0;
929
+ printBotSettings(d.data);
930
+ const rows = d.data.catalog.map((c) => {
931
+ const excluded = c.agents.filter((a) => a.excluded).map((a) => a.agent);
932
+ return [c.company, c.status, c.status === "partial" ? excluded.join(", ") : c.agents.map((a) => a.agent).join(", ")];
933
+ });
934
+ out(section("Known crawlers", table(["Company", "Status", "Agents"], rows.map((r) => [r[0], r[1], truncate(r[2], 60)]))));
935
+ return 0;
936
+ }
937
+ case "usage": {
938
+ const d = await client.get("/bot-traffic/usage", params());
939
+ if (flags.json)
940
+ return printJson(d), 0;
941
+ const u = d.data;
942
+ out(`${bold(num(u.usage))}${u.allowance === null ? " bot requests (no limit)" : ` of ${num(u.allowance)} bot requests (${pct(u.percentUsed ?? 0)})`}`);
943
+ if (u.paused)
944
+ out(`Bot tracking is paused until ${date(u.resetAt)}${u.dropped ? `; ${num(u.dropped)} requests not recorded` : ""}.`);
945
+ else
946
+ out(dim(`Resets ${date(u.resetAt)}.${u.enforced || u.allowance === null ? "" : " The allowance isn't enforced on this account yet."}`));
947
+ if (u.websites.length)
948
+ out(section("By website", table(["Website", "Requests"], u.websites.map((w) => [w.name, num(w.requests)]))));
949
+ return 0;
950
+ }
951
+ case "exclude":
952
+ case "include": {
953
+ if (!rest.length)
954
+ throw new UsageError(`Use: metricraven bots ${sub} <name…> [--company] (names from \`metricraven bots settings\`).`);
955
+ const key = `${sub === "exclude" ? "disable" : "enable"}${flags.company ? "Companies" : "Agents"}`;
956
+ const d = await needs("write", client.patch("/bot-traffic/settings", { [key]: rest }, params()));
957
+ if (flags.json)
958
+ return printJson(d), 0;
959
+ const what = flags.company ? (rest.length === 1 ? "company" : "companies") : rest.length === 1 ? "agent" : "agents";
960
+ out(d.changed ? `${sub === "exclude" ? "Excluded" : "Included"} ${what} ${rest.join(", ")}. This applies to new crawl events.` : "Nothing changed.");
961
+ printBotSettings(d.data);
962
+ return 0;
963
+ }
964
+ case "require-token": {
965
+ const value = rest[0];
966
+ if (value !== "on" && value !== "off")
967
+ throw new UsageError("Use: metricraven bots require-token on|off");
968
+ const d = await needs("write", client.patch("/bot-traffic/settings", { rejectWithoutToken: value === "on" }, params()));
969
+ if (flags.json)
970
+ return printJson(d), 0;
971
+ out(value === "on" ? "Crawl events without the bot token are now refused." : "Crawl events sent with the secret key are accepted again.");
972
+ return 0;
973
+ }
974
+ }
975
+ throw new UsageError(`Unknown command "bots ${sub}". Use settings, usage, exclude, include or require-token.`);
976
+ }
977
+ const PROXY_STATUS = {
978
+ pending_dns: "Waiting for DNS",
979
+ issuing_certificate: "Issuing certificate",
980
+ active: "Active",
981
+ error: "Needs attention",
982
+ };
983
+ function printProxy(d) {
984
+ const p = d.proxy;
985
+ if (!p) {
986
+ if (!d.available)
987
+ return out("The managed proxy isn't available on this server.");
988
+ out(`No managed proxy. Enable one with \`metricraven proxy enable a.<your-domain>\`; it CNAMEs to ${d.target}.`);
989
+ return;
990
+ }
991
+ out(`${bold(p.hostname)} ${PROXY_STATUS[p.status] ?? p.status}${p.checkedAt ? dim(` (checked ${date(p.checkedAt)})`) : ""}`);
992
+ if (p.error)
993
+ out(p.error);
994
+ if (p.status !== "active")
995
+ 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"]))));
996
+ else
997
+ out(section("Script tag", p.snippet));
998
+ }
999
+ /** `metricraven proxy …`: the managed proxy subdomain (one CNAME; MetricRaven serves the script there). */
1000
+ async function managedProxy(ctx, sub, rest) {
1001
+ const { flags, client } = ctx;
1002
+ const site = await ctx.site();
1003
+ const params = () => new URLSearchParams({ site });
1004
+ const done = (d) => {
1005
+ if (flags.json)
1006
+ printJson(d);
1007
+ else
1008
+ printProxy(d.data);
1009
+ return 0;
1010
+ };
1011
+ switch (sub ?? "status") {
1012
+ case "status":
1013
+ return done(await client.get("/managed-proxy", params()));
1014
+ case "enable": {
1015
+ if (!rest[0])
1016
+ throw new UsageError("Use: metricraven proxy enable <subdomain>, e.g. a.example.com");
1017
+ return done(await needs("write", client.post("/managed-proxy", { hostname: rest[0] }, params())));
1018
+ }
1019
+ case "check":
1020
+ return done(await needs("write", client.post("/managed-proxy/check", {}, params())));
1021
+ case "remove": {
1022
+ if (!flags.yes) {
1023
+ if (!interactive())
1024
+ throw new UsageError("Add --yes to remove without a prompt.");
1025
+ const answer = await prompt("Remove the managed proxy? The script stops loading from that subdomain at once. [y/N] ");
1026
+ if (!/^y(es)?$/i.test(answer))
1027
+ return out("Kept."), 0;
1028
+ }
1029
+ const d = await needs("write", client.del("/managed-proxy", params()));
1030
+ if (flags.json)
1031
+ return printJson(d), 0;
1032
+ out("Removed. Delete the DNS record and point your script tag back at metricraven.com.");
1033
+ return 0;
1034
+ }
1035
+ }
1036
+ throw new UsageError(`Unknown command "proxy ${sub}". Use status, enable, check or remove.`);
1037
+ }
1038
+ // ---------------------------------------------------------------------------------------------
1039
+ // Account profile, websites get/update/delete, access tokens, data deletion, visitor search
1040
+ /** Destructive commands ask first; --yes skips the question (and is required without a terminal). */
1041
+ async function confirmOrStop(flags, question) {
1042
+ if (flags.yes)
1043
+ return true;
1044
+ if (!interactive() || flags.json)
1045
+ throw new UsageError("Add --yes to do this without a prompt.");
1046
+ const answer = await prompt(`${question} [y/N] `);
1047
+ if (/^y(es)?$/i.test(answer))
1048
+ return true;
1049
+ out("Nothing changed.");
1050
+ return false;
1051
+ }
1052
+ async function updateAccount({ flags, client }) {
1053
+ if (flags.name === undefined)
1054
+ throw new UsageError('Use: metricraven account update --name "Your name" (pass "" to clear).');
1055
+ const account = await needs("write", client.patch("/account", { name: flags.name.trim() || null }));
1056
+ if (flags.json)
1057
+ return printJson(account), 0;
1058
+ out(`Name: ${account.user.name ?? dim("(none)")} · ${account.user.email}`);
1059
+ return 0;
1060
+ }
1061
+ async function websiteId(ctx, id) {
1062
+ return id ?? (await ctx.site());
1063
+ }
1064
+ async function getWebsite(ctx, id) {
1065
+ const siteId = await websiteId(ctx, id);
1066
+ const d = await ctx.client.get(`/websites/${encodeURIComponent(siteId)}`);
1067
+ if (ctx.flags.json)
1068
+ return printJson(d), 0;
1069
+ const w = d.website;
1070
+ out(bold(w.name));
1071
+ out(`ID: ${w.id}`);
1072
+ out(`Domains: ${w.domains.join(", ") || "–"}`);
1073
+ if (w.appIds.length)
1074
+ out(`Apps: ${w.appIds.join(", ")}`);
1075
+ out(`Your role: ${w.role}`);
1076
+ if (w.createdAt)
1077
+ out(dim(`Created ${date(w.createdAt)}`));
1078
+ return 0;
1079
+ }
1080
+ async function updateWebsite(ctx, id) {
1081
+ const { flags, client } = ctx;
1082
+ const body = {};
1083
+ if (flags.name !== undefined)
1084
+ body.name = flags.name.trim();
1085
+ if (flags.domain !== undefined)
1086
+ body.domains = flags.domain.split(",").map((d) => d.trim()).filter(Boolean);
1087
+ if (!body.name && !body.domains?.length)
1088
+ throw new UsageError("Use: metricraven websites update [<website_id>] --name <name> and/or --domain example.com[,other.com] (replaces the domains).");
1089
+ const siteId = await websiteId(ctx, id);
1090
+ const d = await needs("write", client.patch(`/websites/${encodeURIComponent(siteId)}`, body));
1091
+ if (flags.json)
1092
+ return printJson(d), 0;
1093
+ out(`Updated ${bold(d.website.name)} (${d.website.domains.join(", ")}).`);
1094
+ return 0;
1095
+ }
1096
+ /**
1097
+ * Deleting a website asks for the same confirmation as the dashboard: type its domain. --yes is
1098
+ * not enough; without a terminal, pass the domain with --domain to confirm.
1099
+ */
1100
+ async function deleteWebsiteCommand(ctx, id) {
1101
+ const { flags, client } = ctx;
1102
+ if (!id)
1103
+ throw new UsageError("Use: metricraven websites delete <website_id> (the ID is required here; see `metricraven websites list`).");
1104
+ const { website } = await client.get(`/websites/${encodeURIComponent(id)}`);
1105
+ if (website.role !== "owner")
1106
+ throw new UsageError(`Only the owner can delete ${website.name}; your role is ${website.role}.`);
1107
+ const expected = website.domains[0] ?? website.name;
1108
+ let typed = flags.domain?.trim();
1109
+ if (!typed) {
1110
+ if (!interactive() || flags.json)
1111
+ throw new UsageError(`Deleting a website needs confirmation: add --domain ${expected} (the website's domain).`);
1112
+ out(`This permanently deletes ${bold(website.name)} and all of its data: pageviews, goals, payments, visitors, funnels, alerts and integrations.`);
1113
+ typed = await prompt(`Type ${expected} to confirm: `);
1114
+ }
1115
+ if (typed.toLowerCase() !== expected.toLowerCase()) {
1116
+ out("That doesn't match. Nothing was deleted.");
1117
+ return 1;
1118
+ }
1119
+ const d = await needs("write", client.del(`/websites/${encodeURIComponent(id)}`, new URLSearchParams({ confirm: typed })));
1120
+ if (flags.json)
1121
+ return printJson(d), 0;
1122
+ const total = Object.values(d.deleted).reduce((a, b) => a + b, 0);
1123
+ out(`Deleted ${website.name} (${d.id}) and ${num(total)} stored records.`);
1124
+ const config = await readConfig();
1125
+ if (config.site === d.id) {
1126
+ await updateConfig({ site: undefined });
1127
+ out(dim("It was your default website; run `metricraven use <id>` to pick another."));
1128
+ }
1129
+ return 0;
1130
+ }
1131
+ async function tokens(ctx, sub, rest) {
1132
+ const { flags, client } = ctx;
1133
+ switch (sub ?? "list") {
1134
+ case "list": {
1135
+ const d = await client.get("/tokens");
1136
+ if (flags.json)
1137
+ return printJson(d), 0;
1138
+ if (!d.tokens.length)
1139
+ return out(dim("No tokens.")), 0;
1140
+ out(table(["", "Name", "Token", "Access", "Websites", "Last used", "ID"], d.tokens.map((t) => [
1141
+ t.current ? "*" : "",
1142
+ t.name,
1143
+ t.hint,
1144
+ scopes(t.scopes),
1145
+ t.siteIds === null ? "all" : t.siteIds.join(", "),
1146
+ t.lastUsedAt ? date(t.lastUsedAt) : "never",
1147
+ t.id,
1148
+ ])));
1149
+ out(dim("* = the token this CLI is using"));
1150
+ return 0;
1151
+ }
1152
+ case "create": {
1153
+ const name = flags.name?.trim();
1154
+ if (!name)
1155
+ throw new UsageError("Use: metricraven tokens create --name <label> [--scopes read,visitors,write] [--sites <id,id>]");
1156
+ const requested = (flags.scopes ?? "read").split(",").map((s) => s.trim()).filter(Boolean);
1157
+ const unknown = requested.filter((s) => !["read", "visitors", "write"].includes(s));
1158
+ if (unknown.length)
1159
+ throw new UsageError(`Unknown scope ${unknown.join(", ")}. Use read, visitors and/or write.`);
1160
+ const body = { name, scopes: requested };
1161
+ if (flags.sites !== undefined)
1162
+ body.siteIds = flags.sites === "all" ? null : flags.sites.split(",").map((s) => s.trim()).filter(Boolean);
1163
+ const d = await needs("write", client.post("/tokens", body));
1164
+ if (flags.json)
1165
+ return printJson(d), 0;
1166
+ out(`Created "${d.token.name}" (${scopes(d.token.scopes)}; websites: ${d.token.siteIds === null ? "all" : d.token.siteIds.join(", ")}).`);
1167
+ out(`Token: ${d.value}`);
1168
+ out(dim("Shown once. Store it somewhere safe, e.g. METRICRAVEN_TOKEN in your CI secrets."));
1169
+ return 0;
1170
+ }
1171
+ case "delete":
1172
+ case "revoke": {
1173
+ const id = rest[0];
1174
+ if (!id)
1175
+ throw new UsageError("Use: metricraven tokens delete <token_id> (IDs from `metricraven tokens list`).");
1176
+ const list = await client.get("/tokens");
1177
+ const target = list.tokens.find((t) => t.id === id);
1178
+ if (!target)
1179
+ throw new UsageError(`No token "${id}". Run \`metricraven tokens list\`.`);
1180
+ const warning = target.current ? " This is the token the CLI is using; you'll need to log in again." : "";
1181
+ if (!(await confirmOrStop(flags, `Delete token "${target.name}" (${target.hint})? It stops working at once.${warning}`)))
1182
+ return 0;
1183
+ const d = await needs("write", client.del(`/tokens/${encodeURIComponent(id)}`));
1184
+ if (flags.json)
1185
+ return printJson(d), 0;
1186
+ out(`Deleted token "${target.name}".`);
1187
+ if (d.current)
1188
+ out(dim("That was this CLI's token. Run `metricraven login` with another one."));
1189
+ return 0;
1190
+ }
1191
+ }
1192
+ throw new UsageError(`Unknown command "tokens ${sub}". Use list, create or delete.`);
1193
+ }
1194
+ /** --from/--to (calendar days in --timezone) as the API's startAt/endAt. */
1195
+ function deletionRange(flags, params) {
1196
+ if (!flags.from && !flags.to)
1197
+ return;
1198
+ if (!flags.from || !flags.to)
1199
+ throw new UsageError("Use --from and --to together (YYYY-MM-DD, inclusive).");
1200
+ const zone = validTimeZone(flags.timezone);
1201
+ if (!zone)
1202
+ throw new UsageError(`Unknown timezone "${flags.timezone}".`);
1203
+ const range = customRange(flags.from, flags.to, zone);
1204
+ if (!range)
1205
+ throw new UsageError("--from and --to must be real dates like 2026-10-01, with --from on or before --to.");
1206
+ params.set("startAt", range.from.toISOString());
1207
+ params.set("endAt", range.to.toISOString());
1208
+ }
1209
+ const plural = (what, n) => (n === 1 ? what.replace(/s$/, "") : what);
1210
+ /** Counts first (dry run), asks, then deletes. */
1211
+ async function deleteWithCount(ctx, path, params, what) {
1212
+ const { flags, client } = ctx;
1213
+ params.set("site", await ctx.site());
1214
+ const preview = await needs("write", client.del(path, new URLSearchParams([...params, ["dry_run", "1"]])));
1215
+ if (flags["dry-run"]) {
1216
+ if (flags.json)
1217
+ return printJson(preview), 0;
1218
+ return out(`${num(preview.matched)} ${plural(what, preview.matched)} would be deleted.`), 0;
1219
+ }
1220
+ if (!preview.matched) {
1221
+ if (flags.json)
1222
+ return printJson(preview), 0;
1223
+ return out(`No ${what} match. Nothing to delete.`), 0;
1224
+ }
1225
+ if (!(await confirmOrStop(flags, `Permanently delete ${num(preview.matched)} ${plural(what, preview.matched)}? Reports change at once.`)))
1226
+ return 0;
1227
+ const d = await needs("write", client.del(path, params));
1228
+ if (flags.json)
1229
+ return printJson(d), 0;
1230
+ out(`Deleted ${num(d.deleted)} ${plural(what, d.deleted)}.`);
1231
+ return 0;
1232
+ }
1233
+ async function deletePayments(ctx) {
1234
+ const { flags } = ctx;
1235
+ const params = new URLSearchParams();
1236
+ if (flags.transaction)
1237
+ params.set("transaction_id", flags.transaction);
1238
+ if (flags.visitor)
1239
+ params.set("visitor_id", flags.visitor);
1240
+ if (flags.user)
1241
+ params.set("user_id", flags.user);
1242
+ if (!flags.transaction)
1243
+ deletionRange(flags, params);
1244
+ if (![...params].length)
1245
+ throw new UsageError("Use: metricraven payments delete --transaction <id> | --visitor <id> | --user <id> [--from --to] | --from <day> --to <day>");
1246
+ return deleteWithCount(ctx, "/payments", params, "payments");
1247
+ }
1248
+ async function deleteGoalEvents(ctx) {
1249
+ const { flags } = ctx;
1250
+ const params = new URLSearchParams();
1251
+ if (flags.goal)
1252
+ params.set("name", flags.goal);
1253
+ if (flags.visitor)
1254
+ params.set("visitor_id", flags.visitor);
1255
+ if (flags.user)
1256
+ params.set("user_id", flags.user);
1257
+ deletionRange(flags, params);
1258
+ if (![...params].length)
1259
+ throw new UsageError("Use: metricraven goals delete-events --goal <name> | --visitor <id> | --user <id> [--from --to] | --from <day> --to <day>");
1260
+ return deleteWithCount(ctx, "/events", params, "goal events");
1261
+ }
1262
+ /** visitors list search flags, sent as the explorer's shortcut parameters. */
1263
+ function visitorSearchParams(flags, params) {
1264
+ const map = [
1265
+ ["page", "visitedPage"],
1266
+ ["page-contains", "visitedPageContains"],
1267
+ ["goal", "completedGoal"],
1268
+ ["referrer", "referrer"],
1269
+ ["channel", "channel"],
1270
+ ["source", "source"],
1271
+ ["utm-source", "utm_source"],
1272
+ ["utm-medium", "utm_medium"],
1273
+ ["utm-campaign", "utm_campaign"],
1274
+ ["country", "country"],
1275
+ ["device", "device"],
1276
+ ["browser", "browser"],
1277
+ ["os", "os"],
1278
+ ];
1279
+ for (const [flag, param] of map) {
1280
+ const value = flags[flag];
1281
+ if (typeof value === "string" && value.trim())
1282
+ params.set(param, value.trim());
1283
+ }
1284
+ const gt = positiveInt(flags["visits-gt"], "visits-gt", 100_000);
1285
+ if (gt !== undefined)
1286
+ params.set("visits_gt", String(gt));
1287
+ const lt = positiveInt(flags["visits-lt"], "visits-lt", 100_000);
1288
+ if (lt !== undefined)
1289
+ params.set("visits_lt", String(lt));
1290
+ }
1291
+ const GRACES = ["none", "24h", "7d"];
1292
+ async function siteKeys(ctx, sub, rest) {
1293
+ const { flags, client } = ctx;
1294
+ const site = await ctx.site();
1295
+ const params = () => new URLSearchParams({ site });
1296
+ const keyPath = (id, suffix = "") => {
1297
+ if (!id)
1298
+ throw new UsageError(`Use: metricraven websites keys ${sub} <key_id> (IDs from \`metricraven websites keys list\`; "default" for the default key).`);
1299
+ return `/site/keys/${encodeURIComponent(id)}${suffix}`;
1300
+ };
1301
+ const confirm = async (question) => {
1302
+ if (flags.yes)
1303
+ return true;
1304
+ if (!interactive() || flags.json)
1305
+ throw new UsageError("Add --yes to do this without a prompt.");
1306
+ return /^y(es)?$/i.test(await prompt(`${question} [y/N] `));
1307
+ };
1308
+ const showSecret = (key, secretKey) => {
1309
+ out(`Secret key for "${key.name}" (${key.id}): ${secretKey}`);
1310
+ out(dim("Shown once. Keep it on your server, never in browser code."));
1311
+ };
1312
+ switch (sub ?? "list") {
1313
+ case "list": {
1314
+ const d = await needs("write", client.get("/site/keys", params()));
1315
+ if (flags.json)
1316
+ return printJson(d), 0;
1317
+ out(table(["Name", "Key", "Created", "Last used", "ID"], [
1318
+ ...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]),
1319
+ ...d.previous.map((k) => [`${k.name}, previous`, k.hint ?? "ana_sec_…", `until ${date(k.expiresAt)}`, k.lastUsedAt ? date(k.lastUsedAt) : "never", k.keyId]),
1320
+ ]));
1321
+ out(dim(`${d.keys.length - 1} of ${d.maxNamedKeys} named keys.`));
1322
+ return 0;
1323
+ }
1324
+ case "create": {
1325
+ const name = flags.name ?? rest[0];
1326
+ if (!name)
1327
+ throw new UsageError("Use: metricraven websites keys create --name <label>");
1328
+ const d = await needs("write", client.post("/site/keys", { name }, params()));
1329
+ if (flags.json)
1330
+ return printJson(d), 0;
1331
+ showSecret(d.key, d.secretKey);
1332
+ return 0;
1333
+ }
1334
+ case "rename": {
1335
+ const path = keyPath(rest[0]);
1336
+ if (!flags.name)
1337
+ throw new UsageError("Use: metricraven websites keys rename <key_id> --name <label>");
1338
+ const d = await needs("write", client.patch(path, { name: flags.name }, params()));
1339
+ if (flags.json)
1340
+ return printJson(d), 0;
1341
+ out(`Renamed ${d.key.id} to "${d.key.name}".`);
1342
+ return 0;
1343
+ }
1344
+ case "revoke":
1345
+ case "delete": {
1346
+ const path = keyPath(rest[0]);
1347
+ if (!(await confirm(`Revoke key ${rest[0]}? Servers using it fail with 401 at once.`)))
1348
+ return out("Kept."), 0;
1349
+ const d = await needs("write", client.del(path, params()));
1350
+ if (flags.json)
1351
+ return printJson(d), 0;
1352
+ out(`Revoked key ${d.id}.`);
1353
+ return 0;
1354
+ }
1355
+ case "roll":
1356
+ case "rotate": {
1357
+ const path = keyPath(rest[0], "/roll");
1358
+ const grace = flags.grace ?? "none";
1359
+ if (!GRACES.includes(grace))
1360
+ throw new UsageError("--grace must be none, 24h or 7d.");
1361
+ const keep = grace === "none" ? "stops working at once" : `keeps working for ${grace}`;
1362
+ if (!(await confirm(`Roll key ${rest[0]}? Its current value ${keep}.`)))
1363
+ return out("Kept."), 0;
1364
+ const d = await needs("write", client.post(path, { grace }, params()));
1365
+ if (flags.json)
1366
+ return printJson(d), 0;
1367
+ showSecret(d.key, d.secretKey);
1368
+ return 0;
1369
+ }
1370
+ }
1371
+ throw new UsageError(`Unknown command "websites keys ${sub}". Use list, create, rename, revoke or roll.`);
1372
+ }
683
1373
  /** The API answers 401 for a missing scope too; name the access the command needs. */
684
1374
  async function needs(access, request) {
685
1375
  try {
@@ -1,18 +1,24 @@
1
1
  import { UsageError } from "./args.js";
2
2
  /** Shell completion scripts for `metricraven completion bash|zsh|fish`. */
3
- const COMMANDS = ["login", "logout", "whoami", "use", "websites", "analytics", "realtime", "visitors", "funnels", "notes", "mentions", "alerts", "members", "completion"];
3
+ const COMMANDS = ["login", "logout", "whoami", "account", "tokens", "payments", "use", "websites", "analytics", "realtime", "visitors", "funnels", "goals", "notes", "mentions", "ai-visibility", "alerts", "members", "bots", "proxy", "completion"];
4
4
  const SUB = {
5
- websites: ["list", "create"],
6
- analytics: ["traffic", "breakdown", "revenue", "conversions", "goal", "insights", "search", "crawlers"],
5
+ websites: ["list", "create", "get", "update", "delete", "keys"],
6
+ account: ["get", "update"],
7
+ tokens: ["list", "create", "delete"],
8
+ payments: ["delete"],
9
+ analytics: ["traffic", "breakdown", "revenue", "conversions", "goal", "insights", "search", "crawlers", "ads", "meta-ads"],
7
10
  visitors: ["list", "get"],
8
11
  funnels: ["list"],
12
+ goals: ["list", "set", "reset", "colors", "delete-events"],
9
13
  notes: ["list", "add"],
10
14
  mentions: ["list"],
11
15
  alerts: ["list", "get", "create", "update", "delete", "history"],
12
16
  members: ["list", "invite", "role", "remove", "revoke"],
17
+ bots: ["settings", "usage", "exclude", "include", "require-token"],
18
+ proxy: ["status", "enable", "check", "remove"],
13
19
  completion: ["bash", "zsh", "fish"],
14
20
  };
15
- const FLAGS = ["--json", "--site", "--token", "--verbose", "--help", "--version", "--period", "--from", "--to", "--timezone", "--filter", "--sort", "--limit", "--offset", "--q", "--payment", "--name", "--domain", "--date", "--text", "--goal", "--trigger", "--subject", "--message", "--notify", "--enabled", "--disabled", "--yes", "--alert", "--platform", "--role"];
21
+ const FLAGS = ["--json", "--fields", "--site", "--token", "--verbose", "--help", "--version", "--period", "--from", "--to", "--timezone", "--filter", "--compare", "--sort", "--limit", "--offset", "--q", "--payment", "--name", "--domain", "--date", "--text", "--goal", "--trigger", "--subject", "--message", "--notify", "--enabled", "--disabled", "--yes", "--alert", "--platform", "--role", "--color", "--description", "--hidden", "--visible", "--company", "--scopes", "--sites", "--transaction", "--visitor", "--user", "--dry-run", "--page", "--page-contains", "--referrer", "--channel", "--source", "--utm-source", "--utm-medium", "--utm-campaign", "--country", "--device", "--browser", "--os", "--visits-gt", "--visits-lt", "--grace", "--provider"];
16
22
  export function completionScript(shell) {
17
23
  if (shell === "bash") {
18
24
  const cases = Object.entries(SUB)
package/dist/format.js CHANGED
@@ -5,6 +5,22 @@ export const dim = (s) => (color ? `\x1b[2m${s}\x1b[22m` : s);
5
5
  const green = (s) => (color ? `\x1b[32m${s}\x1b[39m` : s);
6
6
  const red = (s) => (color ? `\x1b[31m${s}\x1b[39m` : s);
7
7
  const visibleLength = (s) => s.replace(/\x1b\[[0-9;]*m/g, "").length;
8
+ /** The only escape sequences the CLI writes itself: bold, dim, green, red and their resets. */
9
+ const OWN_STYLES = new Set(["\x1b[1m", "\x1b[22m", "\x1b[2m", "\x1b[32m", "\x1b[39m", "\x1b[31m"]);
10
+ /**
11
+ * Makes text safe to print to a terminal. Reports contain strings that visitors and third parties
12
+ * choose (event properties, names, mention text); escape sequences in them could clear or fake the
13
+ * screen, retitle the window, add hidden links or write the clipboard (OSC 52). Keeps newlines,
14
+ * tabs and the CLI's own colours; other escape sequences are removed and other control characters
15
+ * shown as "�".
16
+ */
17
+ export function terminalSafe(s) {
18
+ return s
19
+ .replace(
20
+ // OSC (titles, links, clipboard) and DCS/PM/APC strings up to BEL or ST; CSI; any other escape.
21
+ /\x1b[\]P^_][\s\S]*?(?:\x07|\x1b\\|$)|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-Z\\-_]?/g, (seq) => (OWN_STYLES.has(seq) ? seq : ""))
22
+ .replace(/[\u0000-\u0008\u000b-\u001a\u001c-\u001f\u007f-\u009f]/g, "\ufffd");
23
+ }
8
24
  export function num(n, digits = 0) {
9
25
  if (n === null || n === undefined || !Number.isFinite(n))
10
26
  return "–";
package/dist/index.js CHANGED
@@ -10,11 +10,28 @@ Account
10
10
  login Save an access token (from https://metricraven.com/app/api)
11
11
  logout Remove the saved token
12
12
  whoami Show the token's account, access and websites
13
+ account update --name <name> Change your display name ("" clears it; needs write)
14
+ tokens list Access tokens on the account (* = this one)
15
+ tokens create --name <label> [--scopes read,visitors,write] [--sites <id,id>|all];
16
+ never more access than the token you use; shown once
17
+ tokens delete <token_id> Delete a token (asks first; --yes to skip)
13
18
 
14
19
  Websites
15
20
  websites list Websites this token can use (* = default)
16
21
  websites create --name --domain
17
22
  Add a website; prints its ID, secret key and script
23
+ websites get [<website_id>] Name, domains, app IDs and your role
24
+ websites update [<website_id>] [--name <name>] [--domain a.com,b.com]
25
+ Rename or replace domains (needs write, admin)
26
+ websites delete <website_id> Delete a website and all its data (owner; you type its
27
+ domain, or pass --domain <domain> without a terminal)
28
+ websites keys list Secret keys (default and named): last used, IDs
29
+ websites keys create --name Add a named secret key (shown once)
30
+ websites keys rename <id> --name
31
+ websites keys revoke <id> Revoke a named key (asks first; --yes to skip)
32
+ websites keys roll <id> New value for a key ("default" for the default key);
33
+ --grace none|24h|7d keeps the old one working
34
+ (keys need write access, admin)
18
35
  use <website_id> Set the default website
19
36
 
20
37
  Reports (default: last 30 days)
@@ -28,14 +45,35 @@ Reports (default: last 30 days)
28
45
  analytics insights What converts: sources, countries, time to purchase
29
46
  analytics search Google Search Console queries
30
47
  analytics crawlers AI crawlers and bots
48
+ analytics ads [level] Ad spend, revenue and ROAS for every connected network
49
+ (campaign, adgroup or ad; --provider all|meta|google)
50
+ analytics meta-ads [level] Meta Ads spend, revenue and ROAS by campaign, adset or ad
31
51
  realtime Visitors online now
32
- visitors list Visitors in the period (needs visitor details access)
52
+ visitors list Visitors in the period (needs visitor details access);
53
+ search: --page, --page-contains, --goal, --referrer,
54
+ --channel, --source, --utm-source, --utm-medium,
55
+ --utm-campaign, --country, --device, --browser, --os,
56
+ --visits-gt <n>, --visits-lt <n> (visits in the period)
33
57
  visitors get <visitor_id> One visitor's journey (needs visitor details access)
34
58
  funnels list Saved funnels
59
+ goals list Goal display settings (name, colour, hidden)
60
+ goals set <goal> [--name <label>] [--color <hex|name>] [--description]
61
+ [--hidden | --visible] (needs write access, admin);
62
+ pass "" to clear a text field or colour
63
+ goals reset <goal> Back to the raw name, default colour, visible
64
+ goals colors Colours you can use
65
+ goals delete-events Delete goal events: --goal <name>, --visitor <id>,
66
+ --user <id>, --from/--to <day> (counts, then asks;
67
+ --yes to skip, --dry-run to only count; needs write)
68
+ payments delete Delete payments: --transaction <id>, --visitor <id>,
69
+ --user <id>, --from/--to <day> (same confirmation)
35
70
  notes list Chart notes in the period
36
71
  notes add --text [--date] Add a chart note (needs write access)
37
72
  mentions X and Reddit posts mentioning the website (Growth);
38
73
  --platform x|reddit, --q, -n/--limit, --offset
74
+ ai-visibility What AI assistants answer to your tracked prompts
75
+ (Growth): scores, per-assistant results, brands named;
76
+ --period (default 90d) for the trend
39
77
 
40
78
  Alerts (email when a goal, payment or new customer happens)
41
79
  alerts list Alerts on the website
@@ -54,14 +92,37 @@ Team
54
92
  members role <user_id> --role admin|viewer
55
93
  members remove <user_id> Remove a member (asks first; --yes to skip)
56
94
  members revoke <invite_id> Revoke a pending invitation
95
+
96
+ Bot traffic
97
+ bots settings Excluded crawler companies and agents, bot token status
98
+ bots usage AI and bot requests used this cycle and the allowance
99
+ bots exclude <name…> Stop recording these agents (--company for companies)
100
+ bots include <name…> Record excluded agents again (--company for companies)
101
+ bots require-token on|off Refuse crawl events sent without the bot token
102
+ (changes need write access, admin)
103
+
104
+ Managed proxy (serve the script from your own subdomain)
105
+ proxy status Hostname, DNS record to add and status
106
+ proxy enable <subdomain> Set it up, e.g. a.example.com (needs write access, admin)
107
+ proxy check Look for the DNS record now
108
+ proxy remove Remove it (asks first; --yes to skip)
57
109
  completion bash|zsh|fish Print a shell completion script
58
110
 
59
111
  Period and filters
60
112
  -p, --period <p> today, yesterday, 24h, 7d, 30d, 90d, 6m, 1y, wtd, mtd, all
61
113
  --from, --to <date> Custom days, YYYY-MM-DD (inclusive)
62
114
  -z, --timezone <zone> IANA zone for day boundaries, e.g. Europe/Madrid (default UTC)
63
- -f, --filter <dim:op:value> Repeatable. Ops: is, is_not, contains, not_contains
64
- e.g. -f country:is:US -f page:contains:/blog
115
+ --compare <c> Change figures against: previous (default), year
116
+ (same period last year) or a YYYY-MM-DD start
117
+ -f, --filter <dim:op:value> Repeatable. Ops: is, is_not, contains, not_contains;
118
+ gt, lt for visits. e.g. -f country:is:US
119
+ -f page:contains:/blog -f visits:gt:2
120
+ Revenue also takes plan, currency, paymentType
121
+ (new|renewal), refund (none|partial|refunded) and
122
+ provider: -f plan:is:Pro -f paymentType:is:renewal
123
+ ai-visibility takes model, prompt, group, competitor,
124
+ mention (mentioned|not_mentioned|cited) and citedDomain
125
+ with is or is_not: -f model:is:claude
65
126
 
66
127
  List options
67
128
  --sort, -n/--limit, --offset, --q (search), --payment all|paid|unpaid
@@ -69,6 +130,9 @@ List options
69
130
  Global
70
131
  --site <id> Website for this command (or METRICRAVEN_SITE, or \`use\`)
71
132
  --json Raw API JSON (compact), for scripts and AI agents
133
+ --fields <paths> Only these parts of the answer, as JSON (analytics,
134
+ realtime, visitors list): comma-separated dot paths,
135
+ e.g. --fields overview.current,series.date,series.visitors
72
136
  -v, --verbose Print request URLs and status codes to stderr
73
137
  --token <token> Use this token (prefer METRICRAVEN_TOKEN: flags end up in shell history)
74
138
  -h, --help Show help
package/dist/range.js CHANGED
@@ -115,3 +115,24 @@ export function calendarDate(date, timeZone = "UTC") {
115
115
  const w = wall(date.getTime(), timeZone);
116
116
  return `${w.y}-${String(w.m).padStart(2, "0")}-${String(w.d).padStart(2, "0")}`;
117
117
  }
118
+ /**
119
+ * Start of the comparison window (`--compare`), matching @metricraven/core/compare: "year" is the
120
+ * same calendar day a year earlier (29 Feb → 28 Feb), a YYYY-MM-DD is that day; both keep the
121
+ * range's time of day. "previous" (the default) and "off" return null. Undefined for bad input.
122
+ */
123
+ export function compareStartFor(value, from, timeZone = "UTC") {
124
+ if (value === "previous" || value === "off")
125
+ return null;
126
+ const day = calendarDate(from, timeZone);
127
+ const [y, m, d] = day.split("-").map(Number);
128
+ let target;
129
+ if (value === "year")
130
+ target = { y: y - 1, m, d: Math.min(d, new Date(Date.UTC(y - 1, m, 0)).getUTCDate()) };
131
+ else
132
+ target = parseDate(value);
133
+ if (!target)
134
+ return undefined;
135
+ const intoDay = from.getTime() - startOfDate({ y, m, d }, timeZone).getTime();
136
+ const start = new Date(startOfDate(target, timeZone).getTime() + intoDay);
137
+ return start < from ? start : undefined;
138
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metricraven/cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "MetricRaven from your terminal: traffic, revenue, goals, visitors and websites. Built for people and AI agents.",
5
5
  "type": "module",
6
6
  "license": "MIT",