@metricraven/cli 0.1.0 → 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 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,5 +1,6 @@
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
6
  import { bold, change, date, dim, duration, money, num, pct, section, table, truncate } from "./format.js";
@@ -7,6 +8,19 @@ import { interactive, prompt, promptHidden, readStdin } from "./prompt.js";
7
8
  export const TOKENS_URL = "https://metricraven.com/app/api";
8
9
  const out = (s) => process.stdout.write(`${s}\n`);
9
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
+ }
10
24
  /** Runs a parsed command. Returns the exit code. */
11
25
  export async function run(command, flags) {
12
26
  const [group, sub, ...rest] = command;
@@ -30,14 +44,34 @@ export async function run(command, flags) {
30
44
  switch (group) {
31
45
  case "whoami":
32
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;
33
59
  case "use":
34
60
  return useSite(ctx, sub);
35
61
  case "websites":
36
62
  case "sites":
37
63
  if (sub === "create")
38
64
  return createWebsite(ctx);
65
+ if (sub === "keys")
66
+ return siteKeys(ctx, rest[0], rest.slice(1));
39
67
  if (!sub || sub === "list")
40
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]);
41
75
  break;
42
76
  case "analytics":
43
77
  return analytics(ctx, sub, rest);
@@ -54,6 +88,10 @@ export async function run(command, flags) {
54
88
  if (!sub || sub === "list")
55
89
  return listFunnels(ctx);
56
90
  break;
91
+ case "goals":
92
+ if (sub === "delete-events")
93
+ return deleteGoalEvents(ctx);
94
+ return goals(ctx, sub, rest);
57
95
  case "notes":
58
96
  if (!sub || sub === "list")
59
97
  return listNotes(ctx);
@@ -64,11 +102,20 @@ export async function run(command, flags) {
64
102
  if (!sub || sub === "list")
65
103
  return listMentions(ctx);
66
104
  break;
105
+ case "ai-visibility":
106
+ case "ai":
107
+ if (!sub || sub === "summary")
108
+ return aiVisibility(ctx);
109
+ break;
67
110
  case "alerts":
68
111
  return alerts(ctx, sub, rest);
69
112
  case "members":
70
113
  case "team":
71
114
  return members(ctx, sub, rest);
115
+ case "bots":
116
+ return bots(ctx, sub, rest);
117
+ case "proxy":
118
+ return managedProxy(ctx, sub, rest);
72
119
  }
73
120
  throw new UsageError(`Unknown command "${command.join(" ")}". Run \`metricraven --help\`.`);
74
121
  }
@@ -172,7 +219,7 @@ async function useSite({ flags, client }, id) {
172
219
  out(`Default website: ${bold(site.name)} (${id}).`);
173
220
  return 0;
174
221
  }
175
- const REPORTS = ["traffic", "revenue", "conversions", "insights", "search", "crawlers"];
222
+ const REPORTS = ["traffic", "revenue", "conversions", "insights", "search", "crawlers", "ads", "meta-ads"];
176
223
  async function analytics(ctx, sub, rest) {
177
224
  const { flags, client } = ctx;
178
225
  if (!sub)
@@ -199,18 +246,75 @@ async function analytics(ctx, sub, rest) {
199
246
  throw new UsageError("Use: metricraven analytics goal <name>");
200
247
  params.set("name", rest[0]);
201
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
+ }
202
265
  else if (!REPORTS.includes(sub)) {
203
266
  throw new UsageError(`Unknown report "${sub}". Use ${[...REPORTS, "breakdown", "goal"].join(", ")}.`);
204
267
  }
205
268
  params.set("site", await ctx.site());
269
+ const selected = selectFields(flags, params);
206
270
  const path = sub === "breakdown" ? "/stats/breakdown" : sub === "goal" ? "/stats/goal" : `/stats/${sub}`;
207
271
  const data = await client.get(path, params);
208
- if (flags.json)
272
+ if (flags.json || selected)
209
273
  return printJson(data), 0;
210
274
  const render = RENDER[sub];
211
275
  out(render ? render(data) : JSON.stringify(data, null, 2));
212
276
  return 0;
213
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
+ }
214
318
  function periodLine(p) {
215
319
  if (!p?.from || !p.to)
216
320
  return "";
@@ -273,15 +377,21 @@ const RENDER = {
273
377
  ].join("\n");
274
378
  },
275
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;
276
383
  return [
277
384
  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"])
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"])
280
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\`).`) : "",
281
389
  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"]))
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"]))
283
391
  : "",
284
- ].join("\n");
392
+ ]
393
+ .filter(Boolean)
394
+ .join("\n");
285
395
  },
