@debugkit/cli 0.3.1 → 0.4.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.
Files changed (3) hide show
  1. package/README.md +33 -0
  2. package/dist/cli.js +171 -54
  3. package/package.json +4 -4
package/README.md CHANGED
@@ -26,6 +26,30 @@ Run it from your app's folder. It walks you through these steps:
26
26
  - what the SDK records on its own;
27
27
  - what you add in your own try/catches.
28
28
 
29
+ ## Several environments (preview, production…)
30
+
31
+ When each environment has its own backend, such as separate Firebase projects or AWS accounts, set
32
+ deBug up once per environment:
33
+
34
+ ```bash
35
+ npx debugkit init --env preview # e.g. into your staging Firebase project
36
+ npx debugkit init --env production # into the production one
37
+ ```
38
+
39
+ Each environment gets its own provider, project, endpoint, ingest key and dashboard login. They're
40
+ saved under `environments` in `.debugkit/config.json`, with `.debugkit/dashboard.<env>.env`.
41
+
42
+ - **Expo apps with EAS:** for `development`, `preview` and `production`, the CLI offers to put
43
+ `EXPO_PUBLIC_DEBUG_ENDPOINT`, `EXPO_PUBLIC_DEBUG_KEY` and `EXPO_PUBLIC_DEBUG_ENVIRONMENT` into
44
+ that EAS environment (`eas env:set`). `eas build` and `eas env:pull` then pick them up.
45
+ - **Other apps:** it prints the three values to set wherever that environment's builds get their
46
+ config. With `--env` it never writes `.env`, which would point every build at one environment.
47
+ - **`debug.ts` is the same for every environment:** it's on in release builds that have an
48
+ endpoint, and off in development builds and local runs (`enabled: !__DEV__ && !!endpoint`). To
49
+ leave an environment out, such as development, don't set it up.
50
+ - **Later commands take `--env` too:** `npx debugkit dashboard --env production`, `test`, `guide`
51
+ and `password`.
52
+
29
53
  ## Commands
30
54
 
31
55
  Every command below also works as `npx @debugkit/cli <command>`.
@@ -39,6 +63,15 @@ Every command below also works as `npx @debugkit/cli <command>`.
39
63
 
40
64
  Options: `--provider firebase|aws|local` skips the provider question, `--cwd <dir>` points at another folder, and `--yes` accepts the defaults (for scripts; set `DEBUGKIT_DASHBOARD_PASSWORD`).
41
65
 
66
+ ## What's been verified
67
+
68
+ | Path | Status |
69
+ |---|---|
70
+ | Just this machine | Run end to end: the empty dashboard, then test events arriving |
71
+ | Firebase | Run end to end against a real project: function deployed, indexes added without touching existing ones, test events read back on the dashboard |
72
+ | AWS | Unit-tested (profile parsing, the "not found" handling, key merging) and the bundled Lambda run locally. Not yet run against a real account |
73
+ | Platforms | Vite and React run for real. The Expo, React Native, Next.js, TanStack Start and Node templates are unit-tested |
74
+
42
75
  ## What it needs
43
76
 
44
77
  - Node 20.12 or later.
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*/.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.4.0" : "0.0.0-dev";
169
195
  var DASHBOARD_VERSION = VERSION;
