@getchomp/cli 0.0.0-stage → 0.2.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +39 -2
  3. package/dist/commands/analyze.d.ts +49 -0
  4. package/dist/commands/analyze.js +280 -0
  5. package/dist/commands/connect.d.ts +12 -0
  6. package/dist/commands/connect.js +255 -0
  7. package/dist/commands/export.d.ts +29 -0
  8. package/dist/commands/export.js +356 -0
  9. package/dist/commands/health.d.ts +19 -0
  10. package/dist/commands/health.js +259 -0
  11. package/dist/commands/init.d.ts +40 -0
  12. package/dist/commands/init.js +659 -0
  13. package/dist/commands/mcp.d.ts +2 -0
  14. package/dist/commands/mcp.js +12 -0
  15. package/dist/commands/plugin.d.ts +8 -0
  16. package/dist/commands/plugin.js +198 -0
  17. package/dist/commands/ui.d.ts +20 -0
  18. package/dist/commands/ui.js +252 -0
  19. package/dist/commands/uninstall.d.ts +8 -0
  20. package/dist/commands/uninstall.js +246 -0
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +37 -0
  23. package/dist/ports/portHydrator.d.ts +63 -0
  24. package/dist/ports/portHydrator.js +954 -0
  25. package/dist/ports/portHydratorWorker.d.ts +22 -0
  26. package/dist/ports/portHydratorWorker.js +75 -0
  27. package/dist/server/buildStatusTracker.d.ts +45 -0
  28. package/dist/server/buildStatusTracker.js +122 -0
  29. package/dist/server/graphLayoutState.d.ts +205 -0
  30. package/dist/server/graphLayoutState.js +930 -0
  31. package/dist/server/loopbackSecurity.d.ts +18 -0
  32. package/dist/server/loopbackSecurity.js +57 -0
  33. package/dist/server/routes/authSourceRoutes.d.ts +18 -0
  34. package/dist/server/routes/authSourceRoutes.js +231 -0
  35. package/dist/server/routes/layoutRoutes.d.ts +3 -0
  36. package/dist/server/routes/layoutRoutes.js +857 -0
  37. package/dist/server/routes/pluginRoutes.d.ts +3 -0
  38. package/dist/server/routes/pluginRoutes.js +368 -0
  39. package/dist/server/routes/viewRulesRoutes.d.ts +3 -0
  40. package/dist/server/routes/viewRulesRoutes.js +173 -0
  41. package/dist/server/uiHotkeys.d.ts +26 -0
  42. package/dist/server/uiHotkeys.js +160 -0
  43. package/dist/utils/branding.d.ts +126 -0
  44. package/dist/utils/branding.js +978 -0
  45. package/dist/utils/credentials.d.ts +22 -0
  46. package/dist/utils/credentials.js +126 -0
  47. package/dist/utils/git.d.ts +95 -0
  48. package/dist/utils/git.js +780 -0
  49. package/dist/utils/masterContext.d.ts +112 -0
  50. package/dist/utils/masterContext.js +642 -0
  51. package/dist/visualizer/cloudLayoutClient.d.ts +84 -0
  52. package/dist/visualizer/cloudLayoutClient.js +1200 -0
  53. package/dist/visualizer/layoutCache.d.ts +25 -0
  54. package/dist/visualizer/layoutCache.js +406 -0
  55. package/dist/visualizer/localEngineBridge.d.ts +50 -0
  56. package/dist/visualizer/localEngineBridge.js +80 -0
  57. package/dist/visualizer/pluginPresentationApi.d.ts +111 -0
  58. package/dist/visualizer/pluginPresentationApi.js +432 -0
  59. package/dist/visualizer/rulesConfig.d.ts +11 -0
  60. package/dist/visualizer/rulesConfig.js +266 -0
  61. package/dist/visualizer/sourceAccess.d.ts +45 -0
  62. package/dist/visualizer/sourceAccess.js +204 -0
  63. package/package.json +52 -3
