@metricraven/cli 0.4.4 → 0.5.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/dist/commands.js CHANGED
@@ -3,9 +3,17 @@ import { UsageError, buildFilters, positiveInt, rangeParams } from "./args.js";
3
3
  import { customRange, validTimeZone } from "./range.js";
4
4
  import { AD_PROVIDER_VALUES, completionScript } from "./completion.js";
5
5
  import { configPath, deleteConfigToken, readConfig, resolveSettings, updateConfig } from "./config.js";
6
- import { bold, change, date, dim, duration, money, num, pct, section, table, terminalSafe, truncate } from "./format.js";
6
+ import { bold, change, csvLine, date, dim, duration, money, num, pct, section, table, terminalSafe, truncate } from "./format.js";
7
7
  import { interactive, prompt, promptHidden, readStdin } from "./prompt.js";
8
8
  export const TOKENS_URL = "https://metricraven.com/app/api";
9
+ /** "2.4 s" (LCP) or "180 ms" (INP); "–" without a value. */
10
+ export function vitalText(metric, ms) {
11
+ if (ms === null || ms === undefined || !Number.isFinite(ms))
12
+ return "–";
13
+ return metric === "lcp" && ms >= 1000 ? `${(ms / 1000).toFixed(1)} s` : `${Math.round(ms)} ms`;
14
+ }
15
+ const speedHead = ["LCP p75", "INP p75"];
16
+ const speedCells = (r) => [vitalText("lcp", r.speed?.lcp.p75), vitalText("inp", r.speed?.inp.p75)];
9
17
  /** Every line the CLI prints; terminalSafe strips escape sequences that came from report data. */
10
18
  const out = (s) => process.stdout.write(`${terminalSafe(s)}\n`);
11
19
  const printJson = (data) => out(JSON.stringify(data));