170
196
  function hashPassword(password2) {
171
197
  const salt = randomBytes(16);
@@ -581,7 +607,7 @@ function instrumentWebLifecycle(sink) {
581
607
 
582
608
  // ../sdk/src/client.ts
583
609
  var SDK_NAME = "@debugkit/sdk";
584
- var SDK_VERSION = "0.3.1";
610
+ var SDK_VERSION = "0.4.0";
585
611
  var QUEUE_KEY = "@debugkit/queue";
586
612
  var MAX_QUEUE = 500;
587
613
  var uid = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`).replace(/-/g, "");
@@ -609,6 +635,12 @@ var DebugClient = class {
609
635
  if (this.timer) clearInterval(this.timer);
610
636
  this.uninstrument();
611
637
  this.opts = { flushIntervalMs: 5e3, maxBatch: 50, maxBreadcrumbs: 30, ...options };
638
+ if (options.enabled === false) {
639
+ this.ready = false;
640
+ this.queue = [];
641
+ this.log("disabled for this build (enabled: false)");
642
+ return this;
643
+ }
612
644
  if (!this.opts.context && typeof window !== "undefined") this.opts.context = browserContext();
613
645
  this.auto = resolveAuto(options);
614
646
  this.rawFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.__raw ?? globalThis.fetch : void 0;
@@ -647,6 +679,10 @@ var DebugClient = class {
647
679
  get initialized() {
648
680
  return this.ready;
649
681
  }
682
+ /** False when init() was called with `enabled: false` (or not called yet). */
683
+ get enabled() {
684
+ return this.ready;
685
+ }
650
686
  /** Events waiting to be sent. */
651
687
  get pending() {
652
688
  return this.queue.length;
@@ -1136,9 +1172,9 @@ async function walkthrough(opts) {
1136
1172
  ...opts.remaining.map((l, i) => `${i + 1}. ${l}`),
1137
1173
  `${opts.remaining.length + 1}. Run the app and watch the dashboard fill in`,
1138
1174
  "",
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`
1175
+ `${code(cmdFor("dashboard"))} open the dashboard again`,
1176
+ `${code(cmdFor("test"))} send another test event`,
1177
+ `${code(cmdFor("guide"))} replay this walkthrough`
1142
1178
  ].join("\n"),
1143
1179
  "6 \xB7 Finish wiring your app"
1144
1180
  );
