@diagc/cli 1.1.6 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/api/assets.d.ts +8 -0
  2. package/dist/api/assets.js +54 -0
  3. package/dist/api/diagrams.d.ts +27 -0
  4. package/dist/api/diagrams.js +269 -0
  5. package/dist/api/files.d.ts +7 -0
  6. package/dist/api/files.js +30 -0
  7. package/dist/api/handlers.d.ts +7 -62
  8. package/dist/api/handlers.js +10 -488
  9. package/dist/api/library.d.ts +5 -0
  10. package/dist/api/library.js +88 -0
  11. package/dist/api/result.d.ts +8 -0
  12. package/dist/api/result.js +5 -0
  13. package/dist/api/sidecars.d.ts +13 -0
  14. package/dist/api/sidecars.js +78 -0
  15. package/dist/cli/command.d.ts +26 -0
  16. package/dist/cli/command.js +1 -0
  17. package/dist/cli/io.d.ts +13 -0
  18. package/dist/cli/io.js +7 -0
  19. package/dist/cli/parse.d.ts +51 -0
  20. package/dist/cli/parse.js +109 -0
  21. package/dist/cli/run.d.ts +10 -0
  22. package/dist/cli/run.js +67 -0
  23. package/dist/cli.d.ts +1 -52
  24. package/dist/cli.js +5 -475
  25. package/dist/commands/compile.d.ts +3 -0
  26. package/dist/commands/compile.js +38 -0
  27. package/dist/commands/diff.d.ts +10 -0
  28. package/dist/commands/diff.js +96 -0
  29. package/dist/commands/eject.d.ts +3 -0
  30. package/dist/commands/eject.js +32 -0
  31. package/dist/commands/guide.d.ts +3 -0
  32. package/dist/commands/guide.js +13 -0
  33. package/dist/commands/init.d.ts +3 -0
  34. package/dist/commands/init.js +23 -0
  35. package/dist/commands/lint.d.ts +3 -0
  36. package/dist/commands/lint.js +27 -0
  37. package/dist/commands/publish.d.ts +11 -0
  38. package/dist/commands/publish.js +83 -0
  39. package/dist/commands/shared.d.ts +19 -0
  40. package/dist/commands/shared.js +34 -0
  41. package/dist/commands/studio.d.ts +3 -0
  42. package/dist/commands/studio.js +14 -0
  43. package/dist/commands/watch.d.ts +8 -0
  44. package/dist/commands/watch.js +45 -0
  45. package/dist/compile.d.ts +4 -1
  46. package/dist/compile.js +8 -13
  47. package/dist/diff/compare.d.ts +36 -0
  48. package/dist/diff/compare.js +36 -0
  49. package/dist/diff/describe.d.ts +8 -0
  50. package/dist/diff/describe.js +70 -0
  51. package/dist/diff/index.d.ts +4 -0
  52. package/dist/diff/index.js +6 -0
  53. package/dist/diff/load.d.ts +22 -0
  54. package/dist/diff/load.js +62 -0
  55. package/dist/diff/overview.d.ts +17 -0
  56. package/dist/diff/overview.js +86 -0
  57. package/dist/diff/pages.d.ts +27 -0
  58. package/dist/diff/pages.js +55 -0
  59. package/dist/diff/summary.d.ts +18 -0
  60. package/dist/diff/summary.js +26 -0
  61. package/dist/eject.js +2 -6
  62. package/dist/git-ref.js +21 -3
  63. package/dist/glob.d.ts +5 -0
  64. package/dist/glob.js +7 -0
  65. package/dist/init.d.ts +0 -3
  66. package/dist/init.js +14 -15
  67. package/dist/names.d.ts +3 -0
  68. package/dist/names.js +8 -0
  69. package/dist/paths.d.ts +29 -0
  70. package/dist/paths.js +25 -0
  71. package/dist/publish/discover.js +2 -1
  72. package/dist/publish/publish.d.ts +6 -4
  73. package/dist/publish/publish.js +11 -7
  74. package/dist/snapshots.d.ts +11 -0
  75. package/dist/snapshots.js +20 -3
  76. package/dist/studio.js +8 -8
  77. package/package.json +2 -2
  78. package/dist/command-args.d.ts +0 -9
  79. package/dist/command-args.js +0 -56
  80. package/dist/diff.d.ts +0 -61
  81. package/dist/diff.js +0 -244
