@debugkit/cli 0.0.0-stage → 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.
package/dist/cli.js ADDED
@@ -0,0 +1,2203 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // src/exec.ts
13
+ var exec_exports = {};
14
+ __export(exec_exports, {
15
+ capture: () => capture,
16
+ interactive: () => interactive,
17
+ openUrl: () => openUrl,
18
+ which: () => which
19
+ });
20
+ import { spawn, spawnSync } from "child_process";
21
+ function capture(cmd, args, opts = {}) {
22
+ return new Promise((resolve2) => {
23
+ const child = spawn(cmd, args, { cwd: opts.cwd, env: { ...process.env, ...opts.env }, stdio: ["pipe", "pipe", "pipe"] });
24
+ let stdout = "";
25
+ let stderr = "";
26
+ child.stdout.on("data", (d) => stdout += d);
27
+ child.stderr.on("data", (d) => stderr += d);
28
+ child.on("error", (err) => resolve2({ code: 127, stdout, stderr: stderr + String(err) }));
29
+ child.on("close", (code2) => resolve2({ code: code2 ?? 1, stdout, stderr }));
30
+ if (opts.input) child.stdin.end(opts.input);
31
+ else child.stdin.end();
32
+ });
33
+ }
34
+ function interactive(cmd, args, opts = {}) {
35
+ return new Promise((resolve2) => {
36
+ const child = spawn(cmd, args, { cwd: opts.cwd, env: { ...process.env, ...opts.env }, stdio: "inherit" });
37
+ child.on("error", () => resolve2(127));
38
+ child.on("close", (code2) => resolve2(code2 ?? 1));
39
+ });
40
+ }
41
+ function which(cmd) {
42
+ const r = spawnSync(process.platform === "win32" ? "where" : "which", [cmd], { encoding: "utf8" });
43
+ return r.status === 0 ? r.stdout.split(/\r?\n/)[0]?.trim() || void 0 : void 0;
44
+ }
45
+ function openUrl(url) {
46
+ if (process.env.DEBUGKIT_NO_OPEN || process.env.CI) return;
47
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
48
+ try {
49
+ spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
50
+ } catch {
51
+ }
52
+ }
53
+ var init_exec = __esm({
54
+ "src/exec.ts"() {
55
+ "use strict";
56
+ }
57
+ });
58
+
59
+ // src/cli.ts
60
+ import { randomBytes as randomBytes2 } from "crypto";
61
+ import { resolve } from "path";
62
+
63
+ // src/dashboard.ts
64
+ init_exec();
65
+ import { spawn as spawn2 } from "child_process";
66
+ import { randomBytes, scryptSync } from "crypto";
67
+ import { existsSync as existsSync2 } from "fs";
68
+ import { connect, createServer } from "net";
69
+ import { join as join2 } from "path";
70
+
71
+ // src/state.ts
72
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from "fs";
73
+ import { join } from "path";
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}` : ""}`;
85
+ function paths(cwd) {
86
+ const dir = join(cwd, DIR);
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
+ };
93
+ }
94
+ function readFile(cwd) {
95
+ try {
96
+ return JSON.parse(readFileSync(paths(cwd).config, "utf8"));
97
+ } catch {
98
+ return void 0;
99
+ }
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
+ }
110
+ function writeConfig(cwd, cfg) {
111
+ const { dir, config } = paths(cwd);
112
+ mkdirSync(dir, { recursive: true });
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");
117
+ }
118
+ function upsertEnv(file, values) {
119
+ const lines = existsSync(file) ? readFileSync(file, "utf8").split(/\r?\n/) : [];
120
+ const seen = /* @__PURE__ */ new Set();
121
+ const out = lines.map((line) => {
122
+ const m = /^\s*([A-Z0-9_]+)\s*=/.exec(line);
123
+ if (m && m[1] in values) {
124
+ seen.add(m[1]);
125
+ return `${m[1]}=${quote(values[m[1]])}`;
126
+ }
127
+ return line;
128
+ });
129
+ while (out.length && out[out.length - 1] === "") out.pop();
130
+ for (const [k, v] of Object.entries(values)) if (!seen.has(k)) out.push(`${k}=${quote(v)}`);
131
+ writeFileSync(file, out.join("\n") + "\n");
132
+ }
133
+ var quote = (v) => /[\s#"'=]/.test(v) ? JSON.stringify(v) : v;
134
+ function readEnv(file) {
135
+ const out = {};
136
+ if (!existsSync(file)) return out;
137
+ for (const line of readFileSync(file, "utf8").split(/\r?\n/)) {
138
+ const m = /^\s*([A-Z0-9_]+)\s*=\s*(.*)$/.exec(line);
139
+ if (!m) continue;
140
+ let v = m[2].trim();
141
+ if (v.startsWith('"')) {
142
+ try {
143
+ v = JSON.parse(v);
144
+ } catch {
145
+ }
146
+ }
147
+ out[m[1]] = v;
148
+ }
149
+ return out;
150
+ }
151
+ function ensureGitignored(cwd, entry) {
152
+ const file = join(cwd, ".gitignore");
153
+ const cur = existsSync(file) ? readFileSync(file, "utf8") : "";
154
+ if (cur.split(/\r?\n/).some((l) => l.trim() === entry)) return false;
155
+ appendFileSync(file, `${cur && !cur.endsWith("\n") ? "\n" : ""}${entry}
156
+ `);
157
+ return true;
158
+ }
159
+
160
+ // src/ui.ts
161
+ import * as p from "@clack/prompts";
162
+ import pc from "picocolors";
163
+ var flags = { yes: false, command: "init" };
164
+ function bail(message = flags.command === "init" ? "Setup cancelled. Run npx debugkit init again whenever you're ready." : "Stopped.") {
165
+ p.cancel(message);
166
+ process.exit(0);
167
+ }
168
+ function must(value) {
169
+ if (p.isCancel(value) || typeof value === "symbol") bail();
170
+ return value;
171
+ }
172
+ async function choose(message, options, initial) {
173
+ if (flags.yes) return initial ?? options[0].value;
174
+ return must(await p.select({ message, options, initialValue: initial }));
175
+ }
176
+ async function ask(message, opts = {}) {
177
+ if (flags.yes && opts.initial !== void 0) return opts.initial;
178
+ const v = must(await p.text({ message, initialValue: opts.initial, placeholder: opts.placeholder, validate: opts.validate ? (x) => opts.validate(x ?? "") : void 0 }));
179
+ return String(v).trim();
180
+ }
181
+ async function yes(message, initial = true) {
182
+ if (flags.yes) return initial;
183
+ return must(await p.confirm({ message, initialValue: initial }));
184
+ }
185
+ async function next(message = "Continue") {
186
+ if (flags.yes) return;
187
+ must(await p.confirm({ message, active: "Next", inactive: "Stop here", initialValue: true })) || bail("Stopped the walkthrough. Run npx debugkit guide to pick it up again.");
188
+ }
189
+ var code = (s) => pc.cyan(s);
190
+ var dim = (s) => pc.dim(s);
191
+ var bold = (s) => pc.bold(s);
192
+
193
+ // src/dashboard.ts
194
+ var VERSION = true ? "0.4.0" : "0.0.0-dev";
195
+ var DASHBOARD_VERSION = VERSION;
196
+ function hashPassword(password2) {
197
+ const salt = randomBytes(16);
198
+ return `scrypt.${salt.toString("hex")}.${scryptSync(password2, salt, 64).toString("hex")}`;
199
+ }
200
+ function inUse(port, host) {
201
+ return new Promise((resolve2) => {
202
+ const sock = connect({ port, host });
203
+ sock.setTimeout(400);
204
+ sock.once("connect", () => (sock.destroy(), resolve2(true)));
205
+ sock.once("timeout", () => (sock.destroy(), resolve2(false)));
206
+ sock.once("error", () => resolve2(false));
207
+ });
208
+ }
209
+ async function freePort(preferred) {
210
+ for (let port = preferred; port < preferred + 50; port++) {
211
+ if (await inUse(port, "127.0.0.1") || await inUse(port, "::1")) continue;
212
+ const ok = await new Promise((resolve2) => {
213
+ const srv = createServer().once("error", () => resolve2(false));
214
+ srv.listen(port, "127.0.0.1", () => srv.close(() => resolve2(true)));
215
+ });
216
+ if (ok) return port;
217
+ }
218
+ return preferred;
219
+ }
220
+ async function prepareDashboardEnv(cwd, storeEnv, port) {
221
+ const file = paths(cwd).dashboardEnv;
222
+ const cur = readEnv(file);
223
+ const values = { ...storeEnv, PORT: String(port) };
224
+ if (!cur.DEBUG_SESSION_SECRET) values.DEBUG_SESSION_SECRET = randomBytes(32).toString("hex");
225
+ if (!cur.DEBUG_API_TOKEN) values.DEBUG_API_TOKEN = `dbk_${randomBytes(24).toString("hex")}`;
226
+ if (!cur.DEBUG_DASHBOARD_USERS) {
227
+ p.note("The dashboard is behind a login, even on your own machine. Pick the email and password you'll sign in with.", "Dashboard login");
228
+ Object.assign(values, await askLogin(cwd));
229
+ }
230
+ upsertEnv(file, values);
231
+ return file;
232
+ }
233
+ async function askLogin(cwd, currentEmail) {
234
+ const gitEmail = currentEmail ?? (await capture("git", ["config", "user.email"], { cwd })).stdout.trim();
235
+ const email = await ask("Dashboard email", { initial: gitEmail || void 0, validate: (v) => /^\S+@\S+\.\S+$/.test(v) ? void 0 : "Enter an email address" });
236
+ const password2 = flags.yes && process.env.DEBUGKIT_DASHBOARD_PASSWORD ? process.env.DEBUGKIT_DASHBOARD_PASSWORD : String(must(await p.password({ message: "Dashboard password (10+ characters)", validate: (v) => (v ?? "").length >= 10 ? void 0 : "At least 10 characters" })));
237
+ return { DEBUG_DASHBOARD_USERS: `${email.toLowerCase()}=${hashPassword(password2)}`, DEBUGKIT_LOGIN_EMAIL: email.toLowerCase() };
238
+ }
239
+ async function resetLogin(cwd) {
240
+ const file = paths(cwd).dashboardEnv;
241
+ upsertEnv(file, await askLogin(cwd, readEnv(file).DEBUGKIT_LOGIN_EMAIL));
242
+ }
243
+ function dashboardCommand() {
244
+ const dir = process.env.DEBUGKIT_DASHBOARD_DIR;
245
+ if (dir && existsSync2(join2(dir, "server.mjs"))) return [process.execPath, [join2(dir, "server.mjs")]];
246
+ return ["npx", ["-y", `@debugkit/dashboard@${DASHBOARD_VERSION}`]];
247
+ }
248
+ async function startDashboard(cwd) {
249
+ const envFile = paths(cwd).dashboardEnv;
250
+ const env = readEnv(envFile);
251
+ const port = Number(env.PORT ?? 4400);
252
+ const url = `http://127.0.0.1:${port}`;
253
+ const [cmd, args] = dashboardCommand();
254
+ const child = spawn2(cmd, args, {
255
+ cwd,
256
+ // The dashboard runs on this machine over plain http, where browsers drop Secure cookies
257
+ // (the login would bounce straight back to the sign-in page). Behind HTTPS, set DEBUG_INSECURE_COOKIES=0.
258
+ env: { ...process.env, ...env, DEBUG_ENV_FILE: envFile, NODE_ENV: "production", DEBUG_INSECURE_COOKIES: env.DEBUG_INSECURE_COOKIES ?? "1" },
259
+ stdio: ["ignore", "pipe", "pipe"]
260
+ });
261
+ let log = "";
262
+ child.stdout?.on("data", (d) => log += d);
263
+ child.stderr?.on("data", (d) => log += d);
264
+ const s = p.spinner();
265
+ s.start(cmd === "npx" ? "Starting the dashboard (the first run downloads it)" : "Starting the dashboard");
266
+ const deadline = Date.now() + 18e4;
267
+ for (; ; ) {
268
+ if (child.exitCode !== null) {
269
+ s.error("The dashboard stopped");
270
+ throw new Error(`The dashboard exited:
271
+ ${log.slice(-1500)}`);
272
+ }
273
+ try {
274
+ const r = await fetch(`${url}/login`, { redirect: "manual" });
275
+ if (r.status < 500 && child.exitCode === null && log.includes("deBug dashboard on")) break;
276
+ } catch {
277
+ }
278
+ if (Date.now() > deadline) {
279
+ s.error("The dashboard didn't start in time");
280
+ child.kill();
281
+ throw new Error(log.slice(-1500));
282
+ }
283
+ await new Promise((r) => setTimeout(r, 500));
284
+ }
285
+ s.stop(`Dashboard running at ${code(url)}`);
286
+ const stop = () => {
287
+ if (child.exitCode === null) child.kill();
288
+ };
289
+ process.once("exit", stop);
290
+ return { url, child, stop };
291
+ }
292
+ async function summary(cwd, url, app) {
293
+ const token = readEnv(paths(cwd).dashboardEnv).DEBUG_API_TOKEN;
294
+ try {
295
+ const r = await fetch(`${url}/api/summary?app=${encodeURIComponent(app)}`, { headers: token ? { authorization: `Bearer ${token}` } : {} });
296
+ const text2 = await r.text();
297
+ let data;
298
+ try {
299
+ data = JSON.parse(text2);
300
+ } catch {
301
+ }
302
+ return { ok: r.ok, status: r.status, data, error: r.ok ? void 0 : text2.slice(0, 300) };
303
+ } catch (err) {
304
+ return { ok: false, status: 0, error: err.message };
305
+ }
306
+ }
307
+ var loginHint = (cwd) => {
308
+ const email = readEnv(paths(cwd).dashboardEnv).DEBUGKIT_LOGIN_EMAIL;
309
+ return email ? `Sign in as ${code(email)} with the password you chose.` : dim("Sign in with the login in .debugkit/dashboard.env.");
310
+ };
311
+
312
+ // src/detect.ts
313
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
314
+ import { join as join3 } from "path";
315
+ var PLATFORM_LABEL = {
316
+ expo: "Expo",
317
+ "react-native": "React Native",
318
+ next: "Next.js",
319
+ "tanstack-start": "TanStack Start",
320
+ "vite-react": "React (Vite)",
321
+ react: "React",
322
+ node: "Node"
323
+ };
324
+ function detectApp(cwd) {
325
+ let pkg = {};
326
+ try {
327
+ pkg = JSON.parse(readFileSync2(join3(cwd, "package.json"), "utf8"));
328
+ } catch {
329
+ throw new Error(`No package.json in ${cwd}. Run npx debugkit init from your app's folder.`);
330
+ }
331
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
332
+ const has = (d) => d in deps;
333
+ const platform = has("expo") ? "expo" : has("react-native") ? "react-native" : has("next") ? "next" : has("@tanstack/react-start") ? "tanstack-start" : has("vite") && has("react") ? "vite-react" : has("react") ? "react" : "node";
334
+ const envPrefix = platform === "expo" ? "EXPO_PUBLIC_" : platform === "next" ? "NEXT_PUBLIC_" : platform === "vite-react" || platform === "tanstack-start" ? "VITE_" : void 0;
335
+ const name = pkg.name ?? cwd.split(/[\\/]/).pop() ?? "app";
336
+ return {
337
+ cwd,
338
+ name,
339
+ appId: toAppId(name),
340
+ version: pkg.version,
341
+ platform,
342
+ expoRouter: has("expo-router"),
343
+ reactNavigation: has("@react-navigation/native"),
344
+ packageManager: existsSync3(join3(cwd, "pnpm-lock.yaml")) ? "pnpm" : existsSync3(join3(cwd, "yarn.lock")) ? "yarn" : existsSync3(join3(cwd, "bun.lockb")) || existsSync3(join3(cwd, "bun.lock")) ? "bun" : "npm",
345
+ hasSdk: has("@debugkit/sdk"),
346
+ missingExpoModules: platform === "expo" ? ["expo-device", "expo-application"].filter((m) => !has(m)) : [],
347
+ sourceDir: existsSync3(join3(cwd, "src")) ? "src" : ".",
348
+ envPrefix,
349
+ typescript: existsSync3(join3(cwd, "tsconfig.json")) || has("typescript")
350
+ };
351
+ }
352
+ function toAppId(name) {
353
+ return name.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "app";
354
+ }
355
+ function installCommand(pm, pkgs) {
356
+ switch (pm) {
357
+ case "pnpm":
358
+ return ["pnpm", ["add", ...pkgs]];
359
+ case "yarn":
360
+ return ["yarn", ["add", ...pkgs]];
361
+ case "bun":
362
+ return ["bun", ["add", ...pkgs]];
363
+ default:
364
+ return ["npm", ["install", ...pkgs]];
365
+ }
366
+ }
367
+
368
+ // ../schema/src/core.ts
369
+ var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
370
+ var GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
371
+ var NOT_IN_APP = [/node_modules/, /\bnative\b/, /\[native code\]/, /InternalBytecode/];
372
+ var RN_BUNDLE = /\.(?:js)?bundle\b/;
373
+ function cleanFile(file) {
374
+ return file.replace(/^address at /, "");
375
+ }
376
+ function parseStack(stack) {
377
+ if (!stack) return [];
378
+ const frames = [];
379
+ for (const raw of stack.split("\n")) {
380
+ const m = V8.exec(raw) ?? GECKO.exec(raw);
381
+ if (!m) continue;
382
+ const [, fn, rawFile, line, col] = m;
383
+ const file = cleanFile(rawFile ?? "");
384
+ frames.push({
385
+ fn: fn || void 0,
386
+ file,
387
+ line: Number(line),
388
+ col: Number(col),
389
+ inApp: RN_BUNDLE.test(file) ? !/^(?:anonymous|eval|global code)$/.test(fn ?? "") : !NOT_IN_APP.some((re) => re.test(file))
390
+ });
391
+ if (frames.length >= 100) break;
392
+ }
393
+ return frames;
394
+ }
395
+
396
+ // ../sdk/src/context.ts
397
+ function mergeContext(a, b) {
398
+ const out = { ...a };
399
+ for (const [k, v] of Object.entries(b)) {
400
+ const prev = out[k];
401
+ out[k] = v && typeof v === "object" && prev && typeof prev === "object" ? { ...prev, ...v } : v ?? prev;
402
+ }
403
+ return out;
404
+ }
405
+ function safe(fn) {
406
+ try {
407
+ return fn();
408
+ } catch {
409
+ return void 0;
410
+ }
411
+ }
412
+ function timezone() {
413
+ return safe(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
414
+ }
415
+ function browserContext() {
416
+ if (typeof navigator === "undefined" || typeof window === "undefined") {
417
+ const ua2 = typeof navigator !== "undefined" ? navigator.userAgent : void 0;
418
+ const node = typeof process !== "undefined" ? process.versions?.node : void 0;
419
+ return {
420
+ runtime: { name: ua2 === "Cloudflare-Workers" ? "cloudflare-workers" : node ? "node" : "edge", version: node },
421
+ os: { name: "server" },
422
+ timezone: timezone()
423
+ };
424
+ }
425
+ const ua = navigator.userAgent;
426
+ const android = /Android ([\d.]+)/.exec(ua)?.[1];
427
+ const ios = /(?:iPhone|iPad|iPod).*? OS (\d+[_\d]*)/.exec(ua)?.[1];
428
+ const os = android ? { name: "android", version: android } : ios ? { name: "ios", version: ios.replace(/_/g, ".") } : /Mac OS X/.test(ua) ? { name: "macos" } : /Windows/.test(ua) ? { name: "windows" } : /Linux/.test(ua) ? { name: "linux" } : { name: "web" };
429
+ const conn = navigator.connection;
430
+ const browser = /Edg\/([\d.]+)/.exec(ua) ? { name: "edge", v: /Edg\/([\d.]+)/.exec(ua)[1] } : /Chrome\/([\d.]+)/.exec(ua) ? { name: "chrome", v: /Chrome\/([\d.]+)/.exec(ua)[1] } : /Version\/([\d.]+).*Safari/.exec(ua) ? { name: "safari", v: /Version\/([\d.]+)/.exec(ua)[1] } : /Firefox\/([\d.]+)/.exec(ua) ? { name: "firefox", v: /Firefox\/([\d.]+)/.exec(ua)[1] } : void 0;
431
+ return {
432
+ os,
433
+ runtime: { name: "browser", version: browser ? `${browser.name} ${browser.v}` : void 0 },
434
+ device: {
435
+ type: /iPad|Tablet/.test(ua) ? "tablet" : /Mobi/.test(ua) ? "phone" : "desktop",
436
+ screen: typeof screen !== "undefined" ? { width: screen.width, height: screen.height, scale: window.devicePixelRatio } : void 0
437
+ },
438
+ network: conn ? {
439
+ type: conn.type === "wifi" ? "wifi" : conn.type === "cellular" ? "cellular" : "unknown",
440
+ effectiveType: conn.effectiveType,
441
+ isConnected: navigator.onLine
442
+ } : void 0,
443
+ locale: navigator.language,
444
+ timezone: timezone()
445
+ };
446
+ }
447
+
448
+ // ../sdk/src/auto.ts
449
+ var g = globalThis;
450
+ var ID_SEGMENT = /^(?:\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,}|(?=[^/]*\d)[\w-]{20,})$/i;
451
+ function normaliseUrl(raw) {
452
+ const m = /^(?:([a-z][a-z0-9+.-]*:)?\/\/([^/?#]*))?([^?#]*)/i.exec(raw.trim());
453
+ let host = m?.[2] ?? "";
454
+ const path2 = (m?.[3] || "/").split("/").map((s) => ID_SEGMENT.test(s) ? ":id" : s).join("/");
455
+ if (host.includes("@")) host = host.slice(host.lastIndexOf("@") + 1);
456
+ const here = typeof location !== "undefined" ? location.host : void 0;
457
+ return !host || host === here ? path2 : `${host}${path2.startsWith("/") ? "" : "/"}${path2}`;
458
+ }
459
+ var insideFetch = 0;
460
+ function instrumentFetch(sink) {
461
+ const orig = g.fetch;
462
+ if (typeof orig !== "function" || orig.__debug) return;
463
+ const wrapped = function(input, init2) {
464
+ const url = typeof input === "string" ? input : input?.href ?? input?.url ?? String(input);
465
+ if (sink.ignored(url)) return orig.call(this, input, init2);
466
+ const method = String(init2?.method ?? input?.method ?? "GET").toUpperCase();
467
+ const start = Date.now();
468
+ const stack = new Error().stack;
469
+ let p2;
470
+ insideFetch++;
471
+ try {
472
+ p2 = orig.call(this, input, init2);
473
+ } finally {
474
+ insideFetch--;
475
+ }
476
+ return p2.then(
477
+ (res) => {
478
+ sink.request({ method, url, status: res.status, durationMs: Date.now() - start, stack });
479
+ return res;
480
+ },
481
+ (error) => {
482
+ const aborted = error?.name === "AbortError";
483
+ sink.request({ method, url, error, aborted, durationMs: Date.now() - start, stack });
484
+ throw error;
485
+ }
486
+ );
487
+ };
488
+ wrapped.__debug = true;
489
+ g.fetch = wrapped;
490
+ return () => {
491
+ if (g.fetch === wrapped) g.fetch = orig;
492
+ };
493
+ }
494
+ function instrumentXhr(sink) {
495
+ const X = g.XMLHttpRequest;
496
+ const proto = X?.prototype;
497
+ if (!proto || proto.open.__debug) return;
498
+ const open = proto.open;
499
+ const send = proto.send;
500
+ const wrappedOpen = function(method, url, ...rest) {
501
+ const u = String(url);
502
+ this.__debug = insideFetch > 0 || sink.ignored(u) ? null : { method: String(method).toUpperCase(), url: u };
503
+ return open.call(this, method, url, ...rest);
504
+ };
505
+ const wrappedSend = function(...args) {
506
+ const d = this.__debug;
507
+ if (d) {
508
+ const start = Date.now();
509
+ const stack = new Error().stack;
510
+ let aborted = false;
511
+ let timedOut = false;
512
+ this.addEventListener("abort", () => aborted = true);
513
+ this.addEventListener("timeout", () => timedOut = true);
514
+ this.addEventListener(
515
+ "loadend",
516
+ () => sink.request({ ...d, status: this.status || void 0, aborted, timedOut, durationMs: Date.now() - start, stack })
517
+ );
518
+ }
519
+ return send.apply(this, args);
520
+ };
521
+ wrappedOpen.__debug = true;
522
+ proto.open = wrappedOpen;
523
+ proto.send = wrappedSend;
524
+ return () => {
525
+ proto.open = open;
526
+ proto.send = send;
527
+ };
528
+ }
529
+ function format(arg) {
530
+ if (typeof arg === "string") return arg;
531
+ if (arg instanceof Error) return `${arg.name}: ${arg.message}`;
532
+ try {
533
+ return JSON.stringify(arg) ?? String(arg);
534
+ } catch {
535
+ return String(arg);
536
+ }
537
+ }
538
+ function instrumentConsole(sink) {
539
+ const c = g.console;
540
+ if (!c) return;
541
+ const restores = [];
542
+ for (const [method, level] of [["warn", "warning"], ["error", "error"]]) {
543
+ const orig = c[method];
544
+ if (typeof orig !== "function") continue;
545
+ c[method] = function(...args) {
546
+ if (args[0] !== "[deBug]") sink.crumb("log", args.map(format).join(" ").slice(0, 500), level);
547
+ return orig.apply(this, args);
548
+ };
549
+ restores.push(() => c[method] = orig);
550
+ }
551
+ return () => restores.forEach((r) => r());
552
+ }
553
+ var path = () => typeof location !== "undefined" ? location.pathname : "";
554
+ function instrumentHistory(sink) {
555
+ const h = g.history;
556
+ if (typeof window === "undefined" || !h?.pushState || typeof g.addEventListener !== "function") return;
557
+ const orig = { pushState: h.pushState, replaceState: h.replaceState };
558
+ for (const k of ["pushState", "replaceState"]) {
559
+ h[k] = function(...args) {
560
+ const out = orig[k].apply(this, args);
561
+ sink.navigated(path());
562
+ return out;
563
+ };
564
+ }
565
+ const onPop = () => sink.navigated(path());
566
+ g.addEventListener("popstate", onPop);
567
+ sink.navigated(path());
568
+ return () => {
569
+ Object.assign(h, orig);
570
+ g.removeEventListener("popstate", onPop);
571
+ };
572
+ }
573
+ var CLICKABLE = 'button,a,[role="button"],[role="link"],[role="tab"],[role="menuitem"],input[type="submit"],input[type="button"],input[type="checkbox"],input[type="radio"],summary,label,[data-testid]';
574
+ function describeElement(el) {
575
+ const tag = el.tagName.toLowerCase();
576
+ const label = el.getAttribute("aria-label") || el.getAttribute("data-testid") || el.getAttribute("title") || (tag === "input" ? el.getAttribute("name") || el.type : el.innerText || el.textContent || "");
577
+ const id = el.id ? `#${el.id}` : "";
578
+ const text2 = label.replace(/\s+/g, " ").trim().slice(0, 60);
579
+ return `${tag}${id}${text2 ? ` "${text2}"` : ""}`;
580
+ }
581
+ function instrumentClicks(sink) {
582
+ const d = g.document;
583
+ if (!d?.addEventListener) return;
584
+ const onClick = (ev) => {
585
+ const t = ev.target;
586
+ const el = t?.closest?.(CLICKABLE);
587
+ if (el) sink.crumb("ui", `Clicked ${describeElement(el)}`);
588
+ };
589
+ d.addEventListener("click", onClick, true);
590
+ return () => d.removeEventListener("click", onClick, true);
591
+ }
592
+ function instrumentWebLifecycle(sink) {
593
+ const d = g.document;
594
+ if (typeof window === "undefined" || !d?.addEventListener) return;
595
+ const onVis = () => sink.lifecycle(d.visibilityState === "hidden" ? "background" : "foreground");
596
+ const onOnline = () => sink.crumb("network", "Device went online");
597
+ const onOffline = () => sink.crumb("network", "Device went offline", "warning");
598
+ d.addEventListener("visibilitychange", onVis);
599
+ g.addEventListener("online", onOnline);
600
+ g.addEventListener("offline", onOffline);
601
+ return () => {
602
+ d.removeEventListener("visibilitychange", onVis);
603
+ g.removeEventListener("online", onOnline);
604
+ g.removeEventListener("offline", onOffline);
605
+ };
606
+ }
607
+
608
+ // ../sdk/src/client.ts
609
+ var SDK_NAME = "@debugkit/sdk";
610
+ var SDK_VERSION = "0.4.0";
611
+ var QUEUE_KEY = "@debugkit/queue";
612
+ var MAX_QUEUE = 500;
613
+ var uid = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`).replace(/-/g, "");
614
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
615
+ var DebugClient = class {
616
+ opts;
617
+ queue = [];
618
+ crumbs = [];
619
+ session = { id: uid(), startedAt: now() };
620
+ user = { anonymousId: uid() };
621
+ timer;
622
+ flushing;
623
+ backoffUntil = 0;
624
+ failures = 0;
625
+ ready = false;
626
+ handlersInstalled = false;
627
+ auto = { errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false, sessions: false };
628
+ restores = [];
629
+ sessionState = { errored: false, crashed: false };
630
+ lastNav;
631
+ limits = /* @__PURE__ */ new Map();
632
+ /** fetch as it was before instrumentation, so our own uploads are never recorded. */
633
+ rawFetch;
634
+ init(options) {
635
+ if (this.timer) clearInterval(this.timer);
636
+ this.uninstrument();
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
+ }
644
+ if (!this.opts.context && typeof window !== "undefined") this.opts.context = browserContext();
645
+ this.auto = resolveAuto(options);
646
+ this.rawFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.__raw ?? globalThis.fetch : void 0;
647
+ this.ready = true;
648
+ void this.restore();
649
+ if (this.auto.errors && !this.handlersInstalled) this.installGlobalHandlers();
650
+ this.instrument();
651
+ if (this.auto.sessions) this.startSession();
652
+ if (this.opts.flushIntervalMs > 0) {
653
+ this.timer = setInterval(() => void this.flush(), this.opts.flushIntervalMs);
654
+ this.timer.unref?.();
655
+ }
656
+ return this;
657
+ }
658
+ /** Which automatic captures are on, after defaults. */
659
+ get autoCapture() {
660
+ return this.auto;
661
+ }
662
+ /**
663
+ * Begin a new session: a fresh id and a "started" marker. Called by `init()`, and by the
664
+ * React Native entry when the app returns after 30 minutes in the background.
665
+ */
666
+ startSession() {
667
+ if (!this.ready) return;
668
+ void this.flush();
669
+ this.session = { id: uid(), startedAt: now() };
670
+ this.sessionState = { errored: false, crashed: false };
671
+ if (this.auto.sessions) this.push({ type: "session", id: uid(), ts: now(), status: "started" });
672
+ }
673
+ /** Record a navigation breadcrumb ("from → to"). Repeated paths are ignored. */
674
+ navigated(to) {
675
+ if (!to || to === this.lastNav) return;
676
+ this.breadcrumb("navigation", this.lastNav ? `${this.lastNav} \u2192 ${to}` : to);
677
+ this.lastNav = to;
678
+ }
679
+ get initialized() {
680
+ return this.ready;
681
+ }
682
+ /** False when init() was called with `enabled: false` (or not called yet). */
683
+ get enabled() {
684
+ return this.ready;
685
+ }
686
+ /** Events waiting to be sent. */
687
+ get pending() {
688
+ return this.queue.length;
689
+ }
690
+ /** Merge extra context (e.g. after an async device lookup). Applies to events sent from now on. */
691
+ setContext(patch) {
692
+ if (this.opts) this.opts.context = mergeContext(this.opts.context ?? {}, patch);
693
+ }
694
+ setUser(id) {
695
+ this.user = { ...this.user, id };
696
+ }
697
+ breadcrumb(category, message, data, level = "info") {
698
+ const msg = message.slice(0, 500);
699
+ const last = this.crumbs[this.crumbs.length - 1];
700
+ if (last && last.category === category && last.message === msg && last.level === level) {
701
+ last.ts = now();
702
+ last.data = { ...data, repeated: Number(last.data?.repeated ?? 1) + 1 };
703
+ return;
704
+ }
705
+ this.crumbs.push({ ts: now(), category, message: msg, data, level });
706
+ if (this.crumbs.length > (this.opts?.maxBreadcrumbs ?? 30)) this.crumbs.shift();
707
+ }
708
+ /** Log an error. `flow` is the part of the app it belongs to, e.g. "auth.login". */
709
+ error(err, meta = {}) {
710
+ this.captureError(normaliseError(err), meta);
711
+ }
712
+ /** Log a custom event. Use outcome to let deBug compute failure rates per flow. */
713
+ event(name, meta = {}) {
714
+ this.breadcrumb("event", name, meta.props);
715
+ this.enqueue({ type: "event", id: uid(), ts: now(), name, flow: meta.flow, step: meta.step, tags: meta.tags, outcome: meta.outcome, props: meta.props });
716
+ }
717
+ /**
718
+ * Wraps an async step: logs a success or failure outcome for the flow, plus the error.
719
+ * Pass `{ captureError: false }` when the error is already reported elsewhere, e.g. a
720
+ * server function wrapped in withDebug, so it isn't counted twice.
721
+ */
722
+ async track(flow, step, fn, opts = {}) {
723
+ try {
724
+ const out = await fn();
725
+ this.event(`${flow}.${step}`, { flow, step, outcome: "success" });
726
+ return out;
727
+ } catch (err) {
728
+ this.event(`${flow}.${step}`, { flow, step, outcome: "failure" });
729
+ if (opts.captureError !== false) this.error(err, { flow, step });
730
+ throw err;
731
+ }
732
+ }
733
+ async flush() {
734
+ if (this.flushing) await this.flushing.catch(() => {
735
+ });
736
+ if (this.flushing) return this.flushing;
737
+ if (!this.ready || this.queue.length === 0 || Date.now() < this.backoffUntil) return;
738
+ const batch = this.queue.splice(0, this.opts.maxBatch);
739
+ this.flushing = this.send(batch).then(() => {
740
+ this.failures = 0;
741
+ }).catch((err) => {
742
+ this.queue.unshift(...batch);
743
+ this.failures++;
744
+ this.backoffUntil = Date.now() + Math.min(6e4, 1e3 * 2 ** this.failures);
745
+ this.log("flush failed", err);
746
+ }).finally(() => {
747
+ this.flushing = void 0;
748
+ void this.persist();
749
+ });
750
+ return this.flushing;
751
+ }
752
+ /** Stop the flush timer, undo automatic instrumentation and send what is queued. */
753
+ close() {
754
+ if (this.timer) clearInterval(this.timer);
755
+ this.uninstrument();
756
+ return this.flush();
757
+ }
758
+ /* ---------------- internals ---------------- */
759
+ /** @internal Used by the platform entry points for errors that have no thrown value. */
760
+ captureError(e, meta, request) {
761
+ if (!this.ready) return;
762
+ const handled = meta.handled ?? true;
763
+ const frames = e.frames ?? parseStack(e.stack);
764
+ if (!meta.fatal && !this.allowError(`${e.name}|${e.message.slice(0, 120)}|${frames[0]?.file ?? ""}:${frames[0]?.line ?? ""}`)) return;
765
+ if (this.auto.sessions && (!handled || meta.fatal)) {
766
+ if (!this.sessionState.errored) {
767
+ this.sessionState.errored = true;
768
+ this.push({ type: "session", id: uid(), ts: now(), status: "errored" });
769
+ }
770
+ if (meta.fatal && !this.sessionState.crashed) {
771
+ this.sessionState.crashed = true;
772
+ this.push({ type: "session", id: uid(), ts: now(), status: "crashed" });
773
+ }
774
+ }
775
+ (meta.fatal ? this.push : this.enqueue).call(this, {
776
+ type: "error",
777
+ id: uid(),
778
+ ts: now(),
779
+ flow: meta.flow,
780
+ step: meta.step,
781
+ tags: meta.tags,
782
+ severity: meta.severity ?? (meta.fatal ? "critical" : void 0),
783
+ handled,
784
+ error: { name: e.name, message: e.message, stack: e.stack, frames },
785
+ breadcrumbs: [...this.crumbs],
786
+ request
787
+ });
788
+ }
789
+ /** Per-minute limits: one runaway error can't flood the queue, the network or your database. */
790
+ allowError(signature) {
791
+ const max = this.opts.maxErrorsPerMinute ?? 60;
792
+ const t = Date.now();
793
+ const hit = (key, cap) => {
794
+ let l = this.limits.get(key);
795
+ if (!l || t - l.since > 6e4) this.limits.set(key, l = { n: 0, since: t });
796
+ return ++l.n <= cap;
797
+ };
798
+ if (this.limits.size > 200) this.limits.clear();
799
+ const ok = hit("*", max) && hit(signature, Math.max(1, Math.ceil(max / 6)));
800
+ if (!ok) this.log("rate limited", signature);
801
+ return ok;
802
+ }
803
+ sampled() {
804
+ const r = this.opts.sampleRate ?? 1;
805
+ return r >= 1 || Math.random() < r;
806
+ }
807
+ enqueue(e) {
808
+ if (!this.ready || !this.sampled()) return;
809
+ this.push(e);
810
+ }
811
+ /** Queue without sampling (sessions must be complete for crash-free rates to be right). */
812
+ push(e) {
813
+ if (!this.ready) return;
814
+ const out = this.opts.beforeSend ? this.opts.beforeSend(e) : e;
815
+ if (!out) return;
816
+ this.queue.push(out);
817
+ if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);
818
+ if (out.type === "error" || this.queue.length >= this.opts.maxBatch) void this.flush();
819
+ else void this.persist();
820
+ }
821
+ buildContext() {
822
+ const c = this.opts.context ?? {};
823
+ return {
824
+ ...c,
825
+ app: { ...c.app ?? {}, ...this.opts.app },
826
+ os: { name: "unknown", ...c.os ?? {} },
827
+ runtime: { name: "unknown", ...c.runtime ?? {} },
828
+ device: c.device ?? {}
829
+ };
830
+ }
831
+ /** Set when the ingest rejects 0.2 fields: it predates them, so send what it understands. */
832
+ legacyIngest = false;
833
+ async send(events) {
834
+ if (this.legacyIngest) events = toLegacy(events);
835
+ if (!events.length) return;
836
+ const body = {
837
+ sdk: { name: SDK_NAME, version: SDK_VERSION },
838
+ context: this.buildContext(),
839
+ user: this.user,
840
+ session: this.session,
841
+ events
842
+ };
843
+ const f = this.opts.fetch ?? this.rawFetch ?? fetch;
844
+ const json = JSON.stringify(body);
845
+ const res = await f(this.opts.endpoint, {
846
+ method: "POST",
847
+ headers: { "content-type": "application/json", "x-debug-key": this.opts.ingestKey },
848
+ body: json,
849
+ // Lets the last batch finish when the page is closing. Browsers cap keepalive bodies at 64 KB.
850
+ ...typeof window !== "undefined" && json.length < 6e4 ? { keepalive: true } : {}
851
+ });
852
+ if (res.status >= 400 && res.status < 500 && res.status !== 429) {
853
+ this.log(`ingest rejected batch (${res.status})`, await res.text().catch(() => ""));
854
+ if (res.status === 400 && !this.legacyIngest && hasNewFields(events)) {
855
+ this.legacyIngest = true;
856
+ return this.send(events);
857
+ }
858
+ return;
859
+ }
860
+ if (!res.ok) throw new Error(`ingest responded ${res.status}`);
861
+ }
862
+ async persist() {
863
+ try {
864
+ await this.opts.storage?.setItem(QUEUE_KEY, JSON.stringify(this.queue));
865
+ } catch {
866
+ }
867
+ }
868
+ async restore() {
869
+ try {
870
+ const raw = await this.opts.storage?.getItem(QUEUE_KEY);
871
+ if (raw) this.queue.unshift(...JSON.parse(raw));
872
+ } catch {
873
+ }
874
+ }
875
+ installGlobalHandlers() {
876
+ this.handlersInstalled = true;
877
+ const g2 = globalThis;
878
+ if (g2.ErrorUtils?.setGlobalHandler) {
879
+ const prev = g2.ErrorUtils.getGlobalHandler?.();
880
+ g2.ErrorUtils.setGlobalHandler((err, isFatal) => {
881
+ this.error(err, { handled: false, fatal: !!isFatal, tags: { source: "global-handler" } });
882
+ void this.flush();
883
+ prev?.(err, isFatal);
884
+ });
885
+ }
886
+ if (typeof window !== "undefined" && typeof g2.addEventListener === "function") {
887
+ g2.addEventListener("error", (ev) => this.error(ev.error ?? ev.message, { handled: false, tags: { source: "window.onerror" } }));
888
+ g2.addEventListener("unhandledrejection", (ev) => this.error(ev.reason, { handled: false, tags: { source: "unhandledrejection" } }));
889
+ }
890
+ }
891
+ instrument() {
892
+ const a = this.auto;
893
+ const sink = this.sink();
894
+ const add = (r) => r && this.restores.push(r);
895
+ if (a.network) {
896
+ const restoreFetch = instrumentFetch(sink);
897
+ if (restoreFetch) globalThis.fetch.__raw = this.rawFetch;
898
+ add(restoreFetch);
899
+ add(instrumentXhr(sink));
900
+ }
901
+ if (a.console) add(instrumentConsole(sink));
902
+ if (a.navigation) add(instrumentHistory(sink));
903
+ if (a.clicks) add(instrumentClicks(sink));
904
+ if (a.lifecycle) add(instrumentWebLifecycle(sink));
905
+ }
906
+ uninstrument() {
907
+ while (this.restores.length) this.restores.pop()();
908
+ }
909
+ /** The bridge the instrumentation (./auto, and the platform entry points) reports through. */
910
+ sink() {
911
+ return {
912
+ request: (r) => this.recordRequest(r),
913
+ crumb: (category, message, level = "info", data) => this.breadcrumb(category, message, data, level),
914
+ navigated: (to) => this.navigated(to),
915
+ lifecycle: (state) => {
916
+ this.breadcrumb("ui", state === "background" ? "App went to the background" : "App came to the foreground");
917
+ if (state === "background") void this.flush();
918
+ },
919
+ ignored: (url) => this.isIgnored(url)
920
+ };
921
+ }
922
+ isIgnored(url) {
923
+ if (!this.ready) return true;
924
+ const ep = this.opts.endpoint.replace(/^https?:/, "");
925
+ if (url.includes(ep) || /\/symbolicate\b|\/logs(?:\?|$)/.test(url)) return true;
926
+ return (this.opts.network?.ignoreUrls ?? []).some((p2) => typeof p2 === "string" ? url.includes(p2) : p2.test(url));
927
+ }
928
+ recordRequest(r) {
929
+ if (!this.ready) return;
930
+ const net = this.opts.network ?? {};
931
+ const url = normaliseUrl(r.url);
932
+ const ms = Math.round(r.durationMs);
933
+ const failed = r.status === void 0 ? !r.aborted : (net.isFailure ?? ((s) => s >= 500))(r.status, url);
934
+ const slow = ms >= (net.slowMs ?? 3e3);
935
+ const outcome = r.aborted ? "aborted" : r.timedOut ? "timed out" : r.status !== void 0 ? String(r.status) : "failed";
936
+ this.breadcrumb("network", `${r.method} ${url} \u2192 ${outcome} (${ms}ms)`, { status: r.status ?? null, durationMs: ms }, failed ? "error" : slow ? "warning" : "info");
937
+ if (!failed) return;
938
+ const flow = net.flows?.find(([p2]) => typeof p2 === "string" ? url.includes(p2) : p2.test(url))?.[1];
939
+ const cause = r.error ? normaliseError(r.error) : void 0;
940
+ const message = r.status !== void 0 ? `${r.method} ${url} responded ${r.status}` : `${r.method} ${url} ${r.timedOut ? "timed out" : "failed"}${cause ? `: ${cause.message}` : ""}`;
941
+ const frames = parseStack(r.stack).slice(1);
942
+ this.captureError(
943
+ { name: r.status !== void 0 ? "HttpError" : "NetworkError", message, stack: r.stack, frames },
944
+ { flow, handled: true, tags: { source: "network" } },
945
+ { method: r.method, url, status: r.status, durationMs: ms }
946
+ );
947
+ }
948
+ log(...args) {
949
+ if (this.opts?.debug) console.warn("[deBug]", ...args);
950
+ }
951
+ };
952
+ function normaliseError(err) {
953
+ if (err instanceof Error) return { name: err.name || "Error", message: err.message, stack: err.stack };
954
+ if (typeof err === "string") return { name: "Error", message: err };
955
+ try {
956
+ return { name: "NonError", message: JSON.stringify(err).slice(0, 2e3) };
957
+ } catch {
958
+ return { name: "NonError", message: String(err) };
959
+ }
960
+ }
961
+ function resolveAuto(o) {
962
+ const all = o.autoCapture !== false;
963
+ const sel = typeof o.autoCapture === "object" ? o.autoCapture : {};
964
+ const pick = (k, dflt = all) => sel[k] ?? dflt;
965
+ return {
966
+ errors: o.captureGlobalErrors ?? pick("errors"),
967
+ network: pick("network"),
968
+ console: pick("console"),
969
+ navigation: pick("navigation"),
970
+ clicks: pick("clicks"),
971
+ lifecycle: pick("lifecycle"),
972
+ sessions: pick("sessions")
973
+ };
974
+ }
975
+ var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type === "error" && e.request);
976
+ function toLegacy(events) {
977
+ const out = [];
978
+ for (const e of events) {
979
+ if (e.type === "session") continue;
980
+ if (e.type === "error" && e.request) {
981
+ const { request: _r, ...rest } = e;
982
+ out.push(rest);
983
+ } else out.push(e);
984
+ }
985
+ return out;
986
+ }
987
+
988
+ // ../sdk/src/index.ts
989
+ var deBug = new DebugClient();
990
+
991
+ // src/guide.ts
992
+ init_exec();
993
+ function automaticFor(platform, app) {
994
+ const common = [
995
+ `${bold("Crashes")}: uncaught errors and unhandled promise rejections, with the stack trace`,
996
+ `${bold("Failed requests")}: every request is a breadcrumb; timeouts, network failures and 5xx responses become errors that point at the line that made the call`,
997
+ `${bold("Sessions")}: each launch is marked started, then errored or crashed, which gives the crash-free rate per release`,
998
+ `${bold("Context")}: device, OS, app version and network on every event`
999
+ ];
1000
+ switch (platform) {
1001
+ case "expo":
1002
+ case "react-native":
1003
+ return [
1004
+ ...common,
1005
+ `${bold("Lifecycle")}: the app going to the background and back; a new session after 30 minutes away`,
1006
+ `${bold("Console")}: console.warn and console.error as breadcrumbs`,
1007
+ app.expoRouter || app.reactNavigation ? `${bold("Screens")}: every screen change, once you add the ${code(app.expoRouter ? "useDebugExpoRouter()" : "trackReactNavigation()")} line` : `${bold("Screens")}: add the router helper from the SDK for screen-change breadcrumbs`,
1008
+ `${bold("Offline")}: events wait in a queue and send when the connection is back`
1009
+ ];
1010
+ case "node":
1011
+ return [...common.slice(0, 2), `${bold("Server errors")}: 5xx responses your server sends, and outgoing node:http requests (axios, SDKs)`, common[3], `${bold("Clean exit")}: on a crash, events are sent before the process exits`];
1012
+ default:
1013
+ return [
1014
+ ...common,
1015
+ `${bold("Navigation")}: every page change, with any router`,
1016
+ `${bold("Clicks")}: buttons and links, by their label (never what people type)`,
1017
+ `${bold("Console and lifecycle")}: console warnings, the tab hidden or shown, going offline`
1018
+ ];
1019
+ }
1020
+ }
1021
+ function sdkImport(platform) {
1022
+ return platform === "expo" ? "@debugkit/sdk/expo" : platform === "react-native" ? "@debugkit/sdk/react-native" : platform === "node" ? "@debugkit/sdk/node" : "@debugkit/sdk/react";
1023
+ }
1024
+ var MANUAL = (platform) => `import { deBug } from "${sdkImport(platform)}";
1025
+
1026
+ // 1. In a try/catch you already have: report it, tagged with the part of the app
1027
+ try {
1028
+ await chargeCard(order);
1029
+ } catch (err) {
1030
+ deBug.error(err, { flow: "checkout.payment", step: "charge" });
1031
+ showPaymentError();
1032
+ }
1033
+
1034
+ // 2. A step that can succeed or fail: deBug logs the outcome (and the error),
1035
+ // so the dashboard can say "18% of logins fail", not just "12 errors"
1036
+ await deBug.track("auth.login", "submit_otp", () => api.verifyOtp(code));
1037
+
1038
+ // 3. Something that isn't an error but matters
1039
+ deBug.event("signup_abandoned", { flow: "onboarding.signup", outcome: "abandoned" });
1040
+
1041
+ // 4. Who it happened to (an id, not personal data), once they sign in
1042
+ deBug.setUser(user.id);`;
1043
+ async function sendTestEvents(cfg, app) {
1044
+ const failures = [];
1045
+ let sent = 0;
1046
+ const client = new DebugClient().init({
1047
+ endpoint: cfg.endpoint,
1048
+ ingestKey: cfg.ingestKey,
1049
+ app: { id: cfg.appId, version: app.version ?? "0.0.0", environment: "debugkit-test" },
1050
+ context: { os: { name: process.platform, version: process.version }, runtime: { name: "debugkit-cli" }, device: { type: "desktop", model: "debugkit test" } },
1051
+ autoCapture: { sessions: true, errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false },
1052
+ flushIntervalMs: 0,
1053
+ fetch: async (url, init2) => {
1054
+ let res;
1055
+ try {
1056
+ res = await fetch(url, init2);
1057
+ } catch (err) {
1058
+ failures.push(`couldn't reach it (${err.message})`);
1059
+ throw err;
1060
+ }
1061
+ if (res.ok) sent += (JSON.parse(String(init2?.body ?? "{}")).events ?? []).length;
1062
+ else failures.push(`it answered ${res.status}: ${(await res.clone().text().catch(() => "")).slice(0, 200)}`);
1063
+ return res;
1064
+ }
1065
+ });
1066
+ client.navigated("/cart");
1067
+ client.navigated("/checkout");
1068
+ client.breadcrumb("ui", 'Clicked button "Pay now"');
1069
+ client.breadcrumb("network", "POST /v1/payments/intent \u2192 503 (1840ms)", { status: 503, durationMs: 1840 }, "error");
1070
+ client.captureError(
1071
+ { name: "HttpError", message: "POST /v1/payments/intent responded 503 (test event from npx debugkit)", stack: new Error().stack },
1072
+ { flow: "onboarding.test", handled: true, tags: { source: "network", test: "true" } },
1073
+ { method: "POST", url: "/v1/payments/intent", status: 503, durationMs: 1840 }
1074
+ );
1075
+ try {
1076
+ JSON.parse("<html>502 Bad Gateway</html>");
1077
+ } catch (err) {
1078
+ client.error(err, { flow: "onboarding.test", step: "parse_receipt", tags: { test: "true" } });
1079
+ }
1080
+ await client.track("onboarding.test", "submit", async () => true);
1081
+ await client.track("onboarding.test", "submit", async () => Promise.reject(new Error("Test failure from deBug.track()")), { captureError: false }).catch(() => {
1082
+ });
1083
+ for (let i = 0; i < 5 && client.pending && !failures.length; i++) await client.flush();
1084
+ await client.close();
1085
+ if (!failures.length && client.pending) failures.push(`${client.pending} events weren't sent`);
1086
+ return { sent, error: failures.length ? failures.join("; ") : void 0 };
1087
+ }
1088
+ async function waitForArrival(cwd, url, appId, timeoutMs = 9e4) {
1089
+ const until = Date.now() + timeoutMs;
1090
+ let last;
1091
+ while (Date.now() < until) {
1092
+ last = await summary(cwd, url, appId);
1093
+ if (last.ok && last.data?.app === appId && last.data?.issues?.length) return last;
1094
+ await new Promise((r) => setTimeout(r, 2e3));
1095
+ }
1096
+ return last;
1097
+ }
1098
+ async function walkthrough(opts) {
1099
+ const { cwd, app, cfg, dashboardUrl } = opts;
1100
+ const before = await summary(cwd, dashboardUrl, cfg.appId);
1101
+ const empty = before.status === 404 || before.ok && before.data?.app !== cfg.appId;
1102
+ p.note(
1103
+ [
1104
+ `${bold("Your dashboard is running")} at ${code(dashboardUrl)}`,
1105
+ loginHint(cwd),
1106
+ "",
1107
+ empty ? `It's connected to your ${cfg.provider === "local" ? "local" : cfg.provider === "aws" ? "DynamoDB" : "Firestore"} data and ${bold("empty")}: nothing has been sent yet.` : before.ok ? "It's connected, and already has data for this app." : `It couldn't read your data yet (${before.status || "no answer"}: ${before.error ?? "unknown"}). The test below will tell us more.`
1108
+ ].join("\n"),
1109
+ "1 \xB7 The dashboard"
1110
+ );
1111
+ openUrl(dashboardUrl);
1112
+ await next("I'm signed in");
1113
+ p.note(
1114
+ [
1115
+ `${bold("A written summary")}: how many errors today, the worst part of the app, the top issue, the struggling release`,
1116
+ `${bold("Issues by severity")}: errors grouped by cause; open one for the stack trace and the steps that led to it`,
1117
+ `${bold("Release health")}: crash-free and error-free sessions per app version`,
1118
+ `${bold("Failing endpoints")}: requests that time out, fail or return 5xx`,
1119
+ `${bold("Where the app is failing")}: errors and failure rates per flow, like auth.login`,
1120
+ `${bold("Breakdowns")}: by OS, app version and device`
1121
+ ].join("\n"),
1122
+ "2 \xB7 What you'll see there"
1123
+ );
1124
+ await next("Send a test event");
1125
+ const s = p.spinner();
1126
+ s.start(`Sending test events to ${cfg.endpoint}`);
1127
+ const sent = await sendTestEvents(cfg, app);
1128
+ if (sent.error) {
1129
+ s.error(`The ingest didn't accept them: ${sent.error}`);
1130
+ p.log.warn(cfg.provider === "firebase" ? "A brand-new Cloud Function can take a minute to answer. Try again with npx debugkit test." : "Check the endpoint and key in .debugkit/config.json, then run npx debugkit test.");
1131
+ } else {
1132
+ s.message("Sent. Waiting for the dashboard to show them");
1133
+ const after = await waitForArrival(cwd, dashboardUrl, cfg.appId);
1134
+ if (after?.ok && after.data?.issues?.length) {
1135
+ s.stop("They arrived");
1136
+ const d = after.data;
1137
+ p.note(
1138
+ [
1139
+ ...(d.narrative ?? []).map((l) => `\u201C${l}\u201D`),
1140
+ "",
1141
+ `${bold(String(d.issues.length))} issues \xB7 ${bold(String(d.health?.sessions14d ?? 0))} session \xB7 failing endpoint ${code(d.health?.endpoints?.[0]?.endpoint ?? "\u2014")}`,
1142
+ "",
1143
+ `Refresh the dashboard. You'll see a ${pc.red("HttpError")} from a failed request (captured the way the SDK does it automatically),`,
1144
+ `a ${pc.red("SyntaxError")} reported from a try/catch, and the ${code("onboarding.test")} flow with a 50% failure rate from track().`,
1145
+ dim("They're tagged environment debugkit-test, version " + (app.version ?? "0.0.0") + ". Raw events expire after 30 days.")
1146
+ ].join("\n"),
1147
+ "3 \xB7 Your first events"
1148
+ );
1149
+ } else {
1150
+ s.error("Sent, but the dashboard doesn't show them yet");
1151
+ p.log.warn(`The dashboard said: ${after?.status ?? "?"} ${after?.error ?? ""}. Refresh it in a minute, or run npx debugkit test again.`);
1152
+ }
1153
+ }
1154
+ await next("What does the SDK do on its own?");
1155
+ p.note(
1156
+ [`Once ${code("debug." + (app.typescript ? "ts" : "js"))} runs, the SDK records this in the background, with no other code:`, "", ...automaticFor(app.platform, app).map((l) => `\u2022 ${l}`), "", dim("Every error carries the last 30 breadcrumbs: the screen, the tap, the request that failed. Query strings and request bodies never leave the device.")].join("\n"),
1157
+ `4 \xB7 Automatic in ${PLATFORM_LABEL[app.platform]}`
1158
+ );
1159
+ await next("What do I add myself?");
1160
+ p.note(
1161
+ [
1162
+ "Automatic capture says what broke. What it can't know is which part of your app a step belongs to, and whether it worked.",
1163
+ `That's what ${code("flow")} is for: a dotted name like ${code("auth.login")} that the dashboard groups everything by.`,
1164
+ "",
1165
+ MANUAL(app.platform)
1166
+ ].join("\n"),
1167
+ "5 \xB7 What you add in your own try/catches"
1168
+ );
1169
+ await next("Show me what's left to do");
1170
+ p.note(
1171
+ [
1172
+ ...opts.remaining.map((l, i) => `${i + 1}. ${l}`),
1173
+ `${opts.remaining.length + 1}. Run the app and watch the dashboard fill in`,
1174
+ "",
1175
+ `${code(cmdFor("dashboard"))} open the dashboard again`,
1176
+ `${code(cmdFor("test"))} send another test event`,
1177
+ `${code(cmdFor("guide"))} replay this walkthrough`
1178
+ ].join("\n"),
1179
+ "6 \xB7 Finish wiring your app"
1180
+ );
1181
+ }
1182
+
1183
+ // src/providers/aws.ts
1184
+ init_exec();
1185
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
1186
+ import { homedir } from "os";
1187
+ import { dirname, join as join4 } from "path";
1188
+ import { fileURLToPath } from "url";
1189
+ import { zipSync } from "fflate";
1190
+
1191
+ // src/keys.ts
1192
+ var keyEntry = (key, appId) => `${key}:${appId}`;
1193
+ function mergeKeys(existing, key, appId) {
1194
+ const pairs = (existing ?? "").split(",").map((s) => s.trim()).filter((s) => /^[^:\s]+:[^:\s]+$/.test(s));
1195
+ if (!pairs.some((p2) => p2.split(":")[0] === key)) pairs.push(keyEntry(key, appId));
1196
+ return pairs.join(",");
1197
+ }
1198
+
1199
+ // src/providers/aws.ts
1200
+ var REGIONS = [
1201
+ { value: "af-south-1", label: "Cape Town (af-south-1)" },
1202
+ { value: "eu-west-1", label: "Ireland (eu-west-1)" },
1203
+ { value: "eu-central-1", label: "Frankfurt (eu-central-1)" },
1204
+ { value: "us-east-1", label: "N. Virginia (us-east-1)" },
1205
+ { value: "us-west-2", label: "Oregon (us-west-2)" },
1206
+ { value: "ap-southeast-1", label: "Singapore (ap-southeast-1)" }
1207
+ ];
1208
+ function awsProfiles(home = homedir()) {
1209
+ const out = /* @__PURE__ */ new Map();
1210
+ const read = (file, isConfig) => {
1211
+ if (!existsSync4(file)) return;
1212
+ let cur;
1213
+ for (const line of readFileSync3(file, "utf8").split(/\r?\n/)) {
1214
+ const h = /^\s*\[\s*(?:profile\s+)?([^\]\s]+)\s*\]/.exec(line);
1215
+ if (h) {
1216
+ if (isConfig && h[1] && /^sso-session\b/.test(line.replace(/^\s*\[\s*/, ""))) {
1217
+ cur = void 0;
1218
+ continue;
1219
+ }
1220
+ cur = out.get(h[1]) ?? { name: h[1], sso: false };
1221
+ out.set(cur.name, cur);
1222
+ continue;
1223
+ }
1224
+ const kv = /^\s*([a-z_]+)\s*=\s*(.+?)\s*$/.exec(line);
1225
+ if (!cur || !kv) continue;
1226
+ if (kv[1] === "region") cur.region = kv[2];
1227
+ if (kv[1].startsWith("sso_")) cur.sso = true;
1228
+ }
1229
+ };
1230
+ read(process.env.AWS_CONFIG_FILE ?? join4(home, ".aws", "config"), true);
1231
+ read(process.env.AWS_SHARED_CREDENTIALS_FILE ?? join4(home, ".aws", "credentials"), false);
1232
+ return [...out.values()];
1233
+ }
1234
+ function lambdaZip() {
1235
+ const here = dirname(fileURLToPath(import.meta.url));
1236
+ const file = [join4(here, "lambda", "index.mjs"), join4(here, "..", "dist", "lambda", "index.mjs")].find(existsSync4);
1237
+ if (!file) throw new Error("The bundled ingest Lambda is missing. Reinstall debugkit.");
1238
+ return zipSync({ "index.mjs": readFileSync3(file) }, { level: 9 });
1239
+ }
1240
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1241
+ async function setupAws(ctx) {
1242
+ p.note(
1243
+ [
1244
+ "deBug creates a DynamoDB table, a Lambda function with a public URL, and an IAM role in your own AWS account.",
1245
+ "It uses an AWS profile on this machine. With AWS SSO (IAM Identity Center) you sign in through your browser; no access keys are needed.",
1246
+ "Your credentials stay on this machine. deBug doesn't receive them."
1247
+ ].join("\n"),
1248
+ "Sign in to AWS"
1249
+ );
1250
+ const profiles = awsProfiles();
1251
+ const SSO = "__sso__";
1252
+ const ENV = "__env__";
1253
+ const options = [
1254
+ ...profiles.map((x) => ({ value: x.name, label: x.name, hint: [x.sso ? "SSO" : "keys", x.region].filter(Boolean).join(" \xB7 ") })),
1255
+ ...process.env.AWS_ACCESS_KEY_ID ? [{ value: ENV, label: "Credentials from the environment (AWS_ACCESS_KEY_ID)" }] : [],
1256
+ { value: SSO, label: "Sign in with AWS SSO (IAM Identity Center)", hint: which("aws") ? "opens your browser" : "needs the AWS CLI" }
1257
+ ];
1258
+ let profile = await choose("Which AWS credentials should deBug use?", options, profiles[0]?.name ?? SSO);
1259
+ if (profile === SSO) {
1260
+ if (!which("aws")) bail("AWS SSO sign-in needs the AWS CLI: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html");
1261
+ const name = await ask("Name for the new AWS profile", { initial: "debugkit" });
1262
+ p.log.step(`Running ${code(`aws configure sso --profile ${name}`)}. It asks for your SSO start URL and region, then opens your browser to approve access.`);
1263
+ if (await interactive("aws", ["configure", "sso", "--profile", name]) !== 0) bail("AWS SSO setup didn't finish.");
1264
+ profile = name;
1265
+ } else if (profile === ENV) profile = void 0;
1266
+ const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
1267
+ const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
1268
+ const defaultRegion = profiles.find((x) => x.name === profile)?.region ?? process.env.AWS_REGION ?? "af-south-1";
1269
+ const region = await choose("Which AWS region?", REGIONS.some((r) => r.value === defaultRegion) ? REGIONS : [{ value: defaultRegion, label: defaultRegion }, ...REGIONS], defaultRegion);
1270
+ const credentials = fromNodeProviderChain(profile ? { profile } : {});
1271
+ const base = { region, credentials };
1272
+ let identity;
1273
+ try {
1274
+ identity = await new STSClient(base).send(new GetCallerIdentityCommand({}));
1275
+ } catch (err) {
1276
+ const sso = profiles.find((x) => x.name === profile)?.sso;
1277
+ if (sso && which("aws")) {
1278
+ p.log.info("Your SSO session has expired. Signing in again.");
1279
+ if (await interactive("aws", ["sso", "login", "--profile", profile]) !== 0) bail("AWS SSO sign-in didn't finish.");
1280
+ identity = await new STSClient({ region, credentials: fromNodeProviderChain({ profile }) }).send(new GetCallerIdentityCommand({}));
1281
+ } else bail(`Those AWS credentials didn't work: ${err.message}`);
1282
+ }
1283
+ p.log.success(`Signed in to AWS account ${code(identity.Account ?? "?")} ${dim(identity.Arn ?? "")}`);
1284
+ if (!identity.Account) bail("AWS didn't say which account these credentials belong to.");
1285
+ const account = identity.Account;
1286
+ const table = await ask("DynamoDB table name", {
1287
+ initial: environment.get() ? `debugkit-${environment.get()}` : "debugkit",
1288
+ validate: (v) => /^[A-Za-z0-9_.-]{3,40}$/.test(v) ? void 0 : "3\u201340 characters: letters, digits, _ . -"
1289
+ });
1290
+ const functionName = `debugkit-ingest-${table}`.slice(0, 64);
1291
+ const roleName = `debugkit-ingest-${table}-${region}`.slice(0, 64);
1292
+ await next(`Create the table, role and function in ${region}`);
1293
+ const s = p.spinner();
1294
+ const [ddbMod, iamMod, lambdaMod] = await Promise.all([import("@aws-sdk/client-dynamodb"), import("@aws-sdk/client-iam"), import("@aws-sdk/client-lambda")]);
1295
+ const ddb = new ddbMod.DynamoDBClient(base);
1296
+ s.start(`Checking DynamoDB table ${table}`);
1297
+ let tableArn;
1298
+ let ownTable = false;
1299
+ const found = await lookup(() => ddb.send(new ddbMod.DescribeTableCommand({ TableName: table })));
1300
+ if (found) {
1301
+ tableArn = found.Table?.TableArn;
1302
+ const tags = await ddb.send(new ddbMod.ListTagsOfResourceCommand({ ResourceArn: tableArn }));
1303
+ ownTable = !!tags.Tags?.some((t) => t.Key === CREATED_BY && t.Value === "debugkit");
1304
+ const keys = Object.fromEntries((found.Table?.KeySchema ?? []).map((k) => [k.KeyType, k.AttributeName]));
1305
+ const types = Object.fromEntries((found.Table?.AttributeDefinitions ?? []).map((a) => [a.AttributeName, a.AttributeType]));
1306
+ if (keys.HASH !== "pk" || keys.RANGE !== "sk" || types.pk !== "S" || types.sk !== "S") {
1307
+ s.error(`Table ${table} exists with a different key schema`);
1308
+ bail(`${table} isn't a deBug table (it needs string keys pk and sk). Run again and choose another table name.`);
1309
+ }
1310
+ s.stop(ownTable ? `Reusing deBug's table ${table}` : `Table ${table} exists and wasn't created by deBug`);
1311
+ if (!ownTable && !await yes(`Store deBug's data in your existing table ${table}? deBug only adds its own items (pk APPS and APP#\u2026).`, false))
1312
+ bail("Run again and choose a new table name.");
1313
+ } else {
1314
+ s.message(`Creating DynamoDB table ${table}`);
1315
+ const out = await ddb.send(
1316
+ new ddbMod.CreateTableCommand({
1317
+ TableName: table,
1318
+ BillingMode: "PAY_PER_REQUEST",
1319
+ AttributeDefinitions: [
1320
+ { AttributeName: "pk", AttributeType: "S" },
1321
+ { AttributeName: "sk", AttributeType: "S" }
1322
+ ],
1323
+ KeySchema: [
1324
+ { AttributeName: "pk", KeyType: "HASH" },
1325
+ { AttributeName: "sk", KeyType: "RANGE" }
1326
+ ],
1327
+ Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
1328
+ })
1329
+ );
1330
+ tableArn = out.TableDescription?.TableArn;
1331
+ ownTable = true;
1332
+ let active = false;
1333
+ for (let i = 0; i < 90 && !active; i++) {
1334
+ active = (await ddb.send(new ddbMod.DescribeTableCommand({ TableName: table }))).Table?.TableStatus === "ACTIVE";
1335
+ if (!active) await sleep(2e3);
1336
+ }
1337
+ if (!active) throw new Error(`Table ${table} didn't become active within 3 minutes. Check it in the AWS console, then run npx debugkit init again.`);
1338
+ }
1339
+ if (!tableArn) throw new Error(`AWS didn't return the ARN for table ${table}.`);
1340
+ const ttl = (await ddb.send(new ddbMod.DescribeTimeToLiveCommand({ TableName: table }))).TimeToLiveDescription;
1341
+ const ttlOn = ttl?.TimeToLiveStatus === "ENABLED" || ttl?.TimeToLiveStatus === "ENABLING";
1342
+ if (ttlOn && ttl?.AttributeName !== "ttl") {
1343
+ p.log.warn(`${table} already expires items on "${ttl?.AttributeName}", so deBug's raw events won't expire on their own. Clean them up yourself, or use a separate table.`);
1344
+ } else if (!ttlOn) {
1345
+ await ddb.send(new ddbMod.UpdateTimeToLiveCommand({ TableName: table, TimeToLiveSpecification: { AttributeName: "ttl", Enabled: true } }));
1346
+ }
1347
+ p.log.success(`DynamoDB table ${table} is ready (30-day expiry on raw events)`);
1348
+ const iam = new iamMod.IAMClient(base);
1349
+ s.start(`Setting up IAM role ${roleName}`);
1350
+ let roleArn;
1351
+ let newRole = false;
1352
+ const role = await lookup(() => iam.send(new iamMod.GetRoleCommand({ RoleName: roleName })));
1353
+ if (role) {
1354
+ if (!role.Role?.Tags?.some((t) => t.Key === CREATED_BY && t.Value === "debugkit")) {
1355
+ s.error(`Role ${roleName} exists and wasn't created by deBug`);
1356
+ bail(`deBug won't change a role it didn't create. Delete or rename ${roleName}, or choose another table name.`);
1357
+ }
1358
+ roleArn = role.Role.Arn;
1359
+ } else {
1360
+ roleArn = (await iam.send(
1361
+ new iamMod.CreateRoleCommand({
1362
+ RoleName: roleName,
1363
+ Description: `deBug ingest Lambda: writes to the DynamoDB table ${table}`.slice(0, 1e3),
1364
+ AssumeRolePolicyDocument: JSON.stringify({
1365
+ Version: "2012-10-17",
1366
+ Statement: [{ Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole", Condition: { StringEquals: { "aws:SourceAccount": account } } }]
1367
+ }),
1368
+ Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
1369
+ })
1370
+ )).Role.Arn;
1371
+ newRole = true;
1372
+ }
1373
+ await iam.send(new iamMod.AttachRolePolicyCommand({ RoleName: roleName, PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" }));
1374
+ await iam.send(
1375
+ new iamMod.PutRolePolicyCommand({
1376
+ RoleName: roleName,
1377
+ PolicyName: "debugkit-table-write",
1378
+ PolicyDocument: JSON.stringify({
1379
+ Version: "2012-10-17",
1380
+ Statement: [{ Effect: "Allow", Action: ["dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:BatchWriteItem", "dynamodb:GetItem"], Resource: tableArn }]
1381
+ })
1382
+ })
1383
+ );
1384
+ s.stop(`IAM role ${roleName} can write to ${table} and nothing else`);
1385
+ const lambda = new lambdaMod.LambdaClient(base);
1386
+ const zip = lambdaZip();
1387
+ s.start(`Deploying Lambda ${functionName}`);
1388
+ const fn = await lookup(() => lambda.send(new lambdaMod.GetFunctionCommand({ FunctionName: functionName })));
1389
+ if (fn) {
1390
+ if (fn.Tags?.[CREATED_BY] !== "debugkit") {
1391
+ s.error(`Function ${functionName} exists and wasn't created by deBug`);
1392
+ bail(`deBug won't overwrite a function it didn't create. Rename ${functionName}, or choose another table name.`);
1393
+ }
1394
+ const keys = mergeKeys(fn.Configuration?.Environment?.Variables?.DEBUG_INGEST_KEYS, ctx.ingestKey, ctx.app.appId);
1395
+ await lambda.send(new lambdaMod.UpdateFunctionCodeCommand({ FunctionName: functionName, ZipFile: zip }));
1396
+ await waitUpdated(lambda, lambdaMod, functionName);
1397
+ await lambda.send(
1398
+ new lambdaMod.UpdateFunctionConfigurationCommand({
1399
+ FunctionName: functionName,
1400
+ Role: roleArn,
1401
+ Environment: { Variables: { ...fn.Configuration?.Environment?.Variables, DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keys } }
1402
+ })
1403
+ );
1404
+ } else {
1405
+ const env = { Variables: { DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId) } };
1406
+ for (let attempt = 0; ; attempt++) {
1407
+ try {
1408
+ await lambda.send(
1409
+ new lambdaMod.CreateFunctionCommand({
1410
+ FunctionName: functionName,
1411
+ Runtime: "nodejs22.x",
1412
+ Architectures: ["arm64"],
1413
+ Handler: "index.handler",
1414
+ Role: roleArn,
1415
+ Code: { ZipFile: zip },
1416
+ MemorySize: 256,
1417
+ Timeout: 10,
1418
+ Environment: env,
1419
+ Description: "deBug ingest: receives SDK events and writes them to DynamoDB",
1420
+ Tags: { [CREATED_BY]: "debugkit" }
1421
+ })
1422
+ );
1423
+ break;
1424
+ } catch (err) {
1425
+ if (attempt < 10 && /cannot be assumed|role defined for the function/i.test(err.message)) {
1426
+ s.message(newRole ? "Waiting for the new IAM role to be ready" : "Retrying");
1427
+ await sleep(3e3);
1428
+ } else throw err;
1429
+ }
1430
+ }
1431
+ }
1432
+ await waitUpdated(lambda, lambdaMod, functionName);
1433
+ const urlCfg = await lookup(() => lambda.send(new lambdaMod.GetFunctionUrlConfigCommand({ FunctionName: functionName })));
1434
+ const url = urlCfg?.FunctionUrl ?? (await lambda.send(new lambdaMod.CreateFunctionUrlConfigCommand({ FunctionName: functionName, AuthType: "NONE" }))).FunctionUrl;
1435
+ if (!url) throw new Error(`AWS didn't return a URL for ${functionName}.`);
1436
+ for (const [sid, input] of [
1437
+ ["debugkit-public-url", { Action: "lambda:InvokeFunctionUrl", FunctionUrlAuthType: "NONE" }],
1438
+ ["debugkit-public-invoke", { Action: "lambda:InvokeFunction", InvokedViaFunctionUrl: true }]
1439
+ ]) {
1440
+ try {
1441
+ await lambda.send(new lambdaMod.AddPermissionCommand({ FunctionName: functionName, StatementId: sid, Principal: "*", ...input }));
1442
+ } catch (err) {
1443
+ if (err.name !== "ResourceConflictException") p.log.warn(`Couldn't add ${sid}: ${err.message}`);
1444
+ }
1445
+ }
1446
+ s.stop(`Lambda ${functionName} is live at ${url}`);
1447
+ let readOnlyPolicyArn = `arn:aws:iam::${account}:policy/debugkit-dashboard-readonly-${table}`.slice(0, 2048);
1448
+ try {
1449
+ if (!await lookup(() => iam.send(new iamMod.GetPolicyCommand({ PolicyArn: readOnlyPolicyArn }))))
1450
+ await iam.send(
1451
+ new iamMod.CreatePolicyCommand({
1452
+ PolicyName: `debugkit-dashboard-readonly-${table}`.slice(0, 128),
1453
+ PolicyDocument: JSON.stringify({
1454
+ Version: "2012-10-17",
1455
+ Statement: [{ Effect: "Allow", Action: ["dynamodb:GetItem", "dynamodb:Query", "dynamodb:DescribeTable"], Resource: tableArn }]
1456
+ }),
1457
+ Description: `Read-only access to the deBug table ${table}, for hosting the dashboard`,
1458
+ Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
1459
+ })
1460
+ );
1461
+ } catch (err) {
1462
+ p.log.warn(`Skipped the read-only dashboard policy: ${err.message}`);
1463
+ readOnlyPolicyArn = void 0;
1464
+ }
1465
+ return {
1466
+ config: { provider: "aws", endpoint: url.replace(/\/$/, ""), ingestKey: ctx.ingestKey, aws: { region, profile, table, functionName, roleName, readOnlyPolicyArn } },
1467
+ dashboardEnv: { DEBUG_STORE: "dynamodb", AWS_REGION: region, DEBUG_DYNAMO_TABLE: table, ...profile ? { AWS_PROFILE: profile } : {} },
1468
+ created: [
1469
+ `DynamoDB table ${code(table)} in ${region}${ownTable ? " (on-demand)" : " (your existing table)"}`,
1470
+ `Lambda ${code(functionName)} with a public URL: ${code(url)}`,
1471
+ `IAM role ${code(roleName)} that can only write to the table`,
1472
+ ...readOnlyPolicyArn ? [`Read-only policy for hosting the dashboard: ${code(readOnlyPolicyArn)}`] : []
1473
+ ]
1474
+ };
1475
+ }
1476
+ var CREATED_BY = "created-by";
1477
+ async function lookup(fn) {
1478
+ try {
1479
+ return await fn();
1480
+ } catch (err) {
1481
+ const name = err.name ?? "";
1482
+ if (name === "ResourceNotFoundException" || name === "NoSuchEntityException" || name === "NoSuchEntity") return void 0;
1483
+ throw err;
1484
+ }
1485
+ }
1486
+ async function waitUpdated(lambda, mod, name) {
1487
+ for (let i = 0; i < 60; i++) {
1488
+ const c = await lambda.send(new mod.GetFunctionConfigurationCommand({ FunctionName: name }));
1489
+ if (c.State !== "Pending" && c.LastUpdateStatus !== "InProgress") return;
1490
+ await sleep(1500);
1491
+ }
1492
+ }
1493
+
1494
+ // src/providers/firebase.ts
1495
+ init_exec();
1496
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "fs";
1497
+ import { join as join5 } from "path";
1498
+
1499
+ // ../adapters/firestore.indexes.json
1500
+ var firestore_indexes_default = {
1501
+ indexes: [
1502
+ {
1503
+ collectionGroup: "rollups",
1504
+ queryScope: "COLLECTION",
1505
+ fields: [
1506
+ { fieldPath: "dimension", order: "ASCENDING" },
1507
+ { fieldPath: "day", order: "ASCENDING" }
1508
+ ]
1509
+ },
1510
+ {
1511
+ collectionGroup: "events",
1512
+ queryScope: "COLLECTION",
1513
+ fields: [
1514
+ { fieldPath: "fingerprint", order: "ASCENDING" },
1515
+ { fieldPath: "ts", order: "DESCENDING" }
1516
+ ]
1517
+ }
1518
+ ],
1519
+ fieldOverrides: [
1520
+ {
1521
+ collectionGroup: "events",
1522
+ fieldPath: "expireAt",
1523
+ ttl: true,
1524
+ indexes: []
1525
+ }
1526
+ ]
1527
+ };
1528
+
1529
+ // src/providers/firebase.ts
1530
+ var LOCATIONS = [
1531
+ { value: "africa-south1", label: "Johannesburg (africa-south1)", region: "africa-south1" },
1532
+ { value: "eur3", label: "Europe, multi-region (eur3)", region: "europe-west1" },
1533
+ { value: "europe-west1", label: "Belgium (europe-west1)", region: "europe-west1" },
1534
+ { value: "nam5", label: "United States, multi-region (nam5)", region: "us-central1" },
1535
+ { value: "us-central1", label: "Iowa (us-central1)", region: "us-central1" },
1536
+ { value: "asia-southeast1", label: "Singapore (asia-southeast1)", region: "asia-southeast1" }
1537
+ ];
1538
+ var FUNCTION_NAME = "debugIngest";
1539
+ var CODEBASE = "debugkit";
1540
+ var MIN_FIREBASE_TOOLS = 14;
1541
+ async function firebaseCli() {
1542
+ if (which("firebase")) {
1543
+ const v = await capture("firebase", ["--version"]);
1544
+ const major = Number(/^(\d+)/.exec(v.stdout.trim())?.[1] ?? 0);
1545
+ if (major >= MIN_FIREBASE_TOOLS) return ["firebase", []];
1546
+ p.log.info(dim(`Your Firebase CLI is ${v.stdout.trim()}; deBug needs ${MIN_FIREBASE_TOOLS}+ for Node 22, so it'll use npx firebase-tools@latest (same sign-in).`));
1547
+ }
1548
+ return ["npx", ["-y", "firebase-tools@latest"]];
1549
+ }
1550
+ var emailsIn = (text2) => [...new Set(text2.match(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g) ?? [])];
1551
+ async function setupFirebase(ctx) {
1552
+ const [fbCmd, fbPre] = await firebaseCli();
1553
+ const fb = (args, opts = {}) => capture(fbCmd, [...fbPre, ...args], opts);
1554
+ const fbLive = (args, opts = {}) => interactive(fbCmd, [...fbPre, ...args], opts);
1555
+ p.note(
1556
+ [
1557
+ "deBug deploys a small ingest function and a Firestore database into your own Firebase project.",
1558
+ "Firebase will ask you to sign in with Google and allow the Firebase CLI to manage your projects.",
1559
+ "That access stays on this machine. deBug doesn't receive it."
1560
+ ].join("\n"),
1561
+ "Sign in to Firebase"
1562
+ );
1563
+ let accounts = emailsIn((await fb(["login:list"])).stdout);
1564
+ let account;
1565
+ if (!accounts.length) {
1566
+ await next("Open the Google sign-in page");
1567
+ if (await fbLive(["login"]) !== 0) bail("Firebase sign-in didn't finish. Run npx debugkit init to try again.");
1568
+ accounts = emailsIn((await fb(["login:list"])).stdout);
1569
+ }
1570
+ const ADD = "__add__";
1571
+ const picked = await choose(
1572
+ "Which Google account should own the deBug resources?",
1573
+ [...accounts.map((a) => ({ value: a, label: a })), { value: ADD, label: "Sign in with another account" }],
1574
+ accounts[0]
1575
+ );
1576
+ if (picked === ADD) {
1577
+ if (await fbLive(["login:add"]) !== 0) bail("Firebase sign-in didn't finish.");
1578
+ const now2 = emailsIn((await fb(["login:list"])).stdout);
1579
+ account = now2.find((a) => !accounts.includes(a)) ?? now2[0] ?? bail("No Firebase account is signed in.");
1580
+ } else account = picked;
1581
+ const acct = ["--account", account];
1582
+ const s = p.spinner();
1583
+ s.start("Loading your Firebase projects");
1584
+ const list = await fb(["projects:list", "--json", ...acct]);
1585
+ s.stop("Loaded your Firebase projects");
1586
+ let projects = [];
1587
+ try {
1588
+ projects = JSON.parse(list.stdout).result ?? [];
1589
+ } catch {
1590
+ p.log.warn(`Couldn't read the project list: ${dim(list.stderr.slice(-300))}`);
1591
+ }
1592
+ const NEW = "__new__";
1593
+ let projectId = await choose(
1594
+ "Which Firebase project should deBug use?",
1595
+ [
1596
+ { value: NEW, label: "Create a new project", hint: "recommended: keeps deBug's data and bill separate" },
1597
+ ...projects.map((x) => ({ value: x.projectId, label: x.displayName ? `${x.displayName}` : x.projectId, hint: x.projectId }))
1598
+ ],
1599
+ NEW
1600
+ );
1601
+ if (projectId === NEW) {
1602
+ const suggested = `${ctx.app.appId}-debug`.slice(0, 26).replace(/-+$/, "") + `-${Math.random().toString(36).slice(2, 6)}`;
1603
+ projectId = await ask("Project id (lowercase, globally unique)", {
1604
+ initial: suggested,
1605
+ validate: (v) => /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(v) ? void 0 : "6\u201330 characters: lowercase letters, digits and dashes"
1606
+ });
1607
+ if (await fbLive(["projects:create", projectId, "--display-name", `${ctx.app.name} deBug`.slice(0, 30), ...acct]) !== 0)
1608
+ bail(`Couldn't create ${projectId}. Pick an existing project or another id.`);
1609
+ }
1610
+ const proj = ["--project", projectId, ...acct];
1611
+ p.note(
1612
+ [
1613
+ "Cloud Functions only run on Firebase's pay-as-you-go plan (Blaze).",
1614
+ "deBug's ingest typically stays inside the free monthly allowance, but Google requires a billing account.",
1615
+ `If ${projectId} is already on Blaze, skip this.`
1616
+ ].join("\n"),
1617
+ "Billing"
1618
+ );
1619
+ if (await yes(`Open the billing page for ${projectId} to check or upgrade?`, true)) {
1620
+ openUrl(`https://console.firebase.google.com/project/${projectId}/usage/details`);
1621
+ await next("I've checked: it's on Blaze");
1622
+ }
1623
+ let location2;
1624
+ const existingDb = await defaultDatabase(fb, proj);
1625
+ if (existingDb) {
1626
+ location2 = existingDb.locationId;
1627
+ p.log.info(`Using the existing Firestore database in ${projectId} (${location2})`);
1628
+ } else {
1629
+ location2 = await choose("Where should the Firestore database live? This can't be changed later.", LOCATIONS.map(({ value, label }) => ({ value, label })), "africa-south1");
1630
+ s.start(`Creating the Firestore database in ${location2}`);
1631
+ const r = await fb(["firestore:databases:create", "(default)", "--location", location2, ...proj]);
1632
+ if (r.code !== 0 && !/already exists/i.test(r.stderr + r.stdout)) {
1633
+ s.error("Couldn't create the database");
1634
+ p.log.error((r.stderr || r.stdout).slice(-600));
1635
+ bail("Fix the error above (often: the Firestore API needs enabling, or billing), then run npx debugkit init again.");
1636
+ }
1637
+ s.stop(`Created the Firestore database (${location2})`);
1638
+ }
1639
+ const region = functionRegion(location2);
1640
+ const dir = writeFunctionSource(ctx, region);
1641
+ s.start("Installing the ingest function's dependencies");
1642
+ const inst = await capture("npm", ["install", "--no-audit", "--no-fund"], { cwd: join5(dir, "functions") });
1643
+ if (inst.code !== 0) {
1644
+ s.error("npm install failed");
1645
+ p.log.error(inst.stderr.slice(-600));
1646
+ bail();
1647
+ }
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.");
1661
+ p.log.step("Adding deBug's Firestore indexes (your existing indexes are left alone)");
1662
+ if (await fbLive(["deploy", "--only", "firestore:indexes", "--non-interactive", ...proj], { cwd: dir }) !== 0)
1663
+ p.log.warn("The indexes didn't deploy. The dashboard needs them; deploy them later with the command printed at the end.");
1664
+ p.log.step(`Deploying ${code(FUNCTION_NAME)}. The first deploy turns on the Google APIs it needs and takes a few minutes.`);
1665
+ for (; ; ) {
1666
+ const exit = await fbLive(["deploy", "--only", `functions:${CODEBASE}`, "--force", ...proj], { cwd: dir });
1667
+ if (exit === 0) break;
1668
+ p.log.warn("The deploy didn't finish: see the error above. Common causes: the project isn't on the Blaze plan, or your account lacks permission to deploy functions.");
1669
+ const again = await choose(
1670
+ "What now?",
1671
+ [
1672
+ { value: "retry", label: "Retry the deploy" },
1673
+ { value: "billing", label: "Open billing, then retry" },
1674
+ { value: "stop", label: "Stop here" }
1675
+ ],
1676
+ "retry"
1677
+ );
1678
+ if (again === "stop") bail(`Fix the error above, then run npx debugkit init again (it reuses what's already set up), or deploy by hand: cd ${paths(ctx.app.cwd).firebase} && npx firebase-tools@latest deploy --only functions:${CODEBASE} --project ${projectId}`);
1679
+ if (again === "billing") {
1680
+ openUrl(`https://console.firebase.google.com/project/${projectId}/usage/details`);
1681
+ await next("Upgraded: retry the deploy");
1682
+ }
1683
+ }
1684
+ const endpoint = `https://${region}-${projectId}.cloudfunctions.net/${FUNCTION_NAME}`;
1685
+ await ensureDashboardAccess(projectId);
1686
+ return {
1687
+ config: { provider: "firebase", endpoint, ingestKey: ctx.ingestKey, firebase: { projectId, region, account, location: location2 } },
1688
+ dashboardEnv: { DEBUG_STORE: "firestore", GOOGLE_CLOUD_PROJECT: projectId, GCLOUD_PROJECT: projectId },
1689
+ created: [
1690
+ `Firestore database in ${code(projectId)} (${location2}), with indexes and 30-day expiry on raw events`,
1691
+ `Cloud Function ${code(FUNCTION_NAME)} in ${region}: ${code(endpoint)}`,
1692
+ `Function source in ${code(".debugkit/firebase")}, so you can redeploy it with the Firebase CLI`
1693
+ ]
1694
+ };
1695
+ }
1696
+ async function ensureDashboardAccess(projectId) {
1697
+ if (!which("gcloud")) {
1698
+ p.log.warn(
1699
+ [
1700
+ "The dashboard reads Firestore with Google Cloud credentials, and gcloud isn't installed.",
1701
+ `Install it (${code("https://cloud.google.com/sdk/docs/install")}), then run ${code("gcloud auth application-default login")}.`,
1702
+ "Or create a read-only service account (role: Cloud Datastore Viewer) and set GOOGLE_APPLICATION_CREDENTIALS in .debugkit/dashboard.env."
1703
+ ].join("\n")
1704
+ );
1705
+ return;
1706
+ }
1707
+ const t = await capture("gcloud", ["auth", "application-default", "print-access-token"]);
1708
+ if (t.code === 0) {
1709
+ p.log.success("The dashboard will read Firestore with your Google Cloud credentials");
1710
+ return;
1711
+ }
1712
+ p.note("One more Google sign-in: this one lets the dashboard on this machine read deBug's data.", "Dashboard access");
1713
+ await next("Open the Google sign-in page");
1714
+ const exit = await interactive("gcloud", ["auth", "application-default", "login", "--quiet"]);
1715
+ if (exit !== 0) p.log.warn("Google Cloud sign-in didn't finish. The dashboard won't be able to read Firestore until you run: gcloud auth application-default login");
1716
+ else await capture("gcloud", ["auth", "application-default", "set-quota-project", projectId]);
1717
+ }
1718
+ async function defaultDatabase(fb, proj) {
1719
+ const r = await fb(["firestore:databases:get", "(default)", "--json", ...proj]);
1720
+ if (r.code !== 0) return void 0;
1721
+ try {
1722
+ const db = JSON.parse(r.stdout).result;
1723
+ return db?.locationId ? { locationId: db.locationId } : void 0;
1724
+ } catch {
1725
+ return void 0;
1726
+ }
1727
+ }
1728
+ function functionRegion(location2) {
1729
+ const known = LOCATIONS.find((l) => l.value === location2)?.region;
1730
+ if (known) return known;
1731
+ if (location2 === "nam7") return "us-central1";
1732
+ if (location2.startsWith("eur")) return "europe-west1";
1733
+ if (location2.startsWith("nam")) return "us-central1";
1734
+ return /^[a-z]+-[a-z]+\d+$/.test(location2) ? location2 : "us-central1";
1735
+ }
1736
+ function writeFunctionSource(ctx, region) {
1737
+ const dir = paths(ctx.app.cwd).firebase;
1738
+ mkdirSync2(join5(dir, "functions"), { recursive: true });
1739
+ writeFileSync2(
1740
+ join5(dir, "firebase.json"),
1741
+ JSON.stringify(
1742
+ {
1743
+ functions: [{ source: "functions", codebase: CODEBASE, runtime: "nodejs22" }],
1744
+ firestore: { database: "(default)", indexes: "firestore.indexes.json" }
1745
+ },
1746
+ null,
1747
+ 2
1748
+ ) + "\n"
1749
+ );
1750
+ writeFileSync2(join5(dir, "firestore.indexes.json"), JSON.stringify(firestore_indexes_default, null, 2) + "\n");
1751
+ writeFileSync2(
1752
+ join5(dir, "functions", "package.json"),
1753
+ JSON.stringify(
1754
+ {
1755
+ name: "debugkit-ingest",
1756
+ private: true,
1757
+ type: "module",
1758
+ main: "index.js",
1759
+ engines: { node: "22" },
1760
+ dependencies: {
1761
+ // Same release as this CLI (the packages are versioned together).
1762
+ "@debugkit/adapters": `^${VERSION}`,
1763
+ "@debugkit/ingest": `^${VERSION}`,
1764
+ "firebase-admin": "^13.0.0",
1765
+ "firebase-functions": "^7.0.0"
1766
+ }
1767
+ },
1768
+ null,
1769
+ 2
1770
+ ) + "\n"
1771
+ );
1772
+ writeFileSync2(
1773
+ join5(dir, "functions", "index.js"),
1774
+ `// deBug ingest, deployed by npx debugkit init. Receives events from the SDK and writes them to Firestore.
1775
+ import { initializeApp } from "firebase-admin/app";
1776
+ import { getFirestore } from "firebase-admin/firestore";
1777
+ import { onRequest } from "firebase-functions/v2/https";
1778
+ import { FirestoreStore } from "@debugkit/adapters/firestore";
1779
+ import { parseIngestKeys } from "@debugkit/ingest";
1780
+ import { firebaseHandler } from "@debugkit/ingest/firebase";
1781
+
1782
+ initializeApp();
1783
+
1784
+ export const ${FUNCTION_NAME} = onRequest(
1785
+ { region: ${JSON.stringify(region)}, invoker: "public", memory: "256MiB", maxInstances: 10 },
1786
+ firebaseHandler({ store: new FirestoreStore(getFirestore()), keys: parseIngestKeys(process.env.DEBUG_INGEST_KEYS) }),
1787
+ );
1788
+ `
1789
+ );
1790
+ const envFile = join5(dir, "functions", ".env");
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)}
1793
+ `);
1794
+ return dir;
1795
+ }
1796
+
1797
+ // src/providers/local.ts
1798
+ import { networkInterfaces } from "os";
1799
+ function lanAddress() {
1800
+ for (const list of Object.values(networkInterfaces())) {
1801
+ for (const a of list ?? []) if (a.family === "IPv4" && !a.internal && !a.address.startsWith("169.254.")) return a.address;
1802
+ }
1803
+ return void 0;
1804
+ }
1805
+ async function setupLocal(ctx) {
1806
+ const mobile = ctx.app.platform === "expo" || ctx.app.platform === "react-native";
1807
+ const host = mobile ? lanAddress() ?? "127.0.0.1" : "127.0.0.1";
1808
+ const endpoint = `http://${host}:${ctx.dashboardPort}/api/ingest`;
1809
+ if (mobile) p.log.info(`Phones and emulators reach this Mac at ${code(host)}, so the dashboard will listen on your local network (password protected).`);
1810
+ return {
1811
+ config: { provider: "local", endpoint, ingestKey: ctx.ingestKey, local: { port: ctx.dashboardPort } },
1812
+ dashboardEnv: {
1813
+ DEBUG_STORE: "memory",
1814
+ DEBUG_LOCAL_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId),
1815
+ ...mobile ? { HOST: "0.0.0.0", DEBUG_INSECURE_COOKIES: "1" } : {}
1816
+ },
1817
+ created: [
1818
+ `Nothing in the cloud: the dashboard stores events in memory while it runs`,
1819
+ `Ingest endpoint: ${code(endpoint)} (only while ${code(cmdFor("dashboard"))} is running)`
1820
+ ]
1821
+ };
1822
+ }
1823
+
1824
+ // src/wire.ts
1825
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
1826
+ import { dirname as dirname2, join as join6, relative } from "path";
1827
+ init_exec();
1828
+ var ENV_ENDPOINT = "DEBUG_ENDPOINT";
1829
+ var ENV_KEY = "DEBUG_KEY";
1830
+ async function installSdk(app) {
1831
+ if (!app.hasSdk) {
1832
+ const [cmd, args] = installCommand(app.packageManager, ["@debugkit/sdk"]);
1833
+ if (await yes(`Install ${code("@debugkit/sdk")} with ${app.packageManager}?`)) {
1834
+ const s = p.spinner();
1835
+ s.start(`${cmd} ${args.join(" ")}`);
1836
+ const r = await capture(cmd, args, { cwd: app.cwd });
1837
+ if (r.code !== 0) {
1838
+ s.error("Install failed");
1839
+ p.log.error(r.stderr.slice(-800));
1840
+ throw new Error("Couldn't install @debugkit/sdk. Install it yourself and run npx debugkit init again.");
1841
+ }
1842
+ s.stop(`Installed @debugkit/sdk`);
1843
+ app.hasSdk = true;
1844
+ }
1845
+ }
1846
+ if (app.platform === "expo" && app.missingExpoModules.length) {
1847
+ const exit = await interactive("npx", ["expo", "install", ...app.missingExpoModules], { cwd: app.cwd });
1848
+ if (exit !== 0) p.log.warn("Couldn't install expo-device and expo-application. Run: npx expo install expo-device expo-application");
1849
+ }
1850
+ }
1851
+ function writeAppEnv(app, conn) {
1852
+ if (!app.envPrefix) return void 0;
1853
+ const file = join6(app.cwd, ".env");
1854
+ upsertEnv(file, { [`${app.envPrefix}${ENV_ENDPOINT}`]: conn.endpoint, [`${app.envPrefix}${ENV_KEY}`]: conn.ingestKey });
1855
+ return file;
1856
+ }
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) {
1864
+ const ext = app.typescript ? "ts" : "js";
1865
+ const path2 = join6(app.cwd, app.sourceDir, `debug.${ext}`);
1866
+ const rel = relative(app.cwd, path2);
1867
+ const env = (k) => app.envPrefix === "VITE_" ? `import.meta.env.${app.envPrefix}${k}` : `process.env.${app.envPrefix ?? ""}${k}`;
1868
+ const header = `// Set up by npx debugkit init. Import this file once, as early as possible.
1869
+ `;
1870
+ const appId = JSON.stringify(app.appId);
1871
+ const importLine = `${code(`import "./${rel.replace(/\.(ts|js)$/, "")}";`)}`;
1872
+ switch (app.platform) {
1873
+ case "expo":
1874
+ return {
1875
+ path: path2,
1876
+ contents: `${header}import { initExpo } from "@debugkit/sdk/expo";
1877
+
1878
+ const endpoint = ${env(ENV_ENDPOINT)};
1879
+
1880
+ export const deBug = initExpo({
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") },
1886
+ });
1887
+ `,
1888
+ then: [
1889
+ `Import it first in your root layout (${code(app.expoRouter ? "app/_layout.tsx" : "App.tsx")}): ${importLine} (adjust the path)`,
1890
+ `Wrap the root in ${code("<DebugErrorBoundary>")} from ${code("@debugkit/sdk/expo")} to catch render crashes`,
1891
+ ...app.expoRouter ? [`Call ${code("useDebugExpoRouter()")} from ${code("@debugkit/sdk/expo-router")} in the root layout for screen breadcrumbs`] : []
1892
+ ]
1893
+ };
1894
+ case "react-native":
1895
+ return {
1896
+ path: path2,
1897
+ contents: `${header}import { initReactNative } from "@debugkit/sdk/react-native";
1898
+ // Optional, for model and app version: npm install react-native-device-info, then pass deviceInfo: DeviceInfo.
1899
+
1900
+ export const deBug = initReactNative({
1901
+ enabled: ${multiEnv ? "!__DEV__ // release builds only" : "true"},
1902
+ endpoint: ${JSON.stringify(conn.endpoint)},
1903
+ ingestKey: ${JSON.stringify(conn.ingestKey)}, // public and write-only: safe to ship in the app
1904
+ app: { id: ${appId}, environment: __DEV__ ? "development" : "production" },
1905
+ });
1906
+ `,
1907
+ then: [
1908
+ `Import it first in ${code("index.js")}: ${importLine}`,
1909
+ `Wrap your root component in ${code("<DebugErrorBoundary>")} from ${code("@debugkit/sdk/react-native")}`,
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.`] : []
1912
+ ]
1913
+ };
1914
+ case "node":
1915
+ return {
1916
+ path: path2,
1917
+ contents: `${header}import { initNode } from "@debugkit/sdk/node";
1918
+
1919
+ export const deBug = initNode({
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 },
1924
+ });
1925
+ `,
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`]
1927
+ };
1928
+ default: {
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";
1933
+ return {
1934
+ path: path2,
1935
+ contents: `${header}import { deBug } from "@debugkit/sdk/react";
1936
+
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} },
1944
+ });
1945
+
1946
+ export { deBug };
1947
+ `,
1948
+ then: [
1949
+ `Import it first in your client entry (${code(app.platform === "next" ? "a client component in app/layout.tsx" : app.platform === "tanstack-start" ? "src/router.tsx" : "src/main.tsx")})`,
1950
+ `Wrap the app in ${code("<DebugErrorBoundary>")} from ${code("@debugkit/sdk/react")}`,
1951
+ ...app.platform === "tanstack-start" || app.platform === "next" ? [`For server errors, see ${code("initNode")} and ${code("withDebug")} in the SDK README`] : []
1952
+ ]
1953
+ };
1954
+ }
1955
+ }
1956
+ }
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
+ }
1968
+ }
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
+ }
1995
+ }
1996
+ const f = initFile(app, conn);
1997
+ const rel = relative(app.cwd, f.path);
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)) {
2001
+ mkdirSync3(dirname2(f.path), { recursive: true });
2002
+ writeFileSync3(f.path, f.contents);
2003
+ p.log.success(`${current2 === void 0 ? "Created" : "Updated"} ${code(rel)}`);
2004
+ } else {
2005
+ p.log.info(`Kept your ${rel}. The generated version is:
2006
+ ${dim(f.contents)}`);
2007
+ }
2008
+ return [...extra, ...f.then];
2009
+ }
2010
+
2011
+ // src/cli.ts
2012
+ var HELP = `${bold("debugkit")} ${VERSION}: set up deBug in your app
2013
+ ${dim("Run as npx debugkit <command> once @debugkit/sdk is installed, or npx @debugkit/cli <command> anywhere.")}
2014
+
2015
+ ${code("npx debugkit init")} choose a cloud, deploy ingest to your account, wire the SDK, walk through the dashboard
2016
+ ${code("npx debugkit dashboard")} run the dashboard against your data
2017
+ ${code("npx debugkit test")} send test events and check they arrive
2018
+ ${code("npx debugkit guide")} replay the walkthrough
2019
+ ${code("npx debugkit password")} reset the dashboard login
2020
+
2021
+ Options
2022
+ --env <name> one of several environments, like preview or production. Each has
2023
+ its own provider, project, endpoint and dashboard login
2024
+ --provider <firebase|aws|local> skip the provider question
2025
+ --cwd <dir> the app's folder (default: current folder)
2026
+ --yes accept defaults (for scripts)
2027
+ `;
2028
+ function parseArgs(argv) {
2029
+ const out = { cwd: process.cwd(), yes: false, help: false };
2030
+ for (let i = 0; i < argv.length; i++) {
2031
+ const a = argv[i];
2032
+ if (a === "--provider") out.provider = argv[++i];
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];
2036
+ else if (a === "--cwd") out.cwd = resolve(argv[++i] ?? ".");
2037
+ else if (a === "--yes" || a === "-y") out.yes = true;
2038
+ else if (a === "--help" || a === "-h") out.help = true;
2039
+ else if (!a.startsWith("-") && !out.cmd) out.cmd = a;
2040
+ }
2041
+ return out;
2042
+ }
2043
+ var envLabel = () => environment.get() ? ` (${environment.get()})` : "";
2044
+ function requireConfig(cwd) {
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.`);
2053
+ return cfg;
2054
+ }
2055
+ async function init(cwd, preset) {
2056
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} ${dim("observability you own")}${environment.get() ? ` \xB7 ${bold(environment.get())} environment` : ""}`);
2057
+ let app;
2058
+ try {
2059
+ app = detectApp(cwd);
2060
+ } catch (err) {
2061
+ bail(err.message);
2062
+ }
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)}.`);
2064
+ const existing = readConfig(cwd);
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"))}.`);
2067
+ return;
2068
+ }
2069
+ await installSdk(app);
2070
+ p.note(
2071
+ [
2072
+ "Your events are stored in your own cloud account, not ours.",
2073
+ `${bold("Firebase")}: a Cloud Function and Firestore. Good if the app already uses Firebase.`,
2074
+ `${bold("AWS")}: a Lambda with a public URL and DynamoDB.`,
2075
+ `${bold("Just this machine")}: no cloud. The dashboard keeps events in memory while it runs. Good for a first look.`
2076
+ ].join("\n"),
2077
+ "Where should your data live?"
2078
+ );
2079
+ const provider = preset ?? await choose(
2080
+ "Choose a provider",
2081
+ [
2082
+ { value: "firebase", label: "Firebase", hint: "Google sign-in" },
2083
+ { value: "aws", label: "AWS", hint: "AWS profile or SSO" },
2084
+ { value: "local", label: "Just this machine", hint: "no account needed" }
2085
+ ],
2086
+ "firebase"
2087
+ );
2088
+ const dashboardPort = await freePort(4400);
2089
+ const ingestKey = existing?.provider === provider && existing.ingestKey ? existing.ingestKey : `pk_${provider === "local" ? "local" : "live"}_${randomBytes2(12).toString("hex")}`;
2090
+ const ctx = { app, ingestKey, dashboardPort };
2091
+ let result;
2092
+ try {
2093
+ result = provider === "firebase" ? await setupFirebase(ctx) : provider === "aws" ? await setupAws(ctx) : await setupLocal(ctx);
2094
+ } catch (err) {
2095
+ p.log.error(err.message);
2096
+ bail("Setup stopped. Nothing else was changed in your app. Fix the error above and run npx debugkit init again.");
2097
+ }
2098
+ const cfg = { ...result.config, appId: app.appId, dashboardPort, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
2099
+ writeConfig(cwd, cfg);
2100
+ p.note(result.created.map((l) => `\u2022 ${l}`).join("\n"), "Created");
2101
+ const remaining = await wireApp(app, cfg);
2102
+ await prepareDashboardEnv(cwd, result.dashboardEnv, dashboardPort);
2103
+ let dash;
2104
+ try {
2105
+ dash = await startDashboard(cwd);
2106
+ } catch (err) {
2107
+ p.log.error(err.message);
2108
+ p.outro(`deBug is set up, but the dashboard didn't start. Try ${code(cmdFor("dashboard"))}.`);
2109
+ return;
2110
+ }
2111
+ await walkthrough({ cwd, app, cfg, dashboardUrl: dash.url, remaining });
2112
+ if (provider === "local") {
2113
+ p.log.info(`The dashboard is your ingest on this setup, so keep it running while you try the app. Stop it with ${code("Ctrl-C")}.`);
2114
+ p.outro("deBug is set up.");
2115
+ await new Promise((r) => dash.child.once("exit", () => r()));
2116
+ return;
2117
+ }
2118
+ dash.stop();
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
+ );
2124
+ }
2125
+ async function dashboard(cwd) {
2126
+ const cfg = requireConfig(cwd);
2127
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} dashboard${envLabel()}`);
2128
+ const dash = await startDashboard(cwd);
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`);
2130
+ const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_exec(), exec_exports));
2131
+ openUrl2(dash.url);
2132
+ await new Promise((r) => dash.child.once("exit", () => r()));
2133
+ }
2134
+ async function test(cwd) {
2135
+ const cfg = requireConfig(cwd);
2136
+ const app = detectApp(cwd);
2137
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} test`);
2138
+ const s = p.spinner();
2139
+ s.start(`Sending test events to ${cfg.endpoint}`);
2140
+ const r = await sendTestEvents(cfg, app);
2141
+ if (r.error) {
2142
+ s.error(`Not accepted: ${r.error}`);
2143
+ process.exitCode = 1;
2144
+ if (cfg.provider === "local") p.log.info(`On this setup the dashboard is the ingest: start it with ${code(cmdFor("dashboard"))} first.`);
2145
+ return;
2146
+ }
2147
+ s.stop("Accepted by your ingest");
2148
+ p.outro(`Open the dashboard (${code(cmdFor("dashboard"))}) to see them under the ${code("onboarding.test")} flow.`);
2149
+ }
2150
+ async function guide(cwd) {
2151
+ const cfg = requireConfig(cwd);
2152
+ const app = detectApp(cwd);
2153
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} walkthrough`);
2154
+ const dash = await startDashboard(cwd);
2155
+ await walkthrough({ cwd, app, cfg, dashboardUrl: dash.url, remaining: initFile(app, cfg).then });
2156
+ if (cfg.provider === "local") {
2157
+ p.outro("Keep the dashboard running while you try the app. Ctrl-C to stop.");
2158
+ await new Promise((r) => dash.child.once("exit", () => r()));
2159
+ } else {
2160
+ dash.stop();
2161
+ p.outro("Done.");
2162
+ }
2163
+ }
2164
+ async function password(cwd) {
2165
+ requireConfig(cwd);
2166
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} reset the dashboard login`);
2167
+ await resetLogin(cwd);
2168
+ p.outro(`Saved. Restart the dashboard (${code(cmdFor("dashboard"))}) and sign in with the new password.`);
2169
+ }
2170
+ async function main() {
2171
+ const args = parseArgs(process.argv.slice(2));
2172
+ flags.yes = args.yes;
2173
+ flags.command = args.cmd ?? "help";
2174
+ if (args.help || !args.cmd) {
2175
+ console.log(HELP);
2176
+ return;
2177
+ }
2178
+ try {
2179
+ environment.set(args.env);
2180
+ } catch (err) {
2181
+ bail(err.message);
2182
+ }
2183
+ if (args.provider && !["firebase", "aws", "local"].includes(args.provider)) bail(`Unknown provider ${args.provider}. Use firebase, aws or local.`);
2184
+ switch (args.cmd) {
2185
+ case "init":
2186
+ return init(args.cwd, args.provider);
2187
+ case "dashboard":
2188
+ return dashboard(args.cwd);
2189
+ case "test":
2190
+ return test(args.cwd);
2191
+ case "guide":
2192
+ return guide(args.cwd);
2193
+ case "password":
2194
+ return password(args.cwd);
2195
+ default:
2196
+ console.log(HELP);
2197
+ process.exitCode = 1;
2198
+ }
2199
+ }
2200
+ main().catch((err) => {
2201
+ p.log.error(err instanceof Error ? err.message : String(err));
2202
+ process.exit(1);
2203
+ });