@emit-vision/cli 0.2.5 โ†’ 0.2.7

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.
Files changed (3) hide show
  1. package/README.md +6 -7
  2. package/dist/index.js +485 -47
  3. package/package.json +10 -13
package/README.md CHANGED
@@ -4,7 +4,7 @@ Command-line interface for [Emit Vision](https://emitvision.com) โ€” the self-ho
4
4
 
5
5
  Query telemetry, manage projects and ingest keys, and control feature flags from your terminal, a deploy script, or a coding agent.
6
6
 
7
- ๐Ÿ“– **[Full CLI reference โ†’](https://app.emitvision.com/docs/cli)**
7
+ ๐Ÿ“– **[Full CLI reference โ†’](https://emitvision.com/docs/cli)**
8
8
 
9
9
  ## Installation
10
10
 
@@ -91,12 +91,11 @@ Run `emit-vision --help` for the complete command list, or `emit-vision --versio
91
91
 
92
92
  ## Documentation
93
93
 
94
- - [CLI reference](https://app.emitvision.com/docs/cli) โ€” every command, flag, and example
95
- - [Getting started](https://app.emitvision.com/docs/introduction)
96
- - [Installation & configuration](https://app.emitvision.com/docs/installation)
97
- - [Browser SDK](https://app.emitvision.com/docs/sdk-js) ยท [Node SDK](https://app.emitvision.com/docs/sdk-node)
98
- - [Changelog](https://app.emitvision.com/docs/changelog)
99
- - [Troubleshooting](https://app.emitvision.com/docs/troubleshooting)
94
+ - [CLI reference](https://emitvision.com/docs/cli) โ€” every command, flag, and example
95
+ - [Getting started](https://emitvision.com/docs/introduction)
96
+ - [Installation & configuration](https://emitvision.com/docs/installation)
97
+ - [Browser SDK](https://emitvision.com/docs/sdk-js) ยท [Node SDK](https://emitvision.com/docs/sdk-node)
98
+ - [Troubleshooting](https://emitvision.com/docs/troubleshooting)
100
99
 
101
100
  ## License
102
101
 
package/dist/index.js CHANGED
@@ -42,13 +42,40 @@ var ApiError = class extends Error {
42
42
  }
43
43
  status;
44
44
  };
45
+ var ApiShapeError = class extends Error {
46
+ constructor(path, missing, received) {
47
+ super(
48
+ `Unexpected response shape from ${path}
49
+ missing field(s): ${missing.join(", ")}
50
+ response had: ${received.join(", ") || "(no fields)"}
51
+ This usually means the CLI is out of date with the API. Try \`npm i -g @emit-vision/cli@latest\`, or re-run with --json to see the raw response.`
52
+ );
53
+ this.path = path;
54
+ this.missing = missing;
55
+ this.received = received;
56
+ this.name = "ApiShapeError";
57
+ }
58
+ path;
59
+ missing;
60
+ received;
61
+ };
62
+ function assertShape(data, expect, path) {
63
+ const sample = Array.isArray(data) ? data[0] : data;
64
+ if (sample === void 0 || sample === null || typeof sample !== "object") {
65
+ return;
66
+ }
67
+ const received = Object.keys(sample);
68
+ const missing = expect.filter((field) => !received.includes(field));
69
+ if (missing.length > 0) {
70
+ throw new ApiShapeError(path, missing, received);
71
+ }
72
+ }
45
73
  async function apiFetch(path, options = {}) {
46
74
  const config = loadConfig();
47
75
  const apiUrl = options.apiUrl ?? config.apiUrl ?? DEFAULT_API_URL;
48
76
  const pat = options.pat ?? config.pat;
49
- const headers = {
50
- "Content-Type": "application/json"
51
- };
77
+ const headers = {};
78
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
52
79
  if (pat) headers["Authorization"] = `Bearer ${pat}`;
53
80
  let res;
54
81
  try {
@@ -70,7 +97,10 @@ async function apiFetch(path, options = {}) {
70
97
  } catch {
71
98
  }
72
99
  const suffix = code ? ` (${code})` : "";
73
- throw new ApiError(401, `Not authenticated${suffix}. Run \`emit-vision login\` first.`);
100
+ throw new ApiError(
101
+ 401,
102
+ `Not authenticated${suffix}. Run \`emit-vision login\` first.`
103
+ );
74
104
  }
75
105
  if (!res.ok) {
76
106
  let msg = `HTTP ${res.status}`;
@@ -82,7 +112,11 @@ async function apiFetch(path, options = {}) {
82
112
  throw new ApiError(res.status, msg);
83
113
  }
84
114
  if (res.status === 204) return void 0;
85
- return res.json();
115
+ const data = await res.json();
116
+ if (options.expect) {
117
+ assertShape(data, options.expect, path.split("?")[0] ?? path);
118
+ }
119
+ return data;
86
120
  }
87
121
 
88
122
  // src/commands/login.ts
@@ -252,6 +286,25 @@ function runLogout() {
252
286
  console.log("Logged out.");
253
287
  }
254
288
 
289
+ // src/lib/format-date.ts
290
+ var PLACEHOLDER = "\u2014";
291
+ function pad(value, width = 2) {
292
+ return String(value).padStart(width, "0");
293
+ }
294
+ function formatTimestamp(value) {
295
+ const date = new Date(value);
296
+ if (Number.isNaN(date.getTime())) return PLACEHOLDER;
297
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
298
+ }
299
+ function formatDate(value) {
300
+ const date = new Date(value);
301
+ if (Number.isNaN(date.getTime())) return PLACEHOLDER;
302
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
303
+ }
304
+ function formatDateOrDash(value) {
305
+ return value === null || value === void 0 ? PLACEHOLDER : formatDate(value);
306
+ }
307
+
255
308
  // src/commands/project.ts
256
309
  async function runProjectList() {
257
310
  const projects = await apiFetch("/v1/management/projects");
@@ -265,7 +318,7 @@ async function runProjectList() {
265
318
  p.name,
266
319
  p.id,
267
320
  p.environment ?? "\u2014",
268
- p.createdAt ? new Date(p.createdAt).toLocaleDateString() : "\u2014"
321
+ formatDateOrDash(p.createdAt)
269
322
  ]);
270
323
  printTable(["Name", "ID", "Environment", "Created"], rows);
271
324
  }
