@getchomp/cli 0.0.0-stage → 0.2.42
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/README.md +39 -2
- package/dist/commands/analyze.d.ts +49 -0
- package/dist/commands/analyze.js +280 -0
- package/dist/commands/connect.d.ts +12 -0
- package/dist/commands/connect.js +255 -0
- package/dist/commands/export.d.ts +29 -0
- package/dist/commands/export.js +356 -0
- package/dist/commands/health.d.ts +19 -0
- package/dist/commands/health.js +259 -0
- package/dist/commands/init.d.ts +40 -0
- package/dist/commands/init.js +654 -0
- package/dist/commands/mcp.d.ts +2 -0
- package/dist/commands/mcp.js +12 -0
- package/dist/commands/plugin.d.ts +8 -0
- package/dist/commands/plugin.js +198 -0
- package/dist/commands/ui.d.ts +20 -0
- package/dist/commands/ui.js +250 -0
- package/dist/commands/uninstall.d.ts +8 -0
- package/dist/commands/uninstall.js +238 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +37 -0
- package/dist/ports/portHydrator.d.ts +63 -0
- package/dist/ports/portHydrator.js +954 -0
- package/dist/ports/portHydratorWorker.d.ts +22 -0
- package/dist/ports/portHydratorWorker.js +75 -0
- package/dist/server/buildStatusTracker.d.ts +45 -0
- package/dist/server/buildStatusTracker.js +122 -0
- package/dist/server/graphLayoutState.d.ts +205 -0
- package/dist/server/graphLayoutState.js +930 -0
- package/dist/server/loopbackSecurity.d.ts +18 -0
- package/dist/server/loopbackSecurity.js +57 -0
- package/dist/server/routes/authSourceRoutes.d.ts +18 -0
- package/dist/server/routes/authSourceRoutes.js +231 -0
- package/dist/server/routes/layoutRoutes.d.ts +3 -0
- package/dist/server/routes/layoutRoutes.js +857 -0
- package/dist/server/routes/pluginRoutes.d.ts +3 -0
- package/dist/server/routes/pluginRoutes.js +368 -0
- package/dist/server/routes/viewRulesRoutes.d.ts +3 -0
- package/dist/server/routes/viewRulesRoutes.js +173 -0
- package/dist/server/uiHotkeys.d.ts +26 -0
- package/dist/server/uiHotkeys.js +160 -0
- package/dist/utils/branding.d.ts +126 -0
- package/dist/utils/branding.js +976 -0
- package/dist/utils/credentials.d.ts +22 -0
- package/dist/utils/credentials.js +126 -0
- package/dist/utils/git.d.ts +95 -0
- package/dist/utils/git.js +780 -0
- package/dist/utils/masterContext.d.ts +102 -0
- package/dist/utils/masterContext.js +559 -0
- package/dist/visualizer/cloudLayoutClient.d.ts +84 -0
- package/dist/visualizer/cloudLayoutClient.js +1200 -0
- package/dist/visualizer/layoutCache.d.ts +25 -0
- package/dist/visualizer/layoutCache.js +406 -0
- package/dist/visualizer/localEngineBridge.d.ts +50 -0
- package/dist/visualizer/localEngineBridge.js +80 -0
- package/dist/visualizer/pluginPresentationApi.d.ts +111 -0
- package/dist/visualizer/pluginPresentationApi.js +432 -0
- package/dist/visualizer/rulesConfig.d.ts +11 -0
- package/dist/visualizer/rulesConfig.js +266 -0
- package/dist/visualizer/sourceAccess.d.ts +45 -0
- package/dist/visualizer/sourceAccess.js +204 -0
- package/package.json +51 -3
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview CLI command for listing, running, and diffing Chomp analysis-time plugins
|
|
3
|
+
* (e.g., `chomp plugin list`, `chomp plugin run design-system [path]`, `chomp plugin diff [path]`).
|
|
4
|
+
*
|
|
5
|
+
* Enforces [PAT-DB-03], [PAT-DB-05], and [PAT-CLI-13].
|
|
6
|
+
*/
|
|
7
|
+
import { Command } from "commander";
|
|
8
|
+
export declare function registerPluginCommand(program: Command): void;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview CLI command for listing, running, and diffing Chomp analysis-time plugins
|
|
3
|
+
* (e.g., `chomp plugin list`, `chomp plugin run design-system [path]`, `chomp plugin diff [path]`).
|
|
4
|
+
*
|
|
5
|
+
* Enforces [PAT-DB-03], [PAT-DB-05], and [PAT-CLI-13].
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, statSync } from "node:fs";
|
|
8
|
+
import { dirname, resolve } from "node:path";
|
|
9
|
+
import { diffDesignSystem, getChompPlugin, getPluginMcpToolSummaries, getPluginStateDirRel, listChompPlugins, runAllChompPlugins, runChompPlugin, snapshotDesignSystemBaseline, } from "@getchomp/mcp";
|
|
10
|
+
import { ansi, loadExcludeWorkspaces } from "../utils/branding.js";
|
|
11
|
+
import { resolveDefaultCliTarget, resolveRepoName } from "../utils/masterContext.js";
|
|
12
|
+
import { runAnalyze } from "./analyze.js";
|
|
13
|
+
function printPluginRunSummary(res) {
|
|
14
|
+
console.log(`\n ${ansi.yellowBold("◆")} ${ansi.bold(`Chomp Plugin: ${res.pluginName}`)} ${ansi.dim(`v${res.pluginVersion}`)} (${ansi.cyan(res.layer)})`);
|
|
15
|
+
console.log(` ${ansi.dim("Files scanned:")} ${res.acceptedFileCount} · ${ansi.dim("Overlays written:")} ${ansi.green(String(res.overlayCount))} · ${ansi.dim("Duration:")} ${res.durationMs}ms`);
|
|
16
|
+
const plugin = getChompPlugin(res.pluginName);
|
|
17
|
+
const summaryLines = plugin?.formatCliSummary?.(res, ansi) ?? [];
|
|
18
|
+
for (const line of summaryLines) {
|
|
19
|
+
console.log(` ${line}`);
|
|
20
|
+
}
|
|
21
|
+
console.log("");
|
|
22
|
+
}
|
|
23
|
+
export function registerPluginCommand(program) {
|
|
24
|
+
const pluginCmd = program
|
|
25
|
+
.command("plugin")
|
|
26
|
+
.description("Manage and run Chomp map plugins (design-system, bridges / local-shims, summaries / enrich-nodes)");
|
|
27
|
+
pluginCmd
|
|
28
|
+
.command("list")
|
|
29
|
+
.description("List registered Chomp plugins")
|
|
30
|
+
.action(() => {
|
|
31
|
+
const plugins = listChompPlugins();
|
|
32
|
+
console.log(`\n ${ansi.yellowBold("◆")} ${ansi.bold(`Registered Chomp Plugins (${plugins.length})`)}\n`);
|
|
33
|
+
for (const p of plugins) {
|
|
34
|
+
const tools = getPluginMcpToolSummaries(p).map((t) => t.name);
|
|
35
|
+
console.log(` • ${ansi.bold(p.name)} ${ansi.dim(`v${p.version}`)} → ${ansi.cyan(p.layer)} ${ansi.dim(`[${getPluginStateDirRel(p.name)}/]`)}`);
|
|
36
|
+
console.log(` ${ansi.dim(p.description)}`);
|
|
37
|
+
if (tools.length > 0) {
|
|
38
|
+
console.log(` ${ansi.dim("MCP Tools:")} ${tools.join(", ")}`);
|
|
39
|
+
}
|
|
40
|
+
console.log("");
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
pluginCmd
|
|
44
|
+
.command("run [pluginName] [path]")
|
|
45
|
+
.description("Run a Chomp plugin (e.g. 'design-system' or 'all') against a repository and persist EXTRACTED overlays to .chomp/graph.db")
|
|
46
|
+
.option("--db <path>", "Path to SQLite database file (default: <path>/.chomp/graph.db)")
|
|
47
|
+
.option("--json", "Output full plugin report as JSON", false)
|
|
48
|
+
.action(async (pluginNameOrPath, maybePath, options) => {
|
|
49
|
+
const baseDir = process.env.INIT_CWD ?? process.cwd();
|
|
50
|
+
let pluginName = "design-system";
|
|
51
|
+
let rawTargetPath = maybePath;
|
|
52
|
+
if (pluginNameOrPath) {
|
|
53
|
+
const matched = getChompPlugin(pluginNameOrPath);
|
|
54
|
+
if (matched || pluginNameOrPath.toLowerCase() === "all") {
|
|
55
|
+
pluginName = pluginNameOrPath.toLowerCase();
|
|
56
|
+
}
|
|
57
|
+
else if (!maybePath) {
|
|
58
|
+
rawTargetPath = pluginNameOrPath;
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
pluginName = pluginNameOrPath;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const { targetPath } = resolveDefaultCliTarget(rawTargetPath, baseDir, !options.json);
|
|
65
|
+
if (!existsSync(targetPath)) {
|
|
66
|
+
console.error(`Error: Path does not exist: ${targetPath}`);
|
|
67
|
+
process.exit(1);
|
|
68
|
+
}
|
|
69
|
+
const stat = statSync(targetPath);
|
|
70
|
+
const repoPath = stat.isDirectory() ? targetPath : dirname(targetPath);
|
|
71
|
+
const repoName = resolveRepoName(repoPath);
|
|
72
|
+
const repoId = repoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
73
|
+
const dbPath = options.db
|
|
74
|
+
? resolve(baseDir, options.db)
|
|
75
|
+
: resolve(repoPath, ".chomp", "graph.db");
|
|
76
|
+
if (!existsSync(dbPath)) {
|
|
77
|
+
await runAnalyze(repoPath, { db: dbPath, quiet: true });
|
|
78
|
+
}
|
|
79
|
+
const excludeWorkspaces = loadExcludeWorkspaces(repoPath);
|
|
80
|
+
if (pluginName === "all") {
|
|
81
|
+
const results = await runAllChompPlugins({
|
|
82
|
+
repoPath,
|
|
83
|
+
repoId,
|
|
84
|
+
repoName,
|
|
85
|
+
dbPath,
|
|
86
|
+
excludeWorkspaces,
|
|
87
|
+
persist: true,
|
|
88
|
+
});
|
|
89
|
+
if (options.json) {
|
|
90
|
+
console.log(JSON.stringify(results, null, 2));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
for (const r of results) {
|
|
94
|
+
printPluginRunSummary(r);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
const res = await runChompPlugin(pluginName, {
|
|
99
|
+
repoPath,
|
|
100
|
+
repoId,
|
|
101
|
+
repoName,
|
|
102
|
+
dbPath,
|
|
103
|
+
excludeWorkspaces,
|
|
104
|
+
persist: true,
|
|
105
|
+
});
|
|
106
|
+
if (options.json) {
|
|
107
|
+
console.log(JSON.stringify(res, null, 2));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
printPluginRunSummary(res);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
pluginCmd
|
|
114
|
+
.command("diff [path]")
|
|
115
|
+
.description("Compare working-tree Design System adherence against the pinned baseline snapshot (see `chomp plugin baseline`)")
|
|
116
|
+
.option("--db <path>", "Path to SQLite database file (default: <path>/.chomp/graph.db)")
|
|
117
|
+
.option("--baseline <path>", "Path to the baseline snapshot (default: designSystem.baseline.path)")
|
|
118
|
+
.option("--json", "Output diff report as JSON", false)
|
|
119
|
+
.action(async (inputPath, options) => {
|
|
120
|
+
const baseDir = process.env.INIT_CWD ?? process.cwd();
|
|
121
|
+
const { targetPath } = resolveDefaultCliTarget(inputPath, baseDir, !options.json);
|
|
122
|
+
if (!existsSync(targetPath)) {
|
|
123
|
+
console.error(`Error: Path does not exist: ${targetPath}`);
|
|
124
|
+
process.exit(1);
|
|
125
|
+
}
|
|
126
|
+
const stat = statSync(targetPath);
|
|
127
|
+
const repoPath = stat.isDirectory() ? targetPath : dirname(targetPath);
|
|
128
|
+
const repoName = resolveRepoName(repoPath);
|
|
129
|
+
const repoId = repoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
130
|
+
const dbPath = options.db
|
|
131
|
+
? resolve(baseDir, options.db)
|
|
132
|
+
: resolve(repoPath, ".chomp", "graph.db");
|
|
133
|
+
const diffRes = await diffDesignSystem({
|
|
134
|
+
repoPath,
|
|
135
|
+
repoId,
|
|
136
|
+
repoName,
|
|
137
|
+
dbPath,
|
|
138
|
+
baselinePath: options.baseline,
|
|
139
|
+
});
|
|
140
|
+
if (options.json) {
|
|
141
|
+
console.log(JSON.stringify(diffRes, null, 2));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const badge = diffRes.gateStatus === "PASS"
|
|
145
|
+
? ansi.green("PASS")
|
|
146
|
+
: diffRes.gateStatus === "NO_BASELINE"
|
|
147
|
+
? ansi.yellow("NO BASELINE (unknown, not a pass)")
|
|
148
|
+
: ansi.yellow("WARN");
|
|
149
|
+
console.log(`\n ${ansi.yellowBold("◆")} ${ansi.bold("Design System Diff Gate:")} ${badge}`);
|
|
150
|
+
console.log(` ${ansi.dim("New undefined var():")} ${diffRes.summary.newUndefinedTokenCount} · ${ansi.dim("New arbitrary Tw:")} ${diffRes.summary.newArbitraryTailwindCount} · ${ansi.dim("New hardcoded:")} ${diffRes.summary.newHardcodedLiteralCount} · ${ansi.dim("New raw atoms:")} ${diffRes.summary.newRawPrimitiveCount} · ${ansi.dim("Contrast failures:")} ${diffRes.summary.newContrastFailureCount}`);
|
|
151
|
+
console.log(` ${ansi.dim("Components improved:")} ${ansi.green(String(diffRes.summary.improvedComponentCount))} · ${ansi.dim("Components regressed:")} ${diffRes.summary.regressedComponentCount === 0
|
|
152
|
+
? "0"
|
|
153
|
+
: ansi.yellow(String(diffRes.summary.regressedComponentCount))}`);
|
|
154
|
+
for (const msg of diffRes.remediationGuidance) {
|
|
155
|
+
console.log(` • ${msg}`);
|
|
156
|
+
}
|
|
157
|
+
console.log("");
|
|
158
|
+
});
|
|
159
|
+
pluginCmd
|
|
160
|
+
.command("baseline [path]")
|
|
161
|
+
.description("Pin the current working tree as the Design System diff baseline snapshot (run on a clean checkout)")
|
|
162
|
+
.option("--db <path>", "Path to SQLite database file (default: <path>/.chomp/graph.db)")
|
|
163
|
+
.option("--out <path>", "Baseline file path (default: designSystem.baseline.path in chomp.config.json)")
|
|
164
|
+
.option("--json", "Output the snapshot totals as JSON", false)
|
|
165
|
+
.action(async (inputPath, options) => {
|
|
166
|
+
const baseDir = process.env.INIT_CWD ?? process.cwd();
|
|
167
|
+
const { targetPath } = resolveDefaultCliTarget(inputPath, baseDir, !options.json);
|
|
168
|
+
if (!existsSync(targetPath)) {
|
|
169
|
+
console.error(`Error: Path does not exist: ${targetPath}`);
|
|
170
|
+
process.exit(1);
|
|
171
|
+
}
|
|
172
|
+
const stat = statSync(targetPath);
|
|
173
|
+
const repoPath = stat.isDirectory() ? targetPath : dirname(targetPath);
|
|
174
|
+
const repoName = resolveRepoName(repoPath);
|
|
175
|
+
const repoId = repoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
176
|
+
const dbPath = options.db
|
|
177
|
+
? resolve(baseDir, options.db)
|
|
178
|
+
: resolve(repoPath, ".chomp", "graph.db");
|
|
179
|
+
const { path, snapshot, workingTree } = await snapshotDesignSystemBaseline({
|
|
180
|
+
repoPath,
|
|
181
|
+
repoId,
|
|
182
|
+
repoName,
|
|
183
|
+
dbPath: existsSync(dbPath) ? dbPath : undefined,
|
|
184
|
+
baselinePath: options.out,
|
|
185
|
+
});
|
|
186
|
+
if (options.json) {
|
|
187
|
+
console.log(JSON.stringify({ path, totals: snapshot.totals, createdAt: snapshot.createdAt }, null, 2));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (workingTree.clean === false) {
|
|
191
|
+
console.log(`\n ${ansi.yellow("!")} ${ansi.bold("Working tree is dirty")} in scope (${workingTree.dirtyFiles.slice(0, 5).join(", ")}${workingTree.dirtyFiles.length > 5 ? ", …" : ""}). Drift in those changes is now part of the baseline (recorded as workingTreeDirty). Re-pin from a clean checkout to avoid hiding it.`);
|
|
192
|
+
}
|
|
193
|
+
const total = Object.values(snapshot.totals).reduce((n, v) => n + v, 0);
|
|
194
|
+
console.log(`\n ${ansi.yellowBold("◆")} ${ansi.bold("Design System baseline pinned")} → ${ansi.cyan(path)}`);
|
|
195
|
+
console.log(` ${ansi.dim("Findings recorded:")} ${total} · ${ansi.dim("mode:")} ${snapshot.mode}${snapshot.commitSha ? ` · ${ansi.dim("commit:")} ${snapshot.commitSha.slice(0, 8)}` : ""}`);
|
|
196
|
+
console.log(` ${ansi.dim("Commit this file to share the baseline; `chomp plugin diff` only reports findings beyond it.")}\n`);
|
|
197
|
+
});
|
|
198
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import { createBuildStatusTracker, LAYOUT_BUILD_STAGES, type BuildStatusTracker, type LayoutBuildStageDef, type LayoutBuildStageId, type LayoutBuildStatusSnapshot } from "../server/buildStatusTracker.js";
|
|
3
|
+
import { buildLayout, getActiveUiTarget } from "../server/graphLayoutState.js";
|
|
4
|
+
import { isAllowedLocalhostOrigin, isLoopbackHostHeader } from "../server/loopbackSecurity.js";
|
|
5
|
+
import { type ResolvedCliTargetMode } from "../utils/masterContext.js";
|
|
6
|
+
export { LAYOUT_BUILD_STAGES, buildLayout, createBuildStatusTracker, getActiveUiTarget, isAllowedLocalhostOrigin, isLoopbackHostHeader, type BuildStatusTracker, type LayoutBuildStageDef, type LayoutBuildStageId, type LayoutBuildStatusSnapshot, };
|
|
7
|
+
export interface StartUiServerOptions {
|
|
8
|
+
port?: string | number;
|
|
9
|
+
host?: string;
|
|
10
|
+
db?: string;
|
|
11
|
+
open?: boolean;
|
|
12
|
+
watch?: boolean;
|
|
13
|
+
debug?: boolean;
|
|
14
|
+
cloudUrl?: string;
|
|
15
|
+
hostedUi?: string | boolean;
|
|
16
|
+
remote?: boolean;
|
|
17
|
+
targetMode?: ResolvedCliTargetMode;
|
|
18
|
+
}
|
|
19
|
+
export declare function startUiServer(targetPath: string, options?: StartUiServerOptions): Promise<void>;
|
|
20
|
+
export declare function registerUiCommand(program: Command): void;
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { existsSync, statSync, watch, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
3
|
+
import express from "express";
|
|
4
|
+
import { attachTtyBuildProgressSpinner, createBuildStatusTracker, LAYOUT_BUILD_STAGES, } from "../server/buildStatusTracker.js";
|
|
5
|
+
import { buildLayout, cancelActivePortHydration, createUiServerState, getActiveUiTarget, invalidateAllServerCaches, scheduleBackgroundPortHydration, } from "../server/graphLayoutState.js";
|
|
6
|
+
import { isAllowedLocalhostOrigin, isLoopbackHostHeader, registerLoopbackSecurityMiddleware, } from "../server/loopbackSecurity.js";
|
|
7
|
+
import { buildAuthStatusPayload, registerAuthAndSourceRoutes, } from "../server/routes/authSourceRoutes.js";
|
|
8
|
+
import { registerLayoutRoutes } from "../server/routes/layoutRoutes.js";
|
|
9
|
+
import { registerPluginRoutes } from "../server/routes/pluginRoutes.js";
|
|
10
|
+
import { registerViewAndRulesRoutes } from "../server/routes/viewRulesRoutes.js";
|
|
11
|
+
import { attachUiInteractiveHotkeys } from "../server/uiHotkeys.js";
|
|
12
|
+
import { ansi, openBrowserUrl } from "../utils/branding.js";
|
|
13
|
+
import { getGitInfoFromFs, isLinkedGitWorktree, resolveRepoName, } from "../utils/git.js";
|
|
14
|
+
import { resolveDefaultCliTarget, setActiveChompTarget, } from "../utils/masterContext.js";
|
|
15
|
+
import { DEFAULT_CLOUD_API_URL, DEFAULT_HOSTED_UI_URL, hasLocalMasterLayoutEngine, resolveLocalMasterWebDir, } from "../visualizer/localEngineBridge.js";
|
|
16
|
+
import { runAnalyze } from "./analyze.js";
|
|
17
|
+
export { LAYOUT_BUILD_STAGES, buildLayout, createBuildStatusTracker, getActiveUiTarget, isAllowedLocalhostOrigin, isLoopbackHostHeader, };
|
|
18
|
+
export async function startUiServer(targetPath, options = {}) {
|
|
19
|
+
const port = typeof options.port === "number"
|
|
20
|
+
? options.port
|
|
21
|
+
: parseInt(options.port ?? "5555", 10);
|
|
22
|
+
const baseDir = process.env.INIT_CWD ?? process.cwd();
|
|
23
|
+
const resolvedTarget = resolve(baseDir, targetPath);
|
|
24
|
+
const repoName = resolveRepoName(resolvedTarget);
|
|
25
|
+
const resolvedIsWorktree = isLinkedGitWorktree(resolvedTarget);
|
|
26
|
+
const pinToResolvedTarget = Boolean(options.db ||
|
|
27
|
+
resolvedIsWorktree ||
|
|
28
|
+
options.targetMode === "explicit" ||
|
|
29
|
+
options.targetMode === "worktree" ||
|
|
30
|
+
options.targetMode === "local");
|
|
31
|
+
const defaultDbDir = resolve(resolvedTarget, ".chomp");
|
|
32
|
+
const dbPath = options.db
|
|
33
|
+
? resolve(baseDir, options.db)
|
|
34
|
+
: resolve(defaultDbDir, "graph.db");
|
|
35
|
+
// Self-healing: if .chomp/graph.db does not exist yet, run initial extraction automatically ([PAT-CLI-13])
|
|
36
|
+
if (!existsSync(dbPath)) {
|
|
37
|
+
console.log(`\n ${ansi.yellowBold("◆")} No graph found at ${ansi.cyan(dbPath)} — running initial extraction...`);
|
|
38
|
+
await runAnalyze(resolvedTarget, { db: options.db });
|
|
39
|
+
}
|
|
40
|
+
else if (!options.db && !resolvedIsWorktree) {
|
|
41
|
+
setActiveChompTarget(resolvedTarget);
|
|
42
|
+
}
|
|
43
|
+
const app = express();
|
|
44
|
+
const host = options.host ?? process.env.CHOMP_UI_HOST ?? "127.0.0.1";
|
|
45
|
+
registerLoopbackSecurityMiddleware(app);
|
|
46
|
+
// Serve the local Next.js static export when running inside the master monorepo
|
|
47
|
+
const localWebDir = options.remote ? null : resolveLocalMasterWebDir();
|
|
48
|
+
if (localWebDir) {
|
|
49
|
+
const resolvedWebRoot = resolve(localWebDir);
|
|
50
|
+
app.use((req, res, next) => {
|
|
51
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
52
|
+
return next();
|
|
53
|
+
const cleanRel = req.path.replace(/^\/+|\/+$/g, "");
|
|
54
|
+
if (!cleanRel || cleanRel === "api" || cleanRel.startsWith("api/"))
|
|
55
|
+
return next();
|
|
56
|
+
if (/\/[^/]+\.[^/]+$/.test(`/${cleanRel}`) || cleanRel.includes(".."))
|
|
57
|
+
return next();
|
|
58
|
+
const htmlCandidate = resolve(resolvedWebRoot, `${cleanRel}.html`);
|
|
59
|
+
if (htmlCandidate.startsWith(`${resolvedWebRoot}${sep}`) &&
|
|
60
|
+
existsSync(htmlCandidate) &&
|
|
61
|
+
statSync(htmlCandidate).isFile()) {
|
|
62
|
+
return res.sendFile(htmlCandidate);
|
|
63
|
+
}
|
|
64
|
+
return next();
|
|
65
|
+
});
|
|
66
|
+
app.use(express.static(localWebDir, { redirect: false }));
|
|
67
|
+
}
|
|
68
|
+
const resolvedCloudApiUrl = (options.cloudUrl ??
|
|
69
|
+
process.env.CHOMP_LAYOUT_API_URL ??
|
|
70
|
+
DEFAULT_CLOUD_API_URL)
|
|
71
|
+
.trim()
|
|
72
|
+
.replace(/\/+$/, "");
|
|
73
|
+
const isMasterLocalMode = Boolean(!options.remote &&
|
|
74
|
+
!options.cloudUrl &&
|
|
75
|
+
!process.env.CHOMP_LAYOUT_API_URL &&
|
|
76
|
+
hasLocalMasterLayoutEngine());
|
|
77
|
+
const localDaemonUrl = `http://localhost:${port}`;
|
|
78
|
+
const rawHostedUi = options.hostedUi === true
|
|
79
|
+
? DEFAULT_HOSTED_UI_URL
|
|
80
|
+
: typeof options.hostedUi === "string" && options.hostedUi.trim()
|
|
81
|
+
? options.hostedUi.trim()
|
|
82
|
+
: process.env.CHOMP_HOSTED_UI_URL?.trim() ||
|
|
83
|
+
(!localWebDir ? DEFAULT_HOSTED_UI_URL : "");
|
|
84
|
+
const url = rawHostedUi
|
|
85
|
+
? `${rawHostedUi.replace(/\/+$/, "")}?port=${port}`
|
|
86
|
+
: localDaemonUrl;
|
|
87
|
+
const statusTracker = createBuildStatusTracker(repoName);
|
|
88
|
+
attachTtyBuildProgressSpinner(statusTracker);
|
|
89
|
+
const state = createUiServerState({
|
|
90
|
+
port,
|
|
91
|
+
resolvedTarget,
|
|
92
|
+
repoName,
|
|
93
|
+
dbPath,
|
|
94
|
+
explicitDbOption: options.db,
|
|
95
|
+
pinToResolvedTarget,
|
|
96
|
+
resolvedIsWorktree,
|
|
97
|
+
debug: Boolean(options.debug),
|
|
98
|
+
cloudUrl: options.cloudUrl,
|
|
99
|
+
remote: Boolean(options.remote),
|
|
100
|
+
resolvedCloudApiUrl,
|
|
101
|
+
isMasterLocalMode,
|
|
102
|
+
localWebDir,
|
|
103
|
+
localDaemonUrl,
|
|
104
|
+
url,
|
|
105
|
+
statusTracker,
|
|
106
|
+
});
|
|
107
|
+
// Register domain route controllers
|
|
108
|
+
registerAuthAndSourceRoutes(app, state);
|
|
109
|
+
registerLayoutRoutes(app, state);
|
|
110
|
+
registerViewAndRulesRoutes(app, state);
|
|
111
|
+
registerPluginRoutes(app, state);
|
|
112
|
+
// SPA fallback (or redirect to hosted UI in published NPM mode)
|
|
113
|
+
app.use((_req, res) => {
|
|
114
|
+
if (localWebDir) {
|
|
115
|
+
return res.sendFile(join(localWebDir, "index.html"));
|
|
116
|
+
}
|
|
117
|
+
return res.redirect(302, url);
|
|
118
|
+
});
|
|
119
|
+
const printServerBannerAndShortcuts = () => {
|
|
120
|
+
const { target: activeTarget, dbPath: activeDbPath } = getActiveUiTarget(state);
|
|
121
|
+
const activeBranch = getGitInfoFromFs(activeTarget).branchName;
|
|
122
|
+
const modeBadge = state.pinToResolvedTarget
|
|
123
|
+
? state.resolvedIsWorktree
|
|
124
|
+
? "Worktree · pinned"
|
|
125
|
+
: "Local · pinned"
|
|
126
|
+
: "Tethered · ~/.chomp/context.json";
|
|
127
|
+
console.log(`\n ${ansi.green("●")} ${ansi.bold("Chomp Map")} running at ${ansi.yellowBold(url)}`);
|
|
128
|
+
if (rawHostedUi) {
|
|
129
|
+
console.log(` ${ansi.dim("Local Daemon:")} ${localDaemonUrl}`);
|
|
130
|
+
}
|
|
131
|
+
const authSnap = buildAuthStatusPayload(state);
|
|
132
|
+
const initialAccessLine = isMasterLocalMode
|
|
133
|
+
? "Master Local (Unlimited)"
|
|
134
|
+
: authSnap.authenticated
|
|
135
|
+
? `Authenticated${authSnap.githubHandle ? ` (@${authSnap.githubHandle})` : ""} — Full repository unlocked`
|
|
136
|
+
: "Preview Mode (System Map + 100 stations — sign in with GitHub in browser to unlock full repo)";
|
|
137
|
+
console.log(` ${ansi.dim("Access:")} ${initialAccessLine}`);
|
|
138
|
+
console.log(` ${ansi.dim("Workspace:")} ${activeTarget}${activeBranch ? ` ${ansi.cyan(`(${activeBranch})`)}` : ""} ${ansi.dim(`[${modeBadge}]`)} ${ansi.dim("·")} ${ansi.dim("DB:")} ${activeDbPath}`);
|
|
139
|
+
if (options.watch) {
|
|
140
|
+
console.log(` ${ansi.cyan("👀")} Watching source files for structural changes...`);
|
|
141
|
+
}
|
|
142
|
+
if (process.stdin.isTTY) {
|
|
143
|
+
console.log(`\n ${ansi.dim("Shortcuts:")} ${ansi.bold("[o]")} open browser ${ansi.bold("[a]")} re-analyze graph ${ansi.bold("[h]")} health check`);
|
|
144
|
+
console.log(` ${ansi.bold("[c]")} clear console ${ansi.bold("[q]")} quit\n`);
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
console.log("");
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const server = app.listen(port, host, () => {
|
|
151
|
+
try {
|
|
152
|
+
const { dbPath: activeDbPath } = getActiveUiTarget(state);
|
|
153
|
+
const serverMetaPath = join(dirname(activeDbPath), "ui_server.json");
|
|
154
|
+
writeFileSync(serverMetaPath, JSON.stringify({
|
|
155
|
+
url,
|
|
156
|
+
port: Number(port),
|
|
157
|
+
updatedAt: new Date().toISOString(),
|
|
158
|
+
}, null, 2), "utf-8");
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
// Non-fatal if .chomp directory is read-only
|
|
162
|
+
}
|
|
163
|
+
printServerBannerAndShortcuts();
|
|
164
|
+
if (options.open) {
|
|
165
|
+
openBrowserUrl(url);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
server.keepAliveTimeout = 65_000;
|
|
169
|
+
server.headersTimeout = 66_000;
|
|
170
|
+
// Optional --watch mode: re-analyze automatically on source file changes (debounced)
|
|
171
|
+
let watchDebounce = null;
|
|
172
|
+
if (options.watch) {
|
|
173
|
+
try {
|
|
174
|
+
watch(resolvedTarget, { recursive: true }, (_eventType, filename) => {
|
|
175
|
+
if (!filename)
|
|
176
|
+
return;
|
|
177
|
+
const normalized = filename.replace(/\\/g, "/");
|
|
178
|
+
if (normalized.startsWith(".git/") ||
|
|
179
|
+
normalized.startsWith(".chomp/") ||
|
|
180
|
+
normalized.includes("node_modules/") ||
|
|
181
|
+
normalized.includes("/dist/") ||
|
|
182
|
+
normalized.includes("/.next/") ||
|
|
183
|
+
normalized.includes("/out/")) {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(normalized)) {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (watchDebounce)
|
|
190
|
+
clearTimeout(watchDebounce);
|
|
191
|
+
watchDebounce = setTimeout(async () => {
|
|
192
|
+
const { target: activeTarget } = getActiveUiTarget(state);
|
|
193
|
+
console.log(` ${ansi.cyan("↻")} File changed (${normalized}) — re-chomping graph...`);
|
|
194
|
+
cancelActivePortHydration(state);
|
|
195
|
+
await runAnalyze(activeTarget, {
|
|
196
|
+
db: options.db,
|
|
197
|
+
quiet: true,
|
|
198
|
+
});
|
|
199
|
+
invalidateAllServerCaches(state);
|
|
200
|
+
setImmediate(() => {
|
|
201
|
+
void scheduleBackgroundPortHydration(state, false);
|
|
202
|
+
});
|
|
203
|
+
console.log(` ${ansi.green("✓")} Graph updated for ${ansi.yellowBold(url)}`);
|
|
204
|
+
}, 450);
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
// Recursive fs.watch may not be supported on all platforms
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
// Interactive Hotkey Loop & OS Signal Lifecycle (runs heavy commands in child processes)
|
|
212
|
+
attachUiInteractiveHotkeys({
|
|
213
|
+
url,
|
|
214
|
+
dbOption: options.db,
|
|
215
|
+
getActiveTarget: () => getActiveUiTarget(state),
|
|
216
|
+
onPrintBanner: printServerBannerAndShortcuts,
|
|
217
|
+
onOpenBrowser: openBrowserUrl,
|
|
218
|
+
onAfterAnalyze: () => {
|
|
219
|
+
cancelActivePortHydration(state);
|
|
220
|
+
invalidateAllServerCaches(state);
|
|
221
|
+
setImmediate(() => {
|
|
222
|
+
void scheduleBackgroundPortHydration(state, false);
|
|
223
|
+
});
|
|
224
|
+
},
|
|
225
|
+
onShutdown: () => {
|
|
226
|
+
cancelActivePortHydration(state);
|
|
227
|
+
console.log(`\n ${ansi.dim("Shutting down Chomp Map...")}`);
|
|
228
|
+
server.close(() => process.exit(0));
|
|
229
|
+
setTimeout(() => process.exit(0), 300).unref();
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
export function registerUiCommand(program) {
|
|
234
|
+
program
|
|
235
|
+
.command("ui [path]")
|
|
236
|
+
.description("Start the local Chomp server and open Chomp Map (defaults to active connected repo or current directory)")
|
|
237
|
+
.option("-p, --port <number>", "Port to run the local server on", "5555")
|
|
238
|
+
.option("--db <path>", "Path to SQLite database file (default: <path>/.chomp/graph.db)")
|
|
239
|
+
.option("-o, --open", "Automatically open Chomp Map in your browser", false)
|
|
240
|
+
.option("-w, --watch", "Watch source files and automatically re-analyze on changes", false)
|
|
241
|
+
.option("--debug", "Write matrix_debug.csv and layout_debug.csv debug artifacts", false)
|
|
242
|
+
.option("--cloud-url <url>", "Stateless Cloudflare Layout Worker URL (or set CHOMP_LAYOUT_API_URL, e.g. https://api.getchomp.dev)")
|
|
243
|
+
.option("--hosted-ui [url]", "Open the hosted Chomp Map app (defaults to https://app.getchomp.dev?port=<port>)")
|
|
244
|
+
.option("--remote", "Simulate published NPM cloud mode against https://api.getchomp.dev & https://app.getchomp.dev", false)
|
|
245
|
+
.action(async (inputPath, options) => {
|
|
246
|
+
const baseDir = process.env.INIT_CWD ?? process.cwd();
|
|
247
|
+
const { targetPath, mode } = resolveDefaultCliTarget(inputPath, baseDir, true);
|
|
248
|
+
await startUiServer(targetPath, { ...options, targetMode: mode });
|
|
249
|
+
});
|
|
250
|
+
}
|