@@ -0,0 +1,978 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, relative, resolve } from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { Worker } from "node:worker_threads";
5
+ import * as readline from "node:readline";
6
+ import Database from "better-sqlite3";
7
+ import { CORE_EXTRACTOR_VERSION, auditFrameworkCoverage, buildWorkspaceRegistry, collectLedgerSignalCandidates, computeStructuralHealthMetrics, detectFrameworksFromPackageJson as coreDetectFrameworksFromPackageJson, } from "@getchomp/core";
8
+ import { getChompMasterRoot, hasPrivateResearchLedger, resolveRepoName, } from "./masterContext.js";
9
+ // ---------------------------------------------------------------------------
10
+ // Zero-Dependency ANSI Terminal Styling (Chomp Brand Yellow: #face1d)
11
+ // ---------------------------------------------------------------------------
12
+ const isColorEnabled = !process.env.NO_COLOR &&
13
+ (process.stdout.isTTY || process.env.FORCE_COLOR === "1");
14
+ export const ansi = {
15
+ yellow: (s) => isColorEnabled ? `\x1b[38;2;250;206;29m${s}\x1b[0m` : s,
16
+ yellowBold: (s) => isColorEnabled ? `\x1b[1m\x1b[38;2;250;206;29m${s}\x1b[0m` : s,
17
+ bold: (s) => (isColorEnabled ? `\x1b[1m${s}\x1b[0m` : s),
18
+ dim: (s) => (isColorEnabled ? `\x1b[2m${s}\x1b[0m` : s),
19
+ green: (s) => (isColorEnabled ? `\x1b[32m${s}\x1b[0m` : s),
20
+ cyan: (s) => (isColorEnabled ? `\x1b[36m${s}\x1b[0m` : s),
21
+ amber: (s) => (isColorEnabled ? `\x1b[33m${s}\x1b[0m` : s),
22
+ red: (s) => (isColorEnabled ? `\x1b[31m${s}\x1b[0m` : s),
23
+ };
24
+ // ---------------------------------------------------------------------------
25
+ // Chomp Unicode Logo Mark & Chomping Animation Frames (Authoritative Brand Art)
26
+ // ---------------------------------------------------------------------------
27
+ /**
28
+ * Primary Chomp logo mark (Open Mouth — 13 lines).
29
+ * Normalized to a 2-space left margin while preserving exact relative geometry.
30
+ */
31
+ export const CHOMP_UNICODE_LOGO_LINES = [
32
+ " ◿◺",
33
+ " ◿◸ ◹◺",
34
+ " ◿◸ ◢◣ ◹◺",
35
+ " ◿◸ ◢◣ ◥◤ ◿◸",
36
+ " ◿◸ ◢◣ ◥◤ ◿◸",
37
+ " ◿◸ ◥◤ ◿◸",
38
+ " ⬦ ● ⬦",
39
+ " ◹◺ ◢◣ ◹◺",
40
+ " ◹◺ ◥◤ ◢◣ ◹◺",
41
+ " ◹◺ ◥◤ ◢◣ ◹◺",
42
+ " ◹◺ ◥◤ ◿◸",
43
+ " ◹◺ ◿◸",
44
+ " ◹◸",
45
+ ];
46
+ /**
47
+ * Chomping animation frame (Closed Mouth — 13 lines, padded 3 top / 3 bottom
48
+ * so the eye `●` stays anchored on row index 6).
49
+ */
50
+ export const CHOMP_CHOMPING_FRAME_LINES = [
51
+ "",
52
+ "",
53
+ "",
54
+ " ▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭",
55
+ " ▯ ▯",
56
+ " ▯ ██ ██ ██ ▯",
57
+ " ▯ ● ~~~~~ ⧼",
58
+ " ▯ ██ ██ ██ ▯",
59
+ " ▯ ▯",
60
+ " ▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭▭",
61
+ "",
62
+ "",
63
+ "",
64
+ ];
65
+ /**
66
+ * Computes terminal column width, accounting for fullwidth Unicode characters
67
+ * such as `~` (U+FF5E) which occupy 2 columns in monospace terminals.
68
+ */
69
+ function visualWidth(str) {
70
+ let width = 0;
71
+ for (const ch of str) {
72
+ const code = ch.codePointAt(0) ?? 0;
73
+ if ((code >= 0xff01 && code <= 0xff60) ||
74
+ (code >= 0xffe0 && code <= 0xffe6)) {
75
+ width += 2;
76
+ }
77
+ else {
78
+ width += 1;
79
+ }
80
+ }
81
+ return width;
82
+ }
83
+ function visualPadEnd(str, targetCols) {
84
+ const trimmed = str.trimEnd();
85
+ const w = visualWidth(trimmed);
86
+ return w >= targetCols ? trimmed : trimmed + " ".repeat(targetCols - w);
87
+ }
88
+ /**
89
+ * Renders the Chomp Unicode logo mark (or chomping frame) in brand yellow
90
+ * alongside the wordmark and tagline.
91
+ */
92
+ export function renderChompBanner(subtitle, frame = "open") {
93
+ const sideText = {
94
+ 3: `${ansi.yellowBold("c h o m p")} ${ansi.dim(`v${CORE_EXTRACTOR_VERSION}`)}`,
95
+ 5: ansi.bold("The live map of your codebase."),
96
+ 6: ansi.dim(subtitle || "See how routes, components, and functions actually connect."),
97
+ 8: ansi.dim("Proven from code · Shared by you and your AI agent."),
98
+ };
99
+ const sourceLines = frame === "chomp" ? CHOMP_CHOMPING_FRAME_LINES : CHOMP_UNICODE_LOGO_LINES;
100
+ const lines = sourceLines.map((rawLine, idx) => {
101
+ const padded = visualPadEnd(rawLine, 24);
102
+ const coloredLogo = ansi.yellow(padded);
103
+ const right = sideText[idx] ? ` ${sideText[idx]}` : "";
104
+ return `${coloredLogo}${right}`;
105
+ });
106
+ return ["", ...lines, ""].join("\n");
107
+ }
108
+ export function printChompBanner(subtitle, frame = "open") {
109
+ console.log(renderChompBanner(subtitle, frame));
110
+ }
111
+ /**
112
+ * Plays a live terminal chomping animation that alternates between the open-mouth
113
+ * Chomp logo and the closed-mouth chomping frame in-place, settling on the open-mouth logo.
114
+ * Falls back to printing the static banner once when stdout is not an interactive TTY.
115
+ */
116
+ export async function playChompBannerAnimation(subtitle, options = {}) {
117
+ if (!process.stdout.isTTY || !process.env.NO_COLOR) {
118
+ printChompBanner(subtitle, "open");
119
+ return;
120
+ }
121
+ const cycles = options.cycles ?? 2;
122
+ const frameMs = options.frameMs ?? 190;
123
+ const sequence = ["open"];
124
+ for (let i = 0; i < cycles; i++) {
125
+ sequence.push("chomp", "open");
126
+ }
127
+ const totalLines = CHOMP_UNICODE_LOGO_LINES.length + 2; // leading + 13 art lines + trailing blank line
128
+ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
129
+ // Hide cursor during animation
130
+ process.stdout.write("\x1b[?25l");
131
+ try {
132
+ for (let step = 0; step < sequence.length; step++) {
133
+ const frame = sequence[step];
134
+ if (step > 0) {
135
+ // Move cursor up to top of banner
136
+ process.stdout.write(`\x1b[${totalLines}A\r`);
137
+ }
138
+ const renderedLines = renderChompBanner(subtitle, frame).split("\n");
139
+ for (const line of renderedLines) {
140
+ process.stdout.write(`\x1b[2K${line}\n`);
141
+ }
142
+ if (step < sequence.length - 1) {
143
+ await sleep(frameMs);
144
+ }
145
+ }
146
+ }
147
+ finally {
148
+ // Always restore cursor visibility
149
+ process.stdout.write("\x1b[?25h");
150
+ }
151
+ }
152
+ export function detectFrameworksFromPackageJson(pkgJsonPath) {
153
+ return coreDetectFrameworksFromPackageJson(pkgJsonPath);
154
+ }
155
+ export function loadExcludeWorkspaces(repoRoot) {
156
+ const configPath = resolve(repoRoot, "chomp.config.json");
157
+ if (!existsSync(configPath))
158
+ return [];
159
+ try {
160
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
161
+ return Array.isArray(parsed.excludeWorkspaces)
162
+ ? parsed.excludeWorkspaces.filter((x) => typeof x === "string")
163
+ : [];
164
+ }
165
+ catch {
166
+ return [];
167
+ }
168
+ }
169
+ export function saveExcludeWorkspaces(repoRoot, excludeWorkspaces) {
170
+ const configPath = resolve(repoRoot, "chomp.config.json");
171
+ let existing = {};
172
+ if (existsSync(configPath)) {
173
+ try {
174
+ existing = JSON.parse(readFileSync(configPath, "utf8"));
175
+ }
176
+ catch {
177
+ existing = {};
178
+ }
179
+ }
180
+ const updated = {
181
+ ...existing,
182
+ excludeWorkspaces,
183
+ };
184
+ writeFileSync(configPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
185
+ }
186
+ const FRONTEND_SCAFFOLD_DEPENDENCIES = new Set([
187
+ "react",
188
+ "react-dom",
189
+ "preact",
190
+ "next",
191
+ "vue",
192
+ "nuxt",
193
+ "svelte",
194
+ "@sveltejs/kit",
195
+ "solid-js",
196
+ "astro",
197
+ "@remix-run/react",
198
+ "react-router",
199
+ "react-router-dom",
200
+ "@angular/core",
201
+ "lit",
202
+ "tailwindcss",
203
+ "styled-components",
204
+ "@emotion/react",
205
+ "@emotion/styled",
206
+ "@stitches/react",
207
+ "@vanilla-extract/css",
208
+ "pixi.js",
209
+ ]);
210
+ /**
211
+ * Scaffolds a starter `designSystem` configuration block when frontend packages are detected.
212
+ * - Normal mode (`stealth: false`): merges `designSystem` into root `chomp.config.json`.
213
+ * - Stealth mode (`stealth: true`): writes `.chomp/plugins/design-system/config.json` so tracked files remain 100% git-clean.
214
+ * Never overwrites an existing `designSystem` configuration in either location.
215
+ */
216
+ export function scaffoldDesignSystemConfig(repoRoot, options = {}) {
217
+ const stealth = Boolean(options.stealth);
218
+ const dryRun = Boolean(options.dryRun);
219
+ const rootConfigPath = resolve(repoRoot, "chomp.config.json");
220
+ const stealthConfigPath = resolve(repoRoot, ".chomp", "plugins", "design-system", "config.json");
221
+ let rootParsed = {};
222
+ if (existsSync(rootConfigPath)) {
223
+ try {
224
+ const parsed = JSON.parse(readFileSync(rootConfigPath, "utf8"));
225
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
226
+ rootParsed = parsed;
227
+ }
228
+ }
229
+ catch {
230
+ rootParsed = {};
231
+ }
232
+ }
233
+ if (rootParsed.designSystem && typeof rootParsed.designSystem === "object") {
234
+ return {
235
+ written: false,
236
+ wouldWrite: false,
237
+ alreadyConfigured: true,
238
+ frontendPackages: [],
239
+ configRelPath: "chomp.config.json",
240
+ };
241
+ }
242
+ if (existsSync(stealthConfigPath)) {
243
+ return {
244
+ written: false,
245
+ wouldWrite: false,
246
+ alreadyConfigured: true,
247
+ frontendPackages: [],
248
+ configRelPath: ".chomp/plugins/design-system/config.json",
249
+ };
250
+ }
251
+ const excludedSet = new Set(options.excludeWorkspaces ?? loadExcludeWorkspaces(repoRoot));
252
+ const packages = detectWorkspacePackages(repoRoot).filter((p) => !p.currentlyExcluded &&
253
+ !excludedSet.has(p.name) &&
254
+ !excludedSet.has(p.relPath));
255
+ const frontendPackages = [];
256
+ for (const pkg of packages) {
257
+ const pkgJsonPath = resolve(pkg.absPath, "package.json");
258
+ if (!existsSync(pkgJsonPath))
259
+ continue;
260
+ try {
261
+ const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
262
+ const allDeps = [
263
+ ...Object.keys(pkgJson.dependencies ?? {}),
264
+ ...Object.keys(pkgJson.devDependencies ?? {}),
265
+ ...Object.keys(pkgJson.peerDependencies ?? {}),
266
+ ];
267
+ if (allDeps.some((d) => FRONTEND_SCAFFOLD_DEPENDENCIES.has(d))) {
268
+ frontendPackages.push(pkg.name || pkg.relPath);
269
+ }
270
+ }
271
+ catch {
272
+ // Ignore unreadable package.json
273
+ }
274
+ }
275
+ if (frontendPackages.length === 0) {
276
+ return {
277
+ written: false,
278
+ wouldWrite: false,
279
+ alreadyConfigured: false,
280
+ frontendPackages: [],
281
+ configRelPath: null,
282
+ };
283
+ }
284
+ const designSystemBlock = {
285
+ mode: "auto",
286
+ scope: {
287
+ packages: frontendPackages,
288
+ },
289
+ tokens: {
290
+ sources: [],
291
+ },
292
+ baseline: {
293
+ path: ".chomp/design-system-baseline.json",
294
+ },
295
+ };
296
+ const configRelPath = stealth
297
+ ? ".chomp/plugins/design-system/config.json"
298
+ : "chomp.config.json";
299
+ if (dryRun) {
300
+ return {
301
+ written: false,
302
+ wouldWrite: true,
303
+ alreadyConfigured: false,
304
+ frontendPackages,
305
+ configRelPath,
306
+ };
307
+ }
308
+ if (stealth) {
309
+ mkdirSync(dirname(stealthConfigPath), { recursive: true });
310
+ writeFileSync(stealthConfigPath, JSON.stringify(designSystemBlock, null, 2) + "\n", "utf8");
311
+ }
312
+ else {
313
+ const updated = {
314
+ ...rootParsed,
315
+ designSystem: designSystemBlock,
316
+ };
317
+ writeFileSync(rootConfigPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
318
+ }
319
+ return {
320
+ written: true,
321
+ wouldWrite: false,
322
+ alreadyConfigured: false,
323
+ frontendPackages,
324
+ configRelPath,
325
+ };
326
+ }
327
+ export function detectWorkspacePackages(repoRoot) {
328
+ const registry = buildWorkspaceRegistry(repoRoot);
329
+ const existingExclusions = new Set(loadExcludeWorkspaces(repoRoot));
330
+ const entries = Object.entries(registry);
331
+ if (entries.length === 0) {
332
+ const rootPkgJson = resolve(repoRoot, "package.json");
333
+ let rootName = resolveRepoName(repoRoot);
334
+ if (existsSync(rootPkgJson)) {
335
+ try {
336
+ const parsed = JSON.parse(readFileSync(rootPkgJson, "utf8"));
337
+ if (parsed.name)
338
+ rootName = parsed.name;
339
+ }
340
+ catch {
341
+ // ignore
342
+ }
343
+ }
344
+ return [
345
+ {
346
+ name: rootName,
347
+ relPath: ".",
348
+ absPath: repoRoot,
349
+ frameworks: detectFrameworksFromPackageJson(rootPkgJson),
350
+ currentlyExcluded: false,
351
+ },
352
+ ];
353
+ }
354
+ return entries
355
+ .map(([name, absPath]) => {
356
+ const relPath = relative(repoRoot, absPath).replace(/\\/g, "/") || ".";
357
+ const shortName = name.replace(/^@[^/]+\//, "");
358
+ const frameworks = detectFrameworksFromPackageJson(resolve(absPath, "package.json"));
359
+ const currentlyExcluded = existingExclusions.has(name) ||
360
+ existingExclusions.has(relPath) ||
361
+ existingExclusions.has(shortName);
362
+ return {
363
+ name,
364
+ relPath,
365
+ absPath,
366
+ frameworks,
367
+ currentlyExcluded,
368
+ };
369
+ })
370
+ .sort((a, b) => a.relPath.localeCompare(b.relPath));
371
+ }
372
+ // ---------------------------------------------------------------------------
373
+ // Structural Bite Report (Replaces 4,000-row console.table dump by default)
374
+ // ---------------------------------------------------------------------------
375
+ export function printFrameworkWarnings(warnings) {
376
+ if (warnings.length === 0)
377
+ return;
378
+ console.log(` ${ansi.amber("▲")} ${ansi.bold("Framework & Convention Accuracy Warnings")}`);
379
+ for (const w of warnings) {
380
+ console.log(` ${ansi.amber("•")} ${ansi.dim(`[${w.kind}]`)} ${w.message}`);
381
+ }
382
+ console.log("");
383
+ }
384
+ function readRegisteredLedgerShapeKeys() {
385
+ const keys = new Set();
386
+ try {
387
+ const ledgerPath = resolve(getChompMasterRoot(), "fixtures/research/pattern_ledger.db");
388
+ if (!existsSync(ledgerPath))
389
+ return keys;
390
+ const db = new Database(ledgerPath, { readonly: true });
391
+ try {
392
+ const rows = db
393
+ .prepare("SELECT shape_key FROM pattern_ledger WHERE shape_key IS NOT NULL")
394
+ .all();
395
+ for (const r of rows) {
396
+ if (r.shape_key)
397
+ keys.add(r.shape_key);
398
+ }
399
+ }
400
+ finally {
401
+ db.close();
402
+ }
403
+ }
404
+ catch {
405
+ // Non-fatal if pattern_ledger.db does not exist or cannot be read
406
+ }
407
+ return keys;
408
+ }
409
+ /**
410
+ * Surfaces a concise CLI hint when extraction detects unregistered knowable shape clusters
411
+ * that are not yet tracked in `fixtures/research/pattern_ledger.db`.
412
+ */
413
+ export function printUnregisteredShapeHint(graph, repoName, darkFiles = []) {
414
+ if (!hasPrivateResearchLedger())
415
+ return;
416
+ const registeredShapeKeys = readRegisteredLedgerShapeKeys();
417
+ const candidates = collectLedgerSignalCandidates(graph, {
418
+ registeredShapeKeys,
419
+ onlyKnowable: true,
420
+ onlyActionableOrphans: true,
421
+ darkFiles,
422
+ });
423
+ if (candidates.length === 0)
424
+ return;
425
+ const totalUnresolved = candidates.reduce((sum, c) => sum + c.unresolved, 0);
426
+ const topPreview = candidates
427
+ .slice(0, 3)
428
+ .map((c) => `${c.shapeKey} (${c.unresolved})`)
429
+ .join(", ");
430
+ console.log(` ${ansi.amber("◆")} ${ansi.bold(`${candidates.length} unregistered knowable shape cluster${candidates.length === 1 ? "" : "s"} found`)} ${ansi.dim(`(${totalUnresolved} unresolved: ${topPreview}${candidates.length > 3 ? `, +${candidates.length - 3} more` : ""})`)}`);
431
+ console.log(` ${ansi.dim("Run")} ${ansi.cyan(`pnpm chomp-research ledger pattern measure --repo ${repoName} --ingest`)} ${ansi.dim("to sync into pattern_ledger.db")}\n`);
432
+ }
433
+ export function computeQuickConnectivity(graph) {
434
+ const { connectivityRate, callResolutionCounts } = computeStructuralHealthMetrics(graph);
435
+ const unresolvedCount = callResolutionCounts.provableCallCount - callResolutionCounts.resolvedCount;
436
+ return { connectivityRate, unresolvedCount };
437
+ }
438
+ /**
439
+ * Prints a clear, concise Polaris-style welcome message before workspace detection begins.
440
+ */
441
+ export function printWelcomeMessage(repoName, isDryRun = false) {
442
+ console.log(` ${ansi.bold("Welcome to Chomp!")} Let's set up the architecture graph for ${ansi.cyan(repoName)}.`);
443
+ console.log(` ${ansi.dim("We'll scan your packages, set up automatic Git sync, and connect your AI coding agents.")}`);
444
+ if (isDryRun) {
445
+ console.log(` ${ansi.amber("⚡ Sandbox mode")} ${ansi.dim("— previewing setup without changing any files or databases.")}`);
446
+ }
447
+ console.log("");
448
+ }
449
+ /**
450
+ * Runs a paced, single-line thinking ticker directly underneath the opening Chomp logo
451
+ * so the user has time to take in the brand mark while system discovery runs.
452
+ */
453
+ export async function runDiscoveryTicker(repoName, customMessages) {
454
+ if (!process.stdout.isTTY || process.env.NO_COLOR) {
455
+ return;
456
+ }
457
+ const messages = customMessages ?? [
458
+ `Checking package.json and TypeScript config in ${repoName}...`,
459
+ "Detecting workspace packages and frameworks...",
460
+ "Checking Git repository and AI agent settings...",
461
+ ];
462
+ const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
463
+ const stepMs = 680;
464
+ const tickMs = 80;
465
+ const ticksPerStep = Math.max(1, Math.round(stepMs / tickMs));
466
+ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
467
+ process.stdout.write("\x1b[?25l");
468
+ try {
469
+ let spinIdx = 0;
470
+ for (const msg of messages) {
471
+ for (let t = 0; t < ticksPerStep; t++) {
472
+ const frame = spinnerFrames[spinIdx % spinnerFrames.length];
473
+ spinIdx++;
474
+ process.stdout.write(`\r\x1b[2K ${ansi.yellowBold(frame)} ${ansi.dim(msg)}`);
475
+ await sleep(tickMs);
476
+ }
477
+ }
478
+ process.stdout.write("\r\x1b[2K");
479
+ }
480
+ finally {
481
+ process.stdout.write("\x1b[?25h");
482
+ }
483
+ }
484
+ function truncateCell(text, maxLen) {
485
+ if (text.length <= maxLen)
486
+ return text.padEnd(maxLen);
487
+ return text.slice(0, Math.max(1, maxLen - 1)) + "…";
488
+ }
489
+ function stripAnsi(str) {
490
+ return str.replace(/\x1b\[[0-9;]*m/g, "");
491
+ }
492
+ function padAnsiCell(str, targetCols) {
493
+ const plainWidth = visualWidth(stripAnsi(str));
494
+ return plainWidth >= targetCols
495
+ ? str
496
+ : str + " ".repeat(targetCols - plainWidth);
497
+ }
498
+ /**
499
+ * Renders the detected repository & package configuration inside a structured
500
+ * read-only box table so it is visually distinct from interactive wizard prompts.
501
+ */
502
+ export function printDetectedWorkspaceTable(repoName, packages, vaultNotes = []) {
503
+ const colPkg = 20;
504
+ const colPath = 16;
505
+ const colStack = 40;
506
+ const innerWidth = colPkg + colPath + colStack + 8; // 2 leading + 2 gap + 2 gap + 2 trailing
507
+ const footerContentWidth = innerWidth - 4;
508
+ const titlePlain = ` Workspace Configuration · ${repoName} (${packages.length} package${packages.length === 1 ? "" : "s"}) `;
509
+ const topDashCount = Math.max(2, innerWidth - titlePlain.length - 1);
510
+ console.log(` ${ansi.dim("┌─")}${ansi.bold(titlePlain)}${ansi.dim("─".repeat(topDashCount) + "┐")}`);
511
+ console.log(` ${ansi.dim("│")} ${ansi.dim("PACKAGE".padEnd(colPkg))} ${ansi.dim("PATH".padEnd(colPath))} ${ansi.dim("DETECTED STACK".padEnd(colStack))} ${ansi.dim("│")}`);
512
+ console.log(` ${ansi.dim("├" + "─".repeat(innerWidth) + "┤")}`);
513
+ for (const pkg of packages) {
514
+ const rawStack = pkg.frameworks.length > 0
515
+ ? pkg.frameworks.join(", ")
516
+ : "TypeScript / JS";
517
+ const stackWithStatus = pkg.currentlyExcluded
518
+ ? `${rawStack} (excluded)`
519
+ : rawStack;
520
+ const c1 = ansi.bold(truncateCell(pkg.name, colPkg));
521
+ const c2 = ansi.dim(truncateCell(pkg.relPath, colPath));
522
+ const c3 = pkg.currentlyExcluded
523
+ ? ansi.amber(truncateCell(stackWithStatus, colStack))
524
+ : pkg.frameworks.length > 0
525
+ ? ansi.cyan(truncateCell(stackWithStatus, colStack))
526
+ : ansi.dim(truncateCell(stackWithStatus, colStack));
527
+ console.log(` ${ansi.dim("│")} ${c1} ${c2} ${c3} ${ansi.dim("│")}`);
528
+ }
529
+ console.log(` ${ansi.dim("├" + "─".repeat(innerWidth) + "┤")}`);
530
+ for (const note of vaultNotes) {
531
+ console.log(` ${ansi.dim("│")} ${padAnsiCell(note, footerContentWidth)} ${ansi.dim("│")}`);
532
+ }
533
+ const tipText = ansi.dim("ℹ Update package exclusions anytime in chomp.config.json");
534
+ console.log(` ${ansi.dim("│")} ${padAnsiCell(tipText, footerContentWidth)} ${ansi.dim("│")}`);
535
+ console.log(` ${ansi.dim("└" + "─".repeat(innerWidth) + "┘")}`);
536
+ }
537
+ function resolvePackageNameForNode(nodeId, nodeById) {
538
+ let cursor = nodeById.get(nodeId);
539
+ const visited = new Set();
540
+ while (cursor && !visited.has(cursor.id)) {
541
+ visited.add(cursor.id);
542
+ if (cursor.entityType === "DEPLOYMENT_UNIT") {
543
+ return cursor.name.replace(/^Deployment Unit:\s*/i, "").trim();
544
+ }
545
+ cursor = cursor.parentBoundaryId
546
+ ? nodeById.get(cursor.parentBoundaryId)
547
+ : undefined;
548
+ }
549
+ return undefined;
550
+ }
551
+ function renderChompFrameWithSideLines(frame, sideLines) {
552
+ const sourceLines = frame === "chomp" ? CHOMP_CHOMPING_FRAME_LINES : CHOMP_UNICODE_LOGO_LINES;
553
+ const lines = sourceLines.map((rawLine, idx) => {
554
+ const padded = visualPadEnd(rawLine, 24);
555
+ const coloredLogo = ansi.yellow(padded);
556
+ const right = sideLines[idx] ? ` ${sideLines[idx]}` : "";
557
+ return `${coloredLogo}${right}`;
558
+ });
559
+ return ["", ...lines, ""].join("\n");
560
+ }
561
+ function formatAnalysisTimestamp(date = new Date()) {
562
+ const yyyy = date.getFullYear();
563
+ const mm = String(date.getMonth() + 1).padStart(2, "0");
564
+ const dd = String(date.getDate()).padStart(2, "0");
565
+ const hh = String(date.getHours()).padStart(2, "0");
566
+ const min = String(date.getMinutes()).padStart(2, "0");
567
+ const ss = String(date.getSeconds()).padStart(2, "0");
568
+ return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}`;
569
+ }
570
+ /**
571
+ * Runs the 2-frame Chomp mouth animation continuously during code analysis
572
+ * (guaranteed minimum of 2 full chomp cycles, and more if extraction takes longer)
573
+ * while streaming a live sequence of package & contract discovery events to the right.
574
+ */
575
+ export async function runChompExtractionWithAnimation(opts) {
576
+ const { repoName, repoPath, dbPath, commitSha, branchName, excludeWorkspaces = [], isSandbox = false, executeExtraction, } = opts;
577
+ const excludedSet = new Set(excludeWorkspaces);
578
+ const allPackages = detectWorkspacePackages(repoPath);
579
+ const activePackages = allPackages.filter((p) => !excludedSet.has(p.name) &&
580
+ !excludedSet.has(p.relPath) &&
581
+ !excludedSet.has(p.name.replace(/^@[^/]+\//, "")));
582
+ const packagesToDisplay = activePackages.length > 0 ? activePackages : allPackages;
583
+ const gitTag = commitSha
584
+ ? `${ansi.cyan(branchName ?? "detached")} ${ansi.dim(`(${commitSha.slice(0, 7)})`)}`
585
+ : ansi.dim("untracked");
586
+ const isTTY = Boolean(process.stdout.isTTY && !process.env.NO_COLOR);
587
+ const totalLines = CHOMP_UNICODE_LOGO_LINES.length + 2;
588
+ const frameMs = 200;
589
+ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
590
+ let hasRendered = false;
591
+ const drawFrame = (frame, sideLines) => {
592
+ if (!isTTY)
593
+ return;
594
+ if (hasRendered) {
595
+ process.stdout.write(`\x1b[${totalLines}A\r`);
596
+ }
597
+ const rendered = renderChompFrameWithSideLines(frame, sideLines).split("\n");
598
+ for (const line of rendered) {
599
+ process.stdout.write(`\x1b[2K${line}\n`);
600
+ }
601
+ hasRendered = true;
602
+ };
603
+ if (isTTY) {
604
+ process.stdout.write("\x1b[?25l");
605
+ }
606
+ try {
607
+ let worker = null;
608
+ const animStartMs = Date.now();
609
+ if (isTTY) {
610
+ const firstPkg = packagesToDisplay[0]?.name ?? repoName;
611
+ drawFrame("open", {
612
+ 0: `${ansi.yellowBold("◆")} ${ansi.bold(`Chomping ${repoName}...`)}${isSandbox ? ansi.dim(" [sandbox in-memory]") : ""}`,
613
+ 1: `${ansi.dim("Branch chomped:")} ${gitTag}`,
614
+ 2: ansi.dim("──────────────────────────────────────────────────────────────"),
615
+ 3: `${ansi.yellowBold("▸")} Analyzing ${ansi.bold(firstPkg)}...`,
616
+ });
617
+ // Pre-render live chomping frames for a background Worker thread using direct
618
+ // OS file descriptor 1 writes (`fs.writeSync(1, ...)`) so the mouth chomps
619
+ // continuously at 5fps even while the main thread is busy parsing ASTs.
620
+ const maxVisible = packagesToDisplay.length <= 5 ? packagesToDisplay.length : 4;
621
+ const visiblePkgs = packagesToDisplay.slice(0, maxVisible);
622
+ const workerFrames = [];
623
+ let nextLogoFrame = "chomp";
624
+ const totalSteps = Math.max(4, visiblePkgs.length * 2);
625
+ for (let step = 0; step < totalSteps; step++) {
626
+ const pkgIdx = Math.min(visiblePkgs.length - 1, Math.floor(step / 2));
627
+ const side = {
628
+ 0: `${ansi.yellowBold("◆")} ${ansi.bold(`Chomping ${repoName}...`)}${isSandbox ? ansi.dim(" [sandbox in-memory]") : ""}`,
629
+ 1: `${ansi.dim("Branch chomped:")} ${gitTag}`,
630
+ 2: ansi.dim("──────────────────────────────────────────────────────────────"),
631
+ };
632
+ for (let j = 0; j < pkgIdx; j++) {
633
+ const p = visiblePkgs[j];
634
+ const fw = p.frameworks.length > 0
635
+ ? ansi.dim(` [${p.frameworks.slice(0, 2).join(", ")}]`)
636
+ : "";
637
+ side[3 + j] = `${ansi.green("✓")} Scanned ${ansi.bold(p.name)}${fw}`;
638
+ }
639
+ const activePkg = visiblePkgs[pkgIdx];
640
+ if (activePkg) {
641
+ const fw = activePkg.frameworks.length > 0
642
+ ? ansi.dim(` [${activePkg.frameworks.slice(0, 2).join(", ")}]`)
643
+ : "";
644
+ side[3 + pkgIdx] =
645
+ `${ansi.yellowBold("▸")} Analyzing ${ansi.bold(activePkg.name)}${fw} — extracting AST contracts...`;
646
+ }
647
+ const renderedLines = renderChompFrameWithSideLines(nextLogoFrame, side).split("\n");
648
+ const payload = `\x1b[${totalLines}A\r` +
649
+ renderedLines.map((l) => `\x1b[2K${l}\n`).join("");
650
+ workerFrames.push(payload);
651
+ nextLogoFrame = nextLogoFrame === "open" ? "chomp" : "open";
652
+ }
653
+ try {
654
+ worker = new Worker(`
655
+ const fs = require("node:fs");
656
+ const { workerData } = require("node:worker_threads");
657
+ const { frames, intervalMs } = workerData;
658
+ let i = 0;
659
+ setInterval(() => {
660
+ try {
661
+ fs.writeSync(1, frames[i % frames.length]);
662
+ i++;
663
+ } catch {}
664
+ }, intervalMs);
665
+ `, {
666
+ eval: true,
667
+ workerData: { frames: workerFrames, intervalMs: frameMs },
668
+ });
669
+ }
670
+ catch {
671
+ worker = null;
672
+ }
673
+ }
674
+ let graph;
675
+ let durationMs;
676
+ try {
677
+ const res = await executeExtraction();
678
+ graph = res.graph;
679
+ durationMs = res.durationMs;
680
+ }
681
+ finally {
682
+ if (worker) {
683
+ try {
684
+ await worker.terminate();
685
+ }
686
+ catch {
687
+ // ignore
688
+ }
689
+ }
690
+ }
691
+ // Compute real per-package and overall metrics from the extracted graph
692
+ const userNodes = graph.nodes.filter((n) => (n.scope ?? "USER") === "USER");
693
+ const nodeById = new Map(graph.nodes.map((n) => [n.id, n]));
694
+ const contracts = userNodes.filter((n) => n.type === "CONTRACT");
695
+ const routesAndTools = contracts.filter((c) => [
696
+ "HTTP_ENDPOINT",
697
+ "NEXTJS_PAGE",
698
+ "NEXTJS_LAYOUT",
699
+ "MCP_TOOL",
700
+ "CLI_COMMAND",
701
+ "GRAPHQL_RESOLVER",
702
+ "EVENT_LISTENER",
703
+ ].includes(c.entityType ?? ""));
704
+ const classes = userNodes.filter((n) => n.entityType === "CLASS");
705
+ const openConnectors = userNodes.filter((n) => n.type === "OPEN_CONNECTOR");
706
+ const { connectivityRate, unresolvedCount } = computeQuickConnectivity(graph);
707
+ const contractsByPkgKey = new Map();
708
+ for (const c of contracts) {
709
+ const unitName = resolvePackageNameForNode(c.id, nodeById);
710
+ if (unitName) {
711
+ contractsByPkgKey.set(unitName, (contractsByPkgKey.get(unitName) ?? 0) + 1);
712
+ const shortUnit = unitName.replace(/^@[^/]+\//, "");
713
+ if (shortUnit !== unitName) {
714
+ contractsByPkgKey.set(shortUnit, (contractsByPkgKey.get(shortUnit) ?? 0) + 1);
715
+ }
716
+ }
717
+ }
718
+ const getPkgContractCount = (pkg) => {
719
+ const shortName = pkg.name.replace(/^@[^/]+\//, "");
720
+ const direct = contractsByPkgKey.get(pkg.name) ?? contractsByPkgKey.get(shortName);
721
+ if (typeof direct === "number")
722
+ return direct;
723
+ if (packagesToDisplay.length === 1)
724
+ return contracts.length;
725
+ return 0;
726
+ };
727
+ const maxVisiblePackages = packagesToDisplay.length <= 5 ? packagesToDisplay.length : 4;
728
+ const visiblePackages = packagesToDisplay.slice(0, maxVisiblePackages);
729
+ const hiddenPackages = packagesToDisplay.slice(maxVisiblePackages);
730
+ const completedPkgLines = visiblePackages.map((pkg) => {
731
+ const count = getPkgContractCount(pkg);
732
+ const fwHint = pkg.frameworks.length > 0
733
+ ? ansi.dim(` [${pkg.frameworks.slice(0, 2).join(", ")}]`)
734
+ : "";
735
+ return `${ansi.green("✓")} Analyzed ${ansi.bold(pkg.name)}${fwHint} ${ansi.dim("—")} ${ansi.yellowBold(String(count))} nodes mapped`;
736
+ });
737
+ if (hiddenPackages.length > 0) {
738
+ const extraContracts = hiddenPackages.reduce((sum, p) => sum + getPkgContractCount(p), 0);
739
+ completedPkgLines.push(`${ansi.green("✓")} Analyzed +${hiddenPackages.length} more package${hiddenPackages.length === 1 ? "" : "s"} ${ansi.dim("—")} ${ansi.yellowBold(String(extraContracts))} nodes mapped`);
740
+ }
741
+ const timeTag = ansi.dim(` in ${(durationMs / 1000).toFixed(2)}s`);
742
+ const healthBadge = connectivityRate >= 80
743
+ ? ansi.green(`● ${connectivityRate.toFixed(1)}% PASS`)
744
+ : ansi.amber(`? ${connectivityRate.toFixed(1)}% WARN`);
745
+ const shortDb = relative(repoPath, dbPath) || dbPath;
746
+ const analysisTimestamp = formatAnalysisTimestamp();
747
+ if (isTTY) {
748
+ // Ensure a minimum of 2 full chomp cycles (4 frame transitions = ~800ms)
749
+ // plus progressive package-by-package completion reveal
750
+ const elapsedDuringExtract = Date.now() - animStartMs;
751
+ const minTotalAnimMs = frameMs * 4;
752
+ const remainingSteps = Math.max(completedPkgLines.length, elapsedDuringExtract < minTotalAnimMs ? 4 : completedPkgLines.length);
753
+ let currentFrame = "chomp";
754
+ for (let step = 0; step < remainingSteps; step++) {
755
+ const revealedCount = Math.min(completedPkgLines.length, Math.floor(((step + 1) / remainingSteps) * completedPkgLines.length) || 1);
756
+ const frameSide = {
757
+ 0: `${ansi.yellowBold("◆")} ${ansi.bold(`Chomping ${repoName}...`)}${isSandbox ? ansi.dim(" [sandbox in-memory]") : ""}`,
758
+ 1: `${ansi.dim("Branch chomped:")} ${gitTag}`,
759
+ 2: ansi.dim("──────────────────────────────────────────────────────────────"),
760
+ };
761
+ for (let j = 0; j < revealedCount; j++) {
762
+ frameSide[3 + j] = completedPkgLines[j];
763
+ }
764
+ if (revealedCount < completedPkgLines.length) {
765
+ const nextPkg = visiblePackages[revealedCount]?.name ?? "remaining packages";
766
+ frameSide[3 + revealedCount] = `${ansi.yellowBold("▸")} Analyzing ${ansi.bold(nextPkg)}...`;
767
+ }
768
+ else {
769
+ frameSide[3 + revealedCount] = `${ansi.yellowBold("▸")} Wiring ${graph.edges.length.toLocaleString()} structural relationships...`;
770
+ }
771
+ drawFrame(currentFrame, frameSide);
772
+ currentFrame = currentFrame === "open" ? "chomp" : "open";
773
+ await sleep(frameMs);
774
+ }
775
+ }
776
+ // Final settled frame ("open") with Branch chomped at top, package results, and Local chomp storage + timestamp at bottom
777
+ const finalSide = {
778
+ 0: `${ansi.green("✓")} ${ansi.bold(`Chomped ${repoName}`)}${timeTag}`,
779
+ 1: `${ansi.dim("Branch chomped:")} ${gitTag}`,
780
+ 2: ansi.dim("──────────────────────────────────────────────────────────────"),
781
+ };
782
+ let rowCursor = 3;
783
+ for (const line of completedPkgLines) {
784
+ finalSide[rowCursor++] = line;
785
+ }
786
+ finalSide[rowCursor++] = ansi.dim("──────────────────────────────────────────────────────────────");
787
+ finalSide[rowCursor++] =
788
+ `${ansi.yellowBold("◆")} ${ansi.bold(String(contracts.length))} nodes mapped ${ansi.dim(`(${routesAndTools.length} entry points · ${classes.length} classes · ${openConnectors.length} external calls)`)}`;
789
+ finalSide[rowCursor++] =
790
+ `${ansi.yellowBold("◆")} ${ansi.bold(graph.edges.length.toLocaleString())} connections wired · Map coverage: ${healthBadge}${unresolvedCount > 0 ? ansi.dim(` (? ${unresolvedCount} unresolved)`) : ""}`;
791
+ finalSide[rowCursor++] =
792
+ `${ansi.dim("Local chomp storage:")} ${ansi.cyan(shortDb)} ${ansi.dim(`(${analysisTimestamp})`)}`;
793
+ if (isTTY) {
794
+ drawFrame("open", finalSide);
795
+ }
796
+ else {
797
+ console.log(renderChompFrameWithSideLines("open", finalSide));
798
+ }
799
+ const coverage = auditFrameworkCoverage(repoPath, graph, excludeWorkspaces);
800
+ if (coverage.warnings.length > 0) {
801
+ printFrameworkWarnings(coverage.warnings);
802
+ }
803
+ printUnregisteredShapeHint(graph, repoName, coverage.darkFiles);
804
+ return { graph, durationMs };
805
+ }
806
+ finally {
807
+ if (isTTY) {
808
+ process.stdout.write("\x1b[?25h");
809
+ }
810
+ }
811
+ }
812
+ // ---------------------------------------------------------------------------
813
+ // Interactive Terminal Prompts (Confirm & Multi-Select with Arrow Keys)
814
+ // ---------------------------------------------------------------------------
815
+ export async function confirmPrompt(question, defaultYes = true, description) {
816
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
817
+ return defaultYes;
818
+ }
819
+ const hint = defaultYes ? "[Y/n]" : "[y/N]";
820
+ if (description) {
821
+ console.log(` ${ansi.yellowBold("?")} ${ansi.bold(question)}`);
822
+ for (const line of description.split("\n")) {
823
+ console.log(` ${ansi.dim(line)}`);
824
+ }
825
+ }
826
+ const rl = readline.createInterface({
827
+ input: process.stdin,
828
+ output: process.stdout,
829
+ });
830
+ const promptLine = description
831
+ ? ` ${ansi.yellowBold("❯")} ${ansi.dim(hint)} `
832
+ : ` ${ansi.yellowBold("?")} ${ansi.bold(question)} ${ansi.dim(hint)} `;
833
+ return new Promise((resolvePromise) => {
834
+ rl.question(promptLine, (answer) => {
835
+ rl.close();
836
+ const trimmed = answer.trim().toLowerCase();
837
+ if (!trimmed) {
838
+ resolvePromise(defaultYes);
839
+ }
840
+ else if (trimmed === "y" || trimmed === "yes") {
841
+ resolvePromise(true);
842
+ }
843
+ else if (trimmed === "n" || trimmed === "no") {
844
+ resolvePromise(false);
845
+ }
846
+ else {
847
+ resolvePromise(defaultYes);
848
+ }
849
+ });
850
+ });
851
+ }
852
+ /**
853
+ * Interactive multi-select checklist in the terminal.
854
+ * Supports Up/Down arrows (or j/k), Space to toggle, 'a' to toggle all, and Enter to confirm.
855
+ * Gracefully falls back to comma-separated numbers if raw mode is unavailable.
856
+ */
857
+ export async function multiSelectPrompt(title, subtitle, options) {
858
+ if (options.length === 0 ||
859
+ !process.stdin.isTTY ||
860
+ !process.stdout.isTTY ||
861
+ typeof process.stdin.setRawMode !== "function") {
862
+ return options.filter((o) => o.selected).map((o) => o.value);
863
+ }
864
+ return new Promise((resolvePromise) => {
865
+ const items = options.map((o) => ({ ...o }));
866
+ let cursor = 0;
867
+ let renderedLineCount = 0;
868
+ const render = () => {
869
+ if (renderedLineCount > 0) {
870
+ process.stdout.write(`\x1b[${renderedLineCount}A\x1b[J`);
871
+ }
872
+ const lines = [];
873
+ lines.push(` ${ansi.yellowBold("?")} ${ansi.bold(title)}`);
874
+ lines.push(` ${ansi.dim(subtitle)}`);
875
+ for (let i = 0; i < items.length; i++) {
876
+ const item = items[i];
877
+ const isCurrent = i === cursor;
878
+ const pointer = isCurrent ? ansi.yellowBold("❯") : " ";
879
+ const check = item.selected
880
+ ? ansi.green("◉")
881
+ : ansi.dim("◯");
882
+ const labelText = isCurrent ? ansi.bold(item.label) : item.label;
883
+ const hintText = item.hint ? ` ${ansi.dim(item.hint)}` : "";
884
+ lines.push(` ${pointer} ${check} ${labelText}${hintText}`);
885
+ }
886
+ process.stdout.write(lines.join("\n") + "\n");
887
+ renderedLineCount = lines.length;
888
+ };
889
+ const cleanup = () => {
890
+ process.stdin.removeListener("data", onData);
891
+ try {
892
+ process.stdin.setRawMode(false);
893
+ }
894
+ catch {
895
+ // ignore
896
+ }
897
+ process.stdin.pause();
898
+ process.stdout.write("\x1b[?25h");
899
+ };
900
+ const onData = (buf) => {
901
+ const key = buf.toString("utf8");
902
+ // Ctrl+C
903
+ if (key === "\u0003") {
904
+ cleanup();
905
+ process.exit(130);
906
+ }
907
+ // Enter
908
+ if (key === "\r" || key === "\n") {
909
+ cleanup();
910
+ resolvePromise(items.filter((i) => i.selected).map((i) => i.value));
911
+ return;
912
+ }
913
+ // Space
914
+ if (key === " ") {
915
+ items[cursor].selected = !items[cursor].selected;
916
+ render();
917
+ return;
918
+ }
919
+ // Toggle all ('a')
920
+ if (key === "a" || key === "A") {
921
+ const allSelected = items.every((i) => i.selected);
922
+ for (const item of items) {
923
+ item.selected = !allSelected;
924
+ }
925
+ render();
926
+ return;
927
+ }
928
+ // Up arrow or 'k'
929
+ if (key === "\u001b[A" || key === "k") {
930
+ cursor = (cursor - 1 + items.length) % items.length;
931
+ render();
932
+ return;
933
+ }
934
+ // Down arrow or 'j'
935
+ if (key === "\u001b[B" || key === "j") {
936
+ cursor = (cursor + 1) % items.length;
937
+ render();
938
+ return;
939
+ }
940
+ };
941
+ process.stdout.write("\x1b[?25l");
942
+ process.stdin.setRawMode(true);
943
+ process.stdin.resume();
944
+ process.stdin.on("data", onData);
945
+ render();
946
+ });
947
+ }
948
+ // ---------------------------------------------------------------------------
949
+ // Cross-Platform Browser Opener
950
+ // ---------------------------------------------------------------------------
951
+ export function openBrowserUrl(url) {
952
+ try {
953
+ const platform = process.platform;
954
+ let child;
955
+ if (platform === "darwin") {
956
+ child = spawn("open", [url], { stdio: "ignore", detached: true });
957
+ }
958
+ else if (platform === "win32") {
959
+ child = spawn("cmd", ["/c", "start", "", url], {
960
+ stdio: "ignore",
961
+ detached: true,
962
+ });
963
+ }
964
+ else {
965
+ child = spawn("xdg-open", [url], {
966
+ stdio: "ignore",
967
+ detached: true,
968
+ });
969
+ }
970
+ child.on("error", () => {
971
+ // Non-fatal in headless Linux / SSH / Docker / WSL environments without xdg-open
972
+ });
973
+ child.unref();
974
+ }
975
+ catch {
976
+ // Non-fatal if browser opener is unavailable
977
+ }
978
+ }