@@ -1248,7 +1284,7 @@ async function setupAws(ctx) {
1248
1284
  if (!identity.Account) bail("AWS didn't say which account these credentials belong to.");
1249
1285
  const account = identity.Account;
1250
1286
  const table = await ask("DynamoDB table name", {
1251
- initial: "debugkit",
1287
+ initial: environment.get() ? `debugkit-${environment.get()}` : "debugkit",
1252
1288
  validate: (v) => /^[A-Za-z0-9_.-]{3,40}$/.test(v) ? void 0 : "3\u201340 characters: letters, digits, _ . -"
1253
1289
  });
1254
1290
  const functionName = `debugkit-ingest-${table}`.slice(0, 64);
@@ -1610,6 +1646,18 @@ async function setupFirebase(ctx) {
1610
1646
  bail();
1611
1647
  }
1612
1648
  s.stop("Installed the ingest function's dependencies");
1649
+ p.note(
1650
+ [
1651
+ `In ${bold(projectId)}${environment.get() ? ` (your ${environment.get()} environment)` : ""}, deBug will add:`,
1652
+ `\u2022 a Cloud Function ${code(FUNCTION_NAME)} in ${region}, with a public URL (each request needs the ingest key)`,
1653
+ `\u2022 a ${code("debug_apps")} collection in Firestore, with raw events expiring after 30 days`,
1654
+ `\u2022 two Firestore indexes for it (your existing indexes are left alone)`,
1655
+ "",
1656
+ "Nothing else in the project is changed. Usage is billed to the project's Blaze plan."
1657
+ ].join("\n"),
1658
+ "About to deploy"
1659
+ );
1660
+ if (!await yes(`Deploy deBug into ${projectId}?`)) bail("Nothing was deployed.");
1613
1661
  p.log.step("Adding deBug's Firestore indexes (your existing indexes are left alone)");
1614
1662
  if (await fbLive(["deploy", "--only", "firestore:indexes", "--non-interactive", ...proj], { cwd: dir }) !== 0)
1615
1663
  p.log.warn("The indexes didn't deploy. The dashboard needs them; deploy them later with the command printed at the end.");
@@ -1740,8 +1788,8 @@ export const ${FUNCTION_NAME} = onRequest(
1740
1788
  `
1741
1789
  );
1742
1790
  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)}
1791
+ const current2 = existsSync5(envFile) ? /^DEBUG_INGEST_KEYS=(.*)$/m.exec(readFileSync4(envFile, "utf8"))?.[1] : void 0;
1792
+ writeFileSync2(envFile, `DEBUG_INGEST_KEYS=${mergeKeys(current2, ctx.ingestKey, ctx.app.appId)}
1745
1793
  `);
1746
1794
  return dir;
1747
1795
  }
@@ -1768,13 +1816,13 @@ async function setupLocal(ctx) {
1768
1816
  },
1769
1817
  created: [
1770
1818
  `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)`
1819
+ `Ingest endpoint: ${code(endpoint)} (only while ${code(cmdFor("dashboard"))} is running)`
1772
1820
  ]
1773
1821
  };
1774
1822
  }
1775
1823
 
1776
1824
  // src/wire.ts
1777
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
1825
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
1778
1826
  import { dirname as dirname2, join as join6, relative } from "path";
1779
1827
  init_exec();
1780
1828
  var ENV_ENDPOINT = "DEBUG_ENDPOINT";
@@ -1806,29 +1854,39 @@ function writeAppEnv(app, conn) {
1806
1854
  upsertEnv(file, { [`${app.envPrefix}${ENV_ENDPOINT}`]: conn.endpoint, [`${app.envPrefix}${ENV_KEY}`]: conn.ingestKey });
1807
1855
  return file;
1808
1856
  }
1809
- function initFile(app, conn) {
1857
+ var ENV_ENVIRONMENT = "DEBUG_ENVIRONMENT";
1858
+ var EAS_ENVIRONMENTS = ["development", "preview", "production"];
1859
+ function envValues(app, conn, env) {
1860
+ const pre = app.envPrefix ?? "";
1861
+ return { [`${pre}${ENV_ENDPOINT}`]: conn.endpoint, [`${pre}${ENV_KEY}`]: conn.ingestKey, [`${pre}${ENV_ENVIRONMENT}`]: env };
1862
+ }
1863
+ function initFile(app, conn, multiEnv = environment.get() !== void 0) {
1810
1864
  const ext = app.typescript ? "ts" : "js";
1811
1865
  const path2 = join6(app.cwd, app.sourceDir, `debug.${ext}`);
1812
1866
  const rel = relative(app.cwd, path2);
1813
- const bang = app.typescript ? "!" : "";
1814
1867
  const env = (k) => app.envPrefix === "VITE_" ? `import.meta.env.${app.envPrefix}${k}` : `process.env.${app.envPrefix ?? ""}${k}`;
1815
1868
  const header = `// Set up by npx debugkit init. Import this file once, as early as possible.
1816
1869
  `;
1817
1870
  const appId = JSON.stringify(app.appId);
1871
+ const importLine = `${code(`import "./${rel.replace(/\.(ts|js)$/, "")}";`)}`;
1818
1872
  switch (app.platform) {
1819
1873
  case "expo":
1820
1874
  return {
1821
1875
  path: path2,
1822
1876
  contents: `${header}import { initExpo } from "@debugkit/sdk/expo";
1823
1877
 
1878
+ const endpoint = ${env(ENV_ENDPOINT)};
1879
+
1824
1880
  export const deBug = initExpo({
1825
- endpoint: ${env(ENV_ENDPOINT)}${bang},
1826
- ingestKey: ${env(ENV_KEY)}${bang},
1827
- app: { id: ${appId}, environment: __DEV__ ? "development" : "production" },
1881
+ // ${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."}
1882
+ enabled: ${multiEnv ? "!__DEV__ && !!endpoint" : "!!endpoint"},
1883
+ endpoint: endpoint ?? "",
1884
+ ingestKey: ${env(ENV_KEY)} ?? "",
1885
+ app: { id: ${appId}, environment: ${env(ENV_ENVIRONMENT)} ?? (__DEV__ ? "development" : "production") },
1828
1886
  });
1829
1887
  `,
1830
1888
  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)`,
1889
+ `Import it first in your root layout (${code(app.expoRouter ? "app/_layout.tsx" : "App.tsx")}): ${importLine} (adjust the path)`,
1832
1890
  `Wrap the root in ${code("<DebugErrorBoundary>")} from ${code("@debugkit/sdk/expo")} to catch render crashes`,
1833
1891
  ...app.expoRouter ? [`Call ${code("useDebugExpoRouter()")} from ${code("@debugkit/sdk/expo-router")} in the root layout for screen breadcrumbs`] : []
1834
1892
  ]
