create-backon 0.13.3 → 0.14.1

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/src/tui.ts ADDED
@@ -0,0 +1,336 @@
1
+ import { emitKeypressEvents, type Key } from "node:readline";
2
+ import type { EndpointSummary } from "./route-methods";
3
+ import type { ParsedTable } from "./schema-edit";
4
+ import type { DoctorIssue } from "./doctor";
5
+ import type { DbStatus } from "./db-status";
6
+
7
+ export type TuiTab = "endpoints" | "tables" | "doctor";
8
+
9
+ export interface TuiSnapshot {
10
+ root: string;
11
+ framework: string;
12
+ language: string;
13
+ dbStatus: DbStatus;
14
+ schemaCapable: boolean;
15
+ endpoints: EndpointSummary[];
16
+ tables: ParsedTable[];
17
+ issues: DoctorIssue[];
18
+ }
19
+
20
+ export interface TuiState {
21
+ tab: TuiTab;
22
+ selectedIndex: number;
23
+ statusMessage?: string;
24
+ }
25
+
26
+ export interface TuiActions {
27
+ loadSnapshot: () => Promise<TuiSnapshot>;
28
+ addEndpoint: () => Promise<void>;
29
+ removeEndpoint: (endpoint: EndpointSummary | undefined) => Promise<void>;
30
+ addCrud: (endpoint: EndpointSummary | undefined) => Promise<void>;
31
+ addMethod: (endpoint: EndpointSummary | undefined) => Promise<void>;
32
+ modifyMethod: (endpoint: EndpointSummary | undefined) => Promise<void>;
33
+ removeMethod: (endpoint: EndpointSummary | undefined) => Promise<void>;
34
+ addTable: (tables: ParsedTable[]) => Promise<void>;
35
+ addJunctionTable: (tables: ParsedTable[]) => Promise<void>;
36
+ addColumn: (table: ParsedTable | undefined, tables: ParsedTable[]) => Promise<void>;
37
+ removeTable: (table: ParsedTable | undefined, tables: ParsedTable[]) => Promise<void>;
38
+ generateClient: () => Promise<string>;
39
+ generateDocs: () => Promise<string>;
40
+ }
41
+
42
+ const ANSI_RESET = "\x1b[0m";
43
+ const ANSI_BOLD = "\x1b[1m";
44
+ const ANSI_DIM = "\x1b[2m";
45
+ const ANSI_CYAN = "\x1b[36m";
46
+ const ANSI_GREEN = "\x1b[32m";
47
+ const ANSI_YELLOW = "\x1b[33m";
48
+ const ANSI_RED = "\x1b[31m";
49
+ const ANSI_INVERSE = "\x1b[7m";
50
+ const ANSI_REGEX = /\x1b\[[0-9;]*m/g;
51
+
52
+ function visibleLength(text: string): number {
53
+ return text.replace(ANSI_REGEX, "").length;
54
+ }
55
+
56
+ function padOrTruncate(text: string, width: number): string {
57
+ const len = visibleLength(text);
58
+ if (len === width) return text;
59
+ if (len < width) return text + " ".repeat(width - len);
60
+ const plain = text.replace(ANSI_REGEX, "");
61
+ return width <= 1 ? plain.slice(0, width) : plain.slice(0, width - 1) + "…";
62
+ }
63
+
64
+ function verbBadge(verb: string): string {
65
+ const upper = verb.toUpperCase().padEnd(6);
66
+ if (verb === "get") return `${ANSI_GREEN}${upper}${ANSI_RESET}`;
67
+ if (verb === "post") return `${ANSI_CYAN}${upper}${ANSI_RESET}`;
68
+ if (verb === "put" || verb === "patch") return `${ANSI_YELLOW}${upper}${ANSI_RESET}`;
69
+ if (verb === "delete") return `${ANSI_RED}${upper}${ANSI_RESET}`;
70
+ return upper;
71
+ }
72
+
73
+ export function itemCountForTab(snapshot: TuiSnapshot, tab: TuiTab): number {
74
+ if (tab === "endpoints") return snapshot.endpoints.length;
75
+ if (tab === "tables") return snapshot.tables.length;
76
+ return Math.max(1, snapshot.issues.length);
77
+ }
78
+
79
+ export function clampSelection(snapshot: TuiSnapshot, state: TuiState): TuiState {
80
+ const count = itemCountForTab(snapshot, state.tab);
81
+ const maxIndex = Math.max(0, count - 1);
82
+ const selectedIndex = Math.min(Math.max(0, state.selectedIndex), maxIndex);
83
+ return selectedIndex === state.selectedIndex ? state : { ...state, selectedIndex };
84
+ }
85
+
86
+ const TABS: TuiTab[] = ["endpoints", "tables", "doctor"];
87
+
88
+ export function nextTab(current: TuiTab, delta: 1 | -1): TuiTab {
89
+ const idx = TABS.indexOf(current);
90
+ return TABS[(idx + delta + TABS.length) % TABS.length]!;
91
+ }
92
+
93
+ /** Pure renderer producing a complete terminal frame for testing and live drawing. */
94
+ export function renderTuiFrame(snapshot: TuiSnapshot, rawState: TuiState, width = 96, height = 26): string {
95
+ const state = clampSelection(snapshot, rawState);
96
+ const cols = Math.max(60, width);
97
+ const rows = Math.max(16, height);
98
+ const leftWidth = Math.max(24, Math.min(36, Math.floor(cols * 0.36)));
99
+ const rightWidth = cols - leftWidth - 3;
100
+
101
+ const tabPill = (tab: TuiTab, label: string) =>
102
+ state.tab === tab ? `${ANSI_INVERSE}${ANSI_BOLD} ${label} ${ANSI_RESET}` : `${ANSI_DIM} ${label} ${ANSI_RESET}`;
103
+
104
+ const header =
105
+ `${ANSI_BOLD}${ANSI_CYAN}backon server-config${ANSI_RESET} ${ANSI_DIM}${snapshot.framework} · ${snapshot.dbStatus.driver} · ${snapshot.root}${ANSI_RESET}`;
106
+ const tabBar = [
107
+ tabPill("endpoints", `1 Endpoints (${snapshot.endpoints.length})`),
108
+ tabPill("tables", `2 Tables (${snapshot.tables.length})`),
109
+ tabPill("doctor", `3 Doctor (${snapshot.issues.length})`),
110
+ ].join(" ");
111
+ const rule = `${ANSI_DIM}${"─".repeat(cols)}${ANSI_RESET}`;
112
+
113
+ const leftLines: string[] = [];
114
+ const rightLines: string[] = [];
115
+
116
+ if (state.tab === "endpoints") {
117
+ if (snapshot.endpoints.length === 0) {
118
+ leftLines.push(`${ANSI_DIM}(no endpoints yet)${ANSI_RESET}`);
119
+ rightLines.push(`${ANSI_BOLD}No endpoints mounted${ANSI_RESET}`, "", "Press [a] to add your first endpoint.");
120
+ } else {
121
+ snapshot.endpoints.forEach((ep, i) => {
122
+ const selected = i === state.selectedIndex;
123
+ const prefix = selected ? `${ANSI_CYAN}▸${ANSI_RESET} ` : " ";
124
+ const label = `${prefix}/${ep.route} ${ANSI_DIM}(${ep.methods.length})${ANSI_RESET}`;
125
+ leftLines.push(selected ? `${ANSI_BOLD}${label}${ANSI_RESET}` : label);
126
+ });
127
+ const active = snapshot.endpoints[state.selectedIndex];
128
+ if (active) {
129
+ rightLines.push(`${ANSI_BOLD}Endpoint: /${active.route}${ANSI_RESET}`, "");
130
+ if (active.methods.length === 0) {
131
+ rightLines.push(`${ANSI_DIM}No methods yet. Press [n] to add one or [c] for CRUD.${ANSI_RESET}`);
132
+ } else {
133
+ for (const m of active.methods) {
134
+ rightLines.push(`${verbBadge(m.verb)} ${m.path.padEnd(18)} ${ANSI_DIM}→ ${m.name}()${ANSI_RESET}`);
135
+ }
136
+ }
137
+ }
138
+ }
139
+ } else if (state.tab === "tables") {
140
+ if (!snapshot.schemaCapable) {
141
+ leftLines.push(`${ANSI_DIM}(schema disabled)${ANSI_RESET}`);
142
+ rightLines.push(
143
+ `${ANSI_YELLOW}Schema editor requires Neon or Postgres${ANSI_RESET}`,
144
+ "",
145
+ `Current db driver: ${snapshot.dbStatus.driver}`
146
+ );
147
+ } else if (snapshot.tables.length === 0) {
148
+ leftLines.push(`${ANSI_DIM}(no tables yet)${ANSI_RESET}`);
149
+ rightLines.push(
150
+ `${ANSI_BOLD}No tables in schema${ANSI_RESET}`,
151
+ "",
152
+ "Press [a] to create a table, or [m] for a junction table once 2+ tables exist."
153
+ );
154
+ } else {
155
+ snapshot.tables.forEach((tbl, i) => {
156
+ const selected = i === state.selectedIndex;
157
+ const prefix = selected ? `${ANSI_CYAN}▸${ANSI_RESET} ` : " ";
158
+ const tag = tbl.isJunction ? " [M:N]" : ` (${tbl.columns.length})`;
159
+ const label = `${prefix}${tbl.identifier}${ANSI_DIM}${tag}${ANSI_RESET}`;
160
+ leftLines.push(selected ? `${ANSI_BOLD}${label}${ANSI_RESET}` : label);
161
+ });
162
+ const active = snapshot.tables[state.selectedIndex];
163
+ if (active) {
164
+ const kind = active.isJunction ? ` ${ANSI_CYAN}[junction table]${ANSI_RESET}` : "";
165
+ rightLines.push(`${ANSI_BOLD}${active.identifier}${ANSI_RESET} ${ANSI_DIM}(${active.sqlName})${ANSI_RESET}${kind}`, "");
166
+ for (const c of active.columns) {
167
+ const typeText = c.type ? ` : ${c.type}` : "";
168
+ const refText = c.references ? ` ${ANSI_CYAN}→ ${c.references}.id${ANSI_RESET}` : "";
169
+ rightLines.push(` • ${c.key}${ANSI_DIM}${typeText}${ANSI_RESET}${refText}`);
170
+ }
171
+ }
172
+ }
173
+ } else {
174
+ if (snapshot.issues.length === 0) {
175
+ leftLines.push(`${ANSI_GREEN}✓ Healthy${ANSI_RESET}`);
176
+ rightLines.push(
177
+ `${ANSI_GREEN}${ANSI_BOLD}All endpoint & schema checks passed${ANSI_RESET}`,
178
+ "",
179
+ `Database: ${snapshot.dbStatus.summary}`,
180
+ "",
181
+ "Quick tools:",
182
+ " [g] Run bun run generate-client",
183
+ " [o] Run bun run docs (OpenAPI + Scalar)"
184
+ );
185
+ } else {
186
+ snapshot.issues.forEach((issue, i) => {
187
+ const selected = i === state.selectedIndex;
188
+ const prefix = selected ? `${ANSI_YELLOW}▸${ANSI_RESET} ` : " ";
189
+ leftLines.push(`${prefix}${ANSI_YELLOW}!${ANSI_RESET} ${issue.detail}`);
190
+ });
191
+ const active = snapshot.issues[state.selectedIndex];
192
+ if (active) {
193
+ rightLines.push(`${ANSI_YELLOW}${ANSI_BOLD}Doctor Issue${ANSI_RESET}`, "", active.detail);
194
+ }
195
+ }
196
+ }
197
+
198
+ const bodyRows = Math.max(6, rows - 6);
199
+ const body: string[] = [];
200
+ for (let r = 0; r < bodyRows; r++) {
201
+ const l = padOrTruncate(leftLines[r] ?? "", leftWidth);
202
+ const rt = padOrTruncate(rightLines[r] ?? "", rightWidth);
203
+ body.push(`${l} ${ANSI_DIM}│${ANSI_RESET} ${rt}`);
204
+ }
205
+
206
+ const shortcuts =
207
+ state.tab === "endpoints"
208
+ ? "[a] Add endpoint [c] Add CRUD [n] Add method [m] Modify [x] Rm method [d] Rm endpoint"
209
+ : state.tab === "tables"
210
+ ? "[a] Add table [m] Junction (M:N) [c] Add column [d] Remove table"
211
+ : "[g] Generate client [o] Generate docs [r] Re-run doctor";
212
+
213
+ const statusLine = state.statusMessage ? `${ANSI_CYAN}${state.statusMessage}${ANSI_RESET}` : `${ANSI_DIM}↑/↓ Move Tab/1-3 Switch r Refresh q Quit${ANSI_RESET}`;
214
+ const footer = `${ANSI_DIM}${shortcuts}${ANSI_RESET}\n${statusLine}`;
215
+
216
+ return [padOrTruncate(header, cols), padOrTruncate(tabBar, cols), rule, ...body, rule, footer].join("\n");
217
+ }
218
+
219
+ function enterAltScreen(): void {
220
+ process.stdout.write("\x1b[?1049h\x1b[?25l");
221
+ }
222
+
223
+ function exitAltScreen(): void {
224
+ process.stdout.write("\x1b[?25h\x1b[?1049l");
225
+ }
226
+
227
+ async function waitForAnyKey(): Promise<void> {
228
+ process.stdout.write(`\n${ANSI_DIM}Press any key to return to server-config...${ANSI_RESET}`);
229
+ await new Promise<void>((resolve) => {
230
+ const wasRaw = process.stdin.isRaw;
231
+ process.stdin.setRawMode(true);
232
+ process.stdin.resume();
233
+ const onData = () => {
234
+ process.stdin.removeListener("data", onData);
235
+ if (!wasRaw) process.stdin.setRawMode(false);
236
+ resolve();
237
+ };
238
+ process.stdin.once("data", onData);
239
+ });
240
+ }
241
+
242
+ /** Runs an interactive full-screen keyboard TUI around server-config actions. */
243
+ export async function runServerConfigTui(actions: TuiActions): Promise<void> {
244
+ let snapshot = await actions.loadSnapshot();
245
+ let state: TuiState = { tab: "endpoints", selectedIndex: 0 };
246
+
247
+ emitKeypressEvents(process.stdin);
248
+ enterAltScreen();
249
+
250
+ const draw = () => {
251
+ const width = process.stdout.columns || 96;
252
+ const height = process.stdout.rows || 26;
253
+ process.stdout.write("\x1b[H\x1b[2J" + renderTuiFrame(snapshot, state, width, height));
254
+ };
255
+
256
+ const runInteractive = async (fn: () => Promise<string | void>) => {
257
+ process.stdin.setRawMode(false);
258
+ exitAltScreen();
259
+ try {
260
+ const msg = await fn();
261
+ snapshot = await actions.loadSnapshot();
262
+ state = clampSelection(snapshot, { ...state, statusMessage: msg || undefined });
263
+ } catch (err) {
264
+ state = { ...state, statusMessage: `Error: ${err instanceof Error ? err.message : String(err)}` };
265
+ await waitForAnyKey();
266
+ }
267
+ enterAltScreen();
268
+ process.stdin.setRawMode(true);
269
+ process.stdin.resume();
270
+ draw();
271
+ };
272
+
273
+ try {
274
+ process.stdin.setRawMode(true);
275
+ process.stdin.resume();
276
+ draw();
277
+
278
+ await new Promise<void>((resolve) => {
279
+ const onResize = () => draw();
280
+ const cleanup = () => {
281
+ process.stdin.removeListener("keypress", onKeypress);
282
+ process.stdout.removeListener("resize", onResize);
283
+ };
284
+
285
+ const onKeypress = async (str: string, key: Key) => {
286
+ if ((key.ctrl && key.name === "c") || key.name === "escape" || str === "q") {
287
+ cleanup();
288
+ resolve();
289
+ return;
290
+ }
291
+
292
+ if (str === "1") state = clampSelection(snapshot, { tab: "endpoints", selectedIndex: 0 });
293
+ else if (str === "2") state = clampSelection(snapshot, { tab: "tables", selectedIndex: 0 });
294
+ else if (str === "3") state = clampSelection(snapshot, { tab: "doctor", selectedIndex: 0 });
295
+ else if (key.name === "tab" || key.name === "right") {
296
+ state = clampSelection(snapshot, { tab: nextTab(state.tab, 1), selectedIndex: 0 });
297
+ } else if (key.name === "left") {
298
+ state = clampSelection(snapshot, { tab: nextTab(state.tab, -1), selectedIndex: 0 });
299
+ } else if (key.name === "up" || str === "k") {
300
+ state = clampSelection(snapshot, { ...state, selectedIndex: state.selectedIndex - 1 });
301
+ } else if (key.name === "down" || str === "j") {
302
+ state = clampSelection(snapshot, { ...state, selectedIndex: state.selectedIndex + 1 });
303
+ } else if (str === "r") {
304
+ snapshot = await actions.loadSnapshot();
305
+ state = clampSelection(snapshot, { ...state, statusMessage: "Refreshed." });
306
+ } else if (state.tab === "endpoints") {
307
+ const current = snapshot.endpoints[state.selectedIndex];
308
+ if (str === "a") await runInteractive(() => actions.addEndpoint());
309
+ else if (str === "d") await runInteractive(() => actions.removeEndpoint(current));
310
+ else if (str === "c") await runInteractive(() => actions.addCrud(current));
311
+ else if (str === "n") await runInteractive(() => actions.addMethod(current));
312
+ else if (str === "m") await runInteractive(() => actions.modifyMethod(current));
313
+ else if (str === "x") await runInteractive(() => actions.removeMethod(current));
314
+ } else if (state.tab === "tables") {
315
+ const current = snapshot.tables[state.selectedIndex];
316
+ if (str === "a") await runInteractive(() => actions.addTable(snapshot.tables));
317
+ else if (str === "m") await runInteractive(() => actions.addJunctionTable(snapshot.tables));
318
+ else if (str === "c") await runInteractive(() => actions.addColumn(current, snapshot.tables));
319
+ else if (str === "d") await runInteractive(() => actions.removeTable(current, snapshot.tables));
320
+ } else if (state.tab === "doctor") {
321
+ if (str === "g") await runInteractive(() => actions.generateClient());
322
+ else if (str === "o") await runInteractive(() => actions.generateDocs());
323
+ }
324
+
325
+ draw();
326
+ };
327
+
328
+ process.stdin.on("keypress", onKeypress);
329
+ process.stdout.on("resize", onResize);
330
+ });
331
+ } finally {
332
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
333
+ process.stdin.pause();
334
+ exitAltScreen();
335
+ }
336
+ }