@@ -56,6 +64,12 @@ export async function run(command, flags) {
56
64
  case "payments":
57
65
  if (sub === "delete")
58
66
  return deletePayments(ctx);
67
+ if (!sub || sub === "list")
68
+ return listRaw(ctx, "payments");
69
+ break;
70
+ case "events":
71
+ if (!sub || sub === "list")
72
+ return listRaw(ctx, "events");
59
73
  break;
60
74
  case "use":
61
75
  return useSite(ctx, sub);
@@ -84,11 +98,15 @@ export async function run(command, flags) {
84
98
  return listVisitors(ctx);
85
99
  if (sub === "get")
86
100
  return getVisitor(ctx, rest[0]);
101
+ if (sub === "traits")
102
+ return visitorTraits(ctx);
87
103
  break;
88
104
  case "funnels":
89
- if (!sub || sub === "list")
90
- return listFunnels(ctx);
91
- break;
105
+ if (sub === "dropoff")
106
+ return funnelDropoff(ctx, rest[0]);
107
+ return funnels(ctx, sub, rest);
108
+ case "segments":
109
+ return segments(ctx, sub, rest);
92
110
  case "goals":
93
111
  if (sub === "delete-events")
94
112
  return deleteGoalEvents(ctx);
@@ -220,17 +238,52 @@ async function useSite({ flags, client }, id) {
220
238
  out(`Default website: ${bold(site.name)} (${id}).`);
221
239
  return 0;
222
240
  }
223
- const REPORTS = ["traffic", "revenue", "mrr", "conversions", "insights", "search", "crawlers", "ads", "meta-ads"];
241
+ const REPORTS = ["traffic", "revenue", "mrr", "conversions", "paths", "insights", "speed", "search", "crawlers", "ai-companies", "ads", "meta-ads"];
224
242
  async function analytics(ctx, sub, rest) {
225
243
  const { flags, client } = ctx;
226
244
  if (!sub)
227
- throw new UsageError(`Use: metricraven analytics <${[...REPORTS, "breakdown", "goal"].join("|")}>`);
245
+ throw new UsageError(`Use: metricraven analytics <${[...REPORTS, "breakdown", "goal", "properties", "errors"].join("|")}>`);
228
246
  const params = rangeParams(flags);
247
+ // A saved funnel (--funnel <id>, wins) or unsaved steps (--steps) for the conversions report
248
+ // (and, with --drop-step, the errors report). analytics paths takes --steps as a step count (handled below).
249
+ if (flags.funnel !== undefined || (flags.steps !== undefined && sub !== "paths")) {
250
+ if (sub !== "conversions" && sub !== "errors")
251
+ throw new UsageError("--funnel and --steps go with the conversions report: metricraven analytics conversions --funnel <funnel_id>.");
252
+ if (flags.funnel)
253
+ params.set("funnel", flags.funnel);
254
+ else if (flags.steps)
255
+ params.set("steps", flags.steps);
256
+ }
229
257
  if (sub === "breakdown") {
230
258
  const dimension = rest[0];
231
259
  if (!dimension)
232
- throw new UsageError("Use: metricraven analytics breakdown <dimension>, e.g. country, referrer, page, utmSource.");
260
+ throw new UsageError("Use: metricraven analytics breakdown <dimension>, e.g. country, referrer, page, utmSource, exitPage.");
233
261
  params.set("dimension", dimension);
262
+ if (dimension === "urlParam") {
263
+ if (!flags.param)
264
+ throw new UsageError("Use: metricraven analytics breakdown urlParam --param <name>, e.g. --param plan (one of the site's kept URL parameters).");
265
+ params.set("param", flags.param.trim().toLowerCase());
266
+ }
267
+ else if (flags.param)
268
+ throw new UsageError("--param goes with the urlParam dimension only: metricraven analytics breakdown urlParam --param plan.");
269
+ // Pages only: --attribution viewed credits every page buyers viewed before paying; --group folder rolls pages up.
270
+ if ((flags.attribution || flags.group || flags.folder) && dimension !== "page")
271
+ throw new UsageError("--attribution, --group and --folder go with the page dimension only: metricraven analytics breakdown page --group folder.");
272
+ if (flags.attribution) {
273
+ if (flags.attribution !== "first_touch" && flags.attribution !== "viewed")
274
+ throw new UsageError("Use --attribution first_touch or viewed.");
275
+ params.set("attribution", flags.attribution);
276
+ }
277
+ if (flags.group) {
278
+ if (flags.group !== "page" && flags.group !== "folder")
279
+ throw new UsageError("Use --group page or folder.");
280
+ params.set("group", flags.group);
281
+ }
282
+ if (flags.folder) {
283
+ if (flags.group !== "folder")
284
+ throw new UsageError("--folder needs --group folder: metricraven analytics breakdown page --group folder --folder /blog/.");
285
+ params.set("folder", flags.folder.endsWith("/") ? flags.folder : `${flags.folder}/`);
286
+ }
234
287
  if (flags.sort)
235
288
  params.set("sort", flags.sort);
236
289
  if (flags.order) {
@@ -240,6 +293,16 @@ async function analytics(ctx, sub, rest) {
240
293
  }
241
294
  if (flags.q)
242
295
  params.set("q", flags.q);
296
+ // --include speed,errors: LCP and INP at the 75th percentile per page, and visitors who hit a
297
+ // JavaScript error there and didn't pay (page and entryPage).
298
+ if (flags.include) {
299
+ const include = [...new Set(flags.include.split(",").map((v) => v.trim()))];
300
+ if (!include.length || include.some((v) => v !== "speed" && v !== "errors"))
301
+ throw new UsageError("Use --include speed, errors or speed,errors.");
302
+ if (dimension !== "page" && dimension !== "entryPage")
303
+ throw new UsageError(`--include ${include.join(",")} goes with the page and entryPage dimensions: metricraven analytics breakdown page --include ${include.join(",")}.`);
304
+ params.set("include", include.join(","));
305
+ }
243
306
  const limit = positiveInt(flags.limit, "limit", 100);
244
307
  if (limit !== undefined)
245
308
  params.set("limit", String(Math.max(1, limit)));
@@ -247,11 +310,54 @@ async function analytics(ctx, sub, rest) {
247
310
  if (offset !== undefined)
248
311
  params.set("offset", String(offset));
249
312
  }
313
+ else if (sub === "errors") {
314
+ // JavaScript errors grouped by name and message (GET /stats/errors): one page, one funnel drop-off or one group.
315
+ if (flags.path) {
316
+ if (!flags.path.startsWith("/"))
317
+ throw new UsageError("--path is a page path starting with /, e.g. --path /checkout.");
318
+ params.set("path", flags.path);
319
+ }
320
+ if (flags.group) {
321
+ if (!/^[0-9a-f]{16}$/.test(flags.group))
322
+ throw new UsageError("--group is an error group's 16-character ID, from the list.");
323
+ params.set("group", flags.group);
324
+ }
325
+ if ((flags.funnel || flags.steps) && !flags["drop-step"])
326
+ throw new UsageError("--funnel and --steps need --drop-step <n>: metricraven analytics errors --funnel <id> --drop-step 2.");
327
+ if (flags["drop-step"]) {
328
+ if (flags.path)
329
+ throw new UsageError("Use --path or --drop-step, not both.");
330
+ const step = positiveInt(flags["drop-step"], "drop-step", 7);
331
+ if (!step)
332
+ throw new UsageError("--drop-step is the funnel step visitors didn't reach (1 or more; 0 is the first step).");
333
+ params.set("dropStep", String(step));
334
+ if (flags.funnel)
335
+ params.set("funnel", flags.funnel);
336
+ else if (flags.steps)
337
+ params.set("steps", flags.steps);
338
+ }
339
+ }
250
340
  else if (sub === "goal") {
251
341
  if (!rest[0])
252
342
  throw new UsageError("Use: metricraven analytics goal <name>");
253
343
  params.set("name", rest[0]);
254
344
  }
345
+ else if (sub === "properties") {
346
+ // Event property names (or one property's values) with people counts: GET /stats/filter-values?dimension=prop.
347
+ params.set("dimension", "prop");
348
+ if (rest[0])
349
+ params.set("key", rest[0]);
350
+ if (flags.goal)
351
+ params.set("goal", flags.goal);
352
+ if (flags.q)
353
+ params.set("q", flags.q);
354
+ const limit = positiveInt(flags.limit, "limit", 100);
355
+ if (limit !== undefined)
356
+ params.set("limit", String(Math.max(1, limit)));
357
+ const offset = positiveInt(flags.offset, "offset", 1_000_000);
358
+ if (offset !== undefined)
359
+ params.set("offset", String(offset));
360
+ }
255
361
  else if (sub === "meta-ads" && (rest[0] || flags.account)) {
256
362
  if (rest[0] && !["campaign", "adset", "ad"].includes(rest[0]))
257
363
  throw new UsageError("Use: metricraven analytics meta-ads [campaign|adset|ad] [--account <id>]");
@@ -260,6 +366,26 @@ async function analytics(ctx, sub, rest) {
260
366
  if (flags.account)
261
367
  params.set("account", adAccountId(flags.account));
262
368
  }
369
+ else if (sub === "paths") {
370
+ // Page sequences of payers and non-payers: GET /stats/paths.
371
+ if (flags.steps) {
372
+ const steps = Number(flags.steps);
373
+ if (!Number.isInteger(steps) || steps < 2 || steps > 7)
374
+ throw new UsageError("Use --steps 2 to 7.");
375
+ params.set("steps", String(steps));
376
+ }
377
+ if (flags.group) {
378
+ if (flags.group !== "page" && flags.group !== "section")
379
+ throw new UsageError("Use --group page or section.");
380
+ params.set("group", flags.group);
381
+ }
382
+ if (flags.start)
383
+ params.set("start", flags.start);
384
+ if (flags.end)
385
+ params.set("end", flags.end);
386
+ if (flags.who && !["all", "paid", "unpaid"].includes(flags.who))
387
+ throw new UsageError("Use --who all, paid or unpaid.");
388
+ }
263
389
  else if (sub === "mrr") {
264
390
  if (rest[0] && !["day", "week", "month"].includes(rest[0]))
265
391
  throw new UsageError("Use: metricraven analytics mrr [day|week|month]");
@@ -280,11 +406,23 @@ async function analytics(ctx, sub, rest) {
280
406
  params.set("account", adAccountId(flags.account));
281
407
  }
282
408
  else if (!REPORTS.includes(sub)) {
283
- throw new UsageError(`Unknown report "${sub}". Use ${[...REPORTS, "breakdown", "goal"].join(", ")}.`);
409
+ throw new UsageError(`Unknown report "${sub}". Use ${[...REPORTS, "breakdown", "goal", "properties", "errors"].join(", ")}.`);
284
410
  }
285
411
  params.set("site", await ctx.site());
286
412
  const selected = selectFields(flags, params);
287
- const path = sub === "breakdown" ? "/stats/breakdown" : sub === "goal" ? "/stats/goal" : sub === "mrr" ? "/stats/mrr-history" : `/stats/${sub}`;
413
+ const path = sub === "breakdown"
414
+ ? "/stats/breakdown"
415
+ : sub === "goal"
416
+ ? "/stats/goal"
417
+ : sub === "properties"
418
+ ? "/stats/filter-values"
419
+ : sub === "errors"
420
+ ? "/stats/errors"
421
+ : sub === "mrr"
422
+ ? "/stats/mrr-history"
423
+ : sub === "speed"
424
+ ? "/stats/page-speed"
425
+ : `/stats/${sub}`;
288
426
  const fetched = await client.get(path, params);
289
427
  const data = flags.compare === "off" ? withoutComparison(fetched) : fetched;
290
428
  if (flags.json || selected)
@@ -293,6 +431,10 @@ async function analytics(ctx, sub, rest) {
293
431
  out(`Ad account ${params.get("account")} is not one of this website's chosen ad accounts${params.get("provider") && params.get("provider") !== "all" ? ` on ${NETWORKS[params.get("provider")] ?? params.get("provider")}` : ""}. Run the report without --account to list them.`);
294
432
  return 0;
295
433
  }
434
+ if (sub === "paths") {
435
+ out(pathsText(data, flags.who ?? "all"));
436
+ return 0;
437
+ }
296
438
  const render = RENDER[sub];
297
439
  out(render ? render(data) : JSON.stringify(data, null, 2));
298
440
  return 0;
@@ -398,6 +540,27 @@ export function withoutComparison(data) {
398
540
  };
399
541
  return out;
400
542
  }
543
+ /** analytics paths: the totals line and one list (--who all, paid or unpaid). */
544
+ export function pathsText(d, who = "all") {
545
+ const currency = d.period?.currency ?? "USD";
546
+ const revenue = d.totals.revenue !== null;
547
+ const rows = who === "paid" ? d.paidPaths : who === "unpaid" ? d.unpaidPaths : d.paths;
548
+ const pathText = (r) => truncate(`${r.steps.join(" → ")}${r.more ? " → …" : ""}`, 70);
549
+ return [
550
+ periodLine(d.period),
551
+ revenue
552
+ ? `${num(d.totals.visitors)} visitors · ${num(d.totals.payingVisitors)} paid (${pct(d.totals.purchaseRate)}) · ${money(d.totals.revenue, currency)}`
553
+ : `${num(d.totals.visitors)} visitors`,
554
+ section(who === "paid" ? "Paths of people who paid" : who === "unpaid" ? "Paths of people who didn’t pay" : "Paths", rows.length
555
+ ? revenue
556
+ ? table(["Path", "Visitors", "Paid", "% paid", "Revenue"], rows.map((r) => [pathText(r), num(r.visitors), num(r.payingVisitors), pct(r.purchaseRate), money(r.revenue, currency)]), ["left", "right", "right", "right", "right"])
557
+ : table(["Path", "Visitors"], rows.map((r) => [pathText(r), num(r.visitors)]), ["left", "right"])
558
+ : dim(who === "paid" ? "Nobody paid in this period." : "No pages viewed in this period.")),
559
+ d.sample ? dim(`Visitors who didn’t pay are estimated from a 1 in ${Math.round(1 / d.sample.rate)} sample.`) : "",
560
+ ]
561
+ .filter(Boolean)
562
+ .join("\n");
563
+ }
401
564
  const RENDER = {
402
565
  traffic(d) {
403
566
  const c = d.overview.current;
@@ -425,8 +588,52 @@ const RENDER = {
425
588
  breakdown(d) {
426
589
  if (!d.rows.length)
427
590
  return dim("No data.");
591
+ const speed = d.rows.some((r) => r.speed != null);
592
+ const withSpeed = (head) => (speed ? [...head, ...speedHead] : head);
593
+ const speedRow = (r) => (speed ? speedCells(r) : []);
594
+ // Pages: average time and exit rate, and in viewed mode buyers and buyer rate (▸ marks folders).
595
+ if (d.rows.some((r) => typeof r.avgTime === "number")) {
596
+ const viewed = d.attribution === "viewed";
597
+ const name = (r) => truncate(`${r.kind === "folder" ? "▸ " : ""}${r.name}`, 60);
598
+ const header = withSpeed(viewed
599
+ ? [d.dimension, "Visitors", "Pageviews", "Avg time", "Exit %", "Buyers", "Buyer %", "Revenue"]
600
+ : [d.dimension, "Visitors", "Pageviews", "Avg time", "Exit %", "Revenue"]);
601
+ // --include errors: visitors who hit a JavaScript error on the page and didn't pay.
602
+ const errors = d.rows.some((r) => r.errors);
603
+ if (errors)
604
+ header.push("Errors (didn't pay)");
605
+ return [
606
+ table(header, d.rows.map((r) => [
607
+ name(r),
608
+ num(r.visitors),
609
+ num(r.pageviews),
610
+ duration(r.avgTime),
611
+ pct(r.exitRate, 2),
612
+ ...(viewed ? [num(r.buyers), pct(r.purchaseRate, 2)] : []),
613
+ money(r.revenue),
614
+ ...speedRow(r),
615
+ ...(errors ? [r.errors ? `${num(r.errors.nonBuyers)} of ${num(r.errors.visitors)}` : "–"] : []),
616
+ ]), header.map((_, i) => (i ? "right" : "left"))),
617
+ ...(viewed && d.totals
618
+ ? [dim(`${num(d.totals.buyers)} buyers paid ${money(d.totals.revenue)} in this period; a buyer counts on every page they viewed.`)]
619
+ : []),
620
+ dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`),
621
+ ].join("\n");
622
+ }
623
+ // Paying visitors and purchase rate come with revenue (absent for outbound links and hidden revenue).
624
+ const paying = d.rows.some((r) => typeof r.payingVisitors === "number");
428
625
  return [
429
- table([d.dimension, "Visitors", "Pageviews", "Revenue"], d.rows.map((r) => [truncate(r.name, 60), num(r.visitors), num(r.pageviews), money(r.revenue)]), ["left", "right", "right", "right"]),
626
+ paying
627
+ ? table(withSpeed([d.dimension, "Visitors", "Pageviews", "Revenue", "Paying", "Rate"]), d.rows.map((r) => [
628
+ truncate(r.name, 60),
629
+ num(r.visitors),
630
+ num(r.pageviews),
631
+ money(r.revenue),
632
+ num(r.payingVisitors),
633
+ pct(r.purchaseRate, 2),
634
+ ...speedRow(r),
635
+ ]), withSpeed([d.dimension, "", "", "", "", ""]).map((_, i) => (i ? "right" : "left")))
636
+ : table(withSpeed([d.dimension, "Visitors", "Pageviews", "Revenue"]), d.rows.map((r) => [truncate(r.name, 60), num(r.visitors), num(r.pageviews), money(r.revenue), ...speedRow(r)]), withSpeed([d.dimension, "", "", ""]).map((_, i) => (i ? "right" : "left"))),
430
637
  dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`),
431
638
  ].join("\n");
432
639
  },
@@ -481,6 +688,36 @@ const RENDER = {
481
688
  .filter(Boolean)
482
689
  .join("\n");
483
690
  },
691
+ errors(d) {
692
+ const off = d.enabled ? [] : [dim("JavaScript errors are off for this website: turn them on in Settings → Tracking & install.")];
693
+ const label = (g) => `${g.name}${g.message ? `: ${g.message}` : ""}`;
694
+ if (d.group !== undefined) {
695
+ const g = d.group;
696
+ if (!g)
697
+ return [...off, dim("No errors in this group in this period.")].join("\n");
698
+ return [
699
+ ...off,
700
+ periodLine(d.period),
701
+ bold(truncate(label(g), 200)),
702
+ `${num(g.occurrences)} times · ${num(g.visitors)} visitors · ${num(g.nonBuyers)} didn't pay · last seen ${date(g.lastSeen)}`,
703
+ ...(g.topPaths.length ? [`Pages: ${g.topPaths.map((p) => `${p.path} (${num(p.visitors)})`).join(", ")}`] : []),
704
+ ...(g.browsers.length ? [`Browsers: ${g.browsers.map((b) => `${b.name} (${num(b.visitors)})`).join(", ")}`] : []),
705
+ ...(g.sample?.stack ? [section("Latest stack", g.sample.stack)] : []),
706
+ ...(g.people.length
707
+ ? [section("People", table(["Visitor", "Last hit", "Paid"], g.people.map((p) => [p.visitorId, date(p.at), p.paid ? "yes" : "no"]), ["left", "left", "left"]))]
708
+ : []),
709
+ ].join("\n");
710
+ }
711
+ const groups = d.groups ?? [];
712
+ if (!groups.length)
713
+ return [...off, dim("No errors recorded in this period.")].join("\n");
714
+ return [
715
+ ...off,
716
+ periodLine(d.period),
717
+ table(["Error", "Times", "Visitors", "Didn't pay", "Group"], groups.map((g) => [truncate(label(g), 70), num(g.occurrences), num(g.visitors), num(g.nonBuyers), g.fingerprint]), ["left", "right", "right", "right", "left"]),
718
+ dim("Details: metricraven analytics errors --group <Group>"),
719
+ ].join("\n");
720
+ },
484
721
  conversions(d) {
485
722
  // Hidden goals (Settings → Goals) stay out of the table, like the dashboard; --json has them all.
486
723
  const shown = d.goals.filter((g) => !g.hidden);
@@ -492,12 +729,36 @@ const RENDER = {
492
729
  : dim("No goals in this period.")),
493
730
  hidden ? dim(`${num(hidden)} hidden goal${hidden === 1 ? "" : "s"} not shown (see --json or \`metricraven goals list\`).`) : "",
494
731
  d.funnel?.length
495
- ? 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"]))
732
+ ? section("Funnel", table(["Step", "Visitors", "From start", "Median after previous"], d.funnel.map((s) => [s.displayName || s.step, num(s.visitors), pct(s.fromStart, 0), duration(s.medianSecondsFromPrevious)]), ["left", "right", "right", "right"]))
733
+ : "",
734
+ d.funnel?.length && d.timeToPayment?.payingVisitors
735
+ ? dim(`${num(d.timeToPayment.payingVisitors)} of ${num(d.timeToPayment.visitors)} who finished paid · median ${duration(d.timeToPayment.medianSeconds)} to pay`)
496
736
  : "",
497
737
  ]
498
738
  .filter(Boolean)
499
739
  .join("\n");
500
740
  },
741
+ speed(d) {
742
+ if (!d.pages.length)
743
+ return dim(d.enabled
744
+ ? "No page has enough slow and fast visitors to compare yet (each needs 30 of both)."
745
+ : "Page speed is off. Turn it on in Settings → Tracking & install → Page speed.");
746
+ const header = ["Page", "Slow visitors", "Paid (slow)", "Paid (fast)", "Buyers lost", "LCP p75", "INP p75"];
747
+ return [
748
+ bold("Slow pages that lose buyers"),
749
+ table(header, d.pages.map((p) => [
750
+ truncate(p.path, 50),
751
+ num(p.slowVisitors),
752
+ pct(p.slowConversion, 2),
753
+ pct(p.fastConversion, 2),
754
+ num(p.buyersLost),
755
+ vitalText("lcp", p.lcpP75),
756
+ vitalText("inp", p.inpP75),
757
+ ]), header.map((_, i) => (i ? "right" : "left"))),
758
+ dim("Slow: main content after 4 s or a click answered after 500 ms. A lead, not proof: slow loads come with slower devices and networks."),
759
+ ...(d.truncated ? [dim("Based on the most recent 200,000 page loads in this period.")] : []),
760
+ ].join("\n");
761
+ },
501
762
  insights(d) {
502
763
  const o = d.overview;
503
764
  const cur = d.period.currency ?? "USD";
@@ -507,6 +768,17 @@ const RENDER = {
507
768
  d.timing
508
769
  ? `Time to first purchase: median ${num(d.timing.medianDays, 1)} days, ${num(d.timing.medianVisits)} visits · ${pct(d.timing.firstVisitPercent, 0)} buy on the first visit`
509
770
  : "",
771
+ d.channels?.rows.length
772
+ ? section("Channels", table(["Channel", "Visitors", "Revenue", "Days", "Visits", "Came back", "Then paid"], d.channels.rows.map((r) => [
773
+ r.name,
774
+ num(r.visitors),
775
+ money(r.revenue, cur),
776
+ num(r.medianDays, 1),
777
+ num(r.medianVisits, 1),
778
+ pct(r.returnRate, 1),
779
+ pct(r.returnBuyRate, 1),
780
+ ]), ["left", "right", "right", "right", "right", "right", "right"]))
781
+ : "",
510
782
  d.revenueMix?.sources?.length
511
783
  ? section("Revenue by source", table(["Source", "Revenue"], d.revenueMix.sources.slice(0, 6).map((s) => [s.name, money(s.revenue, cur)]), ["left", "right"]))
512
784
  : "",
@@ -540,6 +812,35 @@ const RENDER = {
540
812
  : dim("No crawler requests in this period."),
541
813
  ].join("\n");
542
814
  },
815
+ /** Per AI company: pages its AI crawlers read, visits its assistants sent, customers and revenue. */
816
+ "ai-companies"(d) {
817
+ const cur = d.period.currency ?? "USD";
818
+ const showMoney = d.companies.some((c) => c.revenue !== null);
819
+ return [
820
+ periodLine(d.period),
821
+ `${num(d.totals.visits)} visits from AI assistants${d.totals.revenue === null ? "" : ` · ${money(d.totals.revenue, cur)} revenue`} · ${num(d.totals.crawlRequests)} AI crawler requests`,
822
+ d.companies.length
823
+ ? section("AI companies", table(["Company", "Pages crawled", "Crawls", "Visits", ...(showMoney ? ["Customers", "Revenue"] : [])], d.companies.map((c) => [
824
+ c.company,
825
+ num(c.pagesCrawled),
826
+ num(c.crawlRequests),
827
+ num(c.visits),
828
+ ...(showMoney ? [c.payingCustomers === null ? "–" : num(c.payingCustomers), money(c.revenue, cur)] : []),
829
+ ]), ["left", "right", "right", "right", ...(showMoney ? ["right", "right"] : [])]))
830
+ : dim("No AI crawler requests or AI assistant visits in this period."),
831
+ ].join("\n");
832
+ },
833
+ properties(d) {
834
+ if (!d.rows.length)
835
+ return dim(d.key ? `No values of ${d.key} in this period.` : "No goal in this period has properties.");
836
+ return [
837
+ table([d.key ? `Value of ${d.key}` : "Property", "People"], d.rows.map((r) => [truncate(r.value), num(r.visitors)]), ["left", "right"]),
838
+ d.nextOffset !== null ? dim(`${num(d.total - d.rows.length)} more: --offset ${d.nextOffset}`) : "",
839
+ d.key ? "" : dim("Values: metricraven analytics properties <name> [--goal <goal>]. Filter: -f prop.<name>[@goal]:is:<value>"),
840
+ ]
841
+ .filter(Boolean)
842
+ .join("\n");
843
+ },
543
844
  goal(d) {
544
845
  const t = d.totals;
545
846
  return [
@@ -549,7 +850,16 @@ const RENDER = {
549
850
  d.sources.length
550
851
  ? section("Sources", table(["Source", "Visitors"], d.sources.slice(0, 10).map((s) => [s.name, num(s.visitors)]), ["left", "right"]))
551
852
  : "",
552
- ...d.properties.slice(0, 5).map((p) => section(`Property: ${p.key}`, table(["Value", "Completions"], p.values.slice(0, 10).map((v) => [truncate(v.value), num(v.events)]), ["left", "right"]))),
853
+ ...d.properties.slice(0, 5).map((p) => {
854
+ // People who paid at or after completing it with the value; no money columns where revenue is hidden.
855
+ const withMoney = p.values.some((v) => typeof v.revenue === "number");
856
+ return section(`Property: ${p.key}`, table(["Value", "Completions", "People", ...(withMoney ? ["Bought", "Purchase %", "Revenue"] : [])], p.values.slice(0, 10).map((v) => [
857
+ truncate(v.value),
858
+ num(v.events),
859
+ num(v.people ?? null),
860
+ ...(withMoney ? [num(v.payingPeople ?? null), pct(v.purchaseRate ?? null), money(v.revenue ?? null, d.period.currency)] : []),
861
+ ]), ["left", "right", "right", ...(withMoney ? ["right", "right", "right"] : [])]));
862
+ }),
553
863
  ]
554
864
  .filter(Boolean)
555
865
  .join("\n");
@@ -597,14 +907,26 @@ async function listVisitors(ctx) {
597
907
  if (!d.rows.length)
598
908
  return out(dim("No visitors match.")), 0;
599
909
  out(periodLine(d.period));
600
- out(table(["Visitor", "Paid", "Pageviews", "Source", "Country", "Last seen"], d.rows.map((r) => [r.name ?? r.email ?? r.visitorId, r.paid ? "yes" : "", num(r.pageviews), r.source ?? "–", r.country ?? "–", date(r.lastPageviewAt)]), ["left", "left", "right", "left", "left", "left"]));
910
+ // With a "Same visit" condition, each row says when its matching visit started.
911
+ const matched = [...params.keys()].some((k) => /^visit[A-Z]/.test(k));
912
+ out(table(["Visitor", ...(matched ? ["Matched visit"] : []), "Paid", "Pageviews", "Source", "Country", "Last seen"], d.rows.map((r) => [
913
+ r.name ?? r.email ?? r.visitorId,
914
+ ...(matched ? [r.matchedVisitAt ? date(r.matchedVisitAt) : "–"] : []),
915
+ r.paid ? "yes" : "",
916
+ num(r.pageviews),
917
+ r.source ?? "–",
918
+ r.country ?? "–",
919
+ date(r.lastPageviewAt),
920
+ ]), ["left", ...(matched ? ["left"] : []), "left", "right", "left", "left", "left"]));
601
921
  out(dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`));
602
922
  return 0;
603
923
  }
604
924
  async function getVisitor(ctx, id) {
605
925
  if (!id)
606
- throw new UsageError("Use: metricraven visitors get <visitor_id>");
926
+ throw new UsageError("Use: metricraven visitors get <visitor_id> [--visit <ISO time>]");
607
927
  const params = new URLSearchParams({ site: await ctx.site() });
928
+ if (ctx.flags.visit)
929
+ params.set("visitAt", ctx.flags.visit);
608
930
  const d = await ctx.client.get(`/visitors/${encodeURIComponent(id)}`, params).catch((e) => needs("visitors", Promise.reject(e)));
609
931
  if (ctx.flags.json)
610
932
  return printJson(d), 0;
@@ -614,16 +936,185 @@ async function getVisitor(ctx, id) {
614
936
  if (s.firstTouch)
615
937
  out(`First touch: ${s.firstTouch.channel ?? "–"} / ${s.firstTouch.source ?? "–"} → ${s.firstTouch.landingPage ?? "–"}`);
616
938
  out(dim(`${date(s.firstSeenAt)} → ${date(s.lastSeenAt)}`));
617
- out(section("Timeline", table(["When", "Type", "Detail"], d.timeline.slice(-50).map((t) => [date(t.at), t.type, truncate(t.path ?? t.name ?? (t.amount !== undefined ? money(t.amount) : ""), 60)]))));
939
+ // Session recordings (Growth) are watched in the dashboard; the CLI only says they exist.
940
+ if (d.replays?.length)
941
+ out(`Recordings: ${num(d.replays.length)} (watch in the dashboard)`);
942
+ // --visit: the visit containing that time, and only its rows; otherwise the last 50 rows.
943
+ const v = d.visit;
944
+ if (v)
945
+ out(`Visit ${num(v.number)} · ${date(v.startedAt)} → ${date(v.endedAt)} · ${v.channel ?? "–"}/${v.source ?? "–"} → ${v.landingPage ?? "–"}`);
946
+ const rows = v ? d.timeline.filter((t) => t.visit === v.number) : d.timeline.slice(-50);
947
+ out(section("Timeline", table(["When", "Type", "Detail"], rows.map((t) => [
948
+ date(t.at),
949
+ t.type,
950
+ // JavaScript errors (L-2): "TypeError: message on /pricing".
951
+ truncate(t.type === "error"
952
+ ? `${t.name}: ${t.message ?? ""}${t.path ? ` on ${t.path}` : ""}`
953
+ : (t.path ?? t.name ?? (t.amount !== undefined ? money(t.amount) : "")), 60),
954
+ ]))));
618
955
  return 0;
619
956
  }
620
- async function listFunnels(ctx) {
621
- const d = await ctx.client.get("/funnels", new URLSearchParams({ site: await ctx.site() }));
622
- if (ctx.flags.json)
957
+ /** core/funnels.ts FUNNEL_STEPS_HELP (the CLI ships without core). */
958
+ export const FUNNEL_STEPS_HELP = "1–8 comma-separated steps, counted in order: visit, page:/path (path prefix), page:=/path (exact page), page:host/path (one hostname), event:goal_name, identify, payment. Example: visit,page:/pricing,event:signup,payment";
959
+ /** Saved funnels: list, create, update, delete (changes need write access). */
960
+ async function funnels(ctx, sub, rest) {
961
+ const { flags, client } = ctx;
962
+ const site = await ctx.site();
963
+ const params = () => new URLSearchParams({ site });
964
+ const funnelPath = (id) => {
965
+ if (!id)
966
+ throw new UsageError(`Use: metricraven funnels ${sub} <funnel_id> (IDs from \`metricraven funnels list\`).`);
967
+ return `/funnels/${encodeURIComponent(id)}`;
968
+ };
969
+ switch (sub ?? "list") {
970
+ case "list": {
971
+ const d = await client.get("/funnels", params());
972
+ if (flags.json)
973
+ return printJson(d), 0;
974
+ if (!d.funnels.length)
975
+ return out(dim("No saved funnels.")), 0;
976
+ out(table(["Funnel", "Steps", "ID"], d.funnels.map((f) => [f.name, truncate(f.steps, 70), f.id])));
977
+ return 0;
978
+ }
979
+ case "create": {
980
+ if (!flags.name?.trim() || !flags.steps?.trim())
981
+ throw new UsageError(`Use: metricraven funnels create --name <name> --steps <steps>. Steps: ${FUNNEL_STEPS_HELP}.`);
982
+ const f = await needs("write", client.post("/funnels", { name: flags.name, steps: flags.steps }, params()));
983
+ if (flags.json)
984
+ return printJson(f), 0;
985
+ const count = f.steps.split(",").filter((step) => step.trim()).length;
986
+ out(`Created funnel "${f.name}" (${count} step${count === 1 ? "" : "s"}). ID ${f.id}`);
987
+ out(dim(`Report it: metricraven analytics conversions --funnel ${f.id}`));
988
+ return 0;
989
+ }
990
+ case "update": {
991
+ const path = funnelPath(rest[0]);
992
+ if (flags.name === undefined && flags.steps === undefined)
993
+ throw new UsageError("Nothing to change. Use --name or --steps.");
994
+ const f = await needs("write", client.put(path, { name: flags.name, steps: flags.steps }, params()));
995
+ if (flags.json)
996
+ return printJson(f), 0;
997
+ out(`Updated funnel "${f.name}".`);
998
+ return 0;
999
+ }
1000
+ case "delete": {
1001
+ const path = funnelPath(rest[0]);
1002
+ if (!(await confirmOrStop(flags, `Delete funnel ${rest[0]}? Its data is kept.`)))
1003
+ return 0;
1004
+ const d = await needs("write", client.del(path, params()));
1005
+ if (flags.json)
1006
+ return printJson(d), 0;
1007
+ out(`Deleted funnel ${rest[0]}.`);
1008
+ return 0;
1009
+ }
1010
+ }
1011
+ throw new UsageError(`Unknown command "funnels ${sub}". Use list, create, update, delete or dropoff.`);
1012
+ }
1013
+ /** "country is US · urlParam.plan is pro · utmCampaign is empty", as --filter would write it. */
1014
+ export function filtersText(filters) {
1015
+ return filters
1016
+ .map((f) => {
1017
+ const slot = f.key ? `${f.dim}.${f.key}${f.goal ? `@${f.goal}` : ""}` : f.dim;
1018
+ return `${slot} ${f.op.replace(/_/g, " ")}${f.values.length ? ` ${f.values.join(", ")}` : ""}`;
1019
+ })
1020
+ .join(" · ");
1021
+ }
1022
+ /** Saved segments: listing needs visitor details access, changes need write access. */
1023
+ async function segments(ctx, sub, rest) {
1024
+ const { flags, client } = ctx;
1025
+ const site = await ctx.site();
1026
+ const params = () => new URLSearchParams({ site });
1027
+ const list = () => needs("visitors", client.get("/segments", params()));
1028
+ const current = async (id) => {
1029
+ if (!id)
1030
+ throw new UsageError(`Use: metricraven segments ${sub} <segment_id> (IDs from \`metricraven segments list\`).`);
1031
+ const segment = (await list()).segments.find((s) => s.id === id);
1032
+ if (!segment)
1033
+ throw new UsageError(`No segment "${id}". Run \`metricraven segments list\`.`);
1034
+ return segment;
1035
+ };
1036
+ const segmentPath = (id) => `/segments/${encodeURIComponent(id)}`;
1037
+ switch (sub ?? "list") {
1038
+ case "list": {
1039
+ const d = await list();
1040
+ if (flags.json)
1041
+ return printJson(d), 0;
1042
+ if (!d.segments.length)
1043
+ return out(dim("No saved segments.")), 0;
1044
+ out(table(["Segment", "Filters", "ID"], d.segments.map((s) => [s.name, truncate(filtersText(s.filters), 70), s.id])));
1045
+ return 0;
1046
+ }
1047
+ case "create": {
1048
+ if (!flags.name?.trim())
1049
+ throw new UsageError("Use: metricraven segments create --name <name> --filter dim:op:value (repeat --filter, up to six).");
1050
+ const filters = buildFilters(flags.filter);
1051
+ if (!filters.length)
1052
+ throw new UsageError("Add at least one --filter, e.g. --filter country:is:US.");
1053
+ const s = await needs("write", client.post("/segments", { name: flags.name, filters }, params()));
1054
+ if (flags.json)
1055
+ return printJson(s), 0;
1056
+ out(`Saved segment "${s.name}". ID ${s.id}`);
1057
+ return 0;
1058
+ }
1059
+ case "update": {
1060
+ if (flags.name === undefined && !flags.filter?.length)
1061
+ throw new UsageError("Nothing to change. Use --name or --filter (filters replace all).");
1062
+ const filters = flags.filter?.length ? buildFilters(flags.filter) : undefined;
1063
+ const seg = await current(rest[0]);
1064
+ const s = await needs("write", client.put(segmentPath(seg.id), { revision: seg.revision, name: flags.name ?? seg.name, filters: filters ?? seg.filters }, params()));
1065
+ if (flags.json)
1066
+ return printJson(s), 0;
1067
+ out(`Updated segment "${s.name}".`);
1068
+ return 0;
1069
+ }
1070
+ case "delete": {
1071
+ const seg = await current(rest[0]);
1072
+ if (!(await confirmOrStop(flags, `Delete segment "${seg.name}"?`)))
1073
+ return 0;
1074
+ const d = await needs("write", client.del(segmentPath(seg.id), params(), { revision: seg.revision }));
1075
+ if (flags.json)
1076
+ return printJson(d), 0;
1077
+ out(`Deleted segment "${seg.name}".`);
1078
+ return 0;
1079
+ }
1080
+ }
1081
+ throw new UsageError(`Unknown command "segments ${sub}". Use list, create, update or delete.`);
1082
+ }
1083
+ /** Who left a funnel after step N (1-based), or went on with --continued. Without an ID: the default funnel. */
1084
+ async function funnelDropoff(ctx, id) {
1085
+ const { flags } = ctx;
1086
+ const step = flags.step === undefined ? undefined : Number(flags.step);
1087
+ if (step === undefined || !Number.isInteger(step) || step < 1 || step > 7)
1088
+ throw new UsageError("Use: metricraven funnels dropoff <funnel_id> --step <n> (n from 1; the last step has no next step) [--continued]");
1089
+ const params = rangeParams(flags);
1090
+ if (id)
1091
+ params.set("funnel", id);
1092
+ else if (flags.steps)
1093
+ params.set("steps", flags.steps);
1094
+ params.set("step", String(step - 1));
1095
+ params.set("outcome", flags.continued ? "continued" : "dropped");
1096
+ if (flags.q)
1097
+ params.set("q", flags.q);
1098
+ const limit = positiveInt(flags.limit, "limit", 100);
1099
+ if (limit !== undefined)
1100
+ params.set("limit", String(Math.max(1, limit)));
1101
+ const offset = positiveInt(flags.offset, "offset", 1_000_000);
1102
+ if (offset !== undefined)
1103
+ params.set("offset", String(offset));
1104
+ params.set("site", await ctx.site());
1105
+ const selected = selectFields(flags, params);
1106
+ const d = await ctx.client
1107
+ .get("/stats/conversions/people", params)
1108
+ .catch((e) => needs("visitors", Promise.reject(e)));
1109
+ if (flags.json || selected)
623
1110
  return printJson(d), 0;
624
- if (!d.funnels.length)
625
- return out(dim("No saved funnels.")), 0;
626
- out(table(["Funnel", "Steps", "ID"], d.funnels.map((f) => [f.name, truncate(f.steps, 70), f.id])));
1111
+ out(bold(d.outcome === "dropped"
1112
+ ? `Reached "${d.stepLabel}" but not "${d.nextLabel}"`
1113
+ : `Reached "${d.stepLabel}" and went on to "${d.nextLabel}"`));
1114
+ if (!d.rows.length)
1115
+ return out(dim(d.outcome === "dropped" ? "Nobody left at this step in this period." : "Nobody reached the next step in this period.")), 0;
1116
+ out(table(["Visitor", "Source", "Country", "Reached", "Spent"], d.rows.map((r) => [r.name ?? r.email ?? r.visitorId, r.source ?? r.channel, r.country ?? "–", date(r.reachedAt), r.spent ? money(r.spent, d.currency) : "–"]), ["left", "left", "left", "left", "right"]));
1117
+ out(dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`));
627
1118
  return 0;
628
1119
  }
629
1120
  /** Notes take calendar days; the period becomes from/to dates in the chosen zone. */
@@ -738,6 +1229,7 @@ async function aiVisibility(ctx) {
738
1229
  }
739
1230
  /** "Signup started (signup_started)" when the goal has a display name, else the raw name. */
740
1231
  const goalText = (g) => g.displayName && g.displayName !== g.name ? `${g.displayName} (${g.name})` : g.name;
1232
+ const CATEGORY_CHOICES = ["conversion", "engagement", "none", "default"];
741
1233
  /** `metricraven goals …`: how goals are shown (display name, colour, description, hidden). */
742
1234
  async function goals(ctx, sub, rest) {
743
1235
  const { flags, client } = ctx;
@@ -759,7 +1251,7 @@ async function goals(ctx, sub, rest) {
759
1251
  return printJson(d), 0;
760
1252
  if (!d.customizations.length)
761
1253
  return out(dim("No goal customisations yet. Use `metricraven goals set <goal> --name <label>`.")), 0;
762
- 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) : "–"])));
1254
+ out(table(["Goal", "Display name", "Colour", "Counts as", "Hidden", "Description"], d.customizations.map((c) => [c.goal, c.displayName ?? "–", colorText(c.color, d.colors), c.category ?? "default", c.hidden ? "yes" : "no", c.description ? truncate(c.description, 50) : "–"])));
763
1255
  return 0;
764
1256
  }
765
1257
  case "colors":
@@ -792,17 +1284,22 @@ async function goals(ctx, sub, rest) {
792
1284
  body.color = match.color;
793
1285
  }
794
1286
  }
1287
+ if (flags.category !== undefined) {
1288
+ if (!CATEGORY_CHOICES.includes(flags.category))
1289
+ throw new UsageError(`--category must be one of: ${CATEGORY_CHOICES.join(", ")}.`);
1290
+ body.category = flags.category === "default" ? null : flags.category;
1291
+ }
795
1292
  if (flags.hidden)
796
1293
  body.hidden = true;
797
1294
  if (flags.visible)
798
1295
  body.hidden = false;
799
1296
  if (Object.keys(body).length === 1)
800
- throw new UsageError("Nothing to change. Use --name, --color, --description, --hidden or --visible.");
1297
+ throw new UsageError("Nothing to change. Use --name, --color, --description, --category, --hidden or --visible.");
801
1298
  const d = await needs("write", client.put("/goals/customizations", body, params()));
802
1299
  if (flags.json)
803
1300
  return printJson(d), 0;
804
1301
  const c = d.customization;
805
- out(`Saved ${bold(goalText({ name: c.goal, displayName: c.displayName }))}: colour ${colorText(c.color, d.colors)}, ${c.hidden ? "hidden" : "visible"}.`);
1302
+ out(`Saved ${bold(goalText({ name: c.goal, displayName: c.displayName }))}: colour ${colorText(c.color, d.colors)}, counts as ${c.category ?? "default"}, ${c.hidden ? "hidden" : "visible"}.`);
806
1303
  return 0;
807
1304
  }
808
1305
  case "reset": {
@@ -816,7 +1313,126 @@ async function goals(ctx, sub, rest) {
816
1313
  return 0;
817
1314
  }
818
1315
  }
819
- throw new UsageError(`Unknown command "goals ${sub}". Use list, set, reset or colors.`);
1316
+ if (sub === "definitions" || sub === "preview" || sub === "define" || sub === "undefine")
1317
+ return goalDefinitions(ctx, sub, rest);
1318
+ throw new UsageError(`Unknown command "goals ${sub}". Use list, set, reset, colors, definitions, preview, define or undefine.`);
1319
+ }
1320
+ const definitionPattern = (d) => d.kind === "outbound"
1321
+ ? `${d.host ?? ""}${d.path ?? ""}`
1322
+ : d.kind === "click"
1323
+ ? `“${d.text ?? ""}”`
1324
+ : d.kind === "form"
1325
+ ? (d.form ?? "")
1326
+ : d.kind === "download"
1327
+ ? (d.file ?? "")
1328
+ : (d.path ?? "");
1329
+ const KIND_LABEL = { page: "page", outbound: "link", click: "button", form: "form", download: "download" };
1330
+ /**
1331
+ * `--page /pricing`, `--link stripe.com [--link-path /checkout/**]`, `--click "Start free trial"`,
1332
+ * `--form signup` or `--download .pdf` as API fields.
1333
+ */
1334
+ function definitionInput(flags) {
1335
+ const given = ["page", "link", "click", "form", "download"].filter((k) => flags[k] !== undefined);
1336
+ if (given.length > 1)
1337
+ throw new UsageError(`Use one of --page, --link, --click, --form or --download, not ${given.map((g) => `--${g}`).join(" and ")}.`);
1338
+ if (flags.page)
1339
+ return { kind: "page", path: flags.page };
1340
+ if (flags.link)
1341
+ return { kind: "outbound", host: flags.link, ...(flags["link-path"] ? { path: flags["link-path"] } : {}) };
1342
+ if (flags.click)
1343
+ return { kind: "click", text: flags.click };
1344
+ if (flags.form)
1345
+ return { kind: "form", form: flags.form };
1346
+ if (flags.download)
1347
+ return { kind: "download", file: flags.download };
1348
+ throw new UsageError("Add --page <path> (e.g. /pricing, /blog/*, /docs/**), --link <site> [--link-path <path>], or from automatic events --click <button text>, --form <id or name> or --download <file or .ext>.");
1349
+ }
1350
+ function previewLines(p) {
1351
+ if (!p.visitors)
1352
+ return ["No visitors matched in the last 30 days. The goal will still count future visits."];
1353
+ const lines = [`${num(p.visitors)} visitors would have converted in the last 30 days (${pct(p.rate)} of ${num(p.totalVisitors)}).`];
1354
+ if (p.payingVisitors !== undefined)
1355
+ lines[0] += ` ${num(p.payingVisitors)} of them paid ${money(p.revenue ?? 0, p.currency)}.`;
1356
+ if (p.matches.length)
1357
+ lines.push(dim(`Matches: ${p.matches.map((m) => `${m.value} (${num(m.visitors)})`).join(", ")}`));
1358
+ return lines;
1359
+ }
1360
+ /** `goals definitions | preview | define <name> | undefine <name>`: goals without code (page, link, button, form, download). */
1361
+ async function goalDefinitions(ctx, sub, rest) {
1362
+ const { flags, client } = ctx;
1363
+ const site = await ctx.site();
1364
+ const params = () => new URLSearchParams({ site });
1365
+ const preview = async () => {
1366
+ const input = definitionInput(flags);
1367
+ const p = params();
1368
+ for (const [k, v] of Object.entries(input))
1369
+ p.set(k, v);
1370
+ return client.get("/goals/definitions/preview", p);
1371
+ };
1372
+ switch (sub) {
1373
+ case "definitions": {
1374
+ const d = await client.get("/goals/definitions", params());
1375
+ if (flags.json)
1376
+ return printJson(d), 0;
1377
+ if (!d.definitions.length)
1378
+ return out(dim("No goals without code yet. Use `metricraven goals define <name> --page /pricing`.")), 0;
1379
+ out(table(["Name", "Type", "Pattern"], d.definitions.map((g) => [g.name, KIND_LABEL[g.kind] ?? g.kind, definitionPattern(g)])));
1380
+ return 0;
1381
+ }
1382
+ case "preview": {
1383
+ const d = await preview();
1384
+ if (flags.json)
1385
+ return printJson(d), 0;
1386
+ for (const line of previewLines(d))
1387
+ out(line);
1388
+ return 0;
1389
+ }
1390
+ case "define": {
1391
+ const name = rest[0];
1392
+ if (!name)
1393
+ throw new UsageError("Use: metricraven goals define <name> --page <path> | --link <site> [--link-path <path>] | --click <text> | --form <id> | --download <file>");
1394
+ const input = definitionInput(flags);
1395
+ if (!flags.json) {
1396
+ for (const line of previewLines(await preview()))
1397
+ out(line);
1398
+ if (!(await confirmOrStop(flags, `Create the goal ${name}? It counts past visits at once.`)))
1399
+ return 0;
1400
+ }
1401
+ else if (!flags.yes)
1402
+ throw new UsageError("Add --yes to do this without a prompt.");
1403
+ const d = await needs("write", client.post("/goals/definitions", { name, ...input }, params()));
1404
+ if (flags.json)
1405
+ return printJson(d), 0;
1406
+ out(`Created ${bold(d.definition.name)} (${KIND_LABEL[d.definition.kind] ?? d.definition.kind} ${definitionPattern(d.definition)}). It already counts past visits.`);
1407
+ return 0;
1408
+ }
1409
+ case "undefine": {
1410
+ const name = rest[0];
1411
+ if (!name)
1412
+ throw new UsageError("Use: metricraven goals undefine <name>");
1413
+ const { definitions } = await client.get("/goals/definitions", params());
1414
+ const def = definitions.find((g) => g.name === name);
1415
+ if (!def)
1416
+ throw new UsageError(`No goal without code named "${name}". See \`metricraven goals definitions\`.`);
1417
+ const path = `/goals/definitions/${encodeURIComponent(def.id)}`;
1418
+ const dry = await needs("write", client.del(path, new URLSearchParams([...params(), ["dryRun", "1"]])));
1419
+ const uses = [
1420
+ dry.usedBy.alerts ? `${num(dry.usedBy.alerts)} ${plural("alerts", dry.usedBy.alerts)}` : "",
1421
+ dry.usedBy.funnels ? `${num(dry.usedBy.funnels)} ${plural("funnels", dry.usedBy.funnels)}` : "",
1422
+ dry.usedBy.primaryGoal ? "the primary goal" : "",
1423
+ ].filter(Boolean);
1424
+ if (uses.length && !flags.json)
1425
+ out(`Still used by ${uses.join(", ")}; they will count 0 until you change them.`);
1426
+ if (!(await confirmOrStop(flags, `Delete the goal ${name}? Reports stop counting it at once.`)))
1427
+ return 0;
1428
+ const d = await needs("write", client.del(path, params()));
1429
+ if (flags.json)
1430
+ return printJson(d), 0;
1431
+ out(`Deleted ${name}.`);
1432
+ return 0;
1433
+ }
1434
+ }
1435
+ return 1;
820
1436
  }
821
1437
  /**
822
1438
  * `--recipients a@x.com,b@x.com` (emails or user IDs), or `all` for every current member. The API
@@ -1385,6 +2001,160 @@ async function deleteWithCount(ctx, path, params, what) {
1385
2001
  out(`Deleted ${num(d.deleted)} ${plural(what, d.deleted)}.`);
1386
2002
  return 0;
1387
2003
  }
2004
+ /** --all stops here (with a note on stderr); continue with --cursor. */
2005
+ export const RAW_ALL_CAP = 100_000;
2006
+ const EVENT_CSV = [
2007
+ ["id", (e) => e.id],
2008
+ ["created_at", (e) => e.createdAt],
2009
+ ["type", (e) => e.type],
2010
+ ["name", (e) => e.name],
2011
+ ["hostname", (e) => e.hostname],
2012
+ ["path", (e) => e.path],
2013
+ ["referrer", (e) => e.referrer],
2014
+ ["utm_source", (e) => e.utm?.source],
2015
+ ["utm_medium", (e) => e.utm?.medium],
2016
+ ["utm_campaign", (e) => e.utm?.campaign],
2017
+ ["utm_term", (e) => e.utm?.term],
2018
+ ["utm_content", (e) => e.utm?.content],
2019
+ ["country", (e) => e.country],
2020
+ ["region", (e) => e.region],
2021
+ ["city", (e) => e.city],
2022
+ ["browser", (e) => e.browser],
2023
+ ["os", (e) => e.os],
2024
+ ["device", (e) => e.device],
2025
+ ["visitor_id", (e) => e.visitorId],
2026
+ ["user_id", (e) => e.userId],
2027
+ ["duration", (e) => e.duration],
2028
+ ["props", (e) => (e.props == null ? null : JSON.stringify(e.props))],
2029
+ ];
2030
+ const PAYMENT_CSV = [
2031
+ ["id", (p) => p.id],
2032
+ ["created_at", (p) => p.createdAt],
2033
+ ["provider", (p) => p.provider],
2034
+ ["amount", (p) => p.amount],
2035
+ ["currency", (p) => p.currency],
2036
+ ["refunded_amount", (p) => p.refundedAmount],
2037
+ ["refunded", (p) => p.refunded],
2038
+ ["free_trial", (p) => p.isFreeTrial],
2039
+ ["renewal", (p) => p.renewal],
2040
+ ["plan", (p) => p.plan],
2041
+ ["subscription_id", (p) => p.subscriptionId],
2042
+ ["customer_id", (p) => p.customerId],
2043
+ ["user_id", (p) => p.userId],
2044
+ ["visitor_id", (p) => p.visitorId],
2045
+ ["customer_email", (p) => p.customer?.email],
2046
+ ["customer_name", (p) => p.customer?.name],
2047
+ ["channel", (p) => p.attribution?.channel],
2048
+ ["source", (p) => p.attribution?.source],
2049
+ ["landing_page", (p) => p.attribution?.landingPage],
2050
+ ["first_referrer", (p) => p.attribution?.referrer],
2051
+ ["first_utm_source", (p) => p.attribution?.utmSource],
2052
+ ["first_utm_medium", (p) => p.attribution?.utmMedium],
2053
+ ["first_utm_campaign", (p) => p.attribution?.utmCampaign],
2054
+ ["first_country", (p) => p.attribution?.country],
2055
+ ["first_seen_at", (p) => p.attribution?.firstSeenAt],
2056
+ ];
2057
+ /** Query parameters of `events list` / `payments list` (GET /events, GET /payments). */
2058
+ export function rawListParams(kind, flags, now = new Date()) {
2059
+ if (!flags.from && !flags.to && flags.period === "all")
2060
+ throw new UsageError("Raw lists need a period: use --period with a preset or --from/--to, not all.");
2061
+ const range = rangeParams({ ...flags, compare: undefined }, now);
2062
+ const params = new URLSearchParams();
2063
+ for (const key of ["from", "to", "filters"]) {
2064
+ const value = range.get(key);
2065
+ if (value)
2066
+ params.set(key, value);
2067
+ }
2068
+ if (kind === "events") {
2069
+ if (flags.type)
2070
+ params.set("type", flags.type);
2071
+ if (flags.goal)
2072
+ params.set("name", flags.goal);
2073
+ }
2074
+ else if (flags.transaction)
2075
+ params.set("transaction_id", flags.transaction);
2076
+ if (flags.visitor)
2077
+ params.set("visitor_id", flags.visitor);
2078
+ if (flags.user)
2079
+ params.set("user_id", flags.user);
2080
+ const limit = positiveInt(flags.limit, "limit", 1000);
2081
+ if (limit !== undefined)
2082
+ params.set("limit", String(Math.max(1, limit)));
2083
+ else if (flags.all)
2084
+ params.set("limit", "1000");
2085
+ if (flags.cursor)
2086
+ params.set("cursor", flags.cursor);
2087
+ return params;
2088
+ }
2089
+ /**
2090
+ * events list / payments list: raw rows, newest first. --all follows nextCursor (up to
2091
+ * RAW_ALL_CAP rows); --csv prints CSV (header once), --json the API's JSON (one object; with
2092
+ * --all every row in it).
2093
+ */
2094
+ async function listRaw(ctx, kind) {
2095
+ const { flags } = ctx;
2096
+ if (flags.csv && flags.json)
2097
+ throw new UsageError("Use --csv or --json, not both.");
2098
+ const params = rawListParams(kind, flags);
2099
+ params.set("site", await ctx.site());
2100
+ const rows = [];
2101
+ let page;
2102
+ let first = null;
2103
+ let capped = false;
2104
+ for (;;) {
2105
+ page = await needs("visitors", ctx.client.get(`/${kind}`, params));
2106
+ first ??= page;
2107
+ const items = (kind === "events" ? page.events : page.payments) ?? [];
2108
+ if (flags.csv) {
2109
+ const columns = (kind === "events" ? EVENT_CSV : PAYMENT_CSV);
2110
+ // CRLF line ends (RFC 4180); escape sequences from report data are still removed.
2111
+ const write = (cells) => process.stdout.write(`${terminalSafe(csvLine(cells))}\r\n`);
2112
+ if (first === page)
2113
+ write(columns.map(([name]) => name));
2114
+ for (const item of items)
2115
+ write(columns.map(([, get]) => get(item)));
2116
+ }
2117
+ rows.push(...items);
2118
+ if (!flags.all || !page.nextCursor)
2119
+ break;
2120
+ if (rows.length >= RAW_ALL_CAP) {
2121
+ capped = true;
2122
+ break;
2123
+ }
2124
+ params.set("cursor", page.nextCursor);
2125
+ }
2126
+ if (capped)
2127
+ process.stderr.write(`Stopped at ${num(rows.length)} rows. Continue with --cursor ${page.nextCursor}\n`);
2128
+ if (flags.csv)
2129
+ return 0;
2130
+ if (flags.json)
2131
+ return printJson({ [kind]: rows, nextCursor: page.nextCursor, from: first.from, to: first.to }), 0;
2132
+ if (!rows.length)
2133
+ return out(dim(kind === "events" ? "No events match." : "No payments match.")), 0;
2134
+ out(periodLine({ from: first.from, to: first.to }));
2135
+ if (kind === "events")
2136
+ out(table(["Time", "Type", "Name/Path", "Source", "Country", "Device", "Visitor"], rows.map((e) => [
2137
+ date(e.createdAt),
2138
+ e.type,
2139
+ truncate(e.name ?? e.path ?? "–", 40),
2140
+ truncate(e.utm?.source ?? e.referrer ?? "–", 28),
2141
+ e.country ?? "–",
2142
+ e.device ?? "–",
2143
+ e.userId ?? e.visitorId?.slice(0, 12) ?? "–",
2144
+ ])));
2145
+ else
2146
+ out(table(["Time", "Amount", "Plan", "Channel", "Source", "Customer", "Status"], rows.map((p) => [
2147
+ date(p.createdAt),
2148
+ money(p.amount, p.currency),
2149
+ p.plan ?? "–",
2150
+ p.attribution?.channel ?? "–",
2151
+ truncate(p.attribution?.source ?? "–", 28),
2152
+ truncate(p.customer?.email ?? p.customer?.name ?? p.userId ?? p.customerId ?? "–", 32),
2153
+ p.refunded ? "refunded" : p.isFreeTrial ? "trial" : "",
2154
+ ]), ["left", "right", "left", "left", "left", "left", "left"]));
2155
+ out(dim(`${num(rows.length)} ${rows.length === 1 ? "row" : "rows"}${page.nextCursor ? ` · next: --cursor ${page.nextCursor}` : ""}`));
2156
+ return 0;
2157
+ }
1388
2158
  async function deletePayments(ctx) {
1389
2159
  const { flags } = ctx;
1390
2160
  const params = new URLSearchParams();
@@ -1430,6 +2200,14 @@ function visitorSearchParams(flags, params) {
1430
2200
  ["device", "device"],
1431
2201
  ["browser", "browser"],
1432
2202
  ["os", "os"],
2203
+ ["visit-source", "visitSource"],
2204
+ ["visit-channel", "visitChannel"],
2205
+ ["visit-campaign", "visitCampaign"],
2206
+ ["visit-referrer", "visitReferrer"],
2207
+ ["visit-entry-page", "visitEntryPage"],
2208
+ ["visit-page", "visitPage"],
2209
+ ["visit-page-contains", "visitPageContains"],
2210
+ ["visit-goal", "visitGoal"],
1433
2211
  ];
1434
2212
  for (const [flag, param] of map) {
1435
2213
  const value = flags[flag];
@@ -1442,6 +2220,53 @@ function visitorSearchParams(flags, params) {
1442
2220
  const lt = positiveInt(flags["visits-lt"], "visits-lt", 100_000);
1443
2221
  if (lt !== undefined)
1444
2222
  params.set("visits_lt", String(lt));
2223
+ // --trait role=founder[,cto] → trait.role=founder,cto (people whose latest identify trait matches).
2224
+ for (const raw of flags.trait ?? []) {
2225
+ const eq = raw.indexOf("=");
2226
+ const key = eq < 0 ? "" : raw.slice(0, eq).trim();
2227
+ const value = eq < 0 ? "" : raw.slice(eq + 1).trim();
2228
+ if (!TRAIT_KEY.test(key) || !value)
2229
+ throw new UsageError("Use --trait key=value, e.g. --trait role=founder.");
2230
+ params.set(`trait.${key}`, value);
2231
+ }
2232
+ }
2233
+ /** core/traits.ts TRAIT_KEY_PATTERN. */
2234
+ const TRAIT_KEY = /^[a-z][a-z0-9_-]{0,63}$/;
2235
+ /** `visitors traits [--key role]`: revenue, customers and purchase rate per value of one identify trait. */
2236
+ async function visitorTraits(ctx) {
2237
+ const { flags } = ctx;
2238
+ const params = rangeParams(flags);
2239
+ if (flags.key !== undefined) {
2240
+ if (!TRAIT_KEY.test(flags.key))
2241
+ throw new UsageError("Use --key <trait>, a lowercase trait name such as role.");
2242
+ params.set("key", flags.key);
2243
+ }
2244
+ visitorSearchParams(flags, params);
2245
+ params.set("site", await ctx.site());
2246
+ const selected = selectFields(flags, params);
2247
+ const d = await ctx.client
2248
+ .get("/stats/visitor-traits", params)
2249
+ .catch((e) => needs("visitors", Promise.reject(e)));
2250
+ if (flags.json || selected)
2251
+ return printJson(d), 0;
2252
+ if (!d.key)
2253
+ return out(dim("No custom traits yet. Send traits such as role or company_size with identify.")), 0;
2254
+ out(periodLine(d.period));
2255
+ const currency = d.period.currency;
2256
+ const label = (r) => r.label === "not_set" ? "Not set" : r.label === "other" ? "Other values" : r.label === "hidden_email" ? "Hidden (email addresses)" : (r.value ?? "–");
2257
+ const rows = [...d.rows, ...[d.other, d.notSet, d.hiddenEmail].filter((r) => !!r)];
2258
+ if (!d.people)
2259
+ out(dim("No identified people in this period and filters."));
2260
+ else
2261
+ out(table([d.key, "People", "Customers", "Purchase rate", "Revenue", "Revenue/person"], rows.map((r) => [label(r), num(r.people), num(r.customers), `${r.conversionRate}%`, money(r.revenue, currency), money(r.revenuePerPerson, currency)]), ["left", "right", "right", "right", "right", "right"]));
2262
+ const visible = d.keys.filter((k) => !k.hidden).map((k) => k.key);
2263
+ const hidden = d.keys.filter((k) => k.hidden).map((k) => k.key);
2264
+ out(dim(`Traits: ${visible.join(", ") || "–"}${hidden.length ? ` (hidden: ${hidden.join(", ")})` : ""}`));
2265
+ if (d.unidentified.payments)
2266
+ out(dim(`${money(d.unidentified.revenue, currency)} from ${num(d.unidentified.payments)} payments by people never identified`));
2267
+ if (d.truncated)
2268
+ out(dim("Based on the first 200,000 identified people."));
2269
+ return 0;
1445
2270
  }
1446
2271
  const GRACES = ["none", "24h", "7d"];
1447
2272
  async function siteKeys(ctx, sub, rest) {