@@ -1840,15 +1898,17 @@ export const deBug = initExpo({
1840
1898
  // Optional, for model and app version: npm install react-native-device-info, then pass deviceInfo: DeviceInfo.
1841
1899
 
1842
1900
  export const deBug = initReactNative({
1901
+ enabled: ${multiEnv ? "!__DEV__ // release builds only" : "true"},
1843
1902
  endpoint: ${JSON.stringify(conn.endpoint)},
1844
1903
  ingestKey: ${JSON.stringify(conn.ingestKey)}, // public and write-only: safe to ship in the app
1845
1904
  app: { id: ${appId}, environment: __DEV__ ? "development" : "production" },
1846
1905
  });
1847
1906
  `,
1848
1907
  then: [
1849
- `Import it first in ${code("index.js")}: ${code(`import "./${rel.replace(/\.(ts|js)$/, "")}";`)}`,
1908
+ `Import it first in ${code("index.js")}: ${importLine}`,
1850
1909
  `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`] : []
1910
+ ...app.reactNavigation ? [`Spread ${code("{...trackReactNavigation(navRef)}")} onto your NavigationContainer for screen breadcrumbs`] : [],
1911
+ ...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
1912
  ]
1853
1913
  };
1854
1914
  case "node":
@@ -1857,23 +1917,30 @@ export const deBug = initReactNative({
1857
1917
  contents: `${header}import { initNode } from "@debugkit/sdk/node";
1858
1918
 
1859
1919
  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 },
1920
+ enabled: !!process.env.${ENV_ENDPOINT}, // off where no endpoint is set
1921
+ endpoint: process.env.${ENV_ENDPOINT} ?? "",
1922
+ ingestKey: process.env.${ENV_KEY} ?? "",
1923
+ app: { id: ${appId}, version: process.env.npm_package_version, environment: process.env.${ENV_ENVIRONMENT} ?? process.env.NODE_ENV },
1863
1924
  });
1864
1925
  `,
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)`]
1926
+ 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
1927
  };
1867
1928
  default: {
1868
- const guard = app.platform === "next" || app.platform === "tanstack-start" ? `if (typeof window !== "undefined") ` : "";
1929
+ const vite = app.envPrefix === "VITE_";
1930
+ const guard = app.platform === "next" || app.platform === "tanstack-start" ? `typeof window !== "undefined" && ` : "";
1931
+ const prod = vite ? "import.meta.env.PROD" : `process.env.NODE_ENV === "production"`;
1932
+ const fallbackEnv = vite ? "import.meta.env.MODE" : "process.env.NODE_ENV";
1869
1933
  return {
1870
1934
  path: path2,
1871
1935
  contents: `${header}import { deBug } from "@debugkit/sdk/react";
1872
1936
 
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)}` : ""} },
1937
+ const endpoint = ${env(ENV_ENDPOINT)};
1938
+
1939
+ deBug.init({
1940
+ enabled: ${guard}${multiEnv ? `${prod} && ` : ""}!!endpoint,
1941
+ endpoint: endpoint ?? "",
1942
+ ingestKey: ${env(ENV_KEY)} ?? "",
1943
+ app: { id: ${appId}${app.version ? `, version: ${JSON.stringify(app.version)}` : ""}, environment: ${env(ENV_ENVIRONMENT)} ?? ${fallbackEnv} },
1877
1944
  });