package/dist/cli.js CHANGED
@@ -19,26 +19,8 @@
19
19
  *
20
20
  * SPDX-License-Identifier: AGPL-3.0-only
21
21
  */
22
- import { existsSync, statSync } from 'node:fs';
23
- import path from 'node:path';
24
- import { fileURLToPath } from 'node:url';
25
- import fg from 'fast-glob';
26
- import { errMessage } from '@diagc/core/internal';
27
- import { compileFile } from './compile.js';
28
- import { compareDiagramSets, formatDiffSummary, loadDiagramSet, writeDiffPages } from './diff.js';
29
- import { checkoutDiagrams } from './git-ref.js';
30
- import { ejectDiagram } from './eject.js';
31
- import { formatLintReport, lintFile } from './lint.js';
32
- import { runGuide } from './guide.js';
33
- import { cliVersion, findHome, homePaths } from './home.js';
34
- import { diagramName, runInit } from './init.js';
35
- import { resolveInclude } from './includes.js';
36
- import { snapshotSession } from './snapshots.js';
37
- import { formatCompileEvent, startWatch } from './watch.js';
38
- import { galleryLink } from './publish/gallery.js';
39
- import { publishDiagrams } from './publish/publish.js';
40
- import { runStudio } from './studio.js';
41
- import { ArgNotTakenError, checkCommandArgs } from './command-args.js';
22
+ import { processIo } from './cli/io.js';
23
+ import { run } from './cli/run.js';
42
24
  const USAGE = `Usage: diagc <init|compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
43
25
 
44
26
  Commands:
@@ -71,160 +53,6 @@ Options:
71
53
  the skill into .claude/skills/diagc/ where Claude Code is in use
72
54
  --help, -h Show this help and exit
73
55
  `;