286
396
  insights(d) {
287
397
  const o = d.overview;
@@ -314,6 +424,8 @@ const RENDER = {
314
424
  : dim("No queries.")),
315
425
  ].join("\n");
316
426
  },
427
+ ads: (d) => renderAds(d),
428
+ "meta-ads": (d) => renderAds(d),
317
429
  crawlers(d) {
318
430
  return [
319
431
  periodLine(d.period),
@@ -327,7 +439,8 @@ const RENDER = {
327
439
  const t = d.totals;
328
440
  return [
329
441
  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`,
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) : "",
331
444
  d.sources.length
332
445
  ? section("Sources", table(["Source", "Visitors"], d.sources.slice(0, 10).map((s) => [s.name, num(s.visitors)]), ["left", "right"]))
333
446
  : "",
@@ -339,8 +452,9 @@ const RENDER = {
339
452
  };
340
453
  async function realtime(ctx) {
341
454
  const params = new URLSearchParams({ site: await ctx.site() });
455
+ const selected = selectFields(ctx.flags, params);
342
456
  const d = await ctx.client.get("/stats/live", params);
343
- if (ctx.flags.json)
457
+ if (ctx.flags.json || selected)
344
458
  return printJson(d), 0;
345
459
  out(`${bold(num(d.visitorsNow))} visitor${d.visitorsNow === 1 ? "" : "s"} online now`);
346
460
  if (d.visitors.length)
@@ -361,6 +475,7 @@ async function listVisitors(ctx) {
361
475
  params.set("q", flags.q);
362
476
  if (flags.payment)
363
477
  params.set("payment", flags.payment);
478
+ visitorSearchParams(flags, params);
364
479
  if (flags.sort)
365
480
  params.set("sort", flags.sort);
366
481
  const limit = positiveInt(flags.limit, "limit", 100);
@@ -370,8 +485,9 @@ async function listVisitors(ctx) {
370
485
  if (offset !== undefined)
371
486
  params.set("offset", String(offset));
372
487
  params.set("site", await ctx.site());
488
+ const selected = selectFields(flags, params);
373
489
  const d = await ctx.client.get("/stats/visitors", params).catch((e) => needs("visitors", Promise.reject(e)));
374
- if (flags.json)
490
+ if (flags.json || selected)
375
491
  return printJson(d), 0;
376
492
  if (!d.rows.length)
377
493
  return out(dim("No visitors match.")), 0;
@@ -485,6 +601,118 @@ async function listMentions(ctx) {
485
601
  out(dim(`Showing ${d.pagination.offset + 1}–${d.pagination.offset + d.data.length} of ${d.pagination.total}. Use --offset for more.`));
486
602
  return 0;
487
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
+ }
488
716
  const triggerText = (t) => (t.type === "goal" ? `goal ${t.goalName}` : t.type === "payment" ? "any payment" : "new customer");
489
717
  /** `metricraven alerts …`: conversion alerts on the website (list/get/create/update/delete/history). */
490
718
  async function alerts(ctx, sub, rest) {
@@ -680,6 +908,467 @@ async function members(ctx, sub, rest) {
680
908
  }
681
909
  throw new UsageError(`Unknown command "members ${sub}". Use list, invite, role, remove or revoke.`);
682
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
+ }
683
1372
  /** The API answers 401 for a missing scope too; name the access the command needs. */
684
1373
  async function needs(access, request) {
685
1374
  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/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.0",
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",