create-backon 0.14.0 → 0.15.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 +626 -418
- package/package.json +5 -2
- package/src/cli.ts +323 -340
- package/src/prompts.ts +10 -1
- package/src/schema-edit.ts +25 -12
- package/src/templates/base.ts +14 -7
- package/src/templates/schema.ts +5 -2
- package/src/tui.ts +410 -73
package/dist/cli.js
CHANGED
|
@@ -88,7 +88,16 @@ async function runPrompts() {
|
|
|
88
88
|
});
|
|
89
89
|
if (p.isCancel(name)) bail();
|
|
90
90
|
if (!name) break;
|
|
91
|
-
|
|
91
|
+
const kebab = toKebabCase(name);
|
|
92
|
+
if (!kebab) {
|
|
93
|
+
p.log.warn("Route name can't be empty.");
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (routes.includes(kebab)) {
|
|
97
|
+
p.log.warn(`"${kebab}" was already added \u2014 skipping duplicate.`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
routes.push(kebab);
|
|
92
101
|
}
|
|
93
102
|
p.outro(`Scaffolding ${projectName}...`);
|
|
94
103
|
return {
|
|
@@ -379,7 +388,7 @@ export const app = createApp();
|
|
|
379
388
|
app.use(exampleMiddleware);
|
|
380
389
|
app.use("/", endpoints);
|
|
381
390
|
|
|
382
|
-
serveApiDocs(app, "/docs", { title:
|
|
391
|
+
serveApiDocs(app, "/docs", { title: ${JSON.stringify(projectName)} });
|
|
383
392
|
${defaultExport}`;
|
|
384
393
|
}
|
|
385
394
|
return `${detectionImport}import { createApp, serveApiDocs } from "@mednours/backon";
|
|
@@ -391,7 +400,7 @@ export const app = createApp();
|
|
|
391
400
|
app.use("*", exampleMiddleware);
|
|
392
401
|
app.route("/", endpoints);
|
|
393
402
|
|
|
394
|
-
serveApiDocs(app, "/docs", { title:
|
|
403
|
+
serveApiDocs(app, "/docs", { title: ${JSON.stringify(projectName)} });
|
|
395
404
|
${defaultExport}`;
|
|
396
405
|
}
|
|
397
406
|
function renderVercelJson(framework) {
|
|
@@ -513,9 +522,9 @@ function renderGenerateDocsScript(projectName, framework) {
|
|
|
513
522
|
import { generateOpenApiSpec, apiReferenceHtmlInline } from "${backonImport}";
|
|
514
523
|
import { app } from "../src/app";
|
|
515
524
|
|
|
516
|
-
const spec = generateOpenApiSpec(app, { title:
|
|
525
|
+
const spec = generateOpenApiSpec(app, { title: ${JSON.stringify(projectName)}, version: "0.1.0" });
|
|
517
526
|
writeFileSync("openapi.json", JSON.stringify(spec, null, 2));
|
|
518
|
-
writeFileSync("docs.html", apiReferenceHtmlInline(spec,
|
|
527
|
+
writeFileSync("docs.html", apiReferenceHtmlInline(spec, ${JSON.stringify(projectName)}));
|
|
519
528
|
|
|
520
529
|
console.log("Wrote openapi.json and docs.html");
|
|
521
530
|
`;
|
|
@@ -598,8 +607,8 @@ for (const route of routes) {
|
|
|
598
607
|
verb: m[1],
|
|
599
608
|
path: m[2],
|
|
600
609
|
name: m[3],
|
|
601
|
-
needsBody:
|
|
602
|
-
needsQuery:
|
|
610
|
+
needsBody: new RegExp("export\\\\s+const\\\\s+" + m[3] + "BodySchema\\\\b").test(controllerContents),
|
|
611
|
+
needsQuery: new RegExp("export\\\\s+const\\\\s+" + m[3] + "QuerySchema\\\\b").test(controllerContents),
|
|
603
612
|
}));
|
|
604
613
|
if (methods.length > 0) groups.push({ route, methods });
|
|
605
614
|
}
|
|
@@ -630,14 +639,21 @@ const helperLines = [
|
|
|
630
639
|
'const BASE_URL = (typeof process !== "undefined" && process.env.API_BASE_URL) || "";',
|
|
631
640
|
"",
|
|
632
641
|
TYPED ? "async function request<T>(path: string, init?: RequestInit): Promise<T> {" : "async function request(path, init) {",
|
|
642
|
+
" const headers = {",
|
|
643
|
+
' ...(init && init.body !== undefined ? { "Content-Type": "application/json" } : {}),',
|
|
644
|
+
" ...(init && init.headers ? init.headers : {}),",
|
|
645
|
+
" };",
|
|
633
646
|
" const res = await fetch(BASE_URL + path, {",
|
|
634
647
|
" ...init,",
|
|
635
|
-
|
|
648
|
+
" headers,",
|
|
636
649
|
" });",
|
|
637
650
|
" if (!res.ok) {",
|
|
638
651
|
TYPED ? " const errBody: any = await res.json().catch(() => undefined);" : " const errBody = await res.json().catch(() => undefined);",
|
|
639
652
|
' throw new Error((errBody && errBody.error && errBody.error.message) || ("Request to " + path + " failed with " + res.status));',
|
|
640
653
|
" }",
|
|
654
|
+
' if (res.status === 204 || res.headers.get("content-length") === "0") {',
|
|
655
|
+
TYPED ? " return undefined as T;" : " return undefined;",
|
|
656
|
+
" }",
|
|
641
657
|
TYPED ? " return res.json() as Promise<T>;" : " return res.json();",
|
|
642
658
|
"}",
|
|
643
659
|
];
|
|
@@ -981,7 +997,7 @@ function requiredBuilders(table) {
|
|
|
981
997
|
if (table.includeTimestamps) builders.add("timestamp");
|
|
982
998
|
if (table.compositePrimaryKey?.length) builders.add("primaryKey");
|
|
983
999
|
for (const col of table.columns) {
|
|
984
|
-
builders.add(col.references ? "integer" : col.type);
|
|
1000
|
+
builders.add(col.references ? col.referenceType ?? "integer" : col.type);
|
|
985
1001
|
}
|
|
986
1002
|
return builders;
|
|
987
1003
|
}
|
|
@@ -990,7 +1006,8 @@ function renderColumnExpression(col) {
|
|
|
990
1006
|
let expr;
|
|
991
1007
|
if (col.references) {
|
|
992
1008
|
const refOpts = col.onDelete ? `, { onDelete: "${col.onDelete}" }` : "";
|
|
993
|
-
|
|
1009
|
+
const fkBuilder = col.referenceType ?? "integer";
|
|
1010
|
+
expr = `${fkBuilder}("${sqlName}").references(() => ${col.references}.id${refOpts})`;
|
|
994
1011
|
} else if (col.type === "varchar") {
|
|
995
1012
|
const length = col.varcharLength ?? 255;
|
|
996
1013
|
expr = `varchar("${sqlName}", { length: ${length} })`;
|
|
@@ -1872,6 +1889,17 @@ async function readSchemaFile(root, ext) {
|
|
|
1872
1889
|
throw err;
|
|
1873
1890
|
}
|
|
1874
1891
|
}
|
|
1892
|
+
function resolveReferenceType(tables, targetIdentifier, colName) {
|
|
1893
|
+
const target = tables.find((t) => t.identifier === targetIdentifier);
|
|
1894
|
+
if (!target) {
|
|
1895
|
+
throw new Error(`Column "${colName}" references unknown table "${targetIdentifier}".`);
|
|
1896
|
+
}
|
|
1897
|
+
const idCol = target.columns.find((c) => c.key === "id");
|
|
1898
|
+
if (!idCol) {
|
|
1899
|
+
throw new Error(`Table "${targetIdentifier}" has no "id" column for "${colName}" to reference.`);
|
|
1900
|
+
}
|
|
1901
|
+
return idCol.type === "uuid" ? "uuid" : "integer";
|
|
1902
|
+
}
|
|
1875
1903
|
async function addTable(spec, cwd = process.cwd()) {
|
|
1876
1904
|
await requireNeonOrPostgres(cwd);
|
|
1877
1905
|
const { root, ext } = await detectProject(cwd);
|
|
@@ -1881,15 +1909,14 @@ async function addTable(spec, cwd = process.cwd()) {
|
|
|
1881
1909
|
if (existingTables.some((t) => t.identifier === identifier)) {
|
|
1882
1910
|
throw new Error(`"${identifier}" is already a table in ${path}.`);
|
|
1883
1911
|
}
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
}
|
|
1912
|
+
const normalizedColumns = spec.columns.map(
|
|
1913
|
+
(col) => col.references ? { ...col, referenceType: col.referenceType ?? resolveReferenceType(existingTables, col.references, col.name) } : col
|
|
1914
|
+
);
|
|
1915
|
+
const normalizedSpec = { ...spec, columns: normalizedColumns };
|
|
1889
1916
|
const withoutPlaceholder = contents.includes(renderBlankSchema()) ? contents.replace(renderBlankSchema(), "") : contents;
|
|
1890
1917
|
const updated = editSource(path, withoutPlaceholder, (_project, sourceFile) => {
|
|
1891
|
-
ensurePgCoreImport(sourceFile, requiredBuilders(
|
|
1892
|
-
appendStatements(sourceFile, renderTableBlock(
|
|
1918
|
+
ensurePgCoreImport(sourceFile, requiredBuilders(normalizedSpec));
|
|
1919
|
+
appendStatements(sourceFile, renderTableBlock(normalizedSpec));
|
|
1893
1920
|
});
|
|
1894
1921
|
await writeFile6(path, updated);
|
|
1895
1922
|
return { root, identifier, filePath: path };
|
|
@@ -1908,11 +1935,9 @@ async function addColumn(table, col, cwd = process.cwd()) {
|
|
|
1908
1935
|
if (target.columns.some((c) => c.key === columnKey)) {
|
|
1909
1936
|
throw new Error(`Column "${columnKey}" already exists on table "${target.identifier}".`);
|
|
1910
1937
|
}
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
const builder = col.references ? "integer" : col.type;
|
|
1915
|
-
const initializer = renderColumnExpression(col);
|
|
1938
|
+
const normalizedCol = col.references ? { ...col, referenceType: col.referenceType ?? resolveReferenceType(existingTables, col.references, col.name) } : col;
|
|
1939
|
+
const builder = normalizedCol.references ? normalizedCol.referenceType ?? "integer" : normalizedCol.type;
|
|
1940
|
+
const initializer = renderColumnExpression(normalizedCol);
|
|
1916
1941
|
const updated = editSource(path, contents, (_project, sourceFile) => {
|
|
1917
1942
|
ensurePgCoreImport(sourceFile, /* @__PURE__ */ new Set([builder]));
|
|
1918
1943
|
const columnsObj = findTableColumnsObject(sourceFile, target.identifier);
|
|
@@ -1968,6 +1993,7 @@ async function removeTable(identifier, cwd = process.cwd()) {
|
|
|
1968
1993
|
|
|
1969
1994
|
// src/tui.ts
|
|
1970
1995
|
import { emitKeypressEvents } from "node:readline";
|
|
1996
|
+
var TUI_CANCEL = /* @__PURE__ */ Symbol("tui-cancel");
|
|
1971
1997
|
var ANSI_RESET = "\x1B[0m";
|
|
1972
1998
|
var ANSI_BOLD = "\x1B[1m";
|
|
1973
1999
|
var ANSI_DIM = "\x1B[2m";
|
|
@@ -1987,6 +2013,25 @@ function padOrTruncate(text3, width) {
|
|
|
1987
2013
|
const plain = text3.replace(ANSI_REGEX, "");
|
|
1988
2014
|
return width <= 1 ? plain.slice(0, width) : plain.slice(0, width - 1) + "\u2026";
|
|
1989
2015
|
}
|
|
2016
|
+
function wrapText(text3, width) {
|
|
2017
|
+
if (width <= 4) return [text3.slice(0, Math.max(1, width))];
|
|
2018
|
+
const out = [];
|
|
2019
|
+
for (const rawLine of text3.split("\n")) {
|
|
2020
|
+
let remaining = rawLine.trim();
|
|
2021
|
+
if (!remaining) {
|
|
2022
|
+
out.push("");
|
|
2023
|
+
continue;
|
|
2024
|
+
}
|
|
2025
|
+
while (remaining.length > width) {
|
|
2026
|
+
let splitAt = remaining.lastIndexOf(" ", width);
|
|
2027
|
+
if (splitAt <= 0) splitAt = width;
|
|
2028
|
+
out.push(remaining.slice(0, splitAt));
|
|
2029
|
+
remaining = remaining.slice(splitAt).trimStart();
|
|
2030
|
+
}
|
|
2031
|
+
if (remaining) out.push(remaining);
|
|
2032
|
+
}
|
|
2033
|
+
return out.length > 0 ? out : [""];
|
|
2034
|
+
}
|
|
1990
2035
|
function verbBadge(verb) {
|
|
1991
2036
|
const upper = verb.toUpperCase().padEnd(6);
|
|
1992
2037
|
if (verb === "get") return `${ANSI_GREEN}${upper}${ANSI_RESET}`;
|
|
@@ -2011,7 +2056,86 @@ function nextTab(current, delta) {
|
|
|
2011
2056
|
const idx = TABS.indexOf(current);
|
|
2012
2057
|
return TABS[(idx + delta + TABS.length) % TABS.length];
|
|
2013
2058
|
}
|
|
2014
|
-
function
|
|
2059
|
+
function renderModalBox(modal, maxWidth, maxHeight) {
|
|
2060
|
+
const boxWidth = Math.max(40, Math.min(68, maxWidth));
|
|
2061
|
+
const innerWidth = boxWidth - 4;
|
|
2062
|
+
const borderColor = modal.kind === "error" ? ANSI_RED : ANSI_CYAN;
|
|
2063
|
+
const titleLabel = modal.kind === "error" ? " Error " : " server-config ";
|
|
2064
|
+
const topDashes = Math.max(0, boxWidth - 2 - titleLabel.length - 1);
|
|
2065
|
+
const topBorder = `${borderColor}\u250C\u2500${ANSI_BOLD}${titleLabel}${ANSI_RESET}${borderColor}${"\u2500".repeat(topDashes)}\u2510${ANSI_RESET}`;
|
|
2066
|
+
const bottomBorder = `${borderColor}\u2514${"\u2500".repeat(boxWidth - 2)}\u2518${ANSI_RESET}`;
|
|
2067
|
+
const boxRow = (content) => `${borderColor}\u2502${ANSI_RESET} ${padOrTruncate(content, innerWidth)} ${borderColor}\u2502${ANSI_RESET}`;
|
|
2068
|
+
const contentLines = [];
|
|
2069
|
+
if (modal.kind === "text") {
|
|
2070
|
+
for (const line of wrapText(modal.message, innerWidth)) {
|
|
2071
|
+
contentLines.push(`${ANSI_BOLD}${line}${ANSI_RESET}`);
|
|
2072
|
+
}
|
|
2073
|
+
contentLines.push("");
|
|
2074
|
+
const shown = modal.value ? modal.value.slice(0, modal.cursor) + "\u2588" + modal.value.slice(modal.cursor) : `\u2588${ANSI_DIM}${modal.placeholder ?? ""}${ANSI_RESET}`;
|
|
2075
|
+
contentLines.push(`${ANSI_CYAN}>${ANSI_RESET} ${shown}`);
|
|
2076
|
+
if (modal.error) {
|
|
2077
|
+
contentLines.push("");
|
|
2078
|
+
for (const errLine of wrapText(modal.error, innerWidth)) {
|
|
2079
|
+
contentLines.push(`${ANSI_RED}${errLine}${ANSI_RESET}`);
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
contentLines.push("");
|
|
2083
|
+
contentLines.push(`${ANSI_DIM}Enter Submit \xB7 Esc Cancel${ANSI_RESET}`);
|
|
2084
|
+
} else if (modal.kind === "select") {
|
|
2085
|
+
for (const line of wrapText(modal.message, innerWidth)) {
|
|
2086
|
+
contentLines.push(`${ANSI_BOLD}${line}${ANSI_RESET}`);
|
|
2087
|
+
}
|
|
2088
|
+
contentLines.push("");
|
|
2089
|
+
const maxVisible = Math.max(4, maxHeight - contentLines.length - 5);
|
|
2090
|
+
const total = modal.options.length;
|
|
2091
|
+
const start = Math.max(0, Math.min(modal.selectedIndex - Math.floor(maxVisible / 2), total - maxVisible));
|
|
2092
|
+
const end = Math.min(total, start + maxVisible);
|
|
2093
|
+
if (start > 0) contentLines.push(`${ANSI_DIM} \u2191 (${start} more)${ANSI_RESET}`);
|
|
2094
|
+
for (let i = start; i < end; i++) {
|
|
2095
|
+
const opt = modal.options[i];
|
|
2096
|
+
const active = i === modal.selectedIndex;
|
|
2097
|
+
const prefix = active ? `${ANSI_CYAN}\u25B8${ANSI_RESET} ` : " ";
|
|
2098
|
+
const hint = opt.hint ? ` ${ANSI_DIM}(${opt.hint})${ANSI_RESET}` : "";
|
|
2099
|
+
const text3 = `${prefix}${active ? ANSI_BOLD : ""}${opt.label}${ANSI_RESET}${hint}`;
|
|
2100
|
+
contentLines.push(text3);
|
|
2101
|
+
}
|
|
2102
|
+
if (end < total) contentLines.push(`${ANSI_DIM} \u2193 (${total - end} more)${ANSI_RESET}`);
|
|
2103
|
+
contentLines.push("");
|
|
2104
|
+
contentLines.push(`${ANSI_DIM}\u2191/\u2193 Move \xB7 Enter Select \xB7 Esc Cancel${ANSI_RESET}`);
|
|
2105
|
+
} else if (modal.kind === "confirm") {
|
|
2106
|
+
for (const line of wrapText(modal.message, innerWidth)) {
|
|
2107
|
+
contentLines.push(`${ANSI_BOLD}${line}${ANSI_RESET}`);
|
|
2108
|
+
}
|
|
2109
|
+
contentLines.push("");
|
|
2110
|
+
const yesBtn = modal.value ? `${ANSI_INVERSE}${ANSI_BOLD} Yes ${ANSI_RESET}` : `${ANSI_DIM} Yes ${ANSI_RESET}`;
|
|
2111
|
+
const noBtn = !modal.value ? `${ANSI_INVERSE}${ANSI_BOLD} No ${ANSI_RESET}` : `${ANSI_DIM} No ${ANSI_RESET}`;
|
|
2112
|
+
contentLines.push(`${yesBtn} ${noBtn}`);
|
|
2113
|
+
contentLines.push("");
|
|
2114
|
+
contentLines.push(`${ANSI_DIM}\u2190/\u2192/Tab Toggle \xB7 y/n \xB7 Enter Confirm \xB7 Esc Cancel${ANSI_RESET}`);
|
|
2115
|
+
} else {
|
|
2116
|
+
for (const line of wrapText(modal.message, innerWidth)) {
|
|
2117
|
+
contentLines.push(`${ANSI_RED}${line}${ANSI_RESET}`);
|
|
2118
|
+
}
|
|
2119
|
+
contentLines.push("");
|
|
2120
|
+
contentLines.push(`${ANSI_DIM}Press any key to continue...${ANSI_RESET}`);
|
|
2121
|
+
}
|
|
2122
|
+
return [topBorder, ...contentLines.map(boxRow), bottomBorder];
|
|
2123
|
+
}
|
|
2124
|
+
function overlayModal(frameLines, modal, cols, rows) {
|
|
2125
|
+
const boxLines = renderModalBox(modal, cols - 4, rows - 4);
|
|
2126
|
+
const boxWidth = visibleLength(boxLines[0]);
|
|
2127
|
+
const startRow = Math.max(2, Math.floor((rows - boxLines.length) / 2));
|
|
2128
|
+
const leftPad = Math.max(0, Math.floor((cols - boxWidth) / 2));
|
|
2129
|
+
const result = frameLines.slice();
|
|
2130
|
+
for (let i = 0; i < boxLines.length; i++) {
|
|
2131
|
+
const targetRow = startRow + i;
|
|
2132
|
+
if (targetRow >= 0 && targetRow < result.length) {
|
|
2133
|
+
result[targetRow] = `${" ".repeat(leftPad)}${boxLines[i]}`;
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
return result;
|
|
2137
|
+
}
|
|
2138
|
+
function renderTuiFrame(snapshot, rawState, width = 96, height = 26, modal) {
|
|
2015
2139
|
const state = clampSelection(snapshot, rawState);
|
|
2016
2140
|
const cols = Math.max(60, width);
|
|
2017
2141
|
const rows = Math.max(16, height);
|
|
@@ -2117,68 +2241,217 @@ function renderTuiFrame(snapshot, rawState, width = 96, height = 26) {
|
|
|
2117
2241
|
}
|
|
2118
2242
|
const shortcuts = state.tab === "endpoints" ? "[a] Add endpoint [c] Add CRUD [n] Add method [m] Modify [x] Rm method [d] Rm endpoint" : state.tab === "tables" ? "[a] Add table [m] Junction (M:N) [c] Add column [d] Remove table" : "[g] Generate client [o] Generate docs [r] Re-run doctor";
|
|
2119
2243
|
const statusLine = state.statusMessage ? `${ANSI_CYAN}${state.statusMessage}${ANSI_RESET}` : `${ANSI_DIM}\u2191/\u2193 Move Tab/1-3 Switch r Refresh q Quit${ANSI_RESET}`;
|
|
2120
|
-
const
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
}
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
process.stdout.write(`
|
|
2132
|
-
${ANSI_DIM}Press any key to return to server-config...${ANSI_RESET}`);
|
|
2133
|
-
await new Promise((resolve) => {
|
|
2134
|
-
const wasRaw = process.stdin.isRaw;
|
|
2135
|
-
process.stdin.setRawMode(true);
|
|
2136
|
-
process.stdin.resume();
|
|
2137
|
-
const onData = () => {
|
|
2138
|
-
process.stdin.removeListener("data", onData);
|
|
2139
|
-
if (!wasRaw) process.stdin.setRawMode(false);
|
|
2140
|
-
resolve();
|
|
2141
|
-
};
|
|
2142
|
-
process.stdin.once("data", onData);
|
|
2143
|
-
});
|
|
2244
|
+
const frameLines = [
|
|
2245
|
+
padOrTruncate(header, cols),
|
|
2246
|
+
padOrTruncate(tabBar, cols),
|
|
2247
|
+
rule,
|
|
2248
|
+
...body,
|
|
2249
|
+
rule,
|
|
2250
|
+
padOrTruncate(`${ANSI_DIM}${shortcuts}${ANSI_RESET}`, cols),
|
|
2251
|
+
padOrTruncate(statusLine, cols)
|
|
2252
|
+
];
|
|
2253
|
+
const finalLines = modal ? overlayModal(frameLines, modal, cols, rows) : frameLines;
|
|
2254
|
+
return finalLines.join("\n");
|
|
2144
2255
|
}
|
|
2145
|
-
|
|
2256
|
+
function enterAltScreen(out) {
|
|
2257
|
+
out.write("\x1B[?1049h\x1B[?25l");
|
|
2258
|
+
}
|
|
2259
|
+
function exitAltScreen(out) {
|
|
2260
|
+
out.write("\x1B[?25h\x1B[?1049l");
|
|
2261
|
+
}
|
|
2262
|
+
async function runServerConfigTui(actions, io = { stdin: process.stdin, stdout: process.stdout }) {
|
|
2263
|
+
const { stdin, stdout } = io;
|
|
2146
2264
|
let snapshot = await actions.loadSnapshot();
|
|
2147
2265
|
let state = { tab: "endpoints", selectedIndex: 0 };
|
|
2148
|
-
emitKeypressEvents(
|
|
2149
|
-
enterAltScreen();
|
|
2266
|
+
emitKeypressEvents(stdin);
|
|
2267
|
+
enterAltScreen(stdout);
|
|
2268
|
+
let activeModal = null;
|
|
2269
|
+
let onModalKey = null;
|
|
2270
|
+
let busy = false;
|
|
2150
2271
|
const draw = () => {
|
|
2151
|
-
const width =
|
|
2152
|
-
const height =
|
|
2153
|
-
|
|
2272
|
+
const width = stdout.columns || 96;
|
|
2273
|
+
const height = stdout.rows || 26;
|
|
2274
|
+
stdout.write("\x1B[H\x1B[2J" + renderTuiFrame(snapshot, state, width, height, activeModal));
|
|
2275
|
+
};
|
|
2276
|
+
const tuiPrompt = {
|
|
2277
|
+
isCancel: (value) => value === TUI_CANCEL,
|
|
2278
|
+
text: (opts) => new Promise((resolve) => {
|
|
2279
|
+
const initial = opts.initialValue ?? "";
|
|
2280
|
+
const modal = {
|
|
2281
|
+
kind: "text",
|
|
2282
|
+
message: opts.message,
|
|
2283
|
+
placeholder: opts.placeholder,
|
|
2284
|
+
value: initial,
|
|
2285
|
+
cursor: initial.length
|
|
2286
|
+
};
|
|
2287
|
+
activeModal = modal;
|
|
2288
|
+
onModalKey = (str, key) => {
|
|
2289
|
+
if (key.name === "escape" || key.ctrl && key.name === "c") {
|
|
2290
|
+
activeModal = null;
|
|
2291
|
+
onModalKey = null;
|
|
2292
|
+
resolve(TUI_CANCEL);
|
|
2293
|
+
return;
|
|
2294
|
+
}
|
|
2295
|
+
if (key.name === "return" || key.name === "enter") {
|
|
2296
|
+
const err = opts.validate?.(modal.value);
|
|
2297
|
+
if (err) {
|
|
2298
|
+
modal.error = err;
|
|
2299
|
+
draw();
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
activeModal = null;
|
|
2303
|
+
onModalKey = null;
|
|
2304
|
+
resolve(modal.value);
|
|
2305
|
+
return;
|
|
2306
|
+
}
|
|
2307
|
+
if (key.name === "backspace") {
|
|
2308
|
+
if (modal.cursor > 0) {
|
|
2309
|
+
modal.value = modal.value.slice(0, modal.cursor - 1) + modal.value.slice(modal.cursor);
|
|
2310
|
+
modal.cursor--;
|
|
2311
|
+
modal.error = void 0;
|
|
2312
|
+
}
|
|
2313
|
+
} else if (key.name === "delete") {
|
|
2314
|
+
if (modal.cursor < modal.value.length) {
|
|
2315
|
+
modal.value = modal.value.slice(0, modal.cursor) + modal.value.slice(modal.cursor + 1);
|
|
2316
|
+
modal.error = void 0;
|
|
2317
|
+
}
|
|
2318
|
+
} else if (key.name === "left") {
|
|
2319
|
+
modal.cursor = Math.max(0, modal.cursor - 1);
|
|
2320
|
+
} else if (key.name === "right") {
|
|
2321
|
+
modal.cursor = Math.min(modal.value.length, modal.cursor + 1);
|
|
2322
|
+
} else if (key.name === "home") {
|
|
2323
|
+
modal.cursor = 0;
|
|
2324
|
+
} else if (key.name === "end") {
|
|
2325
|
+
modal.cursor = modal.value.length;
|
|
2326
|
+
} else if (str && !key.ctrl && !key.meta && str >= " ") {
|
|
2327
|
+
modal.value = modal.value.slice(0, modal.cursor) + str + modal.value.slice(modal.cursor);
|
|
2328
|
+
modal.cursor += str.length;
|
|
2329
|
+
modal.error = void 0;
|
|
2330
|
+
}
|
|
2331
|
+
draw();
|
|
2332
|
+
};
|
|
2333
|
+
draw();
|
|
2334
|
+
}),
|
|
2335
|
+
select: (opts) => new Promise((resolve) => {
|
|
2336
|
+
if (opts.options.length === 0) {
|
|
2337
|
+
resolve(TUI_CANCEL);
|
|
2338
|
+
return;
|
|
2339
|
+
}
|
|
2340
|
+
const initialIdx = opts.initialValue ? Math.max(0, opts.options.findIndex((o) => o.value === opts.initialValue)) : 0;
|
|
2341
|
+
const modal = {
|
|
2342
|
+
kind: "select",
|
|
2343
|
+
message: opts.message,
|
|
2344
|
+
options: opts.options,
|
|
2345
|
+
selectedIndex: initialIdx
|
|
2346
|
+
};
|
|
2347
|
+
activeModal = modal;
|
|
2348
|
+
onModalKey = (str, key) => {
|
|
2349
|
+
if (key.name === "escape" || key.ctrl && key.name === "c") {
|
|
2350
|
+
activeModal = null;
|
|
2351
|
+
onModalKey = null;
|
|
2352
|
+
resolve(TUI_CANCEL);
|
|
2353
|
+
return;
|
|
2354
|
+
}
|
|
2355
|
+
if (key.name === "return" || key.name === "enter") {
|
|
2356
|
+
const chosen = opts.options[modal.selectedIndex];
|
|
2357
|
+
activeModal = null;
|
|
2358
|
+
onModalKey = null;
|
|
2359
|
+
resolve(chosen.value);
|
|
2360
|
+
return;
|
|
2361
|
+
}
|
|
2362
|
+
if (key.name === "up" || str === "k") {
|
|
2363
|
+
modal.selectedIndex = (modal.selectedIndex - 1 + opts.options.length) % opts.options.length;
|
|
2364
|
+
} else if (key.name === "down" || str === "j") {
|
|
2365
|
+
modal.selectedIndex = (modal.selectedIndex + 1) % opts.options.length;
|
|
2366
|
+
}
|
|
2367
|
+
draw();
|
|
2368
|
+
};
|
|
2369
|
+
draw();
|
|
2370
|
+
}),
|
|
2371
|
+
confirm: (opts) => new Promise((resolve) => {
|
|
2372
|
+
const modal = {
|
|
2373
|
+
kind: "confirm",
|
|
2374
|
+
message: opts.message,
|
|
2375
|
+
value: opts.initialValue ?? false
|
|
2376
|
+
};
|
|
2377
|
+
activeModal = modal;
|
|
2378
|
+
onModalKey = (str, key) => {
|
|
2379
|
+
if (key.name === "escape" || key.ctrl && key.name === "c") {
|
|
2380
|
+
activeModal = null;
|
|
2381
|
+
onModalKey = null;
|
|
2382
|
+
resolve(TUI_CANCEL);
|
|
2383
|
+
return;
|
|
2384
|
+
}
|
|
2385
|
+
if (key.name === "return" || key.name === "enter") {
|
|
2386
|
+
const val = modal.value;
|
|
2387
|
+
activeModal = null;
|
|
2388
|
+
onModalKey = null;
|
|
2389
|
+
resolve(val);
|
|
2390
|
+
return;
|
|
2391
|
+
}
|
|
2392
|
+
if (str === "y" || str === "Y") {
|
|
2393
|
+
activeModal = null;
|
|
2394
|
+
onModalKey = null;
|
|
2395
|
+
resolve(true);
|
|
2396
|
+
return;
|
|
2397
|
+
}
|
|
2398
|
+
if (str === "n" || str === "N") {
|
|
2399
|
+
activeModal = null;
|
|
2400
|
+
onModalKey = null;
|
|
2401
|
+
resolve(false);
|
|
2402
|
+
return;
|
|
2403
|
+
}
|
|
2404
|
+
if (key.name === "left" || key.name === "right" || key.name === "tab" || str === "h" || str === "l") {
|
|
2405
|
+
modal.value = !modal.value;
|
|
2406
|
+
}
|
|
2407
|
+
draw();
|
|
2408
|
+
};
|
|
2409
|
+
draw();
|
|
2410
|
+
})
|
|
2154
2411
|
};
|
|
2155
|
-
const
|
|
2156
|
-
|
|
2157
|
-
|
|
2412
|
+
const showErrorModal = (message) => new Promise((resolve) => {
|
|
2413
|
+
activeModal = { kind: "error", message };
|
|
2414
|
+
onModalKey = () => {
|
|
2415
|
+
activeModal = null;
|
|
2416
|
+
onModalKey = null;
|
|
2417
|
+
resolve();
|
|
2418
|
+
};
|
|
2419
|
+
draw();
|
|
2420
|
+
});
|
|
2421
|
+
const runAction = async (fn) => {
|
|
2422
|
+
if (busy) return;
|
|
2423
|
+
busy = true;
|
|
2158
2424
|
try {
|
|
2159
|
-
const msg = await fn();
|
|
2425
|
+
const msg = await fn(tuiPrompt);
|
|
2160
2426
|
snapshot = await actions.loadSnapshot();
|
|
2161
2427
|
state = clampSelection(snapshot, { ...state, statusMessage: msg || void 0 });
|
|
2162
2428
|
} catch (err) {
|
|
2163
|
-
|
|
2164
|
-
|
|
2429
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2430
|
+
state = { ...state, statusMessage: `Error: ${message}` };
|
|
2431
|
+
await showErrorModal(`Error: ${message}`);
|
|
2432
|
+
} finally {
|
|
2433
|
+
activeModal = null;
|
|
2434
|
+
onModalKey = null;
|
|
2435
|
+
busy = false;
|
|
2436
|
+
draw();
|
|
2165
2437
|
}
|
|
2166
|
-
enterAltScreen();
|
|
2167
|
-
process.stdin.setRawMode(true);
|
|
2168
|
-
process.stdin.resume();
|
|
2169
|
-
draw();
|
|
2170
2438
|
};
|
|
2171
2439
|
try {
|
|
2172
|
-
|
|
2173
|
-
|
|
2440
|
+
stdin.setRawMode(true);
|
|
2441
|
+
stdin.resume();
|
|
2174
2442
|
draw();
|
|
2175
2443
|
await new Promise((resolve) => {
|
|
2176
2444
|
const onResize = () => draw();
|
|
2177
2445
|
const cleanup = () => {
|
|
2178
|
-
|
|
2179
|
-
|
|
2446
|
+
stdin.removeListener("keypress", onKeypress);
|
|
2447
|
+
stdout.removeListener("resize", onResize);
|
|
2180
2448
|
};
|
|
2181
2449
|
const onKeypress = async (str, key) => {
|
|
2450
|
+
if (onModalKey) {
|
|
2451
|
+
onModalKey(str, key);
|
|
2452
|
+
return;
|
|
2453
|
+
}
|
|
2454
|
+
if (busy) return;
|
|
2182
2455
|
if (key.ctrl && key.name === "c" || key.name === "escape" || str === "q") {
|
|
2183
2456
|
cleanup();
|
|
2184
2457
|
resolve();
|
|
@@ -2196,39 +2469,51 @@ async function runServerConfigTui(actions) {
|
|
|
2196
2469
|
} else if (key.name === "down" || str === "j") {
|
|
2197
2470
|
state = clampSelection(snapshot, { ...state, selectedIndex: state.selectedIndex + 1 });
|
|
2198
2471
|
} else if (str === "r") {
|
|
2199
|
-
|
|
2200
|
-
|
|
2472
|
+
await runAction(async () => "Refreshed.");
|
|
2473
|
+
return;
|
|
2201
2474
|
} else if (state.tab === "endpoints") {
|
|
2202
2475
|
const current = snapshot.endpoints[state.selectedIndex];
|
|
2203
|
-
if (str === "a") await
|
|
2204
|
-
else if (str === "d") await
|
|
2205
|
-
else if (str === "c") await
|
|
2206
|
-
else if (str === "n") await
|
|
2207
|
-
else if (str === "m") await
|
|
2208
|
-
else if (str === "x") await
|
|
2476
|
+
if (str === "a") await runAction((ui) => actions.addEndpoint(ui));
|
|
2477
|
+
else if (str === "d") await runAction((ui) => actions.removeEndpoint(current, ui));
|
|
2478
|
+
else if (str === "c") await runAction((ui) => actions.addCrud(current, ui));
|
|
2479
|
+
else if (str === "n") await runAction((ui) => actions.addMethod(current, ui));
|
|
2480
|
+
else if (str === "m") await runAction((ui) => actions.modifyMethod(current, ui));
|
|
2481
|
+
else if (str === "x") await runAction((ui) => actions.removeMethod(current, ui));
|
|
2482
|
+
return;
|
|
2209
2483
|
} else if (state.tab === "tables") {
|
|
2210
2484
|
const current = snapshot.tables[state.selectedIndex];
|
|
2211
|
-
if (str === "a") await
|
|
2212
|
-
else if (str === "m") await
|
|
2213
|
-
else if (str === "c") await
|
|
2214
|
-
else if (str === "d") await
|
|
2485
|
+
if (str === "a") await runAction((ui) => actions.addTable(snapshot.tables, ui));
|
|
2486
|
+
else if (str === "m") await runAction((ui) => actions.addJunctionTable(snapshot.tables, ui));
|
|
2487
|
+
else if (str === "c") await runAction((ui) => actions.addColumn(current, snapshot.tables, ui));
|
|
2488
|
+
else if (str === "d") await runAction((ui) => actions.removeTable(current, snapshot.tables, ui));
|
|
2489
|
+
return;
|
|
2215
2490
|
} else if (state.tab === "doctor") {
|
|
2216
|
-
if (str === "g") await
|
|
2217
|
-
else if (str === "o") await
|
|
2491
|
+
if (str === "g") await runAction(() => actions.generateClient());
|
|
2492
|
+
else if (str === "o") await runAction(() => actions.generateDocs());
|
|
2493
|
+
return;
|
|
2218
2494
|
}
|
|
2219
2495
|
draw();
|
|
2220
2496
|
};
|
|
2221
|
-
|
|
2222
|
-
|
|
2497
|
+
stdin.on("keypress", onKeypress);
|
|
2498
|
+
stdout.on("resize", onResize);
|
|
2223
2499
|
});
|
|
2224
2500
|
} finally {
|
|
2225
|
-
if (
|
|
2226
|
-
|
|
2227
|
-
exitAltScreen();
|
|
2501
|
+
if (stdin.isTTY) stdin.setRawMode(false);
|
|
2502
|
+
stdin.pause();
|
|
2503
|
+
exitAltScreen(stdout);
|
|
2228
2504
|
}
|
|
2229
2505
|
}
|
|
2230
2506
|
|
|
2231
2507
|
// src/cli.ts
|
|
2508
|
+
var clackUI = {
|
|
2509
|
+
text: (opts) => p2.text({
|
|
2510
|
+
...opts,
|
|
2511
|
+
validate: opts.validate ? (value) => opts.validate(value ?? "") : void 0
|
|
2512
|
+
}),
|
|
2513
|
+
select: (opts) => p2.select(opts),
|
|
2514
|
+
confirm: (opts) => p2.confirm(opts),
|
|
2515
|
+
isCancel: (value) => p2.isCancel(value)
|
|
2516
|
+
};
|
|
2232
2517
|
var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
|
|
2233
2518
|
var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
|
|
2234
2519
|
var LIST_ROUTES_SUBCOMMANDS = /* @__PURE__ */ new Set(["list-routes", "routes"]);
|
|
@@ -2333,13 +2618,21 @@ async function runProjectOverview() {
|
|
|
2333
2618
|
}
|
|
2334
2619
|
p2.outro("Manage endpoints and methods with `bun run server-config`.");
|
|
2335
2620
|
}
|
|
2336
|
-
async function
|
|
2621
|
+
async function requireSchemaSupport() {
|
|
2337
2622
|
const status = await detectDbStatus();
|
|
2338
|
-
if (status.driver === "neon" || status.driver === "postgres") return
|
|
2339
|
-
|
|
2623
|
+
if (status.driver === "neon" || status.driver === "postgres") return;
|
|
2624
|
+
throw new Error(
|
|
2340
2625
|
`Schema management needs a "neon" or "postgres" db driver (src/config/db reports "${status.driver}") \u2014 SQLite and "none" use a different schema dialect (or none at all) and aren't supported here yet.`
|
|
2341
2626
|
);
|
|
2342
|
-
|
|
2627
|
+
}
|
|
2628
|
+
async function ensureSchemaSupport() {
|
|
2629
|
+
try {
|
|
2630
|
+
await requireSchemaSupport();
|
|
2631
|
+
return true;
|
|
2632
|
+
} catch (err) {
|
|
2633
|
+
p2.log.error(err instanceof Error ? err.message : String(err));
|
|
2634
|
+
return false;
|
|
2635
|
+
}
|
|
2343
2636
|
}
|
|
2344
2637
|
async function readSchemaTables() {
|
|
2345
2638
|
const { root, ext } = await detectProject();
|
|
@@ -2350,20 +2643,20 @@ async function readSchemaTables() {
|
|
|
2350
2643
|
return [];
|
|
2351
2644
|
}
|
|
2352
2645
|
}
|
|
2353
|
-
async function promptDefaultExpr(type) {
|
|
2646
|
+
async function promptDefaultExpr(type, ui = clackUI) {
|
|
2354
2647
|
if (type === "serial") return "";
|
|
2355
2648
|
if (type === "timestamp" || type === "date") {
|
|
2356
|
-
const v2 = await
|
|
2357
|
-
if (
|
|
2649
|
+
const v2 = await ui.confirm({ message: "Default to now()?", initialValue: false });
|
|
2650
|
+
if (ui.isCancel(v2)) return null;
|
|
2358
2651
|
return v2 ? ".defaultNow()" : "";
|
|
2359
2652
|
}
|
|
2360
2653
|
if (type === "uuid") {
|
|
2361
|
-
const v2 = await
|
|
2362
|
-
if (
|
|
2654
|
+
const v2 = await ui.confirm({ message: "Default to a random UUID?", initialValue: false });
|
|
2655
|
+
if (ui.isCancel(v2)) return null;
|
|
2363
2656
|
return v2 ? ".defaultRandom()" : "";
|
|
2364
2657
|
}
|
|
2365
2658
|
if (type === "boolean") {
|
|
2366
|
-
const v2 = await
|
|
2659
|
+
const v2 = await ui.select({
|
|
2367
2660
|
message: "Default value",
|
|
2368
2661
|
options: [
|
|
2369
2662
|
{ value: "none", label: "None" },
|
|
@@ -2372,11 +2665,11 @@ async function promptDefaultExpr(type) {
|
|
|
2372
2665
|
],
|
|
2373
2666
|
initialValue: "none"
|
|
2374
2667
|
});
|
|
2375
|
-
if (
|
|
2668
|
+
if (ui.isCancel(v2)) return null;
|
|
2376
2669
|
return v2 === "none" ? "" : `.default(${v2})`;
|
|
2377
2670
|
}
|
|
2378
2671
|
if (type === "jsonb") {
|
|
2379
|
-
const v2 = await
|
|
2672
|
+
const v2 = await ui.select({
|
|
2380
2673
|
message: "Default JSON value",
|
|
2381
2674
|
options: [
|
|
2382
2675
|
{ value: "none", label: "None" },
|
|
@@ -2385,42 +2678,41 @@ async function promptDefaultExpr(type) {
|
|
|
2385
2678
|
],
|
|
2386
2679
|
initialValue: "none"
|
|
2387
2680
|
});
|
|
2388
|
-
if (
|
|
2681
|
+
if (ui.isCancel(v2)) return null;
|
|
2389
2682
|
return v2 === "none" ? "" : `.default(${v2})`;
|
|
2390
2683
|
}
|
|
2391
2684
|
const isNumber = type === "integer" || type === "real";
|
|
2392
|
-
const v = await
|
|
2685
|
+
const v = await ui.text({
|
|
2393
2686
|
message: "Default value (blank for none)",
|
|
2394
|
-
placeholder: isNumber ? "e.g. 0" : type === "numeric" ? "e.g. 0.00" : "e.g. pending"
|
|
2687
|
+
placeholder: isNumber ? "e.g. 0" : type === "numeric" ? "e.g. 0.00" : "e.g. pending",
|
|
2688
|
+
validate: isNumber ? (value) => value && Number.isNaN(Number(value)) ? `"${value}" isn't a valid number.` : void 0 : void 0
|
|
2395
2689
|
});
|
|
2396
|
-
if (
|
|
2690
|
+
if (ui.isCancel(v)) return null;
|
|
2397
2691
|
if (!v) return "";
|
|
2398
|
-
if (isNumber) {
|
|
2399
|
-
const n = Number(v);
|
|
2400
|
-
if (Number.isNaN(n)) {
|
|
2401
|
-
p2.log.warn(`"${v}" isn't a number \u2014 skipping the default.`);
|
|
2402
|
-
return "";
|
|
2403
|
-
}
|
|
2404
|
-
return `.default(${n})`;
|
|
2405
|
-
}
|
|
2692
|
+
if (isNumber) return `.default(${Number(v)})`;
|
|
2406
2693
|
return `.default(${JSON.stringify(v)})`;
|
|
2407
2694
|
}
|
|
2408
|
-
async function promptSingleColumn(name, existingTables, defaultRequired = true) {
|
|
2695
|
+
async function promptSingleColumn(name, existingTables, defaultRequired = true, ui = clackUI) {
|
|
2696
|
+
const refTables = existingTables.filter((t) => t.columns.some((c) => c.key === "id"));
|
|
2409
2697
|
let references;
|
|
2698
|
+
let referenceType;
|
|
2410
2699
|
let onDelete;
|
|
2411
|
-
if (
|
|
2412
|
-
const refChoice = await
|
|
2700
|
+
if (refTables.length > 0) {
|
|
2701
|
+
const refChoice = await ui.select({
|
|
2413
2702
|
message: `Does "${name}" reference another table's id?`,
|
|
2414
2703
|
options: [
|
|
2415
2704
|
{ value: "__none__", label: "No" },
|
|
2416
|
-
...
|
|
2705
|
+
...refTables.map((t) => ({ value: t.identifier, label: t.identifier }))
|
|
2417
2706
|
],
|
|
2418
2707
|
initialValue: "__none__"
|
|
2419
2708
|
});
|
|
2420
|
-
if (
|
|
2709
|
+
if (ui.isCancel(refChoice)) return null;
|
|
2421
2710
|
if (refChoice !== "__none__") {
|
|
2422
2711
|
references = refChoice;
|
|
2423
|
-
const
|
|
2712
|
+
const targetTable = refTables.find((t) => t.identifier === refChoice);
|
|
2713
|
+
const idCol = targetTable?.columns.find((c) => c.key === "id");
|
|
2714
|
+
referenceType = idCol?.type === "uuid" ? "uuid" : "integer";
|
|
2715
|
+
const deleteChoice = await ui.select({
|
|
2424
2716
|
message: "On referenced row delete",
|
|
2425
2717
|
options: [
|
|
2426
2718
|
{ value: "__none__", label: "Default (no action)" },
|
|
@@ -2428,22 +2720,22 @@ async function promptSingleColumn(name, existingTables, defaultRequired = true)
|
|
|
2428
2720
|
],
|
|
2429
2721
|
initialValue: "cascade"
|
|
2430
2722
|
});
|
|
2431
|
-
if (
|
|
2723
|
+
if (ui.isCancel(deleteChoice)) return null;
|
|
2432
2724
|
if (deleteChoice !== "__none__") onDelete = deleteChoice;
|
|
2433
2725
|
}
|
|
2434
2726
|
}
|
|
2435
|
-
let type = "integer";
|
|
2727
|
+
let type = referenceType ?? "integer";
|
|
2436
2728
|
let varcharLength;
|
|
2437
2729
|
let defaultExpr = "";
|
|
2438
2730
|
if (!references) {
|
|
2439
|
-
const typeChoice = await
|
|
2731
|
+
const typeChoice = await ui.select({
|
|
2440
2732
|
message: "Column type",
|
|
2441
2733
|
options: COLUMN_TYPES.map((t) => ({ value: t, label: t }))
|
|
2442
2734
|
});
|
|
2443
|
-
if (
|
|
2735
|
+
if (ui.isCancel(typeChoice)) return null;
|
|
2444
2736
|
type = typeChoice;
|
|
2445
2737
|
if (type === "varchar") {
|
|
2446
|
-
const lenInput = await
|
|
2738
|
+
const lenInput = await ui.text({
|
|
2447
2739
|
message: "Max varchar length",
|
|
2448
2740
|
initialValue: "255",
|
|
2449
2741
|
validate: (value) => {
|
|
@@ -2451,50 +2743,51 @@ async function promptSingleColumn(name, existingTables, defaultRequired = true)
|
|
|
2451
2743
|
return !value || !Number.isInteger(n) || n <= 0 ? "Enter a positive integer." : void 0;
|
|
2452
2744
|
}
|
|
2453
2745
|
});
|
|
2454
|
-
if (
|
|
2746
|
+
if (ui.isCancel(lenInput)) return null;
|
|
2455
2747
|
varcharLength = Number(lenInput);
|
|
2456
2748
|
}
|
|
2457
|
-
const expr = await promptDefaultExpr(type);
|
|
2749
|
+
const expr = await promptDefaultExpr(type, ui);
|
|
2458
2750
|
if (expr === null) return null;
|
|
2459
2751
|
defaultExpr = expr;
|
|
2460
2752
|
}
|
|
2461
|
-
const notNull = await
|
|
2462
|
-
if (
|
|
2463
|
-
const unique = await
|
|
2464
|
-
if (
|
|
2465
|
-
return { name, type, notNull, unique, defaultExpr, varcharLength, references, onDelete };
|
|
2753
|
+
const notNull = await ui.confirm({ message: "Required (NOT NULL)?", initialValue: defaultRequired });
|
|
2754
|
+
if (ui.isCancel(notNull)) return null;
|
|
2755
|
+
const unique = await ui.confirm({ message: "Unique?", initialValue: false });
|
|
2756
|
+
if (ui.isCancel(unique)) return null;
|
|
2757
|
+
return { name, type, notNull, unique, defaultExpr, varcharLength, references, referenceType, onDelete };
|
|
2466
2758
|
}
|
|
2467
|
-
async function promptForColumns(existingTables, existingKeys = []) {
|
|
2759
|
+
async function promptForColumns(existingTables, existingKeys = [], ui = clackUI) {
|
|
2468
2760
|
const columns = [];
|
|
2469
|
-
p2.log.step("Add columns one at a time. Leave the name blank to finish.");
|
|
2470
2761
|
while (true) {
|
|
2471
|
-
const nameProbe = await
|
|
2472
|
-
message: columns.length === 0 ? "
|
|
2473
|
-
placeholder: columns.length === 0 ? "e.g. email" : ""
|
|
2762
|
+
const nameProbe = await ui.text({
|
|
2763
|
+
message: columns.length === 0 ? "First column name (blank to finish)" : "Another column? (blank to finish)",
|
|
2764
|
+
placeholder: columns.length === 0 ? "e.g. email" : "",
|
|
2765
|
+
validate: (value) => {
|
|
2766
|
+
if (!value) return void 0;
|
|
2767
|
+
const key = columnIdentifier(value);
|
|
2768
|
+
if (existingKeys.includes(key) || columns.some((c) => columnIdentifier(c.name) === key)) {
|
|
2769
|
+
return `"${key}" is already a column on this table.`;
|
|
2770
|
+
}
|
|
2771
|
+
return void 0;
|
|
2772
|
+
}
|
|
2474
2773
|
});
|
|
2475
|
-
if (
|
|
2774
|
+
if (ui.isCancel(nameProbe)) return null;
|
|
2476
2775
|
if (!nameProbe) break;
|
|
2477
|
-
const
|
|
2478
|
-
if (existingKeys.includes(key) || columns.some((c) => columnIdentifier(c.name) === key)) {
|
|
2479
|
-
p2.log.error(`"${key}" is already a column on this table.`);
|
|
2480
|
-
continue;
|
|
2481
|
-
}
|
|
2482
|
-
const spec = await promptSingleColumn(nameProbe, existingTables);
|
|
2776
|
+
const spec = await promptSingleColumn(nameProbe, existingTables, true, ui);
|
|
2483
2777
|
if (spec === null) return null;
|
|
2484
2778
|
columns.push(spec);
|
|
2485
2779
|
}
|
|
2486
2780
|
return columns;
|
|
2487
2781
|
}
|
|
2488
|
-
async function collectTableSpec(existingTables, forcedName) {
|
|
2782
|
+
async function collectTableSpec(existingTables, forcedName, ui = clackUI) {
|
|
2489
2783
|
let name = forcedName;
|
|
2490
2784
|
if (name) {
|
|
2491
2785
|
const id = tableIdentifier(name);
|
|
2492
2786
|
if (existingTables.some((t) => t.identifier === id)) {
|
|
2493
|
-
|
|
2494
|
-
return null;
|
|
2787
|
+
throw new Error(`"${id}" already exists.`);
|
|
2495
2788
|
}
|
|
2496
2789
|
} else {
|
|
2497
|
-
const answer = await
|
|
2790
|
+
const answer = await ui.text({
|
|
2498
2791
|
message: "New table name",
|
|
2499
2792
|
placeholder: "e.g. users",
|
|
2500
2793
|
validate: (value) => {
|
|
@@ -2505,40 +2798,40 @@ async function collectTableSpec(existingTables, forcedName) {
|
|
|
2505
2798
|
return void 0;
|
|
2506
2799
|
}
|
|
2507
2800
|
});
|
|
2508
|
-
if (
|
|
2801
|
+
if (ui.isCancel(answer)) return null;
|
|
2509
2802
|
name = answer;
|
|
2510
2803
|
}
|
|
2511
|
-
const includeId = await
|
|
2804
|
+
const includeId = await ui.confirm({
|
|
2512
2805
|
message: "Add an auto-increment id primary key column?",
|
|
2513
2806
|
initialValue: true
|
|
2514
2807
|
});
|
|
2515
|
-
if (
|
|
2516
|
-
const includeTimestamps = await
|
|
2808
|
+
if (ui.isCancel(includeId)) return null;
|
|
2809
|
+
const includeTimestamps = await ui.confirm({
|
|
2517
2810
|
message: "Add createdAt / updatedAt timestamp columns?",
|
|
2518
2811
|
initialValue: true
|
|
2519
2812
|
});
|
|
2520
|
-
if (
|
|
2521
|
-
const columns = await promptForColumns(existingTables, includeId ? ["id"] : []);
|
|
2813
|
+
if (ui.isCancel(includeTimestamps)) return null;
|
|
2814
|
+
const columns = await promptForColumns(existingTables, includeId ? ["id"] : [], ui);
|
|
2522
2815
|
if (columns === null) return null;
|
|
2523
2816
|
return { name, includeId, includeTimestamps, columns };
|
|
2524
2817
|
}
|
|
2525
|
-
async function collectJunctionTableSpec(existingTables) {
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2818
|
+
async function collectJunctionTableSpec(existingTables, ui = clackUI) {
|
|
2819
|
+
const refTables = existingTables.filter((t) => t.columns.some((c) => c.key === "id"));
|
|
2820
|
+
if (refTables.length < 2) {
|
|
2821
|
+
throw new Error("Need at least 2 existing tables with an id column to create a junction table.");
|
|
2529
2822
|
}
|
|
2530
|
-
const leftTable = await
|
|
2823
|
+
const leftTable = await ui.select({
|
|
2531
2824
|
message: "First table",
|
|
2532
|
-
options:
|
|
2825
|
+
options: refTables.map((t) => ({ value: t.identifier, label: t.identifier }))
|
|
2533
2826
|
});
|
|
2534
|
-
if (
|
|
2535
|
-
const rightTable = await
|
|
2827
|
+
if (ui.isCancel(leftTable)) return null;
|
|
2828
|
+
const rightTable = await ui.select({
|
|
2536
2829
|
message: "Second table",
|
|
2537
|
-
options:
|
|
2830
|
+
options: refTables.map((t) => ({ value: t.identifier, label: t.identifier }))
|
|
2538
2831
|
});
|
|
2539
|
-
if (
|
|
2832
|
+
if (ui.isCancel(rightTable)) return null;
|
|
2540
2833
|
const defaultName = `${leftTable}_${rightTable}`;
|
|
2541
|
-
const name = await
|
|
2834
|
+
const name = await ui.text({
|
|
2542
2835
|
message: "Junction table name",
|
|
2543
2836
|
initialValue: defaultName,
|
|
2544
2837
|
validate: (value) => {
|
|
@@ -2549,29 +2842,30 @@ async function collectJunctionTableSpec(existingTables) {
|
|
|
2549
2842
|
return void 0;
|
|
2550
2843
|
}
|
|
2551
2844
|
});
|
|
2552
|
-
if (
|
|
2553
|
-
const onDelete = await
|
|
2845
|
+
if (ui.isCancel(name)) return null;
|
|
2846
|
+
const onDelete = await ui.select({
|
|
2554
2847
|
message: "Cascade behavior when either referenced row is deleted",
|
|
2555
2848
|
options: ON_DELETE_ACTIONS.map((a) => ({ value: a, label: a })),
|
|
2556
2849
|
initialValue: "cascade"
|
|
2557
2850
|
});
|
|
2558
|
-
if (
|
|
2559
|
-
const includeTimestamps = await
|
|
2851
|
+
if (ui.isCancel(onDelete)) return null;
|
|
2852
|
+
const includeTimestamps = await ui.confirm({
|
|
2560
2853
|
message: "Add createdAt / updatedAt timestamp columns?",
|
|
2561
2854
|
initialValue: true
|
|
2562
2855
|
});
|
|
2563
|
-
if (
|
|
2564
|
-
const addExtra = await
|
|
2856
|
+
if (ui.isCancel(includeTimestamps)) return null;
|
|
2857
|
+
const addExtra = await ui.confirm({
|
|
2565
2858
|
message: "Add extra attributes to the junction table (e.g. role, quantity)?",
|
|
2566
2859
|
initialValue: false
|
|
2567
2860
|
});
|
|
2568
|
-
if (
|
|
2861
|
+
if (ui.isCancel(addExtra)) return null;
|
|
2569
2862
|
const baseSpec = buildJunctionTableSpec({ leftTable, rightTable, name, includeTimestamps, onDelete });
|
|
2570
2863
|
let extraColumns = [];
|
|
2571
2864
|
if (addExtra) {
|
|
2572
2865
|
const cols = await promptForColumns(
|
|
2573
2866
|
existingTables,
|
|
2574
|
-
baseSpec.columns.map((c) => columnIdentifier(c.name))
|
|
2867
|
+
baseSpec.columns.map((c) => columnIdentifier(c.name)),
|
|
2868
|
+
ui
|
|
2575
2869
|
);
|
|
2576
2870
|
if (cols === null) return null;
|
|
2577
2871
|
extraColumns = cols;
|
|
@@ -2587,17 +2881,18 @@ async function runAddTable(args) {
|
|
|
2587
2881
|
let existingTables = await readSchemaTables();
|
|
2588
2882
|
let first = true;
|
|
2589
2883
|
while (true) {
|
|
2590
|
-
const spec = first && junctionFlag ? await collectJunctionTableSpec(existingTables) : await collectTableSpec(existingTables, first ? forcedName : void 0);
|
|
2591
|
-
first = false;
|
|
2592
|
-
if (!spec) {
|
|
2593
|
-
p2.cancel("Cancelled.");
|
|
2594
|
-
return;
|
|
2595
|
-
}
|
|
2596
2884
|
try {
|
|
2885
|
+
const spec = first && junctionFlag ? await collectJunctionTableSpec(existingTables) : await collectTableSpec(existingTables, first ? forcedName : void 0);
|
|
2886
|
+
first = false;
|
|
2887
|
+
if (!spec) {
|
|
2888
|
+
p2.cancel("Cancelled.");
|
|
2889
|
+
return;
|
|
2890
|
+
}
|
|
2597
2891
|
const { filePath, identifier } = await addTable(spec);
|
|
2598
2892
|
p2.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` to create a migration for it.`);
|
|
2599
2893
|
existingTables = await readSchemaTables();
|
|
2600
2894
|
} catch (err) {
|
|
2895
|
+
first = false;
|
|
2601
2896
|
p2.log.error(err instanceof Error ? err.message : String(err));
|
|
2602
2897
|
}
|
|
2603
2898
|
const again = await p2.confirm({ message: "Add another table?", initialValue: false });
|
|
@@ -2705,45 +3000,31 @@ async function runRemoveTable(args) {
|
|
|
2705
3000
|
}
|
|
2706
3001
|
p2.outro("Done.");
|
|
2707
3002
|
}
|
|
2708
|
-
async function serverConfigAddTable(existingTables) {
|
|
2709
|
-
const spec = await collectTableSpec(existingTables);
|
|
2710
|
-
if (!spec)
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
}
|
|
2714
|
-
const { filePath, identifier } = await addTable(spec);
|
|
2715
|
-
p2.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
|
|
2716
|
-
return `Added table "${identifier}"`;
|
|
3003
|
+
async function serverConfigAddTable(existingTables, ui = clackUI) {
|
|
3004
|
+
const spec = await collectTableSpec(existingTables, void 0, ui);
|
|
3005
|
+
if (!spec) return "Cancelled.";
|
|
3006
|
+
const { identifier } = await addTable(spec);
|
|
3007
|
+
return `Added table "${identifier}" (run \`bun run db:generate\` next)`;
|
|
2717
3008
|
}
|
|
2718
|
-
async function serverConfigAddJunctionTable(existingTables) {
|
|
2719
|
-
const spec = await collectJunctionTableSpec(existingTables);
|
|
2720
|
-
if (!spec)
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
}
|
|
2724
|
-
const { filePath, identifier } = await addTable(spec);
|
|
2725
|
-
p2.log.success(`Added junction table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
|
|
2726
|
-
return `Added junction table "${identifier}"`;
|
|
3009
|
+
async function serverConfigAddJunctionTable(existingTables, ui = clackUI) {
|
|
3010
|
+
const spec = await collectJunctionTableSpec(existingTables, ui);
|
|
3011
|
+
if (!spec) return "Cancelled.";
|
|
3012
|
+
const { identifier } = await addTable(spec);
|
|
3013
|
+
return `Added junction table "${identifier}" (run \`bun run db:generate\` next)`;
|
|
2727
3014
|
}
|
|
2728
|
-
async function serverConfigAddColumn(existingTables, forcedTable) {
|
|
2729
|
-
if (existingTables.length === 0)
|
|
2730
|
-
p2.log.info("No tables yet \u2014 add a table first.");
|
|
2731
|
-
return;
|
|
2732
|
-
}
|
|
3015
|
+
async function serverConfigAddColumn(existingTables, forcedTable, ui = clackUI) {
|
|
3016
|
+
if (existingTables.length === 0) return "No tables yet \u2014 add a table first.";
|
|
2733
3017
|
let target = forcedTable;
|
|
2734
3018
|
if (!target) {
|
|
2735
|
-
const choice = await
|
|
3019
|
+
const choice = await ui.select({
|
|
2736
3020
|
message: "Add a column to which table?",
|
|
2737
3021
|
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
|
|
2738
3022
|
});
|
|
2739
|
-
if (
|
|
2740
|
-
p2.cancel("Cancelled.");
|
|
2741
|
-
return;
|
|
2742
|
-
}
|
|
3023
|
+
if (ui.isCancel(choice)) return "Cancelled.";
|
|
2743
3024
|
target = existingTables.find((t) => t.identifier === choice);
|
|
2744
3025
|
}
|
|
2745
3026
|
if (!target) return;
|
|
2746
|
-
const colName = await
|
|
3027
|
+
const colName = await ui.text({
|
|
2747
3028
|
message: `New column name on "${target.identifier}"`,
|
|
2748
3029
|
placeholder: "e.g. avatarUrl",
|
|
2749
3030
|
validate: (value) => {
|
|
@@ -2753,46 +3034,29 @@ async function serverConfigAddColumn(existingTables, forcedTable) {
|
|
|
2753
3034
|
return void 0;
|
|
2754
3035
|
}
|
|
2755
3036
|
});
|
|
2756
|
-
if (
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
}
|
|
2760
|
-
const spec = await promptSingleColumn(colName, existingTables);
|
|
2761
|
-
if (!spec) {
|
|
2762
|
-
p2.cancel("Cancelled.");
|
|
2763
|
-
return;
|
|
2764
|
-
}
|
|
2765
|
-
const { columnKey, filePath } = await addColumn(target.identifier, spec);
|
|
2766
|
-
p2.log.success(`Added column "${columnKey}" to "${target.identifier}" in ${filePath}.`);
|
|
3037
|
+
if (ui.isCancel(colName)) return "Cancelled.";
|
|
3038
|
+
const spec = await promptSingleColumn(colName, existingTables, true, ui);
|
|
3039
|
+
if (!spec) return "Cancelled.";
|
|
3040
|
+
const { columnKey } = await addColumn(target.identifier, spec);
|
|
2767
3041
|
return `Added column "${target.identifier}.${columnKey}"`;
|
|
2768
3042
|
}
|
|
2769
|
-
async function serverConfigRemoveTable(existingTables, forcedTable) {
|
|
2770
|
-
if (existingTables.length === 0)
|
|
2771
|
-
p2.log.info("No tables yet.");
|
|
2772
|
-
return;
|
|
2773
|
-
}
|
|
3043
|
+
async function serverConfigRemoveTable(existingTables, forcedTable, ui = clackUI) {
|
|
3044
|
+
if (existingTables.length === 0) return "No tables yet.";
|
|
2774
3045
|
let choice = forcedTable?.identifier;
|
|
2775
3046
|
if (!choice) {
|
|
2776
|
-
const picked = await
|
|
3047
|
+
const picked = await ui.select({
|
|
2777
3048
|
message: "Remove which table?",
|
|
2778
3049
|
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
|
|
2779
3050
|
});
|
|
2780
|
-
if (
|
|
2781
|
-
p2.cancel("Cancelled.");
|
|
2782
|
-
return;
|
|
2783
|
-
}
|
|
3051
|
+
if (ui.isCancel(picked)) return "Cancelled.";
|
|
2784
3052
|
choice = picked;
|
|
2785
3053
|
}
|
|
2786
|
-
const confirmed = await
|
|
2787
|
-
message: `Remove table "${choice}" from schema.ts? Nothing is dropped from the
|
|
3054
|
+
const confirmed = await ui.confirm({
|
|
3055
|
+
message: `Remove table "${choice}" from schema.ts? Nothing is dropped from the database until you run a migration.`,
|
|
2788
3056
|
initialValue: false
|
|
2789
3057
|
});
|
|
2790
|
-
if (
|
|
2791
|
-
|
|
2792
|
-
return;
|
|
2793
|
-
}
|
|
2794
|
-
const { filePath } = await removeTable(choice);
|
|
2795
|
-
p2.log.success(`Removed "${choice}" from ${filePath}. Run \`bun run db:generate\` next.`);
|
|
3058
|
+
if (ui.isCancel(confirmed) || !confirmed) return "Cancelled.";
|
|
3059
|
+
await removeTable(choice);
|
|
2796
3060
|
return `Removed table "${choice}"`;
|
|
2797
3061
|
}
|
|
2798
3062
|
function suggestMethodName(verb, path) {
|
|
@@ -2897,100 +3161,87 @@ async function runAddMethod() {
|
|
|
2897
3161
|
}
|
|
2898
3162
|
p2.outro("Done.");
|
|
2899
3163
|
}
|
|
2900
|
-
async function serverConfigAddEndpoint() {
|
|
2901
|
-
const name = await
|
|
3164
|
+
async function serverConfigAddEndpoint(ui = clackUI) {
|
|
3165
|
+
const name = await ui.text({
|
|
2902
3166
|
message: "New endpoint name",
|
|
2903
3167
|
placeholder: "e.g. users",
|
|
2904
3168
|
validate: (value) => !value ? "Required." : void 0
|
|
2905
3169
|
});
|
|
2906
|
-
if (
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
const { route, filesWritten } = await addRoute(name);
|
|
2911
|
-
p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet).`);
|
|
2912
|
-
const scaffoldCrud = await p2.confirm({
|
|
2913
|
-
message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
|
|
3170
|
+
if (ui.isCancel(name)) return "Cancelled.";
|
|
3171
|
+
const { route } = await addRoute(name);
|
|
3172
|
+
const scaffoldCrud = await ui.confirm({
|
|
3173
|
+
message: `Added /${route}. Scaffold standard CRUD methods (list, create, getById, update, remove)?`,
|
|
2914
3174
|
initialValue: false
|
|
2915
3175
|
});
|
|
2916
|
-
if (!
|
|
2917
|
-
|
|
3176
|
+
if (!ui.isCancel(scaffoldCrud) && scaffoldCrud) {
|
|
3177
|
+
const result = await addCrudMethods(route);
|
|
3178
|
+
return `Added /${route} with CRUD (${result.added.join(", ") || "none"})`;
|
|
2918
3179
|
}
|
|
3180
|
+
return `Added endpoint /${route}`;
|
|
2919
3181
|
}
|
|
2920
|
-
async function serverConfigRemoveEndpoint(summaries) {
|
|
2921
|
-
if (summaries.length === 0)
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
p2.cancel("Cancelled.");
|
|
2931
|
-
return;
|
|
3182
|
+
async function serverConfigRemoveEndpoint(summaries, forced, ui = clackUI) {
|
|
3183
|
+
if (summaries.length === 0) return "No endpoints yet.";
|
|
3184
|
+
let route = forced?.route;
|
|
3185
|
+
if (!route) {
|
|
3186
|
+
const picked = await ui.select({
|
|
3187
|
+
message: "Remove which endpoint?",
|
|
3188
|
+
options: summaries.map((s) => ({ value: s.route, label: s.route }))
|
|
3189
|
+
});
|
|
3190
|
+
if (ui.isCancel(picked)) return "Cancelled.";
|
|
3191
|
+
route = picked;
|
|
2932
3192
|
}
|
|
2933
|
-
const confirmed = await
|
|
3193
|
+
const confirmed = await ui.confirm({
|
|
2934
3194
|
message: `Remove src/endpoints/${route} and unmount it? This deletes the folder.`,
|
|
2935
3195
|
initialValue: false
|
|
2936
3196
|
});
|
|
2937
|
-
if (
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
}
|
|
2941
|
-
const { removedDir } = await removeRoute(route);
|
|
2942
|
-
p2.log.success(`Removed ${removedDir}.`);
|
|
3197
|
+
if (ui.isCancel(confirmed) || !confirmed) return "Cancelled.";
|
|
3198
|
+
await removeRoute(route);
|
|
3199
|
+
return `Removed endpoint /${route}`;
|
|
2943
3200
|
}
|
|
2944
|
-
async function serverConfigAddMethod(summaries) {
|
|
2945
|
-
const routeChoice = await
|
|
3201
|
+
async function serverConfigAddMethod(summaries, preferred, ui = clackUI) {
|
|
3202
|
+
const routeChoice = await ui.select({
|
|
2946
3203
|
message: "Add a method to which endpoint?",
|
|
3204
|
+
initialValue: preferred?.route ?? summaries[0]?.route ?? "__new__",
|
|
2947
3205
|
options: [
|
|
2948
3206
|
...summaries.map((s) => ({ value: s.route, label: s.route })),
|
|
2949
3207
|
{ value: "__new__", label: "+ New blank endpoint" }
|
|
2950
3208
|
]
|
|
2951
3209
|
});
|
|
2952
|
-
if (
|
|
2953
|
-
p2.cancel("Cancelled.");
|
|
2954
|
-
return;
|
|
2955
|
-
}
|
|
3210
|
+
if (ui.isCancel(routeChoice)) return "Cancelled.";
|
|
2956
3211
|
let route = routeChoice;
|
|
2957
3212
|
let existingMethods = summaries.find((s) => s.route === route)?.methods ?? [];
|
|
2958
3213
|
if (route === "__new__") {
|
|
2959
|
-
const name2 = await
|
|
3214
|
+
const name2 = await ui.text({
|
|
2960
3215
|
message: "New endpoint name",
|
|
2961
3216
|
placeholder: "e.g. users",
|
|
2962
3217
|
validate: (value) => !value ? "Required." : void 0
|
|
2963
3218
|
});
|
|
2964
|
-
if (
|
|
2965
|
-
p2.cancel("Cancelled.");
|
|
2966
|
-
return;
|
|
2967
|
-
}
|
|
3219
|
+
if (ui.isCancel(name2)) return "Cancelled.";
|
|
2968
3220
|
const added = await addRoute(name2);
|
|
2969
3221
|
route = added.route;
|
|
2970
3222
|
existingMethods = [];
|
|
2971
|
-
p2.log.success(`Added blank endpoint src/endpoints/${route}`);
|
|
2972
3223
|
}
|
|
2973
|
-
const verb = await
|
|
3224
|
+
const verb = await ui.select({
|
|
2974
3225
|
message: "HTTP method",
|
|
2975
3226
|
options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() }))
|
|
2976
3227
|
});
|
|
2977
|
-
if (
|
|
2978
|
-
p2.cancel("Cancelled.");
|
|
2979
|
-
return;
|
|
2980
|
-
}
|
|
3228
|
+
if (ui.isCancel(verb)) return "Cancelled.";
|
|
2981
3229
|
const defaultPath = verb === "get" || verb === "post" ? "/" : "/:id";
|
|
2982
|
-
const path = await
|
|
3230
|
+
const path = await ui.text({
|
|
2983
3231
|
message: "Path (relative to this endpoint's mount)",
|
|
2984
3232
|
placeholder: defaultPath,
|
|
2985
3233
|
initialValue: defaultPath,
|
|
2986
|
-
validate: (value) =>
|
|
3234
|
+
validate: (value) => {
|
|
3235
|
+
if (!value?.startsWith("/")) return 'Must start with "/".';
|
|
3236
|
+
if (existingMethods.some((m) => m.verb === verb && m.path === value)) {
|
|
3237
|
+
return `${verb.toUpperCase()} ${value} is already mounted on /${route}.`;
|
|
3238
|
+
}
|
|
3239
|
+
return void 0;
|
|
3240
|
+
}
|
|
2987
3241
|
});
|
|
2988
|
-
if (
|
|
2989
|
-
p2.cancel("Cancelled.");
|
|
2990
|
-
return;
|
|
2991
|
-
}
|
|
3242
|
+
if (ui.isCancel(path)) return "Cancelled.";
|
|
2992
3243
|
const defaultName = suggestMethodName(verb, path);
|
|
2993
|
-
const name = await
|
|
3244
|
+
const name = await ui.text({
|
|
2994
3245
|
message: "Name (controller export + service function)",
|
|
2995
3246
|
placeholder: defaultName,
|
|
2996
3247
|
initialValue: defaultName,
|
|
@@ -3000,101 +3251,83 @@ async function serverConfigAddMethod(summaries) {
|
|
|
3000
3251
|
return void 0;
|
|
3001
3252
|
}
|
|
3002
3253
|
});
|
|
3003
|
-
if (
|
|
3004
|
-
p2.cancel("Cancelled.");
|
|
3005
|
-
return;
|
|
3006
|
-
}
|
|
3254
|
+
if (ui.isCancel(name)) return "Cancelled.";
|
|
3007
3255
|
let needsBody = false;
|
|
3008
3256
|
if (verb === "post" || verb === "put" || verb === "patch") {
|
|
3009
|
-
const answer = await
|
|
3010
|
-
if (
|
|
3011
|
-
p2.cancel("Cancelled.");
|
|
3012
|
-
return;
|
|
3013
|
-
}
|
|
3257
|
+
const answer = await ui.confirm({ message: "Validate a request body?", initialValue: true });
|
|
3258
|
+
if (ui.isCancel(answer)) return "Cancelled.";
|
|
3014
3259
|
needsBody = answer;
|
|
3015
3260
|
}
|
|
3016
|
-
const needsQuery = await
|
|
3017
|
-
if (
|
|
3018
|
-
p2.cancel("Cancelled.");
|
|
3019
|
-
return;
|
|
3020
|
-
}
|
|
3261
|
+
const needsQuery = await ui.confirm({ message: "Validate query params?", initialValue: false });
|
|
3262
|
+
if (ui.isCancel(needsQuery)) return "Cancelled.";
|
|
3021
3263
|
const spec = { verb, path, name, needsBody, needsQuery };
|
|
3022
|
-
|
|
3023
|
-
|
|
3264
|
+
await addMethod(route, spec);
|
|
3265
|
+
return `Added ${verb.toUpperCase()} /${route}${path === "/" ? "" : path} \u2192 ${name}()`;
|
|
3024
3266
|
}
|
|
3025
|
-
async function selectEndpointWithMethods(summaries, message) {
|
|
3267
|
+
async function selectEndpointWithMethods(summaries, message, preferred, ui = clackUI) {
|
|
3026
3268
|
const withMethods = summaries.filter((s) => s.methods.length > 0);
|
|
3027
|
-
if (withMethods.length === 0)
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
}
|
|
3031
|
-
const route = await p2.select({
|
|
3269
|
+
if (withMethods.length === 0) return null;
|
|
3270
|
+
if (preferred && preferred.methods.length > 0) return preferred;
|
|
3271
|
+
const route = await ui.select({
|
|
3032
3272
|
message,
|
|
3033
3273
|
options: withMethods.map((s) => ({ value: s.route, label: s.route }))
|
|
3034
3274
|
});
|
|
3035
|
-
if (
|
|
3036
|
-
p2.cancel("Cancelled.");
|
|
3037
|
-
return null;
|
|
3038
|
-
}
|
|
3275
|
+
if (ui.isCancel(route)) return null;
|
|
3039
3276
|
return withMethods.find((s) => s.route === route) ?? null;
|
|
3040
3277
|
}
|
|
3041
|
-
async function selectMethod(endpoint, message) {
|
|
3042
|
-
const choice = await
|
|
3278
|
+
async function selectMethod(endpoint, message, ui = clackUI) {
|
|
3279
|
+
const choice = await ui.select({
|
|
3043
3280
|
message,
|
|
3044
3281
|
options: endpoint.methods.map((m) => ({
|
|
3045
3282
|
value: `${m.verb}:${m.path}`,
|
|
3046
3283
|
label: `${m.verb.toUpperCase()} ${m.path} \u2192 ${m.name}`
|
|
3047
3284
|
}))
|
|
3048
3285
|
});
|
|
3049
|
-
if (
|
|
3050
|
-
p2.cancel("Cancelled.");
|
|
3051
|
-
return null;
|
|
3052
|
-
}
|
|
3286
|
+
if (ui.isCancel(choice)) return null;
|
|
3053
3287
|
const [verb, path] = choice.split(/:(.*)/s);
|
|
3054
3288
|
return endpoint.methods.find((m) => m.verb === verb && m.path === path) ?? null;
|
|
3055
3289
|
}
|
|
3056
|
-
async function serverConfigRemoveMethod(summaries) {
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3290
|
+
async function serverConfigRemoveMethod(summaries, preferred, ui = clackUI) {
|
|
3291
|
+
if (!summaries.some((s) => s.methods.length > 0)) return "No methods yet \u2014 add one first.";
|
|
3292
|
+
const endpoint = await selectEndpointWithMethods(summaries, "Remove a method from which endpoint?", preferred, ui);
|
|
3293
|
+
if (!endpoint) return "Cancelled.";
|
|
3294
|
+
const method = await selectMethod(endpoint, `Remove which method from /${endpoint.route}?`, ui);
|
|
3295
|
+
if (!method) return "Cancelled.";
|
|
3296
|
+
const confirmed = await ui.confirm({
|
|
3062
3297
|
message: `Remove ${method.verb.toUpperCase()} ${method.path} (${method.name}) from ${endpoint.route}?`,
|
|
3063
3298
|
initialValue: false
|
|
3064
3299
|
});
|
|
3065
|
-
if (
|
|
3066
|
-
p2.cancel("Cancelled.");
|
|
3067
|
-
return;
|
|
3068
|
-
}
|
|
3300
|
+
if (ui.isCancel(confirmed) || !confirmed) return "Cancelled.";
|
|
3069
3301
|
const { removed } = await removeMethod(endpoint.route, method.verb, method.path);
|
|
3070
|
-
|
|
3071
|
-
}
|
|
3072
|
-
async function serverConfigModifyMethod(summaries) {
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
3302
|
+
return `Removed ${removed.verb.toUpperCase()} ${removed.path} (${removed.name})`;
|
|
3303
|
+
}
|
|
3304
|
+
async function serverConfigModifyMethod(summaries, preferred, ui = clackUI) {
|
|
3305
|
+
if (!summaries.some((s) => s.methods.length > 0)) return "No methods yet \u2014 add one first.";
|
|
3306
|
+
const endpoint = await selectEndpointWithMethods(summaries, "Modify a method on which endpoint?", preferred, ui);
|
|
3307
|
+
if (!endpoint) return "Cancelled.";
|
|
3308
|
+
const old = await selectMethod(endpoint, `Modify which method on /${endpoint.route}?`, ui);
|
|
3309
|
+
if (!old) return "Cancelled.";
|
|
3077
3310
|
const { needsBody: oldNeedsBody, needsQuery: oldNeedsQuery } = await detectMethodValidation(endpoint.route, old.name);
|
|
3078
3311
|
const others = endpoint.methods.filter((m) => m !== old);
|
|
3079
|
-
const verb = await
|
|
3312
|
+
const verb = await ui.select({
|
|
3080
3313
|
message: "HTTP method",
|
|
3081
3314
|
initialValue: old.verb,
|
|
3082
3315
|
options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() }))
|
|
3083
3316
|
});
|
|
3084
|
-
if (
|
|
3085
|
-
|
|
3086
|
-
return;
|
|
3087
|
-
}
|
|
3088
|
-
const path = await p2.text({
|
|
3317
|
+
if (ui.isCancel(verb)) return "Cancelled.";
|
|
3318
|
+
const path = await ui.text({
|
|
3089
3319
|
message: "Path (relative to this endpoint's mount)",
|
|
3090
3320
|
initialValue: old.path,
|
|
3091
|
-
validate: (value) =>
|
|
3321
|
+
validate: (value) => {
|
|
3322
|
+
if (!value?.startsWith("/")) return 'Must start with "/".';
|
|
3323
|
+
if (others.some((m) => m.verb === verb && m.path === value)) {
|
|
3324
|
+
return `${verb.toUpperCase()} ${value} is already used by another method on this endpoint.`;
|
|
3325
|
+
}
|
|
3326
|
+
return void 0;
|
|
3327
|
+
}
|
|
3092
3328
|
});
|
|
3093
|
-
if (
|
|
3094
|
-
|
|
3095
|
-
return;
|
|
3096
|
-
}
|
|
3097
|
-
const name = await p2.text({
|
|
3329
|
+
if (ui.isCancel(path)) return "Cancelled.";
|
|
3330
|
+
const name = await ui.text({
|
|
3098
3331
|
message: "Name (controller export + service function)",
|
|
3099
3332
|
initialValue: old.name,
|
|
3100
3333
|
validate: (value) => {
|
|
@@ -3103,33 +3336,23 @@ async function serverConfigModifyMethod(summaries) {
|
|
|
3103
3336
|
return void 0;
|
|
3104
3337
|
}
|
|
3105
3338
|
});
|
|
3106
|
-
if (
|
|
3107
|
-
p2.cancel("Cancelled.");
|
|
3108
|
-
return;
|
|
3109
|
-
}
|
|
3110
|
-
if (others.some((m) => m.verb === verb && m.path === path)) {
|
|
3111
|
-
p2.log.error(`${verb.toUpperCase()} ${path} is already used by another method on this endpoint.`);
|
|
3112
|
-
return;
|
|
3113
|
-
}
|
|
3339
|
+
if (ui.isCancel(name)) return "Cancelled.";
|
|
3114
3340
|
let needsBody = false;
|
|
3115
3341
|
if (verb === "post" || verb === "put" || verb === "patch") {
|
|
3116
|
-
const answer = await
|
|
3117
|
-
if (
|
|
3118
|
-
p2.cancel("Cancelled.");
|
|
3119
|
-
return;
|
|
3120
|
-
}
|
|
3342
|
+
const answer = await ui.confirm({ message: "Validate a request body?", initialValue: oldNeedsBody });
|
|
3343
|
+
if (ui.isCancel(answer)) return "Cancelled.";
|
|
3121
3344
|
needsBody = answer;
|
|
3122
3345
|
}
|
|
3123
|
-
const needsQuery = await
|
|
3124
|
-
if (
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3346
|
+
const needsQuery = await ui.confirm({ message: "Validate query params?", initialValue: oldNeedsQuery });
|
|
3347
|
+
if (ui.isCancel(needsQuery)) return "Cancelled.";
|
|
3348
|
+
const proceed = await ui.confirm({
|
|
3349
|
+
message: `Apply changes to ${old.verb.toUpperCase()} ${old.path} (${old.name})? This regenerates its controller/service stubs.`,
|
|
3350
|
+
initialValue: true
|
|
3351
|
+
});
|
|
3352
|
+
if (ui.isCancel(proceed) || !proceed) return "Cancelled.";
|
|
3128
3353
|
await removeMethod(endpoint.route, old.verb, old.path);
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
`Updated src/endpoints/${endpoint.route}: ${old.verb.toUpperCase()} ${old.path} \u2192 ${verb.toUpperCase()} ${path} (${name}), ${filesWritten.length} files touched.`
|
|
3132
|
-
);
|
|
3354
|
+
await addMethod(endpoint.route, { verb, path, name, needsBody, needsQuery });
|
|
3355
|
+
return `Updated ${old.verb.toUpperCase()} ${old.path} \u2192 ${verb.toUpperCase()} ${path} (${name})`;
|
|
3133
3356
|
}
|
|
3134
3357
|
async function runServerConfig() {
|
|
3135
3358
|
if (process.stdin.isTTY && process.stdout.isTTY) {
|
|
@@ -3154,48 +3377,31 @@ async function runServerConfig() {
|
|
|
3154
3377
|
issues: doctor.issues
|
|
3155
3378
|
};
|
|
3156
3379
|
},
|
|
3157
|
-
addEndpoint:
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
const
|
|
3162
|
-
|
|
3163
|
-
const confirmed = await p2.confirm({
|
|
3164
|
-
message: `Remove src/endpoints/${ep.route} and unmount it? This deletes the folder.`,
|
|
3165
|
-
initialValue: false
|
|
3166
|
-
});
|
|
3167
|
-
if (!p2.isCancel(confirmed) && confirmed) await removeRoute(ep.route);
|
|
3168
|
-
} else {
|
|
3169
|
-
await serverConfigRemoveEndpoint(summaries);
|
|
3170
|
-
}
|
|
3171
|
-
},
|
|
3172
|
-
addCrud: async (ep) => {
|
|
3173
|
-
if (!ep) {
|
|
3174
|
-
await serverConfigAddEndpoint();
|
|
3175
|
-
return;
|
|
3176
|
-
}
|
|
3177
|
-
logCrudResult(await addCrudMethods(ep.route));
|
|
3178
|
-
},
|
|
3179
|
-
addMethod: async () => {
|
|
3180
|
-
await serverConfigAddMethod(await listEndpointsWithMethods());
|
|
3181
|
-
},
|
|
3182
|
-
modifyMethod: async () => {
|
|
3183
|
-
await serverConfigModifyMethod(await listEndpointsWithMethods());
|
|
3184
|
-
},
|
|
3185
|
-
removeMethod: async () => {
|
|
3186
|
-
await serverConfigRemoveMethod(await listEndpointsWithMethods());
|
|
3380
|
+
addEndpoint: (ui) => serverConfigAddEndpoint(ui),
|
|
3381
|
+
removeEndpoint: async (ep, ui) => serverConfigRemoveEndpoint(await listEndpointsWithMethods(), ep, ui),
|
|
3382
|
+
addCrud: async (ep, ui) => {
|
|
3383
|
+
if (!ep) return serverConfigAddEndpoint(ui);
|
|
3384
|
+
const result = await addCrudMethods(ep.route);
|
|
3385
|
+
return `Added CRUD to /${result.route}: ${result.added.join(", ") || "already present"}`;
|
|
3187
3386
|
},
|
|
3188
|
-
|
|
3189
|
-
|
|
3387
|
+
addMethod: async (ep, ui) => serverConfigAddMethod(await listEndpointsWithMethods(), ep, ui),
|
|
3388
|
+
modifyMethod: async (ep, ui) => serverConfigModifyMethod(await listEndpointsWithMethods(), ep, ui),
|
|
3389
|
+
removeMethod: async (ep, ui) => serverConfigRemoveMethod(await listEndpointsWithMethods(), ep, ui),
|
|
3390
|
+
addTable: async (tables, ui) => {
|
|
3391
|
+
await requireSchemaSupport();
|
|
3392
|
+
return serverConfigAddTable(tables, ui);
|
|
3190
3393
|
},
|
|
3191
|
-
addJunctionTable: async (tables) => {
|
|
3192
|
-
|
|
3394
|
+
addJunctionTable: async (tables, ui) => {
|
|
3395
|
+
await requireSchemaSupport();
|
|
3396
|
+
return serverConfigAddJunctionTable(tables, ui);
|
|
3193
3397
|
},
|
|
3194
|
-
addColumn: async (tbl, tables) => {
|
|
3195
|
-
|
|
3398
|
+
addColumn: async (tbl, tables, ui) => {
|
|
3399
|
+
await requireSchemaSupport();
|
|
3400
|
+
return serverConfigAddColumn(tables, tbl, ui);
|
|
3196
3401
|
},
|
|
3197
|
-
removeTable: async (tbl, tables) => {
|
|
3198
|
-
|
|
3402
|
+
removeTable: async (tbl, tables, ui) => {
|
|
3403
|
+
await requireSchemaSupport();
|
|
3404
|
+
return serverConfigRemoveTable(tables, tbl, ui);
|
|
3199
3405
|
},
|
|
3200
3406
|
generateClient: async () => {
|
|
3201
3407
|
const { root, ext } = await detectProject();
|
|
@@ -3239,35 +3445,37 @@ async function runServerConfig() {
|
|
|
3239
3445
|
});
|
|
3240
3446
|
if (p2.isCancel(action) || action === "exit") break;
|
|
3241
3447
|
try {
|
|
3448
|
+
let result = void 0;
|
|
3242
3449
|
switch (action) {
|
|
3243
3450
|
case "add-endpoint":
|
|
3244
|
-
await serverConfigAddEndpoint();
|
|
3451
|
+
result = await serverConfigAddEndpoint(clackUI);
|
|
3245
3452
|
break;
|
|
3246
3453
|
case "remove-endpoint":
|
|
3247
|
-
await serverConfigRemoveEndpoint(summaries);
|
|
3454
|
+
result = await serverConfigRemoveEndpoint(summaries, void 0, clackUI);
|
|
3248
3455
|
break;
|
|
3249
3456
|
case "add-method":
|
|
3250
|
-
await serverConfigAddMethod(summaries);
|
|
3457
|
+
result = await serverConfigAddMethod(summaries, void 0, clackUI);
|
|
3251
3458
|
break;
|
|
3252
3459
|
case "remove-method":
|
|
3253
|
-
await serverConfigRemoveMethod(summaries);
|
|
3460
|
+
result = await serverConfigRemoveMethod(summaries, void 0, clackUI);
|
|
3254
3461
|
break;
|
|
3255
3462
|
case "modify-method":
|
|
3256
|
-
await serverConfigModifyMethod(summaries);
|
|
3463
|
+
result = await serverConfigModifyMethod(summaries, void 0, clackUI);
|
|
3257
3464
|
break;
|
|
3258
3465
|
case "add-table":
|
|
3259
|
-
if (await ensureSchemaSupport()) await serverConfigAddTable(await readSchemaTables());
|
|
3466
|
+
if (await ensureSchemaSupport()) result = await serverConfigAddTable(await readSchemaTables(), clackUI);
|
|
3260
3467
|
break;
|
|
3261
3468
|
case "add-junction":
|
|
3262
|
-
if (await ensureSchemaSupport()) await serverConfigAddJunctionTable(await readSchemaTables());
|
|
3469
|
+
if (await ensureSchemaSupport()) result = await serverConfigAddJunctionTable(await readSchemaTables(), clackUI);
|
|
3263
3470
|
break;
|
|
3264
3471
|
case "add-column":
|
|
3265
|
-
if (await ensureSchemaSupport()) await serverConfigAddColumn(await readSchemaTables());
|
|
3472
|
+
if (await ensureSchemaSupport()) result = await serverConfigAddColumn(await readSchemaTables(), void 0, clackUI);
|
|
3266
3473
|
break;
|
|
3267
3474
|
case "remove-table":
|
|
3268
|
-
if (await ensureSchemaSupport()) await serverConfigRemoveTable(await readSchemaTables());
|
|
3475
|
+
if (await ensureSchemaSupport()) result = await serverConfigRemoveTable(await readSchemaTables(), void 0, clackUI);
|
|
3269
3476
|
break;
|
|
3270
3477
|
}
|
|
3478
|
+
if (result) p2.log.info(result);
|
|
3271
3479
|
} catch (err) {
|
|
3272
3480
|
p2.log.error(err instanceof Error ? err.message : String(err));
|
|
3273
3481
|
}
|