nerdgram1337 0.0.0-stage → 1.2.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/LICENSE +21 -0
- package/README.md +51 -2
- package/bin/nerdgram.js +35 -0
- package/dist/chunk-5EV3XFVE.js +322 -0
- package/dist/chunk-EGA2UGTF.js +1966 -0
- package/dist/chunk-KO565WWM.js +471 -0
- package/dist/cli.js +723 -0
- package/package.json +48 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// server/src/cli.ts
|
|
4
|
+
import fs from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
var BOOL_FLAGS = /* @__PURE__ */ new Set([
|
|
8
|
+
"json",
|
|
9
|
+
"server",
|
|
10
|
+
"strict",
|
|
11
|
+
"help",
|
|
12
|
+
"h",
|
|
13
|
+
"no-update-links",
|
|
14
|
+
"dry-run",
|
|
15
|
+
"yes",
|
|
16
|
+
"match-case",
|
|
17
|
+
"whole-word",
|
|
18
|
+
"regex",
|
|
19
|
+
"front-matter",
|
|
20
|
+
"no-recursive",
|
|
21
|
+
"apply",
|
|
22
|
+
"copy-data",
|
|
23
|
+
"share-data",
|
|
24
|
+
"with-data",
|
|
25
|
+
"keep-data"
|
|
26
|
+
]);
|
|
27
|
+
var HELP = `nerdgram \u2014 automation client for NerdGram1337
|
|
28
|
+
|
|
29
|
+
Usage
|
|
30
|
+
nerdgram render <file|path> -o out.svg|png
|
|
31
|
+
nerdgram list [folder]
|
|
32
|
+
nerdgram search <query>
|
|
33
|
+
nerdgram get <path> [-o file]
|
|
34
|
+
nerdgram put <path> <file>
|
|
35
|
+
nerdgram export <folder> -o dir/
|
|
36
|
+
nerdgram lint [path|file] [--strict]
|
|
37
|
+
nerdgram rename <from> <to>
|
|
38
|
+
nerdgram move <from> [folder]
|
|
39
|
+
nerdgram duplicate <path> (--copy-data | --share-data)
|
|
40
|
+
nerdgram delete <path> (--with-data | --keep-data)
|
|
41
|
+
nerdgram repair-links [--dry-run] [--apply]
|
|
42
|
+
nerdgram generate --path Diagram.mmd --data data.csv
|
|
43
|
+
nerdgram generate --path Diagram.mmd --data neighbors.lldp --format lldp --local-device edge-sw
|
|
44
|
+
nerdgram refresh <path> [--data data.csv]
|
|
45
|
+
nerdgram diff <path> --from <id|name|current> [--to <id|name|current>] [--format md|json|svg]
|
|
46
|
+
nerdgram baseline <path> --name "\u2026" [--note "\u2026"] [--id <revision>]
|
|
47
|
+
nerdgram replace <find> <replace> [--folder path] [--regex] [--whole-word] [--match-case] [--front-matter] [--no-recursive] [--dry-run] [--yes]
|
|
48
|
+
nerdgram replace --undo <id>
|
|
49
|
+
|
|
50
|
+
A local .mmd file is rendered and linted in this process. Anything else uses
|
|
51
|
+
NERDGRAM_URL (default http://127.0.0.1:8787) and NERDGRAM_TOKEN.
|
|
52
|
+
--url and --token override those. --json prints one JSON object.
|
|
53
|
+
--server forces render to use the API. Exit status is 1 on errors.
|
|
54
|
+
Rename and move also move a CSV, JSON, CDP, or LLDP file that sits next to the
|
|
55
|
+
diagram and update nerdgram.source. duplicate --copy-data gives the copy its
|
|
56
|
+
own data file. duplicate --share-data keeps both diagrams on the original file.
|
|
57
|
+
delete --with-data moves that file to the trash with the diagram.
|
|
58
|
+
delete --keep-data leaves it in the workspace. When a data file is present and
|
|
59
|
+
the flag is omitted, duplicate and delete stop and list the file.
|
|
60
|
+
repair-links previews click repairs after a rename or move made outside the
|
|
61
|
+
app. --dry-run is the default and writes nothing. --apply saves the previewed
|
|
62
|
+
rewrites. If the data file moved with that diagram, the same confirmation
|
|
63
|
+
updates nerdgram.source. An ambiguous match is listed and left unchanged.
|
|
64
|
+
diff compares two revisions, or a revision and the current diagram. --to
|
|
65
|
+
defaults to current. --from accepts a revision id, a baseline name, or
|
|
66
|
+
current. --format md prints a Markdown summary, json prints the diff, and
|
|
67
|
+
svg writes the read-only visual diff. svg needs -o file.svg. The diagram
|
|
68
|
+
file is not modified.
|
|
69
|
+
baseline saves the current diagram as a named baseline. --id names an
|
|
70
|
+
existing revision instead. Names are kept when the 20-revision limit drops
|
|
71
|
+
older saves.
|
|
72
|
+
replace prints a preview. --yes applies it and saves each diagram, so the
|
|
73
|
+
previous text is a revision. --dry-run is the default. --folder limits the
|
|
74
|
+
scope. --no-recursive stays in that folder. The diagram body is searched
|
|
75
|
+
unless --front-matter is set. Hidden files, .meta, trash, and templates are
|
|
76
|
+
not changed. --undo restores that replace and skips a file edited since.
|
|
77
|
+
`;
|
|
78
|
+
var renderModule = null;
|
|
79
|
+
function loadRender() {
|
|
80
|
+
renderModule ??= import("./chunk-5EV3XFVE.js");
|
|
81
|
+
return renderModule;
|
|
82
|
+
}
|
|
83
|
+
async function loadLint() {
|
|
84
|
+
return import("./chunk-EGA2UGTF.js");
|
|
85
|
+
}
|
|
86
|
+
async function shutdownCli() {
|
|
87
|
+
if (!renderModule) return;
|
|
88
|
+
const { closeRenderer } = await renderModule;
|
|
89
|
+
await closeRenderer();
|
|
90
|
+
}
|
|
91
|
+
var CliError = class extends Error {
|
|
92
|
+
status;
|
|
93
|
+
constructor(message, status) {
|
|
94
|
+
super(message);
|
|
95
|
+
this.status = status;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
function parseArgs(argv) {
|
|
99
|
+
const flags = /* @__PURE__ */ new Map();
|
|
100
|
+
const positionals = [];
|
|
101
|
+
let command = "";
|
|
102
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
103
|
+
const arg = argv[index] ?? "";
|
|
104
|
+
if (arg === "--") {
|
|
105
|
+
positionals.push(...argv.slice(index + 1));
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
if (arg.startsWith("--")) {
|
|
109
|
+
const eq = arg.indexOf("=");
|
|
110
|
+
const rawName = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
|
|
111
|
+
const name = rawName === "o" ? "output" : rawName;
|
|
112
|
+
if (BOOL_FLAGS.has(rawName) && eq === -1) {
|
|
113
|
+
flags.set(name, true);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const value = eq === -1 ? argv[index + 1] : arg.slice(eq + 1);
|
|
117
|
+
if (eq === -1) index += 1;
|
|
118
|
+
if (value == null || value.startsWith("-")) throw new CliError(`Missing value for --${rawName}`);
|
|
119
|
+
flags.set(name, BOOL_FLAGS.has(rawName) ? value !== "false" : value);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (arg === "-h") {
|
|
123
|
+
flags.set("help", true);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (arg === "-o") {
|
|
127
|
+
const value = argv[index + 1];
|
|
128
|
+
index += 1;
|
|
129
|
+
if (value == null || value.startsWith("-")) throw new CliError("Missing value for -o");
|
|
130
|
+
flags.set("output", value);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (!command) command = arg;
|
|
134
|
+
else positionals.push(arg);
|
|
135
|
+
}
|
|
136
|
+
return { command, positionals, flags };
|
|
137
|
+
}
|
|
138
|
+
function flagString(flags, name) {
|
|
139
|
+
const value = flags.get(name);
|
|
140
|
+
return typeof value === "string" ? value : void 0;
|
|
141
|
+
}
|
|
142
|
+
function isJson(flags) {
|
|
143
|
+
return flags.get("json") === true;
|
|
144
|
+
}
|
|
145
|
+
function writeOut(io, json, payload, human) {
|
|
146
|
+
if (json) io.stdout(`${JSON.stringify({ ok: true, ...payload })}
|
|
147
|
+
`);
|
|
148
|
+
else io.stdout(human.endsWith("\n") ? human : `${human}
|
|
149
|
+
`);
|
|
150
|
+
}
|
|
151
|
+
function configOf(flags, env) {
|
|
152
|
+
const base = (flagString(flags, "url") ?? env.NERDGRAM_URL ?? "http://127.0.0.1:8787").replace(/\/+$/, "");
|
|
153
|
+
const token = flagString(flags, "token") ?? env.NERDGRAM_TOKEN ?? "";
|
|
154
|
+
return { base, token };
|
|
155
|
+
}
|
|
156
|
+
function requireToken(token) {
|
|
157
|
+
if (!token.trim()) throw new CliError("Set NERDGRAM_TOKEN or pass --token.");
|
|
158
|
+
return token.trim();
|
|
159
|
+
}
|
|
160
|
+
async function callApi(base, token, method, apiPath, body) {
|
|
161
|
+
const headers = {};
|
|
162
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
163
|
+
if (body !== void 0 || method !== "GET") headers["Content-Type"] = "application/json";
|
|
164
|
+
let response;
|
|
165
|
+
try {
|
|
166
|
+
response = await fetch(`${base}${apiPath}`, {
|
|
167
|
+
method,
|
|
168
|
+
headers,
|
|
169
|
+
body: body === void 0 ? method === "GET" ? void 0 : "{}" : JSON.stringify(body)
|
|
170
|
+
});
|
|
171
|
+
} catch (err) {
|
|
172
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
173
|
+
throw new CliError(`Could not reach ${base}. ${message}`);
|
|
174
|
+
}
|
|
175
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
176
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
177
|
+
let json = void 0;
|
|
178
|
+
if (contentType.includes("json") || !contentType.includes("image/") && bytes.length > 0 && bytes[0] === 123) {
|
|
179
|
+
try {
|
|
180
|
+
json = JSON.parse(bytes.toString("utf8"));
|
|
181
|
+
} catch {
|
|
182
|
+
json = void 0;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (!response.ok) {
|
|
186
|
+
const record = json && typeof json === "object" ? json : {};
|
|
187
|
+
const message = typeof record.error === "string" ? record.error : `Request failed (${response.status})`;
|
|
188
|
+
throw new CliError(message, response.status);
|
|
189
|
+
}
|
|
190
|
+
return { status: response.status, json, bytes, contentType };
|
|
191
|
+
}
|
|
192
|
+
function formatOf(output) {
|
|
193
|
+
const lower = output.toLowerCase();
|
|
194
|
+
if (lower.endsWith(".svg")) return "svg";
|
|
195
|
+
if (lower.endsWith(".png")) return "png";
|
|
196
|
+
throw new CliError("The output file must end in .svg or .png.");
|
|
197
|
+
}
|
|
198
|
+
async function pathExists(file) {
|
|
199
|
+
try {
|
|
200
|
+
const stat = await fs.stat(file);
|
|
201
|
+
return stat.isFile();
|
|
202
|
+
} catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async function renderCommand(parsed, io) {
|
|
207
|
+
const target = parsed.positionals[0];
|
|
208
|
+
const output = flagString(parsed.flags, "output");
|
|
209
|
+
if (!target) throw new CliError("render needs a file or a workspace path.");
|
|
210
|
+
if (!output) throw new CliError("render needs -o out.svg or -o out.png.");
|
|
211
|
+
const format = formatOf(output);
|
|
212
|
+
const local = !parsed.flags.get("server") && await pathExists(target);
|
|
213
|
+
let bytes;
|
|
214
|
+
if (local) {
|
|
215
|
+
const source = await fs.readFile(target, "utf8");
|
|
216
|
+
const { renderDiagram } = await loadRender();
|
|
217
|
+
const rendered = await renderDiagram({ source, format });
|
|
218
|
+
bytes = rendered.body;
|
|
219
|
+
} else {
|
|
220
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
221
|
+
const result = await callApi(base, requireToken(token), "POST", "/api/v1/render", { path: target, format });
|
|
222
|
+
bytes = result.bytes;
|
|
223
|
+
}
|
|
224
|
+
await fs.mkdir(path.dirname(path.resolve(output)), { recursive: true });
|
|
225
|
+
await fs.writeFile(output, bytes);
|
|
226
|
+
writeOut(io, isJson(parsed.flags), { output, format, bytes: bytes.length, offline: local }, `Wrote ${output}`);
|
|
227
|
+
}
|
|
228
|
+
async function listCommand(parsed, io) {
|
|
229
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
230
|
+
const folder = parsed.positionals[0] ?? "";
|
|
231
|
+
const result = await callApi(base, requireToken(token), "GET", `/api/v1/diagrams?path=${encodeURIComponent(folder)}`);
|
|
232
|
+
const body = result.json;
|
|
233
|
+
const lines = [
|
|
234
|
+
...(body.folders ?? []).map((item) => `${item.path}/`),
|
|
235
|
+
...(body.files ?? []).map((item) => item.path)
|
|
236
|
+
];
|
|
237
|
+
writeOut(io, isJson(parsed.flags), { path: body.path ?? folder, folders: body.folders ?? [], files: body.files ?? [] }, lines.join("\n") || "(empty)");
|
|
238
|
+
}
|
|
239
|
+
async function searchCommand(parsed, io) {
|
|
240
|
+
const query = parsed.positionals.join(" ").trim();
|
|
241
|
+
if (!query) throw new CliError("search needs a query.");
|
|
242
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
243
|
+
const result = await callApi(base, requireToken(token), "GET", `/api/v1/search?q=${encodeURIComponent(query)}`);
|
|
244
|
+
const body = result.json;
|
|
245
|
+
const lines = (body.hits ?? []).map((hit) => `${hit.path}:${hit.line ?? 1}: ${hit.snippet}`);
|
|
246
|
+
writeOut(io, isJson(parsed.flags), { query, hits: body.hits ?? [] }, lines.join("\n") || "(no matches)");
|
|
247
|
+
}
|
|
248
|
+
async function getCommand(parsed, io) {
|
|
249
|
+
const itemPath = parsed.positionals[0];
|
|
250
|
+
if (!itemPath) throw new CliError("get needs a workspace path.");
|
|
251
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
252
|
+
const result = await callApi(base, requireToken(token), "GET", `/api/v1/diagrams/content?path=${encodeURIComponent(itemPath)}`);
|
|
253
|
+
const body = result.json;
|
|
254
|
+
const output = flagString(parsed.flags, "output");
|
|
255
|
+
if (output) {
|
|
256
|
+
await fs.mkdir(path.dirname(path.resolve(output)), { recursive: true });
|
|
257
|
+
await fs.writeFile(output, body.content, "utf8");
|
|
258
|
+
}
|
|
259
|
+
writeOut(
|
|
260
|
+
io,
|
|
261
|
+
isJson(parsed.flags),
|
|
262
|
+
{ path: body.path, hash: body.hash, mtimeMs: body.mtimeMs, content: body.content, output: output ?? null },
|
|
263
|
+
output ? `Wrote ${output}` : body.content
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
async function putCommand(parsed, io) {
|
|
267
|
+
const itemPath = parsed.positionals[0];
|
|
268
|
+
const file = parsed.positionals[1];
|
|
269
|
+
if (!itemPath || !file) throw new CliError("put needs a workspace path and a local file.");
|
|
270
|
+
const content = await fs.readFile(file, "utf8");
|
|
271
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
272
|
+
const result = await callApi(base, requireToken(token), "PUT", "/api/v1/diagrams", { path: itemPath, content, force: true });
|
|
273
|
+
const body = result.json;
|
|
274
|
+
writeOut(io, isJson(parsed.flags), { path: body.path, hash: body.hash ?? null }, `Wrote ${body.path}`);
|
|
275
|
+
}
|
|
276
|
+
async function exportCommand(parsed, io) {
|
|
277
|
+
const folder = parsed.positionals[0] ?? "";
|
|
278
|
+
const output = flagString(parsed.flags, "output");
|
|
279
|
+
if (!output) throw new CliError("export needs -o directory.");
|
|
280
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
281
|
+
const result = await callApi(base, requireToken(token), "GET", `/api/v1/export?path=${encodeURIComponent(folder)}`);
|
|
282
|
+
const body = result.json;
|
|
283
|
+
const root = path.resolve(output);
|
|
284
|
+
await fs.mkdir(root, { recursive: true });
|
|
285
|
+
let count = 0;
|
|
286
|
+
for (const file of body.files ?? []) {
|
|
287
|
+
const destination = path.resolve(root, file.path);
|
|
288
|
+
const relative = path.relative(root, destination);
|
|
289
|
+
if (relative.startsWith("..") || path.isAbsolute(relative)) throw new CliError(`Refusing to write ${file.path}`);
|
|
290
|
+
await fs.mkdir(path.dirname(destination), { recursive: true });
|
|
291
|
+
await fs.writeFile(destination, file.content, "utf8");
|
|
292
|
+
count += 1;
|
|
293
|
+
}
|
|
294
|
+
writeOut(io, isJson(parsed.flags), { path: folder, output, count }, `Exported ${count} diagram${count === 1 ? "" : "s"} to ${output}`);
|
|
295
|
+
}
|
|
296
|
+
async function lintCommand(parsed, io) {
|
|
297
|
+
const target = parsed.positionals[0] ?? flagString(parsed.flags, "source");
|
|
298
|
+
const strict = parsed.flags.get("strict") === true;
|
|
299
|
+
let diagnostics;
|
|
300
|
+
let label = target ?? "(workspace)";
|
|
301
|
+
if (target && (flagString(parsed.flags, "source") || await pathExists(target))) {
|
|
302
|
+
const source = await fs.readFile(target, "utf8");
|
|
303
|
+
const { lintDiagramSource } = await loadLint();
|
|
304
|
+
diagnostics = await lintDiagramSource(source, { sourcePath: target });
|
|
305
|
+
label = target;
|
|
306
|
+
} else {
|
|
307
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
308
|
+
const apiPath = target ? `/api/v1/lint?path=${encodeURIComponent(target)}` : "/api/v1/lint";
|
|
309
|
+
const result = await callApi(base, requireToken(token), "GET", apiPath);
|
|
310
|
+
const body = result.json;
|
|
311
|
+
if (body.diagrams) {
|
|
312
|
+
diagnostics = body.diagrams.flatMap(
|
|
313
|
+
(diagram) => diagram.diagnostics.map((item) => ({ ...item, message: `${diagram.path}: ${item.message}` }))
|
|
314
|
+
);
|
|
315
|
+
writeOut(
|
|
316
|
+
io,
|
|
317
|
+
isJson(parsed.flags),
|
|
318
|
+
{ checked: body.checked ?? 0, diagrams: body.diagrams },
|
|
319
|
+
diagnostics.map((item) => `${item.ruleId}: ${item.message}`).join("\n") || `Checked ${body.checked ?? 0} diagrams.`
|
|
320
|
+
);
|
|
321
|
+
const failed2 = body.diagrams.some(
|
|
322
|
+
(diagram) => diagram.diagnostics.some((item) => item.severity === "error" || strict && diagram.diagnostics.length > 0)
|
|
323
|
+
);
|
|
324
|
+
return failed2 ? 1 : 0;
|
|
325
|
+
}
|
|
326
|
+
diagnostics = body.diagnostics ?? [];
|
|
327
|
+
}
|
|
328
|
+
const lines = diagnostics.map((item) => `${label}:${item.line}: ${item.severity}: ${item.ruleId}: ${item.message}`);
|
|
329
|
+
writeOut(io, isJson(parsed.flags), { path: label, diagnostics }, lines.join("\n") || "No problems.");
|
|
330
|
+
const failed = diagnostics.some((item) => item.severity === "error" || strict && diagnostics.length > 0);
|
|
331
|
+
return failed ? 1 : 0;
|
|
332
|
+
}
|
|
333
|
+
async function repairLinksCommand(parsed, io) {
|
|
334
|
+
const apply = parsed.flags.get("apply") === true && parsed.flags.get("dry-run") !== true;
|
|
335
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
336
|
+
const result = apply ? await callApi(base, requireToken(token), "POST", "/api/v1/link-repairs", { dryRun: false, confirm: true }) : await callApi(base, requireToken(token), "GET", "/api/v1/link-repairs");
|
|
337
|
+
const body = result.json;
|
|
338
|
+
const lines = [];
|
|
339
|
+
for (const change of body.changes ?? []) {
|
|
340
|
+
lines.push(change.path);
|
|
341
|
+
for (const link of change.links) lines.push(` line ${link.line}: ${link.target} -> ${link.next}`);
|
|
342
|
+
}
|
|
343
|
+
const ambiguous = (body.suggestions ?? []).filter((item) => item.to == null || item.match === "ambiguous");
|
|
344
|
+
for (const dataFile of body.dataFiles ?? []) {
|
|
345
|
+
lines.push(`${dataFile.diagram}: ${dataFile.from} -> ${dataFile.to}`);
|
|
346
|
+
}
|
|
347
|
+
if (ambiguous.length > 0) {
|
|
348
|
+
lines.push("Ambiguous, not changed:");
|
|
349
|
+
for (const item of ambiguous) lines.push(` ${item.from} matches ${item.candidates.join(", ")}`);
|
|
350
|
+
}
|
|
351
|
+
if (lines.length === 0) lines.push("No link repairs.");
|
|
352
|
+
else if (!apply) lines.push("Nothing was written. Run nerdgram repair-links --apply to update these files.");
|
|
353
|
+
else if ((body.saved ?? []).length > 0) lines.push(`Updated ${(body.saved ?? []).join(", ")}`);
|
|
354
|
+
else lines.push("No files needed a rewrite.");
|
|
355
|
+
writeOut(
|
|
356
|
+
io,
|
|
357
|
+
isJson(parsed.flags),
|
|
358
|
+
{
|
|
359
|
+
applied: body.applied === true,
|
|
360
|
+
saved: body.saved ?? [],
|
|
361
|
+
suggestions: body.suggestions ?? [],
|
|
362
|
+
changes: body.changes ?? [],
|
|
363
|
+
dataFiles: body.dataFiles ?? []
|
|
364
|
+
},
|
|
365
|
+
lines.join("\n")
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
async function renameCommand(parsed, io) {
|
|
369
|
+
const from = parsed.positionals[0];
|
|
370
|
+
const to = parsed.positionals[1];
|
|
371
|
+
if (!from || !to) throw new CliError("rename needs the current path and the new path.");
|
|
372
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
373
|
+
const result = await callApi(base, requireToken(token), "POST", "/api/v1/diagrams/rename", {
|
|
374
|
+
from,
|
|
375
|
+
to,
|
|
376
|
+
updateLinks: parsed.flags.get("no-update-links") !== true
|
|
377
|
+
});
|
|
378
|
+
const body = result.json;
|
|
379
|
+
const moved = (body.dataFiles ?? []).map((item) => item.to).join(", ");
|
|
380
|
+
writeOut(io, isJson(parsed.flags), body, moved ? `Renamed ${body.path}. Data file ${moved}.` : `Renamed ${body.path}`);
|
|
381
|
+
}
|
|
382
|
+
async function moveCommand(parsed, io) {
|
|
383
|
+
const from = parsed.positionals[0];
|
|
384
|
+
if (!from) throw new CliError("move needs the diagram or folder to move.");
|
|
385
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
386
|
+
const result = await callApi(base, requireToken(token), "POST", "/api/v1/diagrams/move", {
|
|
387
|
+
from,
|
|
388
|
+
toFolder: parsed.positionals[1] ?? "",
|
|
389
|
+
updateLinks: parsed.flags.get("no-update-links") !== true
|
|
390
|
+
});
|
|
391
|
+
const body = result.json;
|
|
392
|
+
const moved = (body.dataFiles ?? []).map((item) => item.to).join(", ");
|
|
393
|
+
writeOut(io, isJson(parsed.flags), body, moved ? `Moved to ${body.path}. Data file ${moved}.` : `Moved to ${body.path}`);
|
|
394
|
+
}
|
|
395
|
+
async function duplicateCommand(parsed, io) {
|
|
396
|
+
const itemPath = parsed.positionals[0];
|
|
397
|
+
if (!itemPath) throw new CliError("duplicate needs a diagram or folder path.");
|
|
398
|
+
const copyData = parsed.flags.get("copy-data") === true;
|
|
399
|
+
const shareData = parsed.flags.get("share-data") === true;
|
|
400
|
+
if (copyData && shareData) throw new CliError("Pass either --copy-data or --share-data.");
|
|
401
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
402
|
+
const result = await callApi(base, requireToken(token), "POST", "/api/v1/diagrams/duplicate", {
|
|
403
|
+
path: itemPath,
|
|
404
|
+
...copyData ? { copyData: true } : {},
|
|
405
|
+
...shareData ? { copyData: false } : {}
|
|
406
|
+
});
|
|
407
|
+
const body = result.json;
|
|
408
|
+
const copied = (body.dataFiles ?? []).map((item) => item.to).join(", ");
|
|
409
|
+
const human = copied ? `Duplicated as ${body.path}. Data file ${copied}.` : shareData ? `Duplicated as ${body.path}. It shares the original data file.` : `Duplicated as ${body.path}`;
|
|
410
|
+
writeOut(io, isJson(parsed.flags), body, human);
|
|
411
|
+
}
|
|
412
|
+
async function deleteCommand(parsed, io) {
|
|
413
|
+
const itemPath = parsed.positionals[0];
|
|
414
|
+
if (!itemPath) throw new CliError("delete needs a diagram or folder path.");
|
|
415
|
+
const withData = parsed.flags.get("with-data") === true;
|
|
416
|
+
const keepData = parsed.flags.get("keep-data") === true;
|
|
417
|
+
if (withData && keepData) throw new CliError("Pass either --with-data or --keep-data.");
|
|
418
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
419
|
+
const result = await callApi(base, requireToken(token), "DELETE", "/api/v1/diagrams", {
|
|
420
|
+
path: itemPath,
|
|
421
|
+
confirmLinks: true,
|
|
422
|
+
...withData ? { deleteData: true } : {},
|
|
423
|
+
...keepData ? { deleteData: false } : {}
|
|
424
|
+
});
|
|
425
|
+
const body = result.json;
|
|
426
|
+
writeOut(io, isJson(parsed.flags), body, `Moved ${body.path ?? itemPath} to the trash.`);
|
|
427
|
+
}
|
|
428
|
+
async function generateCommand(parsed, io) {
|
|
429
|
+
const diagramPath = flagString(parsed.flags, "path") ?? parsed.positionals[0];
|
|
430
|
+
const dataFile = flagString(parsed.flags, "data");
|
|
431
|
+
if (!diagramPath || !dataFile) {
|
|
432
|
+
throw new CliError("generate needs --path Diagram.mmd and --data file.csv, file.json, file.cdp, or file.lldp.");
|
|
433
|
+
}
|
|
434
|
+
const text = await fs.readFile(dataFile, "utf8");
|
|
435
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
436
|
+
const result = await callApi(base, requireToken(token), "POST", "/api/v1/generate", {
|
|
437
|
+
path: diagramPath,
|
|
438
|
+
text,
|
|
439
|
+
format: flagString(parsed.flags, "format"),
|
|
440
|
+
shape: flagString(parsed.flags, "shape"),
|
|
441
|
+
direction: flagString(parsed.flags, "direction"),
|
|
442
|
+
title: flagString(parsed.flags, "title"),
|
|
443
|
+
localDevice: flagString(parsed.flags, "local-device"),
|
|
444
|
+
groupBy: flagString(parsed.flags, "group-by")
|
|
445
|
+
});
|
|
446
|
+
const body = result.json;
|
|
447
|
+
writeOut(io, isJson(parsed.flags), body, `Created ${body.path}${body.dataPath ? ` from ${body.dataPath}` : ""}`);
|
|
448
|
+
}
|
|
449
|
+
async function diffCommand(parsed, io) {
|
|
450
|
+
const itemPath = parsed.positionals[0];
|
|
451
|
+
const from = flagString(parsed.flags, "from");
|
|
452
|
+
if (!itemPath || !from) throw new CliError("diff needs a path and --from <id|name|current>.");
|
|
453
|
+
const to = flagString(parsed.flags, "to") ?? "current";
|
|
454
|
+
const format = (flagString(parsed.flags, "format") ?? (isJson(parsed.flags) ? "json" : "md")).toLowerCase();
|
|
455
|
+
if (format !== "md" && format !== "json" && format !== "svg") {
|
|
456
|
+
throw new CliError("format must be md, json, or svg.");
|
|
457
|
+
}
|
|
458
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
459
|
+
const apiPath = `/api/v1/history/diff?path=${encodeURIComponent(itemPath)}&from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
|
|
460
|
+
const result = await callApi(base, requireToken(token), "GET", apiPath);
|
|
461
|
+
const body = result.json;
|
|
462
|
+
if (format === "svg") {
|
|
463
|
+
const output2 = flagString(parsed.flags, "output");
|
|
464
|
+
if (!output2) throw new CliError("diff --format svg needs -o file.svg.");
|
|
465
|
+
if (!output2.toLowerCase().endsWith(".svg")) throw new CliError("The output file must end in .svg.");
|
|
466
|
+
if (!body.visualSource) {
|
|
467
|
+
throw new CliError(body.note ?? "This diagram has no visual diff. Use --format md or json.");
|
|
468
|
+
}
|
|
469
|
+
const { renderDiagram } = await loadRender();
|
|
470
|
+
const rendered = await renderDiagram({ source: body.visualSource, format: "svg" });
|
|
471
|
+
await fs.mkdir(path.dirname(path.resolve(output2)), { recursive: true });
|
|
472
|
+
await fs.writeFile(output2, rendered.body);
|
|
473
|
+
writeOut(
|
|
474
|
+
io,
|
|
475
|
+
isJson(parsed.flags),
|
|
476
|
+
{ path: itemPath, from, to, output: output2, format, summary: body.summary ?? [] },
|
|
477
|
+
`Wrote ${output2}`
|
|
478
|
+
);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
if (format === "json") {
|
|
482
|
+
writeOut(io, true, body ?? {}, "");
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
const markdown = body.markdown ?? (body.summary ?? []).map((line) => `- ${line}`).join("\n");
|
|
486
|
+
const output = flagString(parsed.flags, "output");
|
|
487
|
+
if (output) {
|
|
488
|
+
await fs.mkdir(path.dirname(path.resolve(output)), { recursive: true });
|
|
489
|
+
await fs.writeFile(output, markdown.endsWith("\n") ? markdown : `${markdown}
|
|
490
|
+
`, "utf8");
|
|
491
|
+
writeOut(io, isJson(parsed.flags), { path: itemPath, from, to, output, format, summary: body.summary ?? [] }, `Wrote ${output}`);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
writeOut(io, isJson(parsed.flags), { path: itemPath, from, to, format, markdown, summary: body.summary ?? [] }, markdown);
|
|
495
|
+
}
|
|
496
|
+
async function baselineCommand(parsed, io) {
|
|
497
|
+
const itemPath = parsed.positionals[0];
|
|
498
|
+
const name = flagString(parsed.flags, "name");
|
|
499
|
+
if (!itemPath || !name) throw new CliError('baseline needs a path and --name "\u2026".');
|
|
500
|
+
const note = flagString(parsed.flags, "note");
|
|
501
|
+
const id = flagString(parsed.flags, "id");
|
|
502
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
503
|
+
const result = await callApi(base, requireToken(token), "POST", "/api/v1/history/baseline", {
|
|
504
|
+
path: itemPath,
|
|
505
|
+
name,
|
|
506
|
+
...id ? { id } : {},
|
|
507
|
+
...note != null ? { note } : {}
|
|
508
|
+
});
|
|
509
|
+
const body = result.json;
|
|
510
|
+
writeOut(
|
|
511
|
+
io,
|
|
512
|
+
isJson(parsed.flags),
|
|
513
|
+
body && typeof body === "object" ? body : {},
|
|
514
|
+
`Saved baseline ${body.name ?? name}${body.id ? ` (${body.id})` : ""}.`
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
function skipLabel(reason) {
|
|
518
|
+
switch (reason) {
|
|
519
|
+
case "locked":
|
|
520
|
+
return "open in an editor";
|
|
521
|
+
case "changed":
|
|
522
|
+
return "changed since the preview";
|
|
523
|
+
case "edited":
|
|
524
|
+
return "edited since the replace";
|
|
525
|
+
case "hidden":
|
|
526
|
+
case "meta":
|
|
527
|
+
case "not-diagram":
|
|
528
|
+
return "not a workspace diagram";
|
|
529
|
+
default:
|
|
530
|
+
return reason;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
async function replaceCommand(parsed, io) {
|
|
534
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
535
|
+
const undo = flagString(parsed.flags, "undo");
|
|
536
|
+
if (undo) {
|
|
537
|
+
const result2 = await callApi(base, requireToken(token), "POST", "/api/v1/replace/undo", { id: undo });
|
|
538
|
+
const body2 = result2.json;
|
|
539
|
+
const restored = body2.restored ?? [];
|
|
540
|
+
const skipped = (body2.skipped ?? []).filter((item) => item.reason !== "none");
|
|
541
|
+
const lines2 = [`Restored ${restored.length} diagram${restored.length === 1 ? "" : "s"}.`];
|
|
542
|
+
for (const item of skipped) lines2.push(`Skipped ${item.path} (${skipLabel(item.reason)}).`);
|
|
543
|
+
for (const item of body2.errors ?? []) lines2.push(`${item.path}: ${item.message}`);
|
|
544
|
+
writeOut(io, isJson(parsed.flags), body2 ?? {}, lines2.join("\n"));
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
if (parsed.flags.get("dry-run") === true && parsed.flags.get("yes") === true) {
|
|
548
|
+
throw new CliError("Use either --dry-run or --yes.");
|
|
549
|
+
}
|
|
550
|
+
const find = parsed.positionals[0];
|
|
551
|
+
const replace = parsed.positionals[1];
|
|
552
|
+
if (find == null || replace == null) throw new CliError("replace needs the text to find and the replacement.");
|
|
553
|
+
const folder = flagString(parsed.flags, "folder");
|
|
554
|
+
const request = {
|
|
555
|
+
find,
|
|
556
|
+
replace,
|
|
557
|
+
matchCase: parsed.flags.get("match-case") === true,
|
|
558
|
+
wholeWord: parsed.flags.get("whole-word") === true,
|
|
559
|
+
regex: parsed.flags.get("regex") === true,
|
|
560
|
+
includeFrontMatter: parsed.flags.get("front-matter") === true,
|
|
561
|
+
scope: {
|
|
562
|
+
...folder ? { folder } : {},
|
|
563
|
+
...parsed.flags.get("no-recursive") === true ? { recursive: false } : {}
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
const preview = await callApi(base, requireToken(token), "POST", "/api/v1/replace/preview", request);
|
|
567
|
+
const body = preview.json;
|
|
568
|
+
const files = body.files ?? [];
|
|
569
|
+
const totals = body.totals ?? { replacements: 0, diagrams: 0, shown: 0 };
|
|
570
|
+
if (parsed.flags.get("yes") !== true) {
|
|
571
|
+
const lines2 = [`${totals.replacements} replacement${totals.replacements === 1 ? "" : "s"} in ${totals.diagrams} diagram${totals.diagrams === 1 ? "" : "s"}.`];
|
|
572
|
+
if (body.message) lines2.push(body.message);
|
|
573
|
+
for (const file of files) {
|
|
574
|
+
const notes = [file.selected ? "" : "left unchecked"];
|
|
575
|
+
if (file.lint.invalid) notes.push("would not parse");
|
|
576
|
+
if (file.generatedWarning) notes.push(file.generatedWarning);
|
|
577
|
+
const suffix = notes.filter(Boolean).join("; ");
|
|
578
|
+
lines2.push(`${file.path} (${file.matchCount})${suffix ? ` \u2014 ${suffix}` : ""}`);
|
|
579
|
+
for (const match of file.matches) {
|
|
580
|
+
const warn = match.warnings.length ? ` [${match.warnings.join(", ")}]` : "";
|
|
581
|
+
lines2.push(` ${match.line}: ${match.before} \u2192 ${match.after}${warn}`);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
lines2.push("Nothing was written. Pass --yes to apply.");
|
|
585
|
+
writeOut(io, isJson(parsed.flags), preview.json ?? {}, lines2.join("\n"));
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
const selected = files.filter((file) => file.selected).map((file) => ({ path: file.path, hash: file.hash }));
|
|
589
|
+
const applied = await callApi(base, requireToken(token), "POST", "/api/v1/replace/apply", { ...request, files: selected });
|
|
590
|
+
const result = applied.json;
|
|
591
|
+
const changed = result.totals ?? { diagrams: 0, replacements: 0 };
|
|
592
|
+
const lines = [`Replaced ${changed.replacements} in ${changed.diagrams} diagram${changed.diagrams === 1 ? "" : "s"}.`];
|
|
593
|
+
for (const item of (result.skipped ?? []).filter((entry) => entry.reason !== "none")) {
|
|
594
|
+
lines.push(`Skipped ${item.path} (${skipLabel(item.reason)}).`);
|
|
595
|
+
}
|
|
596
|
+
for (const item of result.errors ?? []) lines.push(`${item.path}: ${item.message}`);
|
|
597
|
+
const leftOut = files.filter((file) => !file.selected);
|
|
598
|
+
if (leftOut.length > 0) {
|
|
599
|
+
lines.push(`Left out ${leftOut.length} diagram${leftOut.length === 1 ? "" : "s"} that would not parse.`);
|
|
600
|
+
}
|
|
601
|
+
if (result.operationId) lines.push(`Undo with nerdgram replace --undo ${result.operationId}`);
|
|
602
|
+
writeOut(io, isJson(parsed.flags), applied.json ?? {}, lines.join("\n"));
|
|
603
|
+
}
|
|
604
|
+
async function refreshCommand(parsed, io) {
|
|
605
|
+
const diagramPath = parsed.positionals[0] ?? flagString(parsed.flags, "path");
|
|
606
|
+
if (!diagramPath) throw new CliError("refresh needs a diagram path.");
|
|
607
|
+
const dataFile = flagString(parsed.flags, "data");
|
|
608
|
+
const text = dataFile ? await fs.readFile(dataFile, "utf8") : void 0;
|
|
609
|
+
const { base, token } = configOf(parsed.flags, io.env);
|
|
610
|
+
const result = await callApi(base, requireToken(token), "POST", "/api/v1/generate/refresh", {
|
|
611
|
+
path: diagramPath,
|
|
612
|
+
text,
|
|
613
|
+
save: true,
|
|
614
|
+
writeData: text != null
|
|
615
|
+
});
|
|
616
|
+
const body = result.json;
|
|
617
|
+
writeOut(io, isJson(parsed.flags), body, `Refreshed ${body.path}`);
|
|
618
|
+
}
|
|
619
|
+
async function main(argv, io = {}) {
|
|
620
|
+
const streams = {
|
|
621
|
+
stdout: io.stdout ?? ((chunk) => process.stdout.write(chunk)),
|
|
622
|
+
stderr: io.stderr ?? ((chunk) => process.stderr.write(chunk)),
|
|
623
|
+
env: io.env ?? process.env
|
|
624
|
+
};
|
|
625
|
+
let parsed;
|
|
626
|
+
try {
|
|
627
|
+
parsed = parseArgs(argv);
|
|
628
|
+
} catch (err) {
|
|
629
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
630
|
+
streams.stderr(`${message}
|
|
631
|
+
`);
|
|
632
|
+
return 1;
|
|
633
|
+
}
|
|
634
|
+
if (parsed.flags.get("help") === true || parsed.command === "help" || parsed.command === "") {
|
|
635
|
+
streams.stdout(HELP);
|
|
636
|
+
return parsed.command === "" && parsed.flags.get("help") !== true && parsed.positionals.length === 0 ? 0 : 0;
|
|
637
|
+
}
|
|
638
|
+
try {
|
|
639
|
+
switch (parsed.command) {
|
|
640
|
+
case "render":
|
|
641
|
+
await renderCommand(parsed, streams);
|
|
642
|
+
return 0;
|
|
643
|
+
case "list":
|
|
644
|
+
await listCommand(parsed, streams);
|
|
645
|
+
return 0;
|
|
646
|
+
case "search":
|
|
647
|
+
await searchCommand(parsed, streams);
|
|
648
|
+
return 0;
|
|
649
|
+
case "get":
|
|
650
|
+
await getCommand(parsed, streams);
|
|
651
|
+
return 0;
|
|
652
|
+
case "put":
|
|
653
|
+
await putCommand(parsed, streams);
|
|
654
|
+
return 0;
|
|
655
|
+
case "export":
|
|
656
|
+
await exportCommand(parsed, streams);
|
|
657
|
+
return 0;
|
|
658
|
+
case "lint":
|
|
659
|
+
return await lintCommand(parsed, streams);
|
|
660
|
+
case "repair-links":
|
|
661
|
+
await repairLinksCommand(parsed, streams);
|
|
662
|
+
return 0;
|
|
663
|
+
case "rename":
|
|
664
|
+
await renameCommand(parsed, streams);
|
|
665
|
+
return 0;
|
|
666
|
+
case "move":
|
|
667
|
+
await moveCommand(parsed, streams);
|
|
668
|
+
return 0;
|
|
669
|
+
case "duplicate":
|
|
670
|
+
await duplicateCommand(parsed, streams);
|
|
671
|
+
return 0;
|
|
672
|
+
case "delete":
|
|
673
|
+
await deleteCommand(parsed, streams);
|
|
674
|
+
return 0;
|
|
675
|
+
case "generate":
|
|
676
|
+
await generateCommand(parsed, streams);
|
|
677
|
+
return 0;
|
|
678
|
+
case "refresh":
|
|
679
|
+
await refreshCommand(parsed, streams);
|
|
680
|
+
return 0;
|
|
681
|
+
case "diff":
|
|
682
|
+
await diffCommand(parsed, streams);
|
|
683
|
+
return 0;
|
|
684
|
+
case "baseline":
|
|
685
|
+
await baselineCommand(parsed, streams);
|
|
686
|
+
return 0;
|
|
687
|
+
case "replace":
|
|
688
|
+
await replaceCommand(parsed, streams);
|
|
689
|
+
return 0;
|
|
690
|
+
default:
|
|
691
|
+
throw new CliError(`Unknown command ${parsed.command}. Run nerdgram --help.`);
|
|
692
|
+
}
|
|
693
|
+
} catch (err) {
|
|
694
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
695
|
+
const status = err instanceof CliError ? err.status : void 0;
|
|
696
|
+
if (isJson(parsed.flags)) streams.stdout(`${JSON.stringify({ ok: false, error: message, status: status ?? null })}
|
|
697
|
+
`);
|
|
698
|
+
else streams.stderr(`${message}
|
|
699
|
+
`);
|
|
700
|
+
return 1;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
function isDirectRun() {
|
|
704
|
+
const entry = process.argv[1];
|
|
705
|
+
if (!entry) return false;
|
|
706
|
+
const invoked = path.resolve(entry);
|
|
707
|
+
const self = fileURLToPath(import.meta.url);
|
|
708
|
+
return invoked === self || invoked.endsWith(`${path.sep}cli.ts`) || invoked.endsWith(`${path.sep}cli.js`);
|
|
709
|
+
}
|
|
710
|
+
if (isDirectRun()) {
|
|
711
|
+
main(process.argv.slice(2)).then(async (code) => {
|
|
712
|
+
await shutdownCli();
|
|
713
|
+
process.exit(code);
|
|
714
|
+
}).catch(async (err) => {
|
|
715
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
716
|
+
await shutdownCli().catch(() => void 0);
|
|
717
|
+
process.exit(1);
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
export {
|
|
721
|
+
main,
|
|
722
|
+
shutdownCli
|
|
723
|
+
};
|