@debugkit/cli 0.3.1 → 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/cli.js CHANGED
@@ -72,22 +72,48 @@ import { join as join2 } from "path";
72
72
  import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from "fs";
73
73
  import { join } from "path";
74
74
  var DIR = ".debugkit";
75
+ var ENV_NAME = /^[a-z][a-z0-9-]{0,30}$/;
76
+ var current;
77
+ var environment = {
78
+ get: () => current,
79
+ set(name) {
80
+ if (name !== void 0 && !ENV_NAME.test(name)) throw new Error(`"${name}" isn't a valid environment name: use lowercase letters, digits and dashes, like preview.`);
81
+ current = name;
82
+ }
83
+ };
84
+ var cmdFor = (sub) => `npx debugkit ${sub}${current ? ` --env ${current}` : ""}`;
75
85
  function paths(cwd) {
76
86
  const dir = join(cwd, DIR);
77
- return { dir, config: join(dir, "config.json"), dashboardEnv: join(dir, "dashboard.env"), firebase: join(dir, "firebase") };
87
+ return {
88
+ dir,
89
+ config: join(dir, "config.json"),
90
+ dashboardEnv: join(dir, current ? `dashboard.${current}.env` : "dashboard.env"),
91
+ firebase: join(dir, current ? `firebase-${current}` : "firebase")
92
+ };
78
93
  }