@@ -302,7 +355,13 @@ async function runProjectEnvCreate(args) {
302
355
  }
303
356
  const result = await apiFetch(`/v1/management/projects/${encodeURIComponent(projectId)}/environments`, {
304
357
  method: "POST",
305
- body: { name: envName, ...envType ? { type: envType } : {} }
358
+ // The API's body schema is { name, environmentType } โ€” sending `type`
359
+ // made every invocation fail with `invalid_payload` (found 2026-09-11
360
+ // running the instance-telemetry runbook against CLI 0.2.5).
361
+ body: {
362
+ name: envName,
363
+ ...envType ? { environmentType: envType } : {}
364
+ }
306
365
  });
307
366
  if (json) {
308
367
  console.log(JSON.stringify(result, null, 2));
@@ -316,14 +375,16 @@ async function runProjectEnvCreate(args) {
316
375
  console.log(result.rawIngestKey);
317
376
  }
318
377
  }
378
+ var EMPTY_CELL = "\u2014";
319
379
  function printTable(headers, rows) {
380
+ const cells = rows.map((row) => headers.map((_, i) => row[i] ?? EMPTY_CELL));
320
381
  const widths = headers.map(
321
- (h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length))
382
+ (h, i) => Math.max(h.length, ...cells.map((r) => r[i].length))
322
383
  );
323
- const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ");
384
+ const line = (row) => row.map((c, i) => c.padEnd(widths[i])).join(" ");
324
385
  console.log(line(headers));
325
386
  console.log(widths.map((w) => "-".repeat(w)).join(" "));
326
- rows.forEach((r) => console.log(line(r)));
387
+ cells.forEach((r) => console.log(line(r)));
327
388
  }
328
389
 
329
390
  // src/commands/key.ts
@@ -340,7 +401,7 @@ async function runKeyGet(args) {
340
401
  console.log(`Prefix: ${key.keyPrefix}`);
341
402
  console.log(`Scope: ${key.scope}`);
342
403
  console.log(
343
- `Last used: ${key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleDateString() : "Never"}`
404
+ `Last used: ${key.lastUsedAt ? formatDate(key.lastUsedAt) : "Never"}`
344
405
  );
345
406
  }
346
407
  async function runKeyRotate(args) {
@@ -357,7 +418,10 @@ async function runKeyRotate(args) {
357
418
  );
358
419
  process.exit(1);
359
420
  }