1878
1945
 
1879
1946
  export { deBug };
@@ -1887,28 +1954,58 @@ export { deBug };
1887
1954
  }
1888
1955
  }
1889
1956
  }
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")}`);
1957
+ async function writeEasEnv(app, values, env) {
1958
+ const [cmd, pre] = which("eas") ? ["eas", []] : ["npx", ["-y", "eas-cli@latest"]];
1959
+ const s = p.spinner();
1960
+ s.start(`Setting ${Object.keys(values).length} variables in EAS's ${env} environment`);
1961
+ for (const [name, value] of Object.entries(values)) {
1962
+ const r = await capture(cmd, [...pre, "env:set", "--environment", env, "--name", name, "--value", value, "--visibility", "plaintext", "--scope", "project", "--non-interactive"], { cwd: app.cwd });
1963
+ if (r.code !== 0) {
1964
+ s.error(`EAS didn't accept ${name}`);
1965
+ p.log.warn((r.stderr || r.stdout).trim().split("\n").slice(-4).join("\n"));
1966
+ return false;
1967
+ }
1897
1968
  }
1898
- if (envFile || app.platform === "node") {
1899
- if (ensureGitignored(app.cwd, ".env")) p.log.info(dim("Added .env to .gitignore"));
1969
+ s.stop(`Set ${Object.keys(values).map((k) => code(k)).join(", ")} in EAS's ${code(env)} environment`);
1970
+ return true;
1971
+ }
1972
+ async function wireApp(app, conn) {
1973
+ const env = environment.get();
1974
+ const extra = [];
1975
+ if (env) {
1976
+ const values = app.platform === "react-native" ? {} : envValues(app, conn, env);
1977
+ const usesEas = app.platform === "expo" && existsSync6(join6(app.cwd, "eas.json"));
1978
+ let done = Object.keys(values).length === 0;
1979
+ 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);
1980
+ if (!done) {
1981
+ p.note(Object.entries(values).map(([k, v]) => `${k}=${v}`).join("\n"), `Set these for your ${env} builds`);
1982
+ 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`);
1983
+ }
1984
+ } else {
1985
+ const envFile = writeAppEnv(app, conn);
1986
+ if (envFile) {
1987
+ p.log.success(`Wrote ${code(`${app.envPrefix}${ENV_ENDPOINT}`)} and ${code(`${app.envPrefix}${ENV_KEY}`)} to ${code(relative(app.cwd, envFile))}`);
1988
+ } else if (app.platform === "node") {
1989
+ upsertEnv(join6(app.cwd, ".env"), { [ENV_ENDPOINT]: conn.endpoint, [ENV_KEY]: conn.ingestKey });
1990
+ p.log.success(`Wrote ${code(ENV_ENDPOINT)} and ${code(ENV_KEY)} to ${code(".env")}`);
1991
+ }
1992
+ if (envFile || app.platform === "node") {
1993
+ if (ensureGitignored(app.cwd, ".env")) p.log.info(dim("Added .env to .gitignore"));
1994
+ }
1900
1995
  }
1901
1996
  const f = initFile(app, conn);
1902
1997
  const rel = relative(app.cwd, f.path);
1903
- if (!existsSync6(f.path) || await yes(`${rel} already exists. Replace it?`, false)) {
1998
+ const current2 = existsSync6(f.path) ? readFileSync5(f.path, "utf8") : void 0;
1999
+ if (current2 === f.contents) p.log.info(`${code(rel)} is already up to date`);
2000
+ else if (current2 === void 0 || await yes(`${rel} already exists. Replace it?`, false)) {
1904
2001
  mkdirSync3(dirname2(f.path), { recursive: true });
1905
2002
  writeFileSync3(f.path, f.contents);
1906
- p.log.success(`Created ${code(rel)}`);
2003
+ p.log.success(`${current2 === void 0 ? "Created" : "Updated"} ${code(rel)}`);
1907
2004
  } else {
1908
2005
  p.log.info(`Kept your ${rel}. The generated version is:
1909
2006
  ${dim(f.contents)}`);
1910
2007
  }
1911
- return f.then;
2008
+ return [...extra, ...f.then];
1912
2009
  }
1913
2010
 
1914
2011
  // src/cli.ts
@@ -1922,6 +2019,8 @@ ${dim("Run as npx debugkit <command> once @debugkit/sdk is installed, or npx @de
1922
2019
  ${code("npx debugkit password")} reset the dashboard login
1923
2020
 
1924
2021
  Options
2022
+ --env <name> one of several environments, like preview or production. Each has
2023
+ its own provider, project, endpoint and dashboard login
1925
2024
  --provider <firebase|aws|local> skip the provider question
1926
2025
  --cwd <dir> the app's folder (default: current folder)
1927
2026
  --yes accept defaults (for scripts)
@@ -1932,6 +2031,8 @@ function parseArgs(argv) {
1932
2031
  const a = argv[i];
1933
2032
  if (a === "--provider") out.provider = argv[++i];
1934
2033
  else if (a.startsWith("--provider=")) out.provider = a.split("=")[1];
2034
+ else if (a === "--env") out.env = argv[++i];
2035
+ else if (a.startsWith("--env=")) out.env = a.split("=")[1];
1935
2036
  else if (a === "--cwd") out.cwd = resolve(argv[++i] ?? ".");
1936
2037
  else if (a === "--yes" || a === "-y") out.yes = true;
1937
2038
  else if (a === "--help" || a === "-h") out.help = true;
@@ -1939,13 +2040,20 @@ function parseArgs(argv) {
1939
2040
  }
1940
2041
  return out;
1941
2042
  }
2043
+ var envLabel = () => environment.get() ? ` (${environment.get()})` : "";
1942
2044
  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.`);
2045
+ let cfg = readConfig(cwd);
2046
+ if (!cfg && !environment.get()) {
2047
+ const envs = listEnvironments(cwd);
2048
+ if (envs.length === 1) environment.set(envs[0]);
2049
+ 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]}`)}.`);
2050
+ cfg = readConfig(cwd);
2051
+ }
2052
+ if (!cfg) bail(`deBug isn't set up${envLabel()} in ${cwd} yet. Run ${code(cmdFor("init"))} first.`);
1945
2053
  return cfg;