74
- /** Parse argv into command + flags. Unknown flags (anything `--…` that is not
75
- * recognized) are an error rather than being silently treated as a file path,
76
- * so a typo surfaces loudly instead of quietly skewing the file set. */
77
- export function parseArgs(argv) {
78
- let command = 'compile';
79
- const files = [];
80
- let out = '.diagrams/.artifacts';
81
- let outGiven = false;
82
- let images = true;
83
- let updateIncludes = false;
84
- let json = false;
85
- let link;
86
- let imageUrl;
87
- let labels;
88
- let type;
89
- let agents = false;
90
- let commandSeen = false;
91
- for (let i = 0; i < argv.length; i++) {
92
- const arg = argv[i];
93
- if (arg === '--out') {
94
- // No fallback to the default: a trailing --out would quietly write somewhere the
95
- // user did not ask for, and a missing value would swallow the next flag as the dir.
96
- const value = argv[i + 1];
97
- if (value === undefined || value.startsWith('--'))
98
- throw new BadFlagValueError('--out', 'needs a directory, e.g. --out build/artifacts');
99
- out = value;
100
- outGiven = true;
101
- i++;
102
- continue;
103
- }
104
- if (arg === '--no-images') {
105
- images = false;
106
- continue;
107
- }
108
- if (arg === '--update-includes') {
109
- updateIncludes = true;
110
- continue;
111
- }
112
- if (arg === '--json') {
113
- json = true;
114
- continue;
115
- }
116
- if (arg === '--type') {
117
- // No fallback: a missing value would otherwise swallow the next flag as the type.
118
- const value = argv[i + 1];
119
- if (value === undefined || value.startsWith('--'))
120
- throw new BadFlagValueError('--type', "needs a diagram type, e.g. --type c4 ('diagc guide' lists them)");
121
- type = value;
122
- i++;
123
- continue;
124
- }
125
- if (arg === '--agents') {
126
- agents = true;
127
- continue;
128
- }
129
- if (arg === '--image-url') {
130
- const value = argv[++i] ?? '';
131
- if (!value.includes('{path}'))
132
- throw new BadFlagValueError('--image-url', 'needs a {path} placeholder, e.g. https://host/pr-1/{path}');
133
- imageUrl = value;
134
- continue;
135
- }
136
- if (arg === '--labels') {
137
- const parts = (argv[++i] ?? '').split(',');
138
- if (parts.length !== 2 || parts.some((p) => p.trim() === ''))
139
- throw new BadFlagValueError('--labels', 'takes two names, before and after: --labels main,#12');
140
- labels = [parts[0].trim(), parts[1].trim()];
141
- continue;
142
- }
143
- if (arg === '--link') {
144
- // No fallback for a missing value: there is no default address, and the URL
145
- // check is also what stops the next flag being swallowed as one.
146
- const value = argv[++i] ?? '';
147
- try {
148
- galleryLink(value);
149
- }
150
- catch (e) {
151
- throw new BadFlagValueError('--link', errMessage(e));
152
- }
153
- link = value;
154
- continue;
155
- }
156
- if (arg === '--help' || arg === '-h')
157
- throw new HelpRequested();
158
- if (arg.startsWith('--'))
159
- throw new UnknownFlagError(arg);
160
- // The first non-flag argument names the command; anything after it is a
161
- // file path (flags may appear before or after the command).
162
- if (!commandSeen) {
163
- command = arg;
164
- commandSeen = true;
165
- }
166
- else {
167
- files.push(arg);
168
- }
169
- }
170
- return {
171
- command,
172
- files,
173
- out,
174
- outGiven,
175
- images,
176
- updateIncludes,
177
- json,
178
- agents,
179
- ...(type !== undefined ? { type } : {}),
180
- ...(link !== undefined ? { link } : {}),
181
- ...(imageUrl !== undefined ? { imageUrl } : {}),
182
- ...(labels !== undefined ? { labels } : {}),
183
- };
184
- }
185
- /** Thrown by {@link parseArgs} for `--help`/`-h`; `main` prints usage and exits 0. */
186
- export class HelpRequested extends Error {
187
- constructor() {
188
- super('help requested');
189
- this.name = 'HelpRequested';
190
- }
191
- }
192
- /** Thrown by {@link parseArgs} for an unrecognized flag; `main` prints the
193
- * offending flag plus usage and exits 1. */
194
- export class UnknownFlagError extends Error {
195
- constructor(flag) {
196
- super(`Unknown flag '${flag}'`);
197
- this.name = 'UnknownFlagError';
198
- }
199
- }
200
- /** Thrown by {@link parseArgs} for a flag whose value is missing or unusable; `main`
201
- * reports it the same way as an unknown flag. */
202
- export class BadFlagValueError extends Error {
203
- constructor(flag, why) {
204
- super(`${flag}: ${why}`);
205
- this.name = 'BadFlagValueError';
206
- }
207
- }
208
- const SOURCES = '.diagrams/src/**/*.diagram.{ts,json}';
209
- /** The one message a repository with no diagrams gets, on stderr: `lint --json`'s
210
- * stdout stays an array and the exit codes hold, so CI without diagrams passes. */
211
- function warnNoSources(dir = '.diagrams/src') {
212
- console.error(`No diagrams under ${dir} — run 'diagc init' to create one.`);
213
- }
214
- /** Where `publish` compiles to and builds pages from. One object for both steps, so
215
- * the pages are always made from the artifacts this run just wrote. `--out` moves the
216
- * artifacts only: the pages and PNGs stay where `.gitignore`, the docs and the READMEs
217
- * that embed them expect to find them. */
218
- export function publishDirs(args) {
219
- const srcDir = '.diagrams/src';
220
- return {
221
- srcDir,
222
- artifactsDir: args.out,
223
- htmlDir: '.diagrams/html',
224
- staticDir: '.diagrams/static',
225
- assetsDir: path.join(srcDir, 'assets'),
226
- };
227
- }
228
56
  /** End the process once stdout and stderr have taken everything written to them:
229
57
  * `process.exit` straight after a write drops what a pipe has not accepted yet. A
230
58
  * zero-length write's callback runs after everything queued before it. It ends with
@@ -234,306 +62,8 @@ async function exit(code) {
234
62
  await Promise.all([process.stdout, process.stderr].map((s) => new Promise((done) => s.write('', done))));
235
63
  process.exit(code);
236
64
  }
65
+ /** The binary: argv through the process's own streams, then exit with the code. */
237
66
  async function main() {
238
- let args;
239
- try {
240
- args = parseArgs(process.argv.slice(2));
241
- checkCommandArgs(args);
242
- }
243
- catch (e) {
244
- if (e instanceof HelpRequested) {
245
- console.log(USAGE);
246
- return exit(0);
247
- }
248
- if (e instanceof UnknownFlagError || e instanceof BadFlagValueError || e instanceof ArgNotTakenError) {
249
- console.error(`diagc: ${e.message}\n`);
250
- console.error(USAGE);
251
- return exit(1);
252
- }
253
- throw e;
254
- }
255
- const home = homePaths(findHome(fileURLToPath(import.meta.url)));
256
- // One session per CLI invocation, shared across every compile+publish in this
257
- // run: the in-memory lock + touched set must span the whole run for prune()
258
- // to see everything a full-tree compile actually resolved. `watch` builds its
259
- // own separate always-locked session below instead of sharing this one.
260
- const snap = snapshotSession(resolveInclude, '.diagrams', args.updateIncludes ? 'update' : 'locked');
261
- if (args.command === 'compile') {
262
- const files = args.files.length > 0 ? args.files : await fg(SOURCES);
263
- if (args.files.length === 0 && files.length === 0)
264
- warnNoSources();
265
- let failed = false;
266
- for (const file of files) {
267
- try {
268
- const artifact = await compileFile(file, args.out, {
269
- rootDir: '.diagrams/src',
270
- coreEntry: home.coreEntry,
271
- resolver: snap.resolver,
272
- });
273
- console.log(formatCompileEvent({ file, ok: true, artifact }));
274
- }
275
- catch (e) {
276
- failed = true;
277
- console.error(formatCompileEvent({ file, ok: false, error: errMessage(e) }));
278
- }
279
- }
280
- // A source that fails before include resolution (e.g. a pre-compose
281
- // validation error) never touches its remote URLs, so pruning here would
282
- // drop their still-valid lock entries and vendored files right along with
283
- // the genuinely stale ones — skip the prune until every file compiles clean.
284
- if (args.updateIncludes && args.files.length === 0 && !failed)
285
- await snap.prune();
286
- return exit(failed ? 1 : 0);
287
- }
288
- else if (args.command === 'lint') {
289
- const files = args.files.length > 0 ? args.files : await fg(SOURCES);
290
- if (args.files.length === 0 && files.length === 0)
291
- warnNoSources();
292
- const reports = [];
293
- for (const file of files) {
294
- reports.push(...(await lintFile(file, { rootDir: '.diagrams/src', coreEntry: home.coreEntry, resolver: snap.resolver })));
295
- }
296
- if (args.json)
297
- console.log(JSON.stringify(reports, null, 2));
298
- else
299
- for (const r of reports)
300
- console.log(formatLintReport(r));
301
- return exit(reports.length > 0 ? 1 : 0);
302
- }
303
- else if (args.command === 'watch') {
304
- // Always locked, and --update-includes is refused here: watch is a long-running
305
- // live loop with no point at which "refetch and rewrite the lock" makes
306
- // sense, so it has its own session rather than the shared one (mirrors
307
- // studio.ts's own hardcoded 'locked' session).
308
- const dir = args.files[0] ?? '.diagrams/src';
309
- // A directory that does not exist holds no diagrams either; a file is left alone.
310
- if (!existsSync(dir) ||
311
- (statSync(dir).isDirectory() && (await fg('**/*.diagram.{ts,json}', { cwd: dir })).length === 0))
312
- warnNoSources(dir);
313
- const watchSnap = snapshotSession(resolveInclude, '.diagrams', 'locked');
314
- startWatch(dir, args.out, {
315
- coreEntry: home.coreEntry,
316
- resolver: watchSnap.resolver,
317
- onEvent: (e) => {
318
- // Success goes to stdout, failure to stderr, so the streams stay parsed
319
- // separately by anyone piping them.
320
- if (e.ok)
321
- console.log(formatCompileEvent(e));
322
- else
323
- console.error(formatCompileEvent(e));
324
- },
325
- });
326
- console.log(`Watching ${dir} for *.diagram.{ts,json} changes...`);
327
- }
328
- else if (args.command === 'publish') {
329
- if (!existsSync(home.viewerShell)) {
330
- // Only a checkout can be missing it; an installed package ships the shell,
331
- // so there the message would send the reader off to build a repo they
332
- // do not have.
333
- console.error(home.layout === 'monorepo'
334
- ? 'viewer shell not built — run `pnpm --filter @diagc/viewer build` in the monorepo.'
335
- : `viewer shell missing from this install (${home.viewerShell}) — reinstall diagc.`);
336
- return exit(1);
337
- }
338
- const dirs = publishDirs(args);
339
- // Compile first so artifacts reflect current sources (TS + include expansion).
340
- const sources = await fg('**/*.diagram.{ts,json}', { cwd: dirs.srcDir, absolute: true });
341
- if (sources.length === 0)
342
- warnNoSources(dirs.srcDir);
343
- let failed = false;
344
- for (const f of sources) {
345
- try {
346
- await compileFile(f, dirs.artifactsDir, {
347
- rootDir: dirs.srcDir,
348
- coreEntry: home.coreEntry,
349
- resolver: snap.resolver,
350
- });
351
- }
352
- catch (e) {
353
- failed = true;
354
- console.error(`✗ ${f}\n${errMessage(e)}`);
355
- }
356
- }
357
- // publish's glob above ignores args.files (that only scopes which rendered
358
- // pages come out below), so an update run here is always full-tree; like
359
- // compile's, its prune waits until every source compiles.
360
- if (args.updateIncludes && !failed)
361
- await snap.prune();
362
- let images = args.images;
363
- let renderPng;
364
- if (args.images) {
365
- const snapshot = await import('./publish/snapshot.js');
366
- if (snapshot.findChrome() === undefined) {
367
- console.log('No Chrome found — writing HTML only; install Chrome / set CHROME_PATH, or use --no-images.');
368
- images = false;
369
- }
370
- else {
371
- renderPng = snapshot.renderPng;
372
- }
373
- }
374
- const res = await publishDiagrams({
375
- ...dirs,
376
- shellPath: home.viewerShell,
377
- libraryDir: home.libraryDir,
378
- images,
379
- names: args.files,
380
- ...(renderPng !== undefined ? { renderPng } : {}),
381
- ...(args.link !== undefined ? { link: args.link } : {}),
382
- });
383
- console.log(`✓ ${res.pages.length} page(s) -> ${dirs.htmlDir}`);
384
- if (res.images.length > 0)
385
- console.log(`✓ ${res.images.length} image(s) -> ${dirs.staticDir}`);
386
- console.log(`✓ gallery -> ${res.gallery}`);
387
- return exit(0);
388
- }
389
- else if (args.command === 'studio') {
390
- // Studio's own compile-watch loop always resolves includes locked (see
391
- // studio.ts) — same reasoning as watch above.
392
- await runStudio(home, process.cwd());
393
- return;
394
- }
395
- else if (args.command === 'eject') {
396
- // ejectDiagram's post-swap recompile always resolves includes locked (see
397
- // eject.ts) — same reasoning as watch above.
398
- const name = args.files[0] === undefined ? undefined : diagramName(args.files[0]);
399
- if (name === undefined || name === '') {
400
- console.error('diagc: eject needs a diagram name.');
401
- console.error(USAGE);
402
- return exit(1);
403
- }
404
- try {
405
- const res = await ejectDiagram('.diagrams/src', args.out, name, { coreEntry: home.coreEntry });
406
- console.log(`✓ ${res.tsPath}`);
407
- return exit(0);
408
- }
409
- catch (e) {
410
- console.error(errMessage(e));
411
- return exit(1);
412
- }
413
- }
414
- else if (args.command === 'diff') {
415
- return exit(await runDiff(args, home));
416
- }
417
- else if (args.command === 'guide') {
418
- // exitCode and a return, not process.exit: the guide is tens of kilobytes and
419
- // is read through a pipe by an agent. Exiting while part of it is still
420
- // queued would hand over a page that stops mid-sentence.
421
- process.exitCode = runGuide(args.files, {
422
- guideDir: home.guideDir,
423
- startersDir: home.startersDir,
424
- version: cliVersion(home.root),
425
- });
426
- return;
427
- }
428
- else if (args.command === 'init') {
429
- if (args.files.length > 1) {
430
- console.error(`diagc: init takes one name, got ${args.files.length} — e.g. diagc init shop --type c4`);
431
- return exit(1);
432
- }
433
- process.exitCode = await runInit({
434
- cwd: process.cwd(),
435
- ...(args.files[0] !== undefined ? { name: args.files[0] } : {}),
436
- ...(args.type !== undefined ? { type: args.type } : {}),
437
- agents: args.agents,
438
- startersDir: home.startersDir,
439
- skillFile: home.skillFile,
440
- version: cliVersion(home.root),
441
- coreEntry: home.coreEntry,
442
- resolver: snap.resolver,
443
- });
444
- return;
445
- }
446
- else {
447
- console.error(`diagc: Unknown command '${args.command}'.`);
448
- console.error(USAGE);
449
- return exit(1);
450
- }
451
- }
452
- /** `A..B` or `A` (against the working tree). */
453
- export function parseRange(range) {
454
- const at = range.indexOf('..');
455
- if (at === -1)
456
- return { from: range };
457
- const from = range.slice(0, at);
458
- const to = range.slice(at + 2);
459
- if (from === '' || to === '' || to.startsWith('.'))
460
- throw new Error(`'${range}' is not a range: write <from>..<to>, or one ref to compare with the working tree`);
461
- return { from, to };
462
- }
463
- /** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
464
- export function diffOutDir(from, to) {
465
- const safe = (s) => s.replace(/[^A-Za-z0-9._-]+/g, '-');
466
- return path.join('.diagrams', 'diff', `${safe(from)}..${to !== undefined ? safe(to) : 'working-tree'}`);
467
- }
468
- async function runDiff(args, home) {
469
- const range = args.files[0];
470
- if (range === undefined) {
471
- console.error('diagc: diff needs a git ref (diff v1.0) or a range (diff v1.0..v2.0).');
472
- console.error(USAGE);
473
- return 1;
474
- }
475
- const checkouts = [];
476
- try {
477
- const { from, to } = parseRange(range);
478
- const before = await checkoutDiagrams(from, process.cwd());
479
- checkouts.push(before);
480
- let afterDir = '.diagrams';
481
- if (to !== undefined) {
482
- const after = await checkoutDiagrams(to, process.cwd());
483
- checkouts.push(after);
484
- afterDir = after.diagramsDir;
485
- }
486
- const fromLabel = args.labels?.[0] ?? from;
487
- const toLabel = args.labels?.[1] ?? to ?? 'working tree';
488
- const beforeSet = await loadDiagramSet(fromLabel, before.diagramsDir, home.coreEntry);
489
- const afterSet = await loadDiagramSet(toLabel, afterDir, home.coreEntry);
490
- const diffs = compareDiagramSets(beforeSet, afterSet, args.files.slice(1));
491
- if (args.json) {
492
- console.log(JSON.stringify({ from: fromLabel, to: toLabel, diagrams: diffs.map(({ before: _b, after: _a, ...rest }) => rest) }, null, 2));
493
- }
494
- else {
495
- console.log(formatDiffSummary(diffs, fromLabel, toLabel));
496
- }
497
- if (!diffs.some((d) => d.status === 'added' || d.status === 'removed' || d.status === 'changed'))
498
- return 0;
499
- if (!existsSync(home.viewerShell)) {
500
- console.error('viewer shell not available — writing the summary only (see `diagc publish` for how to build it).');
501
- return 0;
502
- }
503
- let renderPng;
504
- if (args.images) {
505
- const snapshot = await import('./publish/snapshot.js');
506
- if (snapshot.findChrome() === undefined)
507
- console.error('No Chrome found — writing HTML only; install Chrome / set CHROME_PATH, or use --no-images.');
508
- else
509
- renderPng = snapshot.renderPng;
510
- }
511
- const outDir = args.outGiven ? args.out : diffOutDir(from, to);
512
- const res = await writeDiffPages(diffs, {
513
- outDir,
514
- shellPath: home.viewerShell,
515
- libraryDir: home.libraryDir,
516
- before: beforeSet,
517
- after: afterSet,
518
- ...(renderPng !== undefined ? { renderPng } : {}),
519
- ...(args.imageUrl !== undefined ? { imageUrl: args.imageUrl } : {}),
520
- });
521
- // stderr, so `--json` output stays parseable on stdout
522
- console.error(`✓ ${res.pages.length} page(s)${res.images.length > 0 ? `, ${res.images.length} image(s)` : ''} -> ${outDir}`);
523
- console.error(`✓ side by side -> ${res.index}`);
524
- console.error(`✓ for an ADR -> ${res.summary}`);
525
- return 0;
526
- }
527
- catch (e) {
528
- console.error(`diagc: ${errMessage(e)}`);
529
- return 1;
530
- }
531
- finally {
532
- for (const c of checkouts)
533
- await c.cleanup();
534
- }
67
+ return exit(await run(process.argv.slice(2), processIo, USAGE));
535
68
  }
536
- main().catch((e) => {
537
- console.error(errMessage(e));
538
- return exit(1);
539
- });
69
+ void main();
@@ -0,0 +1,3 @@
1
+ import type { Command } from '../cli/command.js';
2
+ /** `diagc compile [files...]`: the files named, or every source, into artifacts. */
3
+ export declare const compile: Command<'--out' | '--update-includes'>;
@@ -0,0 +1,38 @@
1
+ import { errMessage } from '@diagc/core/internal';
2
+ import { compileFile } from '../compile.js';
3
+ import { globSorted } from '../glob.js';
4
+ import { RELATIVE_PATHS } from '../paths.js';
5
+ import { formatCompileEvent } from '../watch.js';
6
+ import { SOURCES, warnNoSources } from './shared.js';
7
+ /** `diagc compile [files...]`: the files named, or every source, into artifacts. */
8
+ export const compile = {
9
+ flags: ['--out', '--update-includes'],
10
+ async run({ positionals, flags }, { io, home, snapshots }) {
11
+ const files = positionals.length > 0 ? positionals : await globSorted(SOURCES);
12
+ if (positionals.length === 0 && files.length === 0)
13
+ warnNoSources(io);
14
+ let failed = false;
15
+ for (const file of files) {
16
+ try {
17
+ const artifact = await compileFile(file, flags['--out'] ?? RELATIVE_PATHS.artifactsDir, {
18
+ rootDir: RELATIVE_PATHS.srcDir,
19
+ coreEntry: home.coreEntry,
20
+ resolver: snapshots.resolver,
21
+ warn: io.err,
22
+ });
23
+ io.out(formatCompileEvent({ file, ok: true, artifact }));
24
+ }
25
+ catch (e) {
26
+ failed = true;
27
+ io.err(formatCompileEvent({ file, ok: false, error: errMessage(e) }));
28
+ }
29
+ }
30
+ // A source that fails before include resolution (e.g. a pre-compose
31
+ // validation error) never touches its remote URLs, so pruning here would
32
+ // drop their still-valid lock entries and vendored files right along with
33
+ // the genuinely stale ones — skip the prune until every file compiles clean.
34
+ if (flags['--update-includes'] === true && positionals.length === 0 && !failed)
35
+ await snapshots.prune();
36
+ return failed ? 1 : 0;
37
+ },
38
+ };
@@ -0,0 +1,10 @@
1
+ import type { Command } from '../cli/command.js';
2
+ /** `A..B` or `A` (against the working tree). */
3
+ export declare function parseRange(range: string): {
4
+ from: string;
5
+ to?: string;
6
+ };
7
+ /** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
8
+ export declare function diffOutDir(from: string, to: string | undefined): string;
9
+ /** `diagc diff <from>[..<to>] [names...]`: what changed, and the pages that show it. */
10
+ export declare const diff: Command<'--out' | '--no-images' | '--json' | '--labels' | '--image-url'>;
@@ -0,0 +1,96 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { errMessage } from '@diagc/core/internal';
4
+ import { compareDiagramSets, formatDiffJson, formatDiffSummary, loadDiagramSet, writeDiffPages, } from '../diff/index.js';
5
+ import { checkoutDiagrams } from '../git-ref.js';
6
+ import { RELATIVE_PATHS } from '../paths.js';
7
+ import { diagramNames, pngRenderer } from './shared.js';
8
+ /** `A..B` or `A` (against the working tree). */
9
+ export function parseRange(range) {
10
+ const at = range.indexOf('..');
11
+ if (at === -1)
12
+ return { from: range };
13
+ const from = range.slice(0, at);
14
+ const to = range.slice(at + 2);
15
+ if (from === '' || to === '' || to.startsWith('.'))
16
+ throw new Error(`'${range}' is not a range: write <from>..<to>, or one ref to compare with the working tree`);
17
+ return { from, to };
18
+ }
19
+ /** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
20
+ export function diffOutDir(from, to) {
21
+ const safe = (s) => s.replace(/[^A-Za-z0-9._-]+/g, '-');
22
+ return path.join(RELATIVE_PATHS.diffDir, `${safe(from)}..${to !== undefined ? safe(to) : 'working-tree'}`);
23
+ }
24
+ /** Each sidecar diff left out of its pictures, on stderr so `--json` stays parseable. */
25
+ function warnLeftOut(io, ...sets) {
26
+ for (const set of sets)
27
+ for (const w of set.warnings)
28
+ io.err(w);
29
+ }
30
+ /** `diagc diff <from>[..<to>] [names...]`: what changed, and the pages that show it. */
31
+ export const diff = {
32
+ flags: ['--out', '--no-images', '--json', '--labels', '--image-url'],
33
+ async run({ positionals, flags }, { io, usage, home }) {
34
+ const range = positionals[0];
35
+ if (range === undefined) {
36
+ io.err('diagc: diff needs a git ref (diff v1.0) or a range (diff v1.0..v2.0).');
37
+ io.err(usage);
38
+ return 1;
39
+ }
40
+ const checkouts = [];
41
+ try {
42
+ const { from, to } = parseRange(range);
43
+ const before = await checkoutDiagrams(from, process.cwd());
44
+ checkouts.push(before);
45
+ let afterDir = RELATIVE_PATHS.diagramsDir;
46
+ if (to !== undefined) {
47
+ const after = await checkoutDiagrams(to, process.cwd());
48
+ checkouts.push(after);
49
+ afterDir = after.diagramsDir;
50
+ }
51
+ const fromLabel = flags['--labels']?.[0] ?? from;
52
+ const toLabel = flags['--labels']?.[1] ?? to ?? 'working tree';
53
+ const beforeSet = await loadDiagramSet(fromLabel, before.diagramsDir, home.coreEntry);
54
+ const afterSet = await loadDiagramSet(toLabel, afterDir, home.coreEntry);
55
+ warnLeftOut(io, beforeSet, afterSet);
56
+ const known = new Set([beforeSet, afterSet].flatMap((set) => [...set.versions.keys(), ...set.errors.keys()]));
57
+ const names = diagramNames(io, positionals.slice(1), known);
58
+ if (names === undefined)
59
+ return 1;
60
+ const diffs = compareDiagramSets(beforeSet, afterSet, names);
61
+ io.out(flags['--json'] === true
62
+ ? formatDiffJson(diffs, fromLabel, toLabel)
63
+ : formatDiffSummary(diffs, fromLabel, toLabel));
64
+ if (!diffs.some((d) => d.status === 'added' || d.status === 'removed' || d.status === 'changed'))
65
+ return 0;
66
+ if (!existsSync(home.viewerShell)) {
67
+ io.err('viewer shell not available — writing the summary only (see `diagc publish` for how to build it).');
68
+ return 0;
69
+ }
70
+ const renderPng = await pngRenderer(io, flags['--no-images'] !== true);
71
+ const outDir = flags['--out'] ?? diffOutDir(from, to);
72
+ const res = await writeDiffPages(diffs, {
73
+ outDir,
74
+ shellPath: home.viewerShell,
75
+ libraryDir: home.libraryDir,
76
+ before: beforeSet,
77
+ after: afterSet,
78
+ ...(renderPng !== undefined ? { renderPng } : {}),
79
+ ...(flags['--image-url'] !== undefined ? { imageUrl: flags['--image-url'] } : {}),
80
+ });
81
+ // stderr, so `--json` output stays parseable on stdout
82
+ io.err(`✓ ${res.pages.length} page(s)${res.images.length > 0 ? `, ${res.images.length} image(s)` : ''} -> ${outDir}`);
83
+ io.err(`✓ side by side -> ${res.index}`);
84
+ io.err(`✓ for an ADR -> ${res.summary}`);
85
+ return 0;
86
+ }
87
+ catch (e) {
88
+ io.err(`diagc: ${errMessage(e)}`);
89
+ return 1;
90
+ }
91
+ finally {
92
+ for (const c of checkouts)
93
+ await c.cleanup();
94
+ }
95
+ },
96
+ };
@@ -0,0 +1,3 @@
1
+ import type { Command } from '../cli/command.js';
2
+ /** `diagc eject <name>`: a JSON diagram as a generated TypeScript source. */
3
+ export declare const eject: Command<'--out'>;