360
- const rl = createInterface2({ input: process.stdin, output: process.stdout });
421
+ const rl = createInterface2({
422
+ input: process.stdin,
423
+ output: process.stdout
424
+ });
361
425
  const answer = await new Promise((resolve) => {
362
426
  rl.question(
363
427
  "Rotate the ingest key? This will invalidate the current key. [y/N] ",
@@ -403,11 +467,30 @@ function parseFlags(args) {
403
467
  function buildQs(projectId, flags, extras) {
404
468
  const params = new URLSearchParams({ projectId });
405
469
  const merged = { ...flags, ...extras };
406
- for (const key of ["from", "to", "environment", "release", "limit", "severity"]) {
470
+ for (const key of [
471
+ "from",
472
+ "to",
473
+ "environment",
474
+ "release",
475
+ "limit",
476
+ "severity"
477
+ ]) {
407
478
  if (merged[key]) params.set(key, merged[key]);
408
479
  }
409
480
  return params.toString();
410
481
  }
482
+ var RECENT_FIELDS = ["event_id", "event_name", "timestamp"];
483
+ var GROUPED_FIELDS = [
484
+ "fingerprint",
485
+ "sampleMessage",
486
+ "count",
487
+ "lastSeen"
488
+ ];
489
+ var OVERVIEW_FIELDS = ["totalEvents", "totalErrors"];
490
+ var LOG_FIELDS = ["timestamp", "severity_text", "body"];
491
+ function truncate(value, max) {
492
+ return value.length > max ? `${value.slice(0, max - 3)}...` : value;
493
+ }
411
494
  async function runEventsRecent(args) {
412
495
  const [projectId, ...rest2] = args;
413
496
  if (!projectId) {
@@ -418,7 +501,8 @@ async function runEventsRecent(args) {
418
501
  }
419
502
  const flags = parseFlags(rest2);
420
503
  const events = await apiFetch(
421
- `/v1/events/recent?${buildQs(projectId, flags)}`
504
+ `/v1/events/recent?${buildQs(projectId, flags)}`,
505
+ { expect: RECENT_FIELDS }
422
506
  );
423
507
  if (flags.json) {
424
508
  console.log(JSON.stringify(events, null, 2));
@@ -431,10 +515,10 @@ async function runEventsRecent(args) {
431
515
  printTable(
432
516
  ["Timestamp", "Name", "User", "Environment"],
433
517
  events.map((e) => [
434
- new Date(e.timestamp).toLocaleString(),
435
- e.name,
436
- e.userId ?? "\u2014",
437
- e.environment ?? "\u2014"
518
+ formatTimestamp(e.timestamp),
519
+ e.event_name,
520
+ e.user_id || null,
521
+ e.environment || null
438
522
  ])
439
523
  );
440
524
  }
@@ -448,7 +532,8 @@ async function runErrorsRecent(args) {
448
532
  }
449
533
  const flags = parseFlags(rest2);
450
534
  const errors = await apiFetch(
451
- `/v1/errors/recent?${buildQs(projectId, flags)}`
535
+ `/v1/errors/recent?${buildQs(projectId, flags)}`,
536
+ { expect: RECENT_FIELDS }
452
537
  );
453
538
  if (flags.json) {
454
539
  console.log(JSON.stringify(errors, null, 2));
@@ -461,10 +546,10 @@ async function runErrorsRecent(args) {
461
546
  printTable(
462
547
  ["Timestamp", "Name", "User", "Environment"],
463
548
  errors.map((e) => [
464
- new Date(e.timestamp).toLocaleString(),
465
- e.name,
466
- e.userId ?? "\u2014",
467
- e.environment ?? "\u2014"
549
+ formatTimestamp(e.timestamp),
550
+ e.event_name,
551
+ e.user_id || null,
552
+ e.environment || null
468
553
  ])
469
554
  );
470
555
  }
@@ -478,7 +563,8 @@ async function runErrorsGrouped(args) {
478
563
  }
479
564
  const flags = parseFlags(rest2);
480
565
  const groups = await apiFetch(
481
- `/v1/errors/grouped?${buildQs(projectId, flags)}`
566
+ `/v1/errors/grouped?${buildQs(projectId, flags)}`,
567
+ { expect: GROUPED_FIELDS }
482
568
  );
483
569
  if (flags.json) {
484
570
  console.log(JSON.stringify(groups, null, 2));
@@ -493,8 +579,8 @@ async function runErrorsGrouped(args) {
493
579
  groups.map((g) => [
494
580
  String(g.count),
495
581
  g.status,
496
- new Date(g.lastSeen).toLocaleString(),
497
- g.message.length > 60 ? g.message.slice(0, 57) + "..." : g.message
582
+ formatTimestamp(g.lastSeen),
583
+ truncate(g.sampleMessage, 60)
498
584
  ])
499
585
  );
500
586
  }
@@ -508,7 +594,8 @@ async function runOverview(args) {
508
594
  }
509
595
  const flags = parseFlags(rest2);
510
596
  const data = await apiFetch(
511
- `/v1/overview?${buildQs(projectId, flags)}`
597
+ `/v1/overview?${buildQs(projectId, flags)}`,
598
+ { expect: OVERVIEW_FIELDS }
512
599
  );
513
600
  if (flags.json) {
514
601
  console.log(JSON.stringify(data, null, 2));
@@ -539,6 +626,7 @@ async function runLogs(args) {
539
626
  const { logs } = await apiFetch(
540
627
  `/v1/logs?${buildQs(projectId, flags)}`
541
628
  );
629
+ assertShape(logs, LOG_FIELDS, "/v1/logs");
542
630
  if (flags.json) {
543
631
  console.log(JSON.stringify(logs, null, 2));
544
632
  return;
@@ -550,9 +638,9 @@ async function runLogs(args) {
550
638
  printTable(
551
639
  ["Timestamp", "Severity", "Message"],
552
640
  logs.map((l) => [
553
- new Date(l.timestamp).toLocaleString(),
554
- l.severity,
555
- l.body.length > 80 ? l.body.slice(0, 77) + "..." : l.body
641
+ formatTimestamp(l.timestamp),
642
+ l.severity_text,
643
+ truncate(l.body, 80)
556
644
  ])
557
645
  );
558
646
  }
@@ -660,9 +748,12 @@ async function runUsersList(args) {
660
748
  u.name || "\u2014",
661
749
  String(u.event_count),
662
750
  String(u.error_count),
663
- u.last_seen ? new Date(u.last_seen).toLocaleDateString() : "\u2014"
751
+ formatDateOrDash(u.last_seen)
664
752
  ]);
665
- printTable(["User ID", "Email", "Name", "Events", "Errors", "Last Seen"], rows);
753
+ printTable(
754
+ ["User ID", "Email", "Name", "Events", "Errors", "Last Seen"],
755
+ rows
756
+ );
666
757
  }
667
758
  async function runAudienceExport(args) {
668
759
  const [projectId, ...rest2] = args;
@@ -749,8 +840,7 @@ async function runAudienceSync(args) {
749
840
  );
750
841
  const preview = contacts.slice(0, 5);
751
842
  console.log(JSON.stringify(preview, null, 2));
752
- if (contacts.length > 5)
753
- console.log(`... and ${contacts.length - 5} more`);
843
+ if (contacts.length > 5) console.log(`... and ${contacts.length - 5} more`);
754
844
  return;
755
845
  }
756
846
  const CHUNK = 5e3;
@@ -792,10 +882,12 @@ function printSnippets(pingUrl, intervalSeconds, filter) {
792
882
  process.exit(1);
793
883
  }
794
884
  const types = filter ? [filter] : SNIPPET_TYPES;
885
+ const releaseUrl = `"${pingUrl}?release=$BUILD_NUMBER"`;
795
886
  const snippets = {
796
887
  curl: [
797
888
  "# cURL",
798
- `curl -fsS -o /dev/null ${pingUrl} \\`,
889
+ "# Optionally report the release/build this ping is running (blank is fine \u2014 omit the query param entirely to skip it)",
890
+ `curl -fsS -o /dev/null ${releaseUrl} \\`,
799
891
  ` -H "Authorization: Bearer $EMIT_VISION_INGEST_KEY"`
800
892
  ].join("\n"),
801
893
  docker: [
@@ -806,6 +898,7 @@ function printSnippets(pingUrl, intervalSeconds, filter) {
806
898
  " restart: unless-stopped",
807
899
  " environment:",
808
900
  " - EMIT_VISION_INGEST_KEY=${EMIT_VISION_INGEST_KEY}",
901
+ " - BUILD_NUMBER=${BUILD_NUMBER}",
809
902
  ` - PULSE_URL=${pingUrl}`,
810
903
  ` - PING_INTERVAL=${intervalSeconds}`,
811
904
  " entrypoint: /bin/sh",
@@ -814,7 +907,7 @@ function printSnippets(pingUrl, intervalSeconds, filter) {
814
907
  " - |",
815
908
  " while true; do",
816
909
  ' wget -q --header="Authorization: Bearer $$EMIT_VISION_INGEST_KEY" \\',
817
- ' -O /dev/null "$$PULSE_URL" || true',
910
+ ' -O /dev/null "$$PULSE_URL?release=$$BUILD_NUMBER" || true',
818
911
  " sleep $$PING_INTERVAL",
819
912
  " done"
820
913
  ].join("\n"),
@@ -826,7 +919,9 @@ function printSnippets(pingUrl, intervalSeconds, filter) {
826
919
  "",
827
920
  "[Service]",
828
921
  "Type=oneshot",
829
- `ExecStart=/usr/bin/curl -fsS -o /dev/null ${pingUrl} -H "Authorization: Bearer %d/ingest-key"`,
922
+ "# BUILD_NUMBER as set by your deploy tooling (systemd expands ${VAR} from Environment=/EnvironmentFile=)",
923
+ "EnvironmentFile=-/etc/emit-vision/release.env",
924
+ `ExecStart=/usr/bin/curl -fsS -o /dev/null ${releaseUrl} -H "Authorization: Bearer %d/ingest-key"`,
830
925
  "",
831
926
  "# /etc/systemd/system/pulse-ping.timer",
832
927
  "[Unit]",
@@ -843,7 +938,8 @@ function printSnippets(pingUrl, intervalSeconds, filter) {
843
938
  const minutes = Math.max(1, Math.floor(intervalSeconds / 60));
844
939
  return [
845
940
  "# crontab entry",
846
- `*/${minutes} * * * * curl -fsS -o /dev/null ${pingUrl} -H "Authorization: Bearer $EMIT_VISION_INGEST_KEY"`
941
+ "# BUILD_NUMBER must be exported by whatever sources this job's environment",
942
+ `*/${minutes} * * * * curl -fsS -o /dev/null ${releaseUrl} -H "Authorization: Bearer $EMIT_VISION_INGEST_KEY"`
847
943
  ].join("\n");
848
944
  })()
849
945
  };
@@ -934,10 +1030,14 @@ async function runPulseList(args) {
934
1030
  c.name,
935
1031
  c.slug,
936
1032
  c.status,
937
- c.lastPingAt ? new Date(c.lastPingAt).toLocaleString() : "never",
1033
+ c.lastPingAt ? formatTimestamp(c.lastPingAt) : "never",
1034
+ c.lastReportedRelease ?? "-",
938
1035
  `${c.expectedIntervalSeconds}s`
939
1036
  ]);
940
- printTable(["Name", "Slug", "Status", "Last Ping", "Interval"], rows);
1037
+ printTable(
1038
+ ["Name", "Slug", "Status", "Last Ping", "Release", "Interval"],
1039
+ rows
1040
+ );
941
1041
  }
942
1042
  var STATUS_COLORS = {
943
1043
  up: "\x1B[32m",
@@ -987,11 +1087,12 @@ async function runPulseStatus(args) {
987
1087
  statusLabel,
988
1088
  lastPing,
989
1089
  nextExpected,
1090
+ c.lastReportedRelease ?? "-",
990
1091
  `${c.expectedIntervalSeconds}s`
991
1092
  ];
992
1093
  });
993
1094
  printTable(
994
- ["Name", "Status", "Last Ping", "Next Expected", "Interval"],
1095
+ ["Name", "Status", "Last Ping", "Next Expected", "Release", "Interval"],
995
1096
  rows
996
1097
  );
997
1098
  }
@@ -1010,9 +1111,7 @@ async function verifyPing(pingUrl) {
1010
1111
  if (res.ok) {
1011
1112
  console.log("\u2713 First ping successful \u2014 check is now UP");
1012
1113
  } else {
1013
- console.error(
1014
- `\u2717 Ping failed: HTTP ${res.status}`
1015
- );
1114
+ console.error(`\u2717 Ping failed: HTTP ${res.status}`);
1016
1115
  }
1017
1116
  } catch (err) {
1018
1117
  console.error(
@@ -1067,7 +1166,7 @@ async function runFlagsList(args) {
1067
1166
  f.name,
1068
1167
  f.isEnabled ? "yes" : "no",
1069
1168
  `${f.rolloutPercentage ?? 100}%`,
1070
- f.updatedAt ? new Date(f.updatedAt).toLocaleDateString() : "\u2014"
1169
+ formatDateOrDash(f.updatedAt)
1071
1170
  ])
1072
1171
  );
1073
1172
  }
@@ -1207,7 +1306,10 @@ async function runFlagsArchive(args) {
1207
1306
  );
1208
1307
  process.exit(1);
1209
1308
  }
1210
- const rl = createInterface3({ input: process.stdin, output: process.stdout });
1309
+ const rl = createInterface3({
1310
+ input: process.stdin,
1311
+ output: process.stdout
1312
+ });
1211
1313
  const answer = await new Promise((resolve) => {
1212
1314
  rl.question(
1213
1315
  `Archive flag "${flagKey}"? This cannot be undone. [y/N] `,
@@ -1388,7 +1490,8 @@ async function createBoolean(projectId, key, rest2) {
1388
1490
  variants: booleanVariants()
1389
1491
  };
1390
1492
  if (description !== void 0) body.description = description;
1391
- if (rolloutPercentage !== void 0) body.rolloutPercentage = rolloutPercentage;
1493
+ if (rolloutPercentage !== void 0)
1494
+ body.rolloutPercentage = rolloutPercentage;
1392
1495
  const { flag } = await apiFetch(
1393
1496
  `/v1/flags?projectId=${encodeURIComponent(projectId)}`,
1394
1497
  { method: "POST", body }
@@ -1460,6 +1563,333 @@ At least one of --name, --description, --environments, --default-variant is requ
1460
1563
  console.log(`${flag.key} updated.`);
1461
1564
  }
1462
1565
 
1566
+ // src/commands/migration-export.ts
1567
+ import { mkdirSync as mkdirSync2, createWriteStream } from "fs";
1568
+ import { writeFile } from "fs/promises";
1569
+ import { join as join2 } from "path";
1570
+
1571
+ // src/commands/migration-shared.ts
1572
+ var MIGRATION_SCHEMA_VERSION = 1;
1573
+ var MIGRATION_CLICKHOUSE_TABLES = [
1574
+ "telemetry_events",
1575
+ "error_fingerprints",
1576
+ "error_occurrences",
1577
+ "crawler_hits"
1578
+ ];
1579
+ var MIGRATION_TIMESTAMPED_TABLES = /* @__PURE__ */ new Set([
1580
+ "telemetry_events",
1581
+ "error_occurrences",
1582
+ "crawler_hits"
1583
+ ]);
1584
+ function parseFlagArg(args, name) {
1585
+ const idx = args.indexOf(name);
1586
+ return idx !== -1 ? args[idx + 1] : void 0;
1587
+ }
1588
+ var DataRangeTracker = class {
1589
+ earliest = null;
1590
+ latest = null;
1591
+ observe(timestamp) {
1592
+ if (typeof timestamp !== "string" || !timestamp) return;
1593
+ if (this.earliest === null || timestamp < this.earliest) {
1594
+ this.earliest = timestamp;
1595
+ }
1596
+ if (this.latest === null || timestamp > this.latest) {
1597
+ this.latest = timestamp;
1598
+ }
1599
+ }
1600
+ result() {
1601
+ if (this.earliest === null || this.latest === null) return null;
1602
+ return { earliest: this.earliest, latest: this.latest };
1603
+ }
1604
+ };
1605
+
1606
+ // src/commands/migration-export.ts
1607
+ var PAGE_LIMIT = 5e3;
1608
+ async function runMigrationExport(args) {
1609
+ if (!args.includes("--all")) {
1610
+ console.error(
1611
+ "Usage: emit-vision export --all --out <directory> [--api-url <url>]"
1612
+ );
1613
+ process.exit(1);
1614
+ }
1615
+ const out = parseFlagArg(args, "--out");
1616
+ const apiUrl = parseFlagArg(args, "--api-url");
1617
+ if (!out) {
1618
+ console.error(
1619
+ "Usage: emit-vision export --all --out <directory> [--api-url <url>]"
1620
+ );
1621
+ process.exit(1);
1622
+ }
1623
+ mkdirSync2(out, { recursive: true });
1624
+ console.log("Fetching export size preview\u2026");
1625
+ const preview = await apiFetch(
1626
+ "/v1/admin/migration/manifest",
1627
+ {
1628
+ apiUrl
1629
+ }
1630
+ );
1631
+ for (const [table, count] of Object.entries(preview.tables)) {
1632
+ console.log(` ${table}: ${count.toLocaleString()}`);
1633
+ }
1634
+ console.log("\nExporting organization, projects, flags, alerts, segments\u2026");
1635
+ const { data } = await apiFetch(
1636
+ "/v1/admin/migration/export/postgres",
1637
+ { apiUrl }
1638
+ );
1639
+ await writeFile(join2(out, "postgres.json"), JSON.stringify(data, null, 2));
1640
+ const writtenCounts = {
1641
+ organization: 1,
1642
+ projects: data.projects.length,
1643
+ project_members: data.projectMembers.length,
1644
+ users: data.organizationMembers.length,
1645
+ feature_flags: data.featureFlags.length,
1646
+ feature_flag_variants: data.featureFlagVariants.length,
1647
+ alert_rules: data.alertRules.length,
1648
+ saved_segments: data.savedSegments.length
1649
+ };
1650
+ const dataRange = new DataRangeTracker();
1651
+ for (const table of MIGRATION_CLICKHOUSE_TABLES) {
1652
+ console.log(`Exporting ${table}\u2026`);
1653
+ const written = await exportClickHouseTable({
1654
+ table,
1655
+ out,
1656
+ apiUrl,
1657
+ dataRange
1658
+ });
1659
+ writtenCounts[table] = written;
1660
+ console.log(` ${table}: ${written.toLocaleString()} rows`);
1661
+ }
1662
+ const manifest = {
1663
+ schemaVersion: MIGRATION_SCHEMA_VERSION,
1664
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1665
+ sourceOrganizationId: preview.sourceOrganizationId,
1666
+ sourceApiUrl: apiUrl ?? "",
1667
+ tables: writtenCounts,
1668
+ dataRange: dataRange.result()
1669
+ };
1670
+ await writeFile(
1671
+ join2(out, "manifest.json"),
1672
+ JSON.stringify(manifest, null, 2)
1673
+ );
1674
+ console.log(`
1675
+ Export complete: ${out}`);
1676
+ console.log(
1677
+ "Run `emit-vision import " + out + "` against the destination to migrate."
1678
+ );
1679
+ }
1680
+ async function exportClickHouseTable(params) {
1681
+ const file = createWriteStream(join2(params.out, `${params.table}.ndjson`));
1682
+ const trackTimestamp = MIGRATION_TIMESTAMPED_TABLES.has(params.table);
1683
+ let cursor = null;
1684
+ let total = 0;
1685
+ do {
1686
+ const query = new URLSearchParams({ limit: String(PAGE_LIMIT) });
1687
+ if (cursor) query.set("cursor", cursor);
1688
+ const page = await apiFetch(
1689
+ `/v1/admin/migration/export/clickhouse/${params.table}?${query.toString()}`,
1690
+ { apiUrl: params.apiUrl }
1691
+ );
1692
+ for (const row of page.rows) {
1693
+ if (trackTimestamp) params.dataRange.observe(row.timestamp);
1694
+ file.write(`${JSON.stringify(row)}
1695
+ `);
1696
+ }
1697
+ total += page.count;
1698
+ cursor = page.nextCursor;
1699
+ } while (cursor !== null);
1700
+ await new Promise((resolve, reject) => {
1701
+ file.end(
1702
+ (err) => err ? reject(err) : resolve()
1703
+ );
1704
+ });
1705
+ return total;
1706
+ }
1707
+
1708
+ // src/commands/migration-import.ts
1709
+ import { createInterface as createInterface4 } from "readline";
1710
+ import { createReadStream, existsSync as existsSync2 } from "fs";
1711
+ import { readFile } from "fs/promises";
1712
+ import { join as join3 } from "path";
1713
+ var BATCH_SIZE = 2e3;
1714
+ async function runMigrationImport(args) {
1715
+ const dir = args.find((a) => !a.startsWith("--"));
1716
+ const apiUrl = parseFlagArg(args, "--api-url");
1717
+ const dryRunOnly = args.includes("--dry-run");
1718
+ const confirmed = args.includes("--yes") || args.includes("-y");
1719
+ if (!dir) {
1720
+ console.error(
1721
+ "Usage: emit-vision import <archiveDirectory> [--dry-run] [--yes] [--api-url <url>]"
1722
+ );
1723
+ process.exit(1);
1724
+ }
1725
+ const manifest = await readJson(
1726
+ join3(dir, "manifest.json")
1727
+ );
1728
+ const data = await readJson(join3(dir, "postgres.json"));
1729
+ const planResponse = await apiFetch(
1730
+ "/v1/admin/migration/import",
1731
+ {
1732
+ method: "POST",
1733
+ apiUrl,
1734
+ body: { manifest, data, dataRange: manifest.dataRange, dryRun: true }
1735
+ }
1736
+ );
1737
+ printPlan(planResponse.result, manifest);
1738
+ if (dryRunOnly) return;
1739
+ if (!confirmed) {
1740
+ if (!process.stdin.isTTY) {
1741
+ console.error(
1742
+ "stdin is not a terminal.\nPass --yes to confirm the import non-interactively."
1743
+ );
1744
+ process.exit(1);
1745
+ }
1746
+ const rl = createInterface4({
1747
+ input: process.stdin,
1748
+ output: process.stdout
1749
+ });
1750
+ const answer = await new Promise((resolve) => {
1751
+ rl.question("Proceed with this import? [y/N] ", (a) => {
1752
+ rl.close();
1753
+ resolve(a.trim().toLowerCase());
1754
+ });
1755
+ });
1756
+ if (answer !== "y" && answer !== "yes") {
1757
+ console.log("Aborted.");
1758
+ return;
1759
+ }
1760
+ }
1761
+ const { result } = await apiFetch(
1762
+ "/v1/admin/migration/import",
1763
+ {
1764
+ method: "POST",
1765
+ apiUrl,
1766
+ body: { manifest, data, dataRange: manifest.dataRange }
1767
+ }
1768
+ );
1769
+ console.log(`
1770
+ Created organization ${result.organizationId}.`);
1771
+ const clickhouseCounts = {};
1772
+ for (const table of MIGRATION_CLICKHOUSE_TABLES) {
1773
+ const file = join3(dir, `${table}.ndjson`);
1774
+ if (!existsSync2(file)) {
1775
+ clickhouseCounts[table] = 0;
1776
+ continue;
1777
+ }
1778
+ console.log(`Importing ${table}\u2026`);
1779
+ clickhouseCounts[table] = await importClickHouseTable({
1780
+ file,
1781
+ table,
1782
+ apiUrl,
1783
+ organizationId: result.organizationId,
1784
+ idMap: result.idMap
1785
+ });
1786
+ }
1787
+ printReconciliation(manifest, result, clickhouseCounts);
1788
+ printApiKeys(result);
1789
+ printMembers(result);
1790
+ }
1791
+ async function readJson(path) {
1792
+ try {
1793
+ return JSON.parse(await readFile(path, "utf-8"));
1794
+ } catch (err) {
1795
+ console.error(
1796
+ `Failed to read ${path}: ${err instanceof Error ? err.message : String(err)}
1797
+ Is this a complete archive produced by \`emit-vision export --all\`?`
1798
+ );
1799
+ process.exit(1);
1800
+ }
1801
+ }
1802
+ function printPlan(plan, manifest) {
1803
+ console.log(`
1804
+ Plan for organization "${manifest.sourceOrganizationId}":`);
1805
+ console.log(` Projects to import: ${plan.counts.projects}`);
1806
+ if (plan.projectsOverPlanLimit.length > 0) {
1807
+ console.log(
1808
+ ` \u26A0 Over the free plan's project limit, will NOT be imported: ${plan.projectsOverPlanLimit.join(", ")}`
1809
+ );
1810
+ }
1811
+ if (plan.retentionWarning) {
1812
+ console.log(` \u26A0 ${plan.retentionWarning}`);
1813
+ }
1814
+ console.log(
1815
+ ` Members to invite (existing accounts): ${plan.invitedMembers.length}`
1816
+ );
1817
+ if (plan.unresolvedMembers.length > 0) {
1818
+ console.log(
1819
+ ` Members needing a manual invite (no account yet): ${plan.unresolvedMembers.join(", ")}`
1820
+ );
1821
+ }
1822
+ }
1823
+ async function importClickHouseTable(params) {
1824
+ const rl = createInterface4({
1825
+ input: createReadStream(params.file),
1826
+ crlfDelay: Infinity
1827
+ });
1828
+ let batch = [];
1829
+ let total = 0;
1830
+ const flush = async () => {
1831
+ if (batch.length === 0) return;
1832
+ const { inserted } = await apiFetch(
1833
+ `/v1/admin/migration/import/${encodeURIComponent(params.organizationId)}/clickhouse/${params.table}`,
1834
+ {
1835
+ method: "POST",
1836
+ apiUrl: params.apiUrl,
1837
+ body: { idMap: params.idMap, rows: batch }
1838
+ }
1839
+ );
1840
+ total += inserted;
1841
+ batch = [];
1842
+ };
1843
+ for await (const line of rl) {
1844
+ if (!line.trim()) continue;
1845
+ batch.push(JSON.parse(line));
1846
+ if (batch.length >= BATCH_SIZE) await flush();
1847
+ }
1848
+ await flush();
1849
+ console.log(` ${params.table}: ${total.toLocaleString()} rows imported`);
1850
+ return total;
1851
+ }
1852
+ function printReconciliation(manifest, result, clickhouseCounts) {
1853
+ const actual = {
1854
+ ...result.counts,
1855
+ ...clickhouseCounts
1856
+ };
1857
+ console.log(
1858
+ "\nReconciliation (expected from archive vs. actually imported):"
1859
+ );
1860
+ for (const [table, expected] of Object.entries(manifest.tables)) {
1861
+ if (table === "organization" || table === "users") continue;
1862
+ const got = actual[table];
1863
+ if (got === void 0) continue;
1864
+ const flag = got === expected ? "\u2713" : "\u26A0";
1865
+ console.log(
1866
+ ` ${flag} ${table}: ${got.toLocaleString()} / ${expected.toLocaleString()}`
1867
+ );
1868
+ }
1869
+ }
1870
+ function printApiKeys(result) {
1871
+ if (result.apiKeys.length === 0) return;
1872
+ console.log(
1873
+ "\nNew API keys (source keys can't be recovered \u2014 copy these now, then update your SDKs):"
1874
+ );
1875
+ for (const key of result.apiKeys) {
1876
+ console.log(` ${key.projectName} (${key.type}): ${key.rawKey}`);
1877
+ }
1878
+ }
1879
+ function printMembers(result) {
1880
+ if (result.invitedMembers.length > 0) {
1881
+ console.log(
1882
+ `
1883
+ Invited (pending acceptance): ${result.invitedMembers.join(", ")}`
1884
+ );
1885
+ }
1886
+ if (result.unresolvedMembers.length > 0) {
1887
+ console.log(
1888
+ `Need a manual invite (no hosted account yet): ${result.unresolvedMembers.join(", ")}`
1889
+ );
1890
+ }
1891
+ }
1892
+
1463
1893
  // src/index.ts
1464
1894
  var VERSION = "0.2.5";
1465
1895
  var [cmd, subcmd, ...rest] = process.argv.slice(2);
@@ -1542,6 +1972,10 @@ async function main() {
1542
1972
  printHelp();
1543
1973
  process.exit(1);
1544
1974
  }
1975
+ } else if (cmd === "export") {
1976
+ await runMigrationExport(subcmd ? [subcmd, ...rest] : rest);
1977
+ } else if (cmd === "import") {
1978
+ await runMigrationImport(subcmd ? [subcmd, ...rest] : rest);
1545
1979
  } else if (cmd === "flags") {
1546
1980
  if (subcmd === "list") {
1547
1981
  await runFlagsList(rest);
@@ -1626,6 +2060,10 @@ Commands:
1626
2060
  pulse list --project <projectId> [--json] List pulse checks for a project
1627
2061
  pulse status --project <projectId> [--json] Show check health with colored status indicators
1628
2062
 
2063
+ export --all --out <directory> [--api-url <url>] Export an organization's full data for self-host \u2192 cloud migration
2064
+ import <archiveDirectory> [--dry-run] [--yes] [--api-url <url>]
2065
+ Import an export archive into a fresh organization
2066
+
1629
2067
  flags list <projectId> [--limit <n>] [--offset <n>] [--json] List feature flags for a project
1630
2068
  flags evaluate <projectId> --environment <env> [--user-key <key>] [--flag <key>]... [--json]
1631
2069
  Evaluate flags for a user/environment
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emit-vision/cli",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "CLI for Emit Vision โ€” query telemetry, manage projects and ingest keys, and control feature flags from the terminal.",
5
5
  "private": false,
6
6
  "license": "MIT",
@@ -13,14 +13,12 @@
13
13
  "observability",
14
14
  "cli"
15
15
  ],
16
- "homepage": "https://github.com/develemit/emit-vision/tree/main/packages/cli#readme",
16
+ "homepage": "https://emitvision.com/docs/cli",
17
17
  "repository": {
18
- "type": "git",
19
- "url": "git+https://github.com/develemit/emit-vision.git",
20
- "directory": "packages/cli"
18
+ "url": "https://emitvision.com/docs/cli"
21
19
  },
22
20
  "bugs": {
23
- "url": "https://github.com/develemit/emit-vision/issues"
21
+ "email": "hello@emitvision.com"
24
22
  },
25
23
  "bin": {
26
24
  "emit-vision": "dist/index.js"
@@ -30,16 +28,15 @@
30
28
  "LICENSE",
31
29
  "README.md"
32
30
  ],
33
- "scripts": {
34
- "build": "tsup --config tsup.config.ts",
35
- "typecheck": "tsc -p tsconfig.json --noEmit",
36
- "test": "vitest run",
37
- "prepack": "pnpm run build"
38
- },
39
31
  "publishConfig": {
40
32
  "access": "public"
41
33
  },
42
34
  "devDependencies": {
43
35
  "vitest": "^4.0.15"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup --config tsup.config.ts",
39
+ "typecheck": "tsc -p tsconfig.json --noEmit",
40
+ "test": "vitest run"
44
41
  }
45
- }
42
+ }