1946
2054
  }
1947
2055
  async function init(cwd, preset) {
1948
- p.intro(`${pc.bgRed(pc.white(" deBug "))} ${dim("observability you own")}`);
2056
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} ${dim("observability you own")}${environment.get() ? ` \xB7 ${bold(environment.get())} environment` : ""}`);
1949
2057
  let app;
1950
2058
  try {
1951
2059
  app = detectApp(cwd);
@@ -1954,8 +2062,8 @@ async function init(cwd, preset) {
1954
2062
  }
1955
2063
  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
2064
  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")}.`);
2065
+ if (existing && !await yes(`deBug is already set up${envLabel()} here (${existing.provider}, ${existing.endpoint}). Set it up again?`, false)) {
2066
+ p.outro(`Nothing changed. Try ${code(cmdFor("dashboard"))} or ${code(cmdFor("guide"))}.`);
1959
2067
  return;
1960
2068
  }
1961
2069
  await installSdk(app);
@@ -1997,7 +2105,7 @@ async function init(cwd, preset) {
1997
2105
  dash = await startDashboard(cwd);
1998
2106
  } catch (err) {
1999
2107
  p.log.error(err.message);
2000
- p.outro(`deBug is set up, but the dashboard didn't start. Try ${code("npx debugkit dashboard")}.`);
2108
+ p.outro(`deBug is set up, but the dashboard didn't start. Try ${code(cmdFor("dashboard"))}.`);
2001
2109
  return;
2002
2110
  }