79
- function readConfig(cwd) {
94
+ function readFile(cwd) {
80
95
  try {
81
96
  return JSON.parse(readFileSync(paths(cwd).config, "utf8"));
82
97
  } catch {
83
98
  return void 0;
84
99
  }
85
100
  }
101
+ function readConfig(cwd) {
102
+ const f = readFile(cwd);
103
+ if (!f) return void 0;
104
+ if (current) return f.environments?.[current];
105
+ return f.provider ? f : void 0;
106
+ }
107
+ function listEnvironments(cwd) {
108
+ return Object.keys(readFile(cwd)?.environments ?? {});
109
+ }
86
110
  function writeConfig(cwd, cfg) {
87
111
  const { dir, config } = paths(cwd);
88
112
  mkdirSync(dir, { recursive: true });
89
- writeFileSync(config, JSON.stringify(cfg, null, 2) + "\n");
90
- writeFileSync(join(dir, ".gitignore"), "dashboard.env\nfirebase/functions/node_modules/\nfirebase/.firebase/\n*.log\n");
113
+ const f = readFile(cwd) ?? {};
114
+ const out = current ? { ...f, environments: { ...f.environments, [current]: { ...cfg, environment: current } } } : { ...cfg, ...f.environments ? { environments: f.environments } : {} };
115
+ writeFileSync(config, JSON.stringify(out, null, 2) + "\n");
116
+ writeFileSync(join(dir, ".gitignore"), "dashboard*.env\nfirebase*/functions/node_modules/\nfirebase*/functions/.env.*\nfirebase*/.firebase/\n*.log\n");
91
117
  }
92
118
  function upsertEnv(file, values) {
93
119
  const lines = existsSync(file) ? readFileSync(file, "utf8").split(/\r?\n/) : [];
@@ -165,7 +191,7 @@ var dim = (s) => pc.dim(s);
165
191
  var bold = (s) => pc.bold(s);
166
192
 
167
193
  // src/dashboard.ts
168
- var VERSION = true ? "0.3.1" : "0.0.0-dev";
194
+ var VERSION = true ? "0.5.0" : "0.0.0-dev";
169
195
  var DASHBOARD_VERSION = VERSION;
170
196
  function hashPassword(password2) {
171
197
  const salt = randomBytes(16);
@@ -340,6 +366,11 @@ function installCommand(pm, pkgs) {
340
366
  }
341
367
 
342
368
  // ../schema/src/core.ts
369
+ var LATENCY_BUCKETS_MS = [50, 100, 200, 300, 500, 750, 1e3, 1500, 2e3, 3e3, 5e3, 1e4];
370
+ function latencyBucket(ms) {
371
+ const i = LATENCY_BUCKETS_MS.findIndex((edge) => ms <= edge);
372
+ return i === -1 ? LATENCY_BUCKETS_MS.length : i;
373
+ }
343
374
  var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
344
375
  var GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
345
376
  var NOT_IN_APP = [/node_modules/, /\bnative\b/, /\[native code\]/, /InternalBytecode/];
@@ -581,8 +612,19 @@ function instrumentWebLifecycle(sink) {
581
612
 
582
613
  // ../sdk/src/client.ts
583
614
  var SDK_NAME = "@debugkit/sdk";
584
- var SDK_VERSION = "0.3.1";
615
+ var SDK_VERSION = "0.5.0";
585
616
  var QUEUE_KEY = "@debugkit/queue";
617
+ var ANON_KEY = "@debugkit/anonymousId";
618
+ function webStorage() {
619
+ try {
620
+ const ls = globalThis.localStorage;
621
+ if (!ls) return void 0;
622
+ ls.getItem(ANON_KEY);
623
+ return ls;
624
+ } catch {
625
+ return void 0;
626
+ }
627
+ }
586
628
  var MAX_QUEUE = 500;
587
629
  var uid = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`).replace(/-/g, "");
588
630
  var now = () => (/* @__PURE__ */ new Date()).toISOString();
@@ -609,10 +651,17 @@ var DebugClient = class {
609
651
  if (this.timer) clearInterval(this.timer);
610
652
  this.uninstrument();
611
653
  this.opts = { flushIntervalMs: 5e3, maxBatch: 50, maxBreadcrumbs: 30, ...options };
654
+ if (options.enabled === false) {
655
+ this.ready = false;
656
+ this.queue = [];
657
+ this.log("disabled for this build (enabled: false)");
658
+ return this;
659
+ }
612
660
  if (!this.opts.context && typeof window !== "undefined") this.opts.context = browserContext();
613
661
  this.auto = resolveAuto(options);
614
662
  this.rawFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.__raw ?? globalThis.fetch : void 0;
615
663
  this.ready = true;
664
+ this.loadAnonymousId();
616
665
  void this.restore();
617
666
  if (this.auto.errors && !this.handlersInstalled) this.installGlobalHandlers();
618
667
  this.instrument();
@@ -647,6 +696,10 @@ var DebugClient = class {
647
696
  get initialized() {
648
697
  return this.ready;
649
698
  }
699
+ /** False when init() was called with `enabled: false` (or not called yet). */
700
+ get enabled() {
701
+ return this.ready;
702
+ }
650
703
  /** Events waiting to be sent. */
651
704
  get pending() {
652
705
  return this.queue.length;
@@ -694,7 +747,31 @@ var DebugClient = class {
694
747
  throw err;
695
748
  }
696
749
  }
750
+ /** Response times per endpoint, sent as one metric event each about once a minute. */
751
+ timings = /* @__PURE__ */ new Map();
752
+ timingsSince = Date.now();
753
+ /** Set when the ingest rejects metric events (older than 0.7): stop sending them, keep the rest. */
754
+ noMetrics = false;
755
+ timeRequest(key, ms, failed) {
756
+ if (this.noMetrics) return;
757
+ let t = this.timings.get(key);
758
+ if (!t) {
759
+ if (this.timings.size >= 50) return;
760
+ this.timings.set(key, t = { count: 0, errors: 0, buckets: new Array(LATENCY_BUCKETS_MS.length + 1).fill(0) });
761
+ }
762
+ t.count++;
763
+ if (failed) t.errors++;
764
+ t.buckets[latencyBucket(ms)]++;
765
+ }
766
+ /** Turn the collected timings into metric events (every minute, or now when `force`). */
767
+ queueTimings(force = false) {
768
+ if (!this.timings.size || this.noMetrics || !force && Date.now() - this.timingsSince < 6e4) return;
769
+ for (const [key, t] of this.timings) this.push({ type: "metric", id: uid(), ts: now(), name: "http", key: key.slice(0, 300), count: t.count, errors: t.errors, buckets: t.buckets });
770
+ this.timings.clear();
771
+ this.timingsSince = Date.now();
772
+ }
697
773
  async flush() {
774
+ this.queueTimings(this.closing);
698
775
  if (this.flushing) await this.flushing.catch(() => {
699
776
  });
700
777
  if (this.flushing) return this.flushing;
@@ -714,10 +791,12 @@ var DebugClient = class {
714
791
  return this.flushing;
715
792
  }
716
793
  /** Stop the flush timer, undo automatic instrumentation and send what is queued. */
794
+ closing = false;
717
795
  close() {
718
796
  if (this.timer) clearInterval(this.timer);
719
797
  this.uninstrument();
720
- return this.flush();
798
+ this.closing = true;
799
+ return this.flush().finally(() => this.closing = false);
721
800
  }
722
801
  /* ---------------- internals ---------------- */
723
802
  /** @internal Used by the platform entry points for errors that have no thrown value. */
@@ -795,6 +874,7 @@ var DebugClient = class {
795
874
  /** Set when the ingest rejects 0.2 fields: it predates them, so send what it understands. */
796
875
  legacyIngest = false;
797
876
  async send(events) {
877
+ if (this.noMetrics) events = events.filter((e) => e.type !== "metric");
798
878
  if (this.legacyIngest) events = toLegacy(events);
799
879
  if (!events.length) return;
800
880
  const body = {
@@ -815,6 +895,11 @@ var DebugClient = class {
815
895
  });
816
896
  if (res.status >= 400 && res.status < 500 && res.status !== 429) {
817
897
  this.log(`ingest rejected batch (${res.status})`, await res.text().catch(() => ""));
898
+ if (res.status === 400 && !this.noMetrics && events.some((e) => e.type === "metric")) {
899
+ this.noMetrics = true;
900
+ this.timings.clear();
901
+ return this.send(events);
902
+ }
818
903
  if (res.status === 400 && !this.legacyIngest && hasNewFields(events)) {
819
904
  this.legacyIngest = true;
820
905
  return this.send(events);
@@ -829,6 +914,33 @@ var DebugClient = class {
829
914
  } catch {
830
915
  }
831
916
  }
917
+ /**
918
+ * Reuse the install's anonymous id: from localStorage in browsers straight away, or from the
919
+ * `storage` option (AsyncStorage in React Native) once it loads. Events queued before then
920
+ * carry the new id, which only matters for the very first launch.
921
+ */
922
+ loadAnonymousId() {
923
+ const ws = webStorage();
924
+ if (ws) {
925
+ try {
926
+ const saved = ws.getItem(ANON_KEY);
927
+ if (saved) this.user = { ...this.user, anonymousId: saved };
928
+ else ws.setItem(ANON_KEY, this.user.anonymousId);
929
+ } catch {
930
+ }
931
+ return;
932
+ }
933
+ const storage = this.opts.storage;
934
+ if (!storage) return;
935
+ void (async () => {
936
+ try {
937
+ const saved = await storage.getItem(ANON_KEY);
938
+ if (saved) this.user = { ...this.user, anonymousId: saved };
939
+ else await storage.setItem(ANON_KEY, this.user.anonymousId);
940
+ } catch {
941
+ }
942
+ })();
943
+ }
832
944
  async restore() {
833
945
  try {
834
946
  const raw = await this.opts.storage?.getItem(QUEUE_KEY);
@@ -878,7 +990,10 @@ var DebugClient = class {
878
990
  navigated: (to) => this.navigated(to),
879
991
  lifecycle: (state) => {
880
992
  this.breadcrumb("ui", state === "background" ? "App went to the background" : "App came to the foreground");
881
- if (state === "background") void this.flush();
993
+ if (state === "background") {
994
+ this.queueTimings(true);
995
+ void this.flush();
996
+ }
882
997
  },
883
998
  ignored: (url) => this.isIgnored(url)
884
999
  };
@@ -898,6 +1013,7 @@ var DebugClient = class {
898
1013
  const slow = ms >= (net.slowMs ?? 3e3);
899
1014
  const outcome = r.aborted ? "aborted" : r.timedOut ? "timed out" : r.status !== void 0 ? String(r.status) : "failed";
900
1015
  this.breadcrumb("network", `${r.method} ${url} \u2192 ${outcome} (${ms}ms)`, { status: r.status ?? null, durationMs: ms }, failed ? "error" : slow ? "warning" : "info");
1016
+ if (!r.aborted) this.timeRequest(`${r.method} ${url}`, ms, failed);
901
1017
  if (!failed) return;
902
1018
  const flow = net.flows?.find(([p2]) => typeof p2 === "string" ? url.includes(p2) : p2.test(url))?.[1];
903
1019
  const cause = r.error ? normaliseError(r.error) : void 0;
@@ -940,7 +1056,7 @@ var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type
940
1056
  function toLegacy(events) {
941
1057
  const out = [];
942
1058
  for (const e of events) {
943
- if (e.type === "session") continue;
1059
+ if (e.type === "session" || e.type === "metric") continue;
944
1060
  if (e.type === "error" && e.request) {
945
1061
  const { request: _r, ...rest } = e;
946
1062
  out.push(rest);
@@ -1102,7 +1218,7 @@ async function walkthrough(opts) {
1102
1218
  [
1103
1219
  ...(d.narrative ?? []).map((l) => `\u201C${l}\u201D`),
1104
1220
  "",
1105
- `${bold(String(d.issues.length))} issues \xB7 ${bold(String(d.health?.sessions14d ?? 0))} session \xB7 failing endpoint ${code(d.health?.endpoints?.[0]?.endpoint ?? "\u2014")}`,
1221
+ `${bold(String(d.issues.length))} issues \xB7 ${bold(String(d.health?.sessionsRange ?? 0))} session \xB7 failing endpoint ${code(d.health?.endpoints?.[0]?.endpoint ?? "\u2014")}`,
1106
1222
  "",
1107
1223
  `Refresh the dashboard. You'll see a ${pc.red("HttpError")} from a failed request (captured the way the SDK does it automatically),`,
1108
1224
  `a ${pc.red("SyntaxError")} reported from a try/catch, and the ${code("onboarding.test")} flow with a 50% failure rate from track().`,
@@ -1136,9 +1252,9 @@ async function walkthrough(opts) {
1136
1252
  ...opts.remaining.map((l, i) => `${i + 1}. ${l}`),
1137
1253
  `${opts.remaining.length + 1}. Run the app and watch the dashboard fill in`,
1138
1254
  "",
1139
- `${code("npx debugkit dashboard")} open the dashboard again`,
1140
- `${code("npx debugkit test")} send another test event`,
1141
- `${code("npx debugkit guide")} replay this walkthrough`
1255
+ `${code(cmdFor("dashboard"))} open the dashboard again`,
1256
+ `${code(cmdFor("test"))} send another test event`,
1257
+ `${code(cmdFor("guide"))} replay this walkthrough`
1142
1258
  ].join("\n"),
1143
1259
  "6 \xB7 Finish wiring your app"
1144
1260
  );
@@ -1160,6 +1276,13 @@ function mergeKeys(existing, key, appId) {
1160
1276
  return pairs.join(",");
1161
1277
  }
1162
1278
 
1279
+ // src/providers/types.ts
1280
+ var adminEnv = (endpoint, ctx) => ({
1281
+ DEBUG_ADMIN_URL: `${endpoint.replace(/\/+$/, "")}/admin`,
1282
+ DEBUG_ADMIN_TOKEN: ctx.adminToken,
1283
+ DEBUG_RETENTION_DAYS: String(ctx.retentionDays)
1284
+ });
1285
+
1163
1286
  // src/providers/aws.ts
1164
1287
  var REGIONS = [
1165
1288
  { value: "af-south-1", label: "Cape Town (af-south-1)" },
@@ -1248,7 +1371,7 @@ async function setupAws(ctx) {
1248
1371
  if (!identity.Account) bail("AWS didn't say which account these credentials belong to.");
1249
1372
  const account = identity.Account;
1250
1373
  const table = await ask("DynamoDB table name", {
1251
- initial: "debugkit",
1374
+ initial: environment.get() ? `debugkit-${environment.get()}` : "debugkit",
1252
1375
  validate: (v) => /^[A-Za-z0-9_.-]{3,40}$/.test(v) ? void 0 : "3\u201340 characters: letters, digits, _ . -"
1253
1376
  });
1254
1377
  const functionName = `debugkit-ingest-${table}`.slice(0, 64);
@@ -1362,11 +1485,13 @@ async function setupAws(ctx) {
1362
1485
  new lambdaMod.UpdateFunctionConfigurationCommand({
1363
1486
  FunctionName: functionName,
1364
1487
  Role: roleArn,
1365
- Environment: { Variables: { ...fn.Configuration?.Environment?.Variables, DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keys } }
1488
+ Environment: {
1489
+ Variables: { ...fn.Configuration?.Environment?.Variables, DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keys, DEBUG_RETENTION_DAYS: String(ctx.retentionDays), DEBUG_ADMIN_TOKEN: ctx.adminToken }
1490
+ }
1366
1491
  })
1367
1492
  );
1368
1493
  } else {
1369
- const env = { Variables: { DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId) } };
1494
+ const env = { Variables: { DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId), DEBUG_RETENTION_DAYS: String(ctx.retentionDays), DEBUG_ADMIN_TOKEN: ctx.adminToken } };
1370
1495
  for (let attempt = 0; ; attempt++) {
1371
1496
  try {
1372
1497
  await lambda.send(
@@ -1428,7 +1553,7 @@ async function setupAws(ctx) {
1428
1553
  }
1429
1554
  return {
1430
1555
  config: { provider: "aws", endpoint: url.replace(/\/$/, ""), ingestKey: ctx.ingestKey, aws: { region, profile, table, functionName, roleName, readOnlyPolicyArn } },
1431
- dashboardEnv: { DEBUG_STORE: "dynamodb", AWS_REGION: region, DEBUG_DYNAMO_TABLE: table, ...profile ? { AWS_PROFILE: profile } : {} },
1556
+ dashboardEnv: { DEBUG_STORE: "dynamodb", AWS_REGION: region, DEBUG_DYNAMO_TABLE: table, ...profile ? { AWS_PROFILE: profile } : {}, ...adminEnv(url, ctx) },
1432
1557
  created: [
1433
1558
  `DynamoDB table ${code(table)} in ${region}${ownTable ? " (on-demand)" : " (your existing table)"}`,
1434
1559
  `Lambda ${code(functionName)} with a public URL: ${code(url)}`,
@@ -1467,16 +1592,42 @@ var firestore_indexes_default = {
1467
1592
  collectionGroup: "rollups",
1468
1593
  queryScope: "COLLECTION",
1469
1594
  fields: [
1470
- { fieldPath: "dimension", order: "ASCENDING" },
1471
- { fieldPath: "day", order: "ASCENDING" }
1595
+ {
1596
+ fieldPath: "dimension",
1597
+ order: "ASCENDING"
1598
+ },
1599
+ {
1600
+ fieldPath: "day",
1601
+ order: "ASCENDING"
1602
+ }
1472
1603
  ]
1473
1604
  },
1474
1605
  {
1475
1606
  collectionGroup: "events",
1476
1607
  queryScope: "COLLECTION",
1477
1608
  fields: [
1478
- { fieldPath: "fingerprint", order: "ASCENDING" },
1479
- { fieldPath: "ts", order: "DESCENDING" }
1609
+ {
1610
+ fieldPath: "fingerprint",
1611
+ order: "ASCENDING"
1612
+ },
1613
+ {
1614
+ fieldPath: "ts",
1615
+ order: "DESCENDING"
1616
+ }
1617
+ ]
1618
+ },
1619
+ {
1620
+ collectionGroup: "users",
1621
+ queryScope: "COLLECTION",
1622
+ fields: [
1623
+ {
1624
+ fieldPath: "scope",
1625
+ order: "ASCENDING"
1626
+ },
1627
+ {
1628
+ fieldPath: "lastDay",
1629
+ order: "ASCENDING"
1630
+ }
1480
1631
  ]
1481
1632
  }
1482
1633
  ],
@@ -1486,6 +1637,12 @@ var firestore_indexes_default = {
1486
1637
  fieldPath: "expireAt",
1487
1638
  ttl: true,
1488
1639
  indexes: []
1640
+ },
1641
+ {
1642
+ collectionGroup: "rollups",
1643
+ fieldPath: "expireAt",
1644
+ ttl: true,
1645
+ indexes: []
1489
1646
  }
1490
1647
  ]
1491
1648
  };
@@ -1601,7 +1758,7 @@ async function setupFirebase(ctx) {
1601
1758
  s.stop(`Created the Firestore database (${location2})`);
1602
1759
  }
1603
1760
  const region = functionRegion(location2);
1604
- const dir = writeFunctionSource(ctx, region);
1761
+ const dir = writeFunctionSource(ctx, region, projectId);
1605
1762
  s.start("Installing the ingest function's dependencies");
1606
1763
  const inst = await capture("npm", ["install", "--no-audit", "--no-fund"], { cwd: join5(dir, "functions") });
1607
1764
  if (inst.code !== 0) {
@@ -1610,6 +1767,18 @@ async function setupFirebase(ctx) {
1610
1767
  bail();
1611
1768
  }
1612
1769
  s.stop("Installed the ingest function's dependencies");
1770
+ p.note(
1771
+ [
1772
+ `In ${bold(projectId)}${environment.get() ? ` (your ${environment.get()} environment)` : ""}, deBug will add:`,
1773
+ `\u2022 a Cloud Function ${code(FUNCTION_NAME)} in ${region}, with a public URL (each request needs the ingest key)`,
1774
+ `\u2022 a ${code("debug_apps")} collection in Firestore, with raw events expiring after 30 days`,
1775
+ `\u2022 two Firestore indexes for it (your existing indexes are left alone)`,
1776
+ "",
1777
+ "Nothing else in the project is changed. Usage is billed to the project's Blaze plan."
1778
+ ].join("\n"),
1779
+ "About to deploy"
1780
+ );
1781
+ if (!await yes(`Deploy deBug into ${projectId}?`)) bail("Nothing was deployed.");
1613
1782
  p.log.step("Adding deBug's Firestore indexes (your existing indexes are left alone)");
1614
1783
  if (await fbLive(["deploy", "--only", "firestore:indexes", "--non-interactive", ...proj], { cwd: dir }) !== 0)
1615
1784
  p.log.warn("The indexes didn't deploy. The dashboard needs them; deploy them later with the command printed at the end.");
@@ -1637,7 +1806,7 @@ async function setupFirebase(ctx) {
1637
1806
  await ensureDashboardAccess(projectId);
1638
1807
  return {
1639
1808
  config: { provider: "firebase", endpoint, ingestKey: ctx.ingestKey, firebase: { projectId, region, account, location: location2 } },
1640
- dashboardEnv: { DEBUG_STORE: "firestore", GOOGLE_CLOUD_PROJECT: projectId, GCLOUD_PROJECT: projectId },
1809
+ dashboardEnv: { DEBUG_STORE: "firestore", GOOGLE_CLOUD_PROJECT: projectId, GCLOUD_PROJECT: projectId, ...adminEnv(endpoint, ctx) },
1641
1810
  created: [
1642
1811
  `Firestore database in ${code(projectId)} (${location2}), with indexes and 30-day expiry on raw events`,
1643
1812
  `Cloud Function ${code(FUNCTION_NAME)} in ${region}: ${code(endpoint)}`,
@@ -1685,7 +1854,7 @@ function functionRegion(location2) {
1685
1854
  if (location2.startsWith("nam")) return "us-central1";
1686
1855
  return /^[a-z]+-[a-z]+\d+$/.test(location2) ? location2 : "us-central1";
1687
1856
  }
1688
- function writeFunctionSource(ctx, region) {
1857
+ function writeFunctionSource(ctx, region, projectId = "default") {
1689
1858
  const dir = paths(ctx.app.cwd).firebase;
1690
1859
  mkdirSync2(join5(dir, "functions"), { recursive: true });
1691
1860
  writeFileSync2(
@@ -1735,14 +1904,22 @@ initializeApp();
1735
1904
 
1736
1905
  export const ${FUNCTION_NAME} = onRequest(
1737
1906
  { region: ${JSON.stringify(region)}, invoker: "public", memory: "256MiB", maxInstances: 10 },
1738
- firebaseHandler({ store: new FirestoreStore(getFirestore()), keys: parseIngestKeys(process.env.DEBUG_INGEST_KEYS) }),
1907
+ firebaseHandler({
1908
+ store: new FirestoreStore(getFirestore()),
1909
+ keys: parseIngestKeys(process.env.DEBUG_INGEST_KEYS),
1910
+ retentionDays: Number(process.env.DEBUG_RETENTION_DAYS) || undefined,
1911
+ adminToken: process.env.DEBUG_ADMIN_TOKEN,
1912
+ }),
1739
1913
  );
1740
1914
  `
1741
1915
  );
1742
1916
  const envFile = join5(dir, "functions", ".env");
1743
- const current = existsSync5(envFile) ? /^DEBUG_INGEST_KEYS=(.*)$/m.exec(readFileSync4(envFile, "utf8"))?.[1] : void 0;
1744
- writeFileSync2(envFile, `DEBUG_INGEST_KEYS=${mergeKeys(current, ctx.ingestKey, ctx.app.appId)}
1917
+ const current2 = existsSync5(envFile) ? /^DEBUG_INGEST_KEYS=(.*)$/m.exec(readFileSync4(envFile, "utf8"))?.[1] : void 0;
1918
+ writeFileSync2(envFile, `DEBUG_INGEST_KEYS=${mergeKeys(current2, ctx.ingestKey, ctx.app.appId)}
1919
+ DEBUG_RETENTION_DAYS=${ctx.retentionDays}
1745
1920
  `);
1921
+ writeFileSync2(join5(dir, "functions", `.env.${projectId}`), `DEBUG_ADMIN_TOKEN=${ctx.adminToken}
1922
+ `, { mode: 384 });
1746
1923
  return dir;
1747
1924
  }
1748
1925
 
@@ -1768,13 +1945,13 @@ async function setupLocal(ctx) {
1768
1945
  },
1769
1946
  created: [
1770
1947
  `Nothing in the cloud: the dashboard stores events in memory while it runs`,
1771
- `Ingest endpoint: ${code(endpoint)} (only while ${code("npx debugkit dashboard")} is running)`
1948
+ `Ingest endpoint: ${code(endpoint)} (only while ${code(cmdFor("dashboard"))} is running)`
1772
1949
  ]
1773
1950
  };
1774
1951
  }
1775
1952
 
1776
1953
  // src/wire.ts
1777
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
1954
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
1778
1955
  import { dirname as dirname2, join as join6, relative } from "path";
1779
1956
  init_exec();
1780
1957
  var ENV_ENDPOINT = "DEBUG_ENDPOINT";
@@ -1806,29 +1983,39 @@ function writeAppEnv(app, conn) {
1806
1983
  upsertEnv(file, { [`${app.envPrefix}${ENV_ENDPOINT}`]: conn.endpoint, [`${app.envPrefix}${ENV_KEY}`]: conn.ingestKey });
1807
1984
  return file;
1808
1985
  }
1809
- function initFile(app, conn) {
1986
+ var ENV_ENVIRONMENT = "DEBUG_ENVIRONMENT";
1987
+ var EAS_ENVIRONMENTS = ["development", "preview", "production"];
1988
+ function envValues(app, conn, env) {
1989
+ const pre = app.envPrefix ?? "";
1990
+ return { [`${pre}${ENV_ENDPOINT}`]: conn.endpoint, [`${pre}${ENV_KEY}`]: conn.ingestKey, [`${pre}${ENV_ENVIRONMENT}`]: env };
1991
+ }
1992
+ function initFile(app, conn, multiEnv = environment.get() !== void 0) {
1810
1993
  const ext = app.typescript ? "ts" : "js";
1811
1994
  const path2 = join6(app.cwd, app.sourceDir, `debug.${ext}`);
1812
1995
  const rel = relative(app.cwd, path2);
1813
- const bang = app.typescript ? "!" : "";
1814
1996
  const env = (k) => app.envPrefix === "VITE_" ? `import.meta.env.${app.envPrefix}${k}` : `process.env.${app.envPrefix ?? ""}${k}`;
1815
1997
  const header = `// Set up by npx debugkit init. Import this file once, as early as possible.
1816
1998
  `;
1817
1999
  const appId = JSON.stringify(app.appId);
2000
+ const importLine = `${code(`import "./${rel.replace(/\.(ts|js)$/, "")}";`)}`;
1818
2001
  switch (app.platform) {
1819
2002
  case "expo":
1820
2003
  return {
1821
2004
  path: path2,
1822
2005
  contents: `${header}import { initExpo } from "@debugkit/sdk/expo";
1823
2006
 
2007
+ const endpoint = ${env(ENV_ENDPOINT)};
2008
+
1824
2009
  export const deBug = initExpo({
1825
- endpoint: ${env(ENV_ENDPOINT)}${bang},
1826
- ingestKey: ${env(ENV_KEY)}${bang},
1827
- app: { id: ${appId}, environment: __DEV__ ? "development" : "production" },
2010
+ // ${multiEnv ? "On in release builds whose environment has a deBug endpoint (preview, production); off in\n // development builds and local Metro runs." : "Off when the build has no deBug endpoint."}
2011
+ enabled: ${multiEnv ? "!__DEV__ && !!endpoint" : "!!endpoint"},
2012
+ endpoint: endpoint ?? "",
2013
+ ingestKey: ${env(ENV_KEY)} ?? "",
2014
+ app: { id: ${appId}, environment: ${env(ENV_ENVIRONMENT)} ?? (__DEV__ ? "development" : "production") },
1828
2015
  });
1829
2016
  `,
1830
2017
  then: [
1831
- `Import it first in your root layout (${code(app.expoRouter ? "app/_layout.tsx" : "App.tsx")}): ${code(`import "./${rel.replace(/\.(ts|js)$/, "")}";`)} (adjust the path)`,
2018
+ `Import it first in your root layout (${code(app.expoRouter ? "app/_layout.tsx" : "App.tsx")}): ${importLine} (adjust the path)`,
1832
2019
  `Wrap the root in ${code("<DebugErrorBoundary>")} from ${code("@debugkit/sdk/expo")} to catch render crashes`,
1833
2020
  ...app.expoRouter ? [`Call ${code("useDebugExpoRouter()")} from ${code("@debugkit/sdk/expo-router")} in the root layout for screen breadcrumbs`] : []
1834
2021
  ]
@@ -1840,15 +2027,17 @@ export const deBug = initExpo({
1840
2027
  // Optional, for model and app version: npm install react-native-device-info, then pass deviceInfo: DeviceInfo.
1841
2028
 
1842
2029
  export const deBug = initReactNative({
2030
+ enabled: ${multiEnv ? "!__DEV__ // release builds only" : "true"},
1843
2031
  endpoint: ${JSON.stringify(conn.endpoint)},
1844
2032
  ingestKey: ${JSON.stringify(conn.ingestKey)}, // public and write-only: safe to ship in the app
1845
2033
  app: { id: ${appId}, environment: __DEV__ ? "development" : "production" },
1846
2034
  });
1847
2035
  `,
1848
2036
  then: [
1849
- `Import it first in ${code("index.js")}: ${code(`import "./${rel.replace(/\.(ts|js)$/, "")}";`)}`,
2037
+ `Import it first in ${code("index.js")}: ${importLine}`,
1850
2038
  `Wrap your root component in ${code("<DebugErrorBoundary>")} from ${code("@debugkit/sdk/react-native")}`,
1851
- ...app.reactNavigation ? [`Spread ${code("{...trackReactNavigation(navRef)}")} onto your NavigationContainer for screen breadcrumbs`] : []
2039
+ ...app.reactNavigation ? [`Spread ${code("{...trackReactNavigation(navRef)}")} onto your NavigationContainer for screen breadcrumbs`] : [],
2040
+ ...multiEnv ? [`Bare React Native has no per-build env vars, so ${code("debug.ts")} holds one environment's endpoint. For one per environment, read them with react-native-config.`] : []
1852
2041
  ]
1853
2042
  };
1854
2043
  case "node":
@@ -1857,23 +2046,30 @@ export const deBug = initReactNative({
1857
2046
  contents: `${header}import { initNode } from "@debugkit/sdk/node";
1858
2047
 
1859
2048
  export const deBug = initNode({
1860
- endpoint: process.env.${ENV_ENDPOINT}${bang},
1861
- ingestKey: process.env.${ENV_KEY}${bang},
1862
- app: { id: ${appId}, version: process.env.npm_package_version },
2049
+ enabled: !!process.env.${ENV_ENDPOINT}, // off where no endpoint is set
2050
+ endpoint: process.env.${ENV_ENDPOINT} ?? "",
2051
+ ingestKey: process.env.${ENV_KEY} ?? "",
2052
+ app: { id: ${appId}, version: process.env.npm_package_version, environment: process.env.${ENV_ENVIRONMENT} ?? process.env.NODE_ENV },
1863
2053
  });
1864
2054
  `,
1865
- then: [`Import it at the very top of your server entry`, `Set ${code(ENV_ENDPOINT)} and ${code(ENV_KEY)} in the server's environment (they're in .env)`]
2055
+ then: [`Import it at the very top of your server entry`, `Set ${code(ENV_ENDPOINT)} and ${code(ENV_KEY)} in the server's environment`]
1866
2056
  };
1867
2057
  default: {
1868
- const guard = app.platform === "next" || app.platform === "tanstack-start" ? `if (typeof window !== "undefined") ` : "";
2058
+ const vite = app.envPrefix === "VITE_";
2059
+ const guard = app.platform === "next" || app.platform === "tanstack-start" ? `typeof window !== "undefined" && ` : "";
2060
+ const prod = vite ? "import.meta.env.PROD" : `process.env.NODE_ENV === "production"`;
2061
+ const fallbackEnv = vite ? "import.meta.env.MODE" : "process.env.NODE_ENV";
1869
2062
  return {
1870
2063
  path: path2,
1871
2064
  contents: `${header}import { deBug } from "@debugkit/sdk/react";
1872
2065
 
1873
- ${guard}deBug.init({
1874
- endpoint: ${env(ENV_ENDPOINT)}${bang},
1875
- ingestKey: ${env(ENV_KEY)}${bang},
1876
- app: { id: ${appId}${app.version ? `, version: ${JSON.stringify(app.version)}` : ""} },
2066
+ const endpoint = ${env(ENV_ENDPOINT)};
2067
+
2068
+ deBug.init({
2069
+ enabled: ${guard}${multiEnv ? `${prod} && ` : ""}!!endpoint,
2070
+ endpoint: endpoint ?? "",
2071
+ ingestKey: ${env(ENV_KEY)} ?? "",
2072
+ app: { id: ${appId}${app.version ? `, version: ${JSON.stringify(app.version)}` : ""}, environment: ${env(ENV_ENVIRONMENT)} ?? ${fallbackEnv} },
1877
2073
  });
1878
2074
 
1879
2075
  export { deBug };
@@ -1887,28 +2083,58 @@ export { deBug };
1887
2083
  }
1888
2084
  }
1889
2085
  }
1890
- async function wireApp(app, conn) {
1891
- const envFile = writeAppEnv(app, conn);
1892
- if (envFile) {
1893
- p.log.success(`Wrote ${code(`${app.envPrefix}${ENV_ENDPOINT}`)} and ${code(`${app.envPrefix}${ENV_KEY}`)} to ${code(relative(app.cwd, envFile))}`);
1894
- } else if (app.platform === "node") {
1895
- upsertEnv(join6(app.cwd, ".env"), { [ENV_ENDPOINT]: conn.endpoint, [ENV_KEY]: conn.ingestKey });
1896
- p.log.success(`Wrote ${code(ENV_ENDPOINT)} and ${code(ENV_KEY)} to ${code(".env")}`);
2086
+ async function writeEasEnv(app, values, env) {
2087
+ const [cmd, pre] = which("eas") ? ["eas", []] : ["npx", ["-y", "eas-cli@latest"]];
2088
+ const s = p.spinner();
2089
+ s.start(`Setting ${Object.keys(values).length} variables in EAS's ${env} environment`);
2090
+ for (const [name, value] of Object.entries(values)) {
2091
+ const r = await capture(cmd, [...pre, "env:set", "--environment", env, "--name", name, "--value", value, "--visibility", "plaintext", "--scope", "project", "--non-interactive"], { cwd: app.cwd });
2092
+ if (r.code !== 0) {
2093
+ s.error(`EAS didn't accept ${name}`);
2094
+ p.log.warn((r.stderr || r.stdout).trim().split("\n").slice(-4).join("\n"));
2095
+ return false;
2096
+ }
1897
2097
  }
1898
- if (envFile || app.platform === "node") {
1899
- if (ensureGitignored(app.cwd, ".env")) p.log.info(dim("Added .env to .gitignore"));
2098
+ s.stop(`Set ${Object.keys(values).map((k) => code(k)).join(", ")} in EAS's ${code(env)} environment`);
2099
+ return true;
2100
+ }
2101
+ async function wireApp(app, conn) {
2102
+ const env = environment.get();
2103
+ const extra = [];
2104
+ if (env) {
2105
+ const values = app.platform === "react-native" ? {} : envValues(app, conn, env);
2106
+ const usesEas = app.platform === "expo" && existsSync6(join6(app.cwd, "eas.json"));
2107
+ let done = Object.keys(values).length === 0;
2108
+ if (!done && usesEas && EAS_ENVIRONMENTS.includes(env) && await yes(`Set the endpoint and key in EAS's ${env} environment (eas env:set)?`)) done = await writeEasEnv(app, values, env);
2109
+ if (!done) {
2110
+ p.note(Object.entries(values).map(([k, v]) => `${k}=${v}`).join("\n"), `Set these for your ${env} builds`);
2111
+ extra.push(usesEas ? `Set the variables above in EAS's ${code(env)} environment (${code(`eas env:set --environment ${env}`)})` : `Set the variables above wherever your ${code(env)} builds get their environment`);
2112
+ }
2113
+ } else {
2114
+ const envFile = writeAppEnv(app, conn);
2115
+ if (envFile) {
2116
+ p.log.success(`Wrote ${code(`${app.envPrefix}${ENV_ENDPOINT}`)} and ${code(`${app.envPrefix}${ENV_KEY}`)} to ${code(relative(app.cwd, envFile))}`);
2117
+ } else if (app.platform === "node") {
2118
+ upsertEnv(join6(app.cwd, ".env"), { [ENV_ENDPOINT]: conn.endpoint, [ENV_KEY]: conn.ingestKey });
2119
+ p.log.success(`Wrote ${code(ENV_ENDPOINT)} and ${code(ENV_KEY)} to ${code(".env")}`);
2120
+ }
2121
+ if (envFile || app.platform === "node") {
2122
+ if (ensureGitignored(app.cwd, ".env")) p.log.info(dim("Added .env to .gitignore"));
2123
+ }
1900
2124
  }
1901
2125
  const f = initFile(app, conn);
1902
2126
  const rel = relative(app.cwd, f.path);
1903
- if (!existsSync6(f.path) || await yes(`${rel} already exists. Replace it?`, false)) {
2127
+ const current2 = existsSync6(f.path) ? readFileSync5(f.path, "utf8") : void 0;
2128
+ if (current2 === f.contents) p.log.info(`${code(rel)} is already up to date`);
2129
+ else if (current2 === void 0 || await yes(`${rel} already exists. Replace it?`, false)) {
1904
2130
  mkdirSync3(dirname2(f.path), { recursive: true });
1905
2131
  writeFileSync3(f.path, f.contents);
1906
- p.log.success(`Created ${code(rel)}`);
2132
+ p.log.success(`${current2 === void 0 ? "Created" : "Updated"} ${code(rel)}`);
1907
2133
  } else {
1908
2134
  p.log.info(`Kept your ${rel}. The generated version is:
1909
2135
  ${dim(f.contents)}`);
1910
2136
  }
1911
- return f.then;
2137
+ return [...extra, ...f.then];
1912
2138
  }
1913
2139
 
1914
2140
  // src/cli.ts
@@ -1922,6 +2148,8 @@ ${dim("Run as npx debugkit <command> once @debugkit/sdk is installed, or npx @de
1922
2148
  ${code("npx debugkit password")} reset the dashboard login
1923
2149
 
1924
2150
  Options
2151
+ --env <name> one of several environments, like preview or production. Each has
2152
+ its own provider, project, endpoint and dashboard login
1925
2153
  --provider <firebase|aws|local> skip the provider question
1926
2154
  --cwd <dir> the app's folder (default: current folder)
1927
2155
  --yes accept defaults (for scripts)
@@ -1932,6 +2160,8 @@ function parseArgs(argv) {
1932
2160
  const a = argv[i];
1933
2161
  if (a === "--provider") out.provider = argv[++i];
1934
2162
  else if (a.startsWith("--provider=")) out.provider = a.split("=")[1];
2163
+ else if (a === "--env") out.env = argv[++i];
2164
+ else if (a.startsWith("--env=")) out.env = a.split("=")[1];
1935
2165
  else if (a === "--cwd") out.cwd = resolve(argv[++i] ?? ".");
1936
2166
  else if (a === "--yes" || a === "-y") out.yes = true;
1937
2167
  else if (a === "--help" || a === "-h") out.help = true;
@@ -1939,13 +2169,43 @@ function parseArgs(argv) {
1939
2169
  }
1940
2170
  return out;
1941
2171
  }
2172
+ var envLabel = () => environment.get() ? ` (${environment.get()})` : "";
2173
+ async function askRetention(current2, provider) {
2174
+ const perGb = provider === "aws" ? 0.25 : 0.18;
2175
+ const cost = (d) => {
2176
+ const gb = 1e4 * d * 2 / 1e6;
2177
+ return `${gb < 1 ? gb.toFixed(1) : Math.round(gb)} GB \u2248 $${(gb * perGb).toFixed(2)}/month at 10k events a day`;
2178
+ };
2179
+ p.note(
2180
+ [
2181
+ "Raw events carry the stack trace, breadcrumbs and device details. They expire after the period you pick.",
2182
+ `${bold("Counts, issues and release health are kept forever")}, so charts cover any date range.`,
2183
+ "You can change this later on the dashboard's Settings page."
2184
+ ].join("\n"),
2185
+ "Data retention"
2186
+ );
2187
+ const options = [30, 60, 90, 180, 365].map((d) => ({ value: String(d), label: `${d} days`, hint: cost(d) }));
2188
+ const picked = await choose("Keep raw events for how long?", [...options, { value: "custom", label: "Another number of days" }], String(current2 ?? 60));
2189
+ if (picked !== "custom") return Number(picked);
2190
+ const days = await ask("Days (1 to 3650)", {
2191
+ initial: String(current2 ?? 60),
2192
+ validate: (v) => /^\d+$/.test(v) && Number(v) >= 1 && Number(v) <= 3650 ? void 0 : "A whole number from 1 to 3650"
2193
+ });
2194
+ return Number(days);
2195
+ }
1942
2196
  function requireConfig(cwd) {
1943
- const cfg = readConfig(cwd);
1944
- if (!cfg) bail(`deBug isn't set up in ${cwd} yet. Run ${code("npx debugkit init")} first.`);
2197
+ let cfg = readConfig(cwd);
2198
+ if (!cfg && !environment.get()) {
2199
+ const envs = listEnvironments(cwd);
2200
+ if (envs.length === 1) environment.set(envs[0]);
2201
+ else if (envs.length > 1) bail(`This app has several environments: ${envs.join(", ")}. Pick one with --env, for example ${code(`npx debugkit ${flags.command} --env ${envs[0]}`)}.`);
2202
+ cfg = readConfig(cwd);
2203
+ }
2204
+ if (!cfg) bail(`deBug isn't set up${envLabel()} in ${cwd} yet. Run ${code(cmdFor("init"))} first.`);
1945
2205
  return cfg;
1946
2206
  }
1947
2207
  async function init(cwd, preset) {
1948
- p.intro(`${pc.bgRed(pc.white(" deBug "))} ${dim("observability you own")}`);
2208
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} ${dim("observability you own")}${environment.get() ? ` \xB7 ${bold(environment.get())} environment` : ""}`);
1949
2209
  let app;
1950
2210
  try {
1951
2211
  app = detectApp(cwd);
@@ -1954,8 +2214,8 @@ async function init(cwd, preset) {
1954
2214
  }
1955
2215
  p.log.info(`Found ${bold(app.name)}: ${PLATFORM_LABEL[app.platform]}${app.expoRouter ? " with Expo Router" : ""}, using ${app.packageManager}. App id ${code(app.appId)}.`);
1956
2216
  const existing = readConfig(cwd);
1957
- if (existing && !await yes(`deBug is already set up here (${existing.provider}, ${existing.endpoint}). Set it up again?`, false)) {
1958
- p.outro(`Nothing changed. Try ${code("npx debugkit dashboard")} or ${code("npx debugkit guide")}.`);
2217
+ if (existing && !await yes(`deBug is already set up${envLabel()} here (${existing.provider}, ${existing.endpoint}). Set it up again?`, false)) {
2218
+ p.outro(`Nothing changed. Try ${code(cmdFor("dashboard"))} or ${code(cmdFor("guide"))}.`);
1959
2219
  return;
1960
2220
  }
1961
2221
  await installSdk(app);
@@ -1979,7 +2239,9 @@ async function init(cwd, preset) {
1979
2239
  );
1980
2240
  const dashboardPort = await freePort(4400);
1981
2241
  const ingestKey = existing?.provider === provider && existing.ingestKey ? existing.ingestKey : `pk_${provider === "local" ? "local" : "live"}_${randomBytes2(12).toString("hex")}`;
1982
- const ctx = { app, ingestKey, dashboardPort };
2242
+ const retentionDays = provider === "local" ? 30 : await askRetention(existing?.retentionDays, provider);
2243
+ const adminToken = readEnv(paths(cwd).dashboardEnv).DEBUG_ADMIN_TOKEN ?? `adm_${randomBytes2(24).toString("hex")}`;
2244
+ const ctx = { app, ingestKey, dashboardPort, retentionDays, adminToken };
1983
2245
  let result;
1984
2246
  try {
1985
2247
  result = provider === "firebase" ? await setupFirebase(ctx) : provider === "aws" ? await setupAws(ctx) : await setupLocal(ctx);
@@ -1987,7 +2249,7 @@ async function init(cwd, preset) {
1987
2249
  p.log.error(err.message);
1988
2250
  bail("Setup stopped. Nothing else was changed in your app. Fix the error above and run npx debugkit init again.");
1989
2251
  }
1990
- const cfg = { ...result.config, appId: app.appId, dashboardPort, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
2252
+ const cfg = { ...result.config, appId: app.appId, dashboardPort, retentionDays, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
1991
2253
  writeConfig(cwd, cfg);
1992
2254
  p.note(result.created.map((l) => `\u2022 ${l}`).join("\n"), "Created");
1993
2255
  const remaining = await wireApp(app, cfg);
@@ -1997,7 +2259,7 @@ async function init(cwd, preset) {
1997
2259
  dash = await startDashboard(cwd);
1998
2260
  } catch (err) {
1999
2261
  p.log.error(err.message);
2000
- p.outro(`deBug is set up, but the dashboard didn't start. Try ${code("npx debugkit dashboard")}.`);
2262
+ p.outro(`deBug is set up, but the dashboard didn't start. Try ${code(cmdFor("dashboard"))}.`);
2001
2263
  return;
2002
2264
  }
2003
2265
  await walkthrough({ cwd, app, cfg, dashboardUrl: dash.url, remaining });
@@ -2008,11 +2270,15 @@ async function init(cwd, preset) {
2008
2270
  return;
2009
2271
  }
2010
2272
  dash.stop();
2011
- p.outro(`deBug is set up. Open the dashboard any time with ${code("npx debugkit dashboard")}.`);
2273
+ const others = listEnvironments(cwd).filter((e) => e !== environment.get());
2274
+ p.outro(
2275
+ `deBug is set up${envLabel()}. Open the dashboard any time with ${code(cmdFor("dashboard"))}.` + (environment.get() && !others.length ? `
2276
+ Set up the next environment the same way, e.g. ${code("npx debugkit init --env production")}.` : "")
2277
+ );
2012
2278
  }
2013
2279
  async function dashboard(cwd) {
2014
2280
  const cfg = requireConfig(cwd);
2015
- p.intro(`${pc.bgRed(pc.white(" deBug "))} dashboard`);
2281
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} dashboard${envLabel()}`);
2016
2282
  const dash = await startDashboard(cwd);
2017
2283
  p.log.info(`${code(dash.url)} \xB7 reading ${cfg.provider === "local" ? "in-memory data (and accepting events)" : cfg.provider} \xB7 Ctrl-C to stop`);
2018
2284
  const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_exec(), exec_exports));
@@ -2029,11 +2295,11 @@ async function test(cwd) {
2029
2295
  if (r.error) {
2030
2296
  s.error(`Not accepted: ${r.error}`);
2031
2297
  process.exitCode = 1;
2032
- if (cfg.provider === "local") p.log.info(`On this setup the dashboard is the ingest: start it with ${code("npx debugkit dashboard")} first.`);
2298
+ if (cfg.provider === "local") p.log.info(`On this setup the dashboard is the ingest: start it with ${code(cmdFor("dashboard"))} first.`);
2033
2299
  return;
2034
2300
  }
2035
2301
  s.stop("Accepted by your ingest");
2036
- p.outro(`Open the dashboard (${code("npx debugkit dashboard")}) to see them under the ${code("onboarding.test")} flow.`);
2302
+ p.outro(`Open the dashboard (${code(cmdFor("dashboard"))}) to see them under the ${code("onboarding.test")} flow.`);
2037
2303
  }
2038
2304
  async function guide(cwd) {
2039
2305
  const cfg = requireConfig(cwd);
@@ -2053,7 +2319,7 @@ async function password(cwd) {
2053
2319
  requireConfig(cwd);
2054
2320
  p.intro(`${pc.bgRed(pc.white(" deBug "))} reset the dashboard login`);
2055
2321
  await resetLogin(cwd);
2056
- p.outro(`Saved. Restart the dashboard (${code("npx debugkit dashboard")}) and sign in with the new password.`);
2322
+ p.outro(`Saved. Restart the dashboard (${code(cmdFor("dashboard"))}) and sign in with the new password.`);
2057
2323
  }
2058
2324
  async function main() {
2059
2325
  const args = parseArgs(process.argv.slice(2));
@@ -2063,6 +2329,11 @@ async function main() {
2063
2329
  console.log(HELP);
2064
2330
  return;
2065
2331
  }
2332
+ try {
2333
+ environment.set(args.env);
2334
+ } catch (err) {
2335
+ bail(err.message);
2336
+ }
2066
2337
  if (args.provider && !["firebase", "aws", "local"].includes(args.provider)) bail(`Unknown provider ${args.provider}. Use firebase, aws or local.`);
2067
2338
  switch (args.cmd) {
2068
2339
  case "init":