2003
2111
  await walkthrough({ cwd, app, cfg, dashboardUrl: dash.url, remaining });
@@ -2008,11 +2116,15 @@ async function init(cwd, preset) {
2008
2116
  return;
2009
2117
  }
2010
2118
  dash.stop();
2011
- p.outro(`deBug is set up. Open the dashboard any time with ${code("npx debugkit dashboard")}.`);
2119
+ const others = listEnvironments(cwd).filter((e) => e !== environment.get());
2120
+ p.outro(
2121
+ `deBug is set up${envLabel()}. Open the dashboard any time with ${code(cmdFor("dashboard"))}.` + (environment.get() && !others.length ? `
2122
+ Set up the next environment the same way, e.g. ${code("npx debugkit init --env production")}.` : "")
2123
+ );
2012
2124
  }
2013
2125
  async function dashboard(cwd) {
2014
2126
  const cfg = requireConfig(cwd);
2015
- p.intro(`${pc.bgRed(pc.white(" deBug "))} dashboard`);
2127
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} dashboard${envLabel()}`);
2016
2128
  const dash = await startDashboard(cwd);
2017
2129
  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
2130
  const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_exec(), exec_exports));
@@ -2029,11 +2141,11 @@ async function test(cwd) {
2029
2141
  if (r.error) {
2030
2142
  s.error(`Not accepted: ${r.error}`);
2031
2143
  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.`);
2144
+ if (cfg.provider === "local") p.log.info(`On this setup the dashboard is the ingest: start it with ${code(cmdFor("dashboard"))} first.`);
2033
2145
  return;
2034
2146
  }
2035
2147
  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.`);
2148
+ p.outro(`Open the dashboard (${code(cmdFor("dashboard"))}) to see them under the ${code("onboarding.test")} flow.`);
2037
2149
  }
2038
2150
  async function guide(cwd) {
2039
2151
  const cfg = requireConfig(cwd);
@@ -2053,7 +2165,7 @@ async function password(cwd) {
2053
2165
  requireConfig(cwd);
2054
2166
  p.intro(`${pc.bgRed(pc.white(" deBug "))} reset the dashboard login`);
2055
2167
  await resetLogin(cwd);
2056
- p.outro(`Saved. Restart the dashboard (${code("npx debugkit dashboard")}) and sign in with the new password.`);
2168
+ p.outro(`Saved. Restart the dashboard (${code(cmdFor("dashboard"))}) and sign in with the new password.`);
2057
2169
  }
2058
2170
  async function main() {
2059
2171
  const args = parseArgs(process.argv.slice(2));
@@ -2063,6 +2175,11 @@ async function main() {
2063
2175
  console.log(HELP);
2064
2176
  return;
2065
2177
  }
2178
+ try {
2179
+ environment.set(args.env);
2180
+ } catch (err) {
2181
+ bail(err.message);
2182
+ }
2066
2183
  if (args.provider && !["firebase", "aws", "local"].includes(args.provider)) bail(`Unknown provider ${args.provider}. Use firebase, aws or local.`);
2067
2184
  switch (args.cmd) {
2068
2185
  case "init":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@debugkit/cli",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Set up deBug in your app: npx @debugkit/cli init (or npx debugkit init once @debugkit/sdk is installed). Deploys ingest to your own cloud, wires the SDK and walks you through the dashboard.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,9 +20,9 @@
20
20
  },
21
21
  "devDependencies": {
22
22
  "@aws-sdk/lib-dynamodb": "^3.700.0",
23
- "@debugkit/sdk": "^0.3.1",
24
- "@debugkit/ingest": "^0.3.1",
25
- "@debugkit/adapters": "^0.3.1"
23
+ "@debugkit/adapters": "^0.4.0",
24
+ "@debugkit/ingest": "^0.4.0",
25
+ "@debugkit/sdk": "^0.4.0"
26
26
  },
27
27
  "engines": {
28
28
  "node": ">=20.12"