@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
@@ -0,0 +1,62 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import fg from 'fast-glob';
5
+ import { errMessage, isDrawings } from '@diagc/core/internal';
6
+ import { loadModel } from '../compile.js';
7
+ /** A sidecar's JSON, nothing when there is no file, or why it is left out: it does
8
+ * not parse, or `shape` refuses it. */
9
+ async function readSidecar(file, shape) {
10
+ if (!existsSync(file))
11
+ return {};
12
+ let value;
13
+ try {
14
+ value = JSON.parse(await readFile(file, 'utf8'));
15
+ }
16
+ catch (e) {
17
+ return { why: `does not parse (${errMessage(e)})` };
18
+ }
19
+ return shape === undefined || shape.fits(value) ? { value } : { why: `not ${shape.what}` };
20
+ }
21
+ /** Compile every source under `diagramsDir/src` in memory — nothing is written. */
22
+ export async function loadDiagramSet(label, diagramsDir, coreEntry) {
23
+ const srcDir = path.join(diagramsDir, 'src');
24
+ const versions = new Map();
25
+ const errors = new Map();
26
+ const warnings = [];
27
+ const files = existsSync(srcDir) ? await fg('**/*.diagram.{ts,json}', { cwd: srcDir }) : [];
28
+ for (const rel of files.sort()) {
29
+ const name = rel.replace(/\.diagram\.(ts|json)$/, '');
30
+ let model;
31
+ try {
32
+ model = await loadModel(path.join(srcDir, rel), {
33
+ rootDir: srcDir,
34
+ ...(coreEntry !== undefined ? { coreEntry } : {}),
35
+ });
36
+ }
37
+ catch (e) {
38
+ errors.set(name, errMessage(e));
39
+ continue;
40
+ }
41
+ // A sidecar that cannot be read is left out of the picture and named, as publish
42
+ // does with malformed drawings: the model is still compared.
43
+ const layout = await readSidecar(path.join(srcDir, `${name}.layout.json`));
44
+ const drawings = await readSidecar(path.join(srcDir, `${name}.drawings.json`), {
45
+ fits: isDrawings,
46
+ what: 'a drawings overlay',
47
+ });
48
+ for (const [file, read] of [
49
+ [`${name}.layout.json`, layout],
50
+ [`${name}.drawings.json`, drawings],
51
+ ]) {
52
+ if (read.why !== undefined)
53
+ warnings.push(`${file} at ${label}: ${read.why} — compared and drawn without it`);
54
+ }
55
+ versions.set(name, {
56
+ model,
57
+ ...(layout.value !== undefined ? { layout: layout.value } : {}),
58
+ ...(drawings.value !== undefined ? { drawings: drawings.value } : {}),
59
+ });
60
+ }
61
+ return { label, diagramsDir, versions, errors, warnings };
62
+ }
@@ -0,0 +1,17 @@
1
+ import type { DiagramDiff } from './compare.js';
2
+ import type { DiagramSet } from './load.js';
3
+ /**
4
+ * The colours the pictures outline a change in, which the key's swatches show. The
5
+ * renderer draws with its own copy, `.dg-canvas`'s `--dg-diff-*` in
6
+ * packages/renderer/src/styles.css; the CLI cannot import the renderer, so
7
+ * overview.test.ts holds the two together.
8
+ */
9
+ export declare const DIFF_MARK_COLORS: {
10
+ readonly added: "#16a34a";
11
+ readonly removed: "#dc2626";
12
+ readonly changed: "#d97706";
13
+ };
14
+ export declare function indexHtml(diffs: readonly DiagramDiff[], files: Map<string, {
15
+ before?: string;
16
+ after?: string;
17
+ }>, before: DiagramSet, after: DiagramSet): string;
@@ -0,0 +1,86 @@
1
+ import { THEME_HEAD_SCRIPT, THEME_SWITCH, themeCss } from '../publish/pageTheme.js';
2
+ import { describeDiff } from './describe.js';
3
+ const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
4
+ /**
5
+ * The colours the pictures outline a change in, which the key's swatches show. The
6
+ * renderer draws with its own copy, `.dg-canvas`'s `--dg-diff-*` in
7
+ * packages/renderer/src/styles.css; the CLI cannot import the renderer, so
8
+ * overview.test.ts holds the two together.
9
+ */
10
+ export const DIFF_MARK_COLORS = { added: '#16a34a', removed: '#dc2626', changed: '#d97706' };
11
+ // The overview's two palettes. The frames are export renders and stay light in both, and
12
+ // so do the swatches of the key, which show the outline colours drawn in those pictures.
13
+ const OVERVIEW_LIGHT = '--bg:#fff;--card:#fff;--border:#d0d7de;--text:#1f2328;--muted:#57606a;--faint:#8c959f;' +
14
+ '--add:#16a34a;--del:#dc2626;--chg:#b45309';
15
+ const OVERVIEW_DARK = '--bg:#12161b;--card:#1b222b;--border:#2d3743;--text:#e6ebf0;--muted:#a3afbb;--faint:#8b98a5;' +
16
+ '--add:#4ade80;--del:#f87171;--chg:#fbbf24';
17
+ // The overview's own rules, after the theme's: an entry per line of the stylesheet.
18
+ const OVERVIEW_CSS = [
19
+ 'body { font: 14px/1.45 system-ui, sans-serif; margin: 0 auto; padding: 16px 24px 48px; max-width: 1800px; ' +
20
+ 'color: var(--text); background: var(--bg); }',
21
+ 'header { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }',
22
+ 'h1 { font-size: 20px; } h2 { font-size: 16px; margin: 32px 0 6px; } ' +
23
+ 'h3 { font-size: 13px; margin: 0 0 6px; color: var(--muted); }',
24
+ 'ul { margin: 0 0 12px; padding-left: 18px; font-family: ui-monospace, monospace; font-size: 12.5px; }',
25
+ 'li.add { color: var(--add); } li.del { color: var(--del); } li.chg { color: var(--chg); }',
26
+ '.key span { display: inline-block; margin-right: 14px; } ' +
27
+ '.key i { display: inline-block; width: 12px; height: 12px; border: 3px solid; border-radius: 3px; ' +
28
+ 'vertical-align: -2px; margin-right: 4px; }',
29
+ '.pair { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }',
30
+ '.side iframe { width: 100%; height: 70vh; border: 1px solid var(--border); border-radius: 6px; }',
31
+ '.side.empty p { height: 70vh; margin: 0; display: grid; place-items: center; ' +
32
+ 'border: 1px dashed var(--border); border-radius: 6px; color: var(--faint); }',
33
+ '@media (max-width: 900px) { .pair { grid-template-columns: 1fr; } }',
34
+ ]
35
+ .map((line) => ` ${line}`)
36
+ .join('\n');
37
+ /** One swatch of the key: a box with the border `style` gives it, and what that means. */
38
+ const swatch = (style, meaning) => `<span><i style="${style}"></i>${meaning}</span>`;
39
+ const KEY = `<p class="key">${[
40
+ swatch(`border-color:${DIFF_MARK_COLORS.added}`, 'added'),
41
+ swatch(`border-color:${DIFF_MARK_COLORS.removed};border-style:dashed`, 'removed'),
42
+ swatch(`border-color:${DIFF_MARK_COLORS.changed}`, 'changed'),
43
+ swatch(`border-color:${DIFF_MARK_COLORS.changed};border-style:dashed`, 'holds a change (folded box, on the linked pages)'),
44
+ ].join('')}</p>`;
45
+ export function indexHtml(diffs, files, before, after) {
46
+ const from = before.label;
47
+ const to = after.label;
48
+ // The frames load each page unfolded (`?export=1`, the PNG's own mode): side by
49
+ // side, the whole picture is the point. The headings link the interactive pages.
50
+ const side = (rel, label) => {
51
+ const heading = escapeHtml(label);
52
+ if (rel === undefined)
53
+ return `<div class="side empty"><h3>${heading}</h3><p>not present</p></div>`;
54
+ const page = `${escapeHtml(rel)}.html`;
55
+ const frame = `<iframe src="${page}?export=1" title="${heading}"></iframe>`;
56
+ return `<div class="side"><h3><a href="${page}">${heading}</a></h3>${frame}</div>`;
57
+ };
58
+ // A diagram that did not compile has no pictures, but is listed as the summary lists it.
59
+ const sections = diffs.flatMap((d) => {
60
+ if (d.status === 'unchanged')
61
+ return [];
62
+ if (d.status === 'error')
63
+ return [`<section><h2>${escapeHtml(d.name)}</h2><p>Not compared: ${escapeHtml(d.error)}</p></section>`];
64
+ const f = files.get(d.name) ?? {};
65
+ const list = describeDiff(d)
66
+ .map((l) => `<li class="${l[0] === '+' ? 'add' : l[0] === '-' ? 'del' : 'chg'}">${escapeHtml(l)}</li>`)
67
+ .join('');
68
+ const pair = `<div class="pair">${side(f.before, `Before · ${from}`)}${side(f.after, `After · ${to}`)}</div>`;
69
+ return [`<section><h2>${escapeHtml(d.name)}</h2><ul>${list}</ul>${pair}</section>`];
70
+ });
71
+ const warnings = [...before.warnings, ...after.warnings];
72
+ const notes = warnings.length === 0 ? '' : `<ul>${warnings.map((w) => `<li>${escapeHtml(w)}</li>`).join('')}</ul>\n`;
73
+ return `<!doctype html>
74
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
75
+ <title>Diagram diff ${escapeHtml(from)} → ${escapeHtml(to)}</title>
76
+ ${THEME_HEAD_SCRIPT}
77
+ <style>
78
+ ${themeCss(OVERVIEW_LIGHT, OVERVIEW_DARK)}
79
+ ${OVERVIEW_CSS}
80
+ </style></head><body>
81
+ <header><h1>Diagram diff · ${escapeHtml(from)} → ${escapeHtml(to)}</h1>${THEME_SWITCH}</header>
82
+ ${KEY}
83
+ ${notes}${sections.length > 0 ? sections.join('\n') : '<p>No diagram changed.</p>'}
84
+ </body></html>
85
+ `;
86
+ }
@@ -0,0 +1,27 @@
1
+ import type { DiagramDiff } from './compare.js';
2
+ import type { DiagramSet } from './load.js';
3
+ export interface DiffPagesOptions {
4
+ outDir: string;
5
+ shellPath: string;
6
+ libraryDir: string;
7
+ before: DiagramSet;
8
+ after: DiagramSet;
9
+ renderPng?: (htmlPath: string, pngPath: string) => Promise<void>;
10
+ /** where `summary.md`'s images will be served from, `{path}` standing for
11
+ * each PNG's path under `outDir` — for a summary posted somewhere else (a PR
12
+ * comment), where the relative links would not resolve */
13
+ imageUrl?: string;
14
+ }
15
+ export interface DiffPagesResult {
16
+ pages: string[];
17
+ images: string[];
18
+ index: string;
19
+ summary: string;
20
+ }
21
+ /**
22
+ * A page per side of every diagram that changed — the same single-file viewer
23
+ * `publish` writes, with the changes outlined — plus a PNG of each when
24
+ * `renderPng` is given, an `index.html` showing the two sides next to each
25
+ * other, and a `summary.md` laid out to paste into an ADR.
26
+ */
27
+ export declare function writeDiffPages(diffs: readonly DiagramDiff[], opts: DiffPagesOptions): Promise<DiffPagesResult>;
@@ -0,0 +1,55 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { diffMarks } from '@diagc/core/internal';
4
+ import { inlineAssets } from '../publish/publish.js';
5
+ import { stampHtml } from '../publish/html.js';
6
+ import { indexHtml } from './overview.js';
7
+ import { summaryMarkdown } from './summary.js';
8
+ /**
9
+ * A page per side of every diagram that changed — the same single-file viewer
10
+ * `publish` writes, with the changes outlined — plus a PNG of each when
11
+ * `renderPng` is given, an `index.html` showing the two sides next to each
12
+ * other, and a `summary.md` laid out to paste into an ADR.
13
+ */
14
+ export async function writeDiffPages(diffs, opts) {
15
+ const shell = await readFile(opts.shellPath, 'utf8');
16
+ await mkdir(opts.outDir, { recursive: true });
17
+ const caches = { before: new Map(), after: new Map() };
18
+ const pages = [];
19
+ const images = [];
20
+ const shown = diffs.filter((d) => d.status === 'added' || d.status === 'removed' || d.status === 'changed');
21
+ const files = new Map();
22
+ for (const d of shown) {
23
+ const entry = { png: opts.renderPng !== undefined };
24
+ const versions = { before: 'before' in d ? d.before : undefined, after: 'after' in d ? d.after : undefined };
25
+ for (const side of ['before', 'after']) {
26
+ const v = versions[side];
27
+ if (v === undefined)
28
+ continue;
29
+ const set = opts[side];
30
+ const model = await inlineAssets(v.model, { libraryDir: opts.libraryDir, assetsDir: path.join(set.diagramsDir, 'src', 'assets') }, caches[side], `diagram "${d.name}" at ${set.label}`);
31
+ const rel = `${d.name}.${side}`;
32
+ const pagePath = path.join(opts.outDir, `${rel}.html`);
33
+ await mkdir(path.dirname(pagePath), { recursive: true });
34
+ await writeFile(pagePath, stampHtml(shell, {
35
+ model,
36
+ ...(v.layout !== undefined ? { layout: v.layout } : {}),
37
+ ...(v.drawings !== undefined ? { drawings: v.drawings } : {}),
38
+ diff: { marks: diffMarks(d.diff, side) },
39
+ }));
40
+ pages.push(pagePath);
41
+ entry[side] = rel;
42
+ if (opts.renderPng !== undefined) {
43
+ const pngPath = path.join(opts.outDir, `${rel}.png`);
44
+ await opts.renderPng(pagePath, pngPath);
45
+ images.push(pngPath);
46
+ }
47
+ }
48
+ files.set(d.name, entry);
49
+ }
50
+ const index = path.join(opts.outDir, 'index.html');
51
+ await writeFile(index, indexHtml(diffs, files, opts.before, opts.after));
52
+ const summary = path.join(opts.outDir, 'summary.md');
53
+ await writeFile(summary, summaryMarkdown({ diffs, files, before: opts.before, after: opts.after, imageUrl: opts.imageUrl }));
54
+ return { pages, images, index, summary };
55
+ }
@@ -0,0 +1,18 @@
1
+ import type { DiagramDiff } from './compare.js';
2
+ import type { DiagramSet } from './load.js';
3
+ /** What `summary.md` is written from. */
4
+ export interface SummaryOptions {
5
+ diffs: readonly DiagramDiff[];
6
+ /** each shown diagram's pages by side, as paths under the output directory without
7
+ * the extension, and whether a PNG was rendered beside each */
8
+ files: Map<string, {
9
+ before?: string;
10
+ after?: string;
11
+ png: boolean;
12
+ }>;
13
+ before: DiagramSet;
14
+ after: DiagramSet;
15
+ /** where the images are served from, as `DiffPagesOptions.imageUrl` */
16
+ imageUrl?: string;
17
+ }
18
+ export declare function summaryMarkdown({ diffs, files, before, after, imageUrl }: SummaryOptions): string;
@@ -0,0 +1,26 @@
1
+ import { describeDiff } from './describe.js';
2
+ export function summaryMarkdown({ diffs, files, before, after, imageUrl }) {
3
+ const from = before.label;
4
+ const to = after.label;
5
+ const png = (rel) => (imageUrl !== undefined ? imageUrl.split('{path}').join(`${rel}.png`) : `${rel}.png`);
6
+ const out = [`# Diagram changes: ${from} → ${to}`, ''];
7
+ for (const w of [...before.warnings, ...after.warnings])
8
+ out.push(`> ${w}`, '');
9
+ const shown = diffs.filter((d) => d.status !== 'unchanged');
10
+ if (shown.length === 0)
11
+ out.push('No diagram changed.', '');
12
+ for (const d of shown) {
13
+ out.push(`## ${d.name}`, '');
14
+ if (d.status === 'error') {
15
+ out.push(`Not compared: ${d.error}`, '');
16
+ continue;
17
+ }
18
+ const f = files.get(d.name);
19
+ const cell = (rel, label) => rel === undefined ? '—' : f?.png === true ? `![${label}](${png(rel)})` : `[${label}](${rel}.html)`;
20
+ out.push(`| Before (${from}) | After (${to}) |`, '| --- | --- |', `| ${cell(f?.before, 'before')} | ${cell(f?.after, 'after')} |`, '');
21
+ for (const l of describeDiff(d))
22
+ out.push(`- \`${l[0]}\` ${l.slice(2)}`);
23
+ out.push('');
24
+ }
25
+ return out.join('\n');
26
+ }
package/dist/eject.js CHANGED
@@ -4,8 +4,7 @@ import path from 'node:path';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { ejectSource, errMessage, validate } from '@diagc/core/internal';
6
6
  import { compileFile, executeDiagramTs } from './compile.js';
7
- import { resolveInclude } from './includes.js';
8
- import { snapshotSession } from './snapshots.js';
7
+ import { lockedResolverFor } from './snapshots.js';
9
8
  export class EjectError extends Error {
10
9
  code;
11
10
  constructor(message, code) {
@@ -109,12 +108,9 @@ export async function ejectDiagram(diagramsDir, artifactsDir, name, opts) {
109
108
  }
110
109
  await writeFile(tsPath, source);
111
110
  await unlink(jsonPath);
112
- // path.dirname(diagramsDir) is the .diagrams root when diagramsDir is
113
- // .diagrams/src — the same rootDir a locked session uses elsewhere.
114
- const snap = snapshotSession(resolveInclude, path.dirname(diagramsDir), 'locked');
115
111
  await compileFile(tsPath, artifactsDir, {
116
112
  rootDir: diagramsDir,
117
- resolver: snap.resolver,
113
+ resolver: lockedResolverFor(diagramsDir),
118
114
  ...(opts?.coreEntry !== undefined ? { coreEntry: opts.coreEntry } : {}),
119
115
  });
120
116
  return { tsPath };
package/dist/git-ref.js CHANGED
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { promisify } from 'node:util';
6
+ import { RELATIVE_PATHS } from './paths.js';
6
7
  const run = promisify(execFile);
7
8
  /** `ref` resolved to a commit, or a readable error for a typo'd tag. */
8
9
  export async function verifyRef(ref, cwd) {
@@ -22,11 +23,28 @@ export async function verifyRef(ref, cwd) {
22
23
  *
23
24
  * `diagramsDir` is relative to `cwd`, which may sit below the repository root.
24
25
  */
25
- export async function checkoutDiagrams(ref, cwd, diagramsDir = '.diagrams') {
26
- const commit = await verifyRef(ref, cwd);
26
+ export async function checkoutDiagrams(ref, cwd, diagramsDir = RELATIVE_PATHS.diagramsDir) {
27
27
  // Every git call below runs at the top level with a top-level path: from a
28
28
  // subdirectory, ls-tree and archive would read their paths relative to it.
29
- const { stdout: top } = await run('git', ['rev-parse', '--show-toplevel'], { cwd });
29
+ // Asked first, so a directory outside any repository hears that, not that its
30
+ // ref does not exist. Git fails this call the same way for other reasons (a bare
31
+ // repository, "dubious ownership" in a container), so those pass on git's own
32
+ // words; a git that did not run at all keeps its own error.
33
+ let top;
34
+ try {
35
+ ({ stdout: top } = await run('git', ['rev-parse', '--show-toplevel'], { cwd }));
36
+ }
37
+ catch (e) {
38
+ const { code, stderr } = e;
39
+ if (typeof code !== 'number')
40
+ throw e;
41
+ const said = typeof stderr === 'string' ? stderr.trim() : '';
42
+ if (said === '' || /not a git repository/i.test(said)) {
43
+ throw new Error(`not a git repository (or any parent): ${cwd}`, { cause: e });
44
+ }
45
+ throw new Error(`git cannot read the repository at ${cwd}: ${said.replace(/^fatal: /, '')}`, { cause: e });
46
+ }
47
+ const commit = await verifyRef(ref, cwd);
30
48
  const { stdout: prefix } = await run('git', ['rev-parse', '--show-prefix'], { cwd });
31
49
  const repoPath = path.posix.normalize(path.posix.join(prefix.trim(), diagramsDir.split(path.sep).join('/')));
32
50
  if (repoPath.startsWith('..'))
package/dist/glob.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { type Options } from 'fast-glob';
2
+ /** The paths `pattern` matches, in path order. fast-glob answers in the order the file
3
+ * system lists entries, which changes from run to run, and so would every output
4
+ * that follows it. */
5
+ export declare function globSorted(pattern: string, options?: Options): Promise<string[]>;
package/dist/glob.js ADDED
@@ -0,0 +1,7 @@
1
+ import fg from 'fast-glob';
2
+ /** The paths `pattern` matches, in path order. fast-glob answers in the order the file
3
+ * system lists entries, which changes from run to run, and so would every output
4
+ * that follows it. */
5
+ export async function globSorted(pattern, options = {}) {
6
+ return (await fg(pattern, options)).sort();
7
+ }
package/dist/init.d.ts CHANGED
@@ -51,9 +51,6 @@ export declare const withAgentsBlock: (existing: string) => {
51
51
  export declare class InitError extends Error {
52
52
  constructor(message: string);
53
53
  }
54
- /** `shop.diagram.ts` and `.diagrams/src/shop` both mean `shop` — the trim `eject`
55
- * applies, so a name copied from a listing is not an "unsafe name". */
56
- export declare function diagramName(arg: string): string;
57
54
  /** Which of `wanted` a `.gitignore` text still lacks. A line counts after trimming,
58
55
  * with or without a leading or trailing slash: `/.diagrams/html` already ignores
59
56
  * what `.diagrams/html/` would. */
package/dist/init.js CHANGED
@@ -3,15 +3,18 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import fg from 'fast-glob';
5
5
  import { errMessage } from '@diagc/core/internal';
6
- import { isSafeName } from './names.js';
6
+ import { diagramName, isSafeName } from './names.js';
7
7
  import { compileFile } from './compile.js';
8
+ import { projectPaths, RELATIVE_PATHS } from './paths.js';
8
9
  import { readStarter, UnknownStarterError } from './starters.js';
9
10
  export const DEFAULT_NAME = 'example';
10
11
  export const DEFAULT_TYPE = 'basic';
11
- const SRC_DIR = '.diagrams/src';
12
- const ARTIFACTS_DIR = '.diagrams/.artifacts';
13
12
  /** build output a repository should not commit; `init` adds what is missing */
14
- export const IGNORED = ['.diagrams/.artifacts/', '.diagrams/html/', '.diagrams/diff/'];
13
+ export const IGNORED = [
14
+ RELATIVE_PATHS.artifactsDir,
15
+ RELATIVE_PATHS.htmlDir,
16
+ RELATIVE_PATHS.diffDir,
17
+ ].map((dir) => `${dir}/`);
15
18
  export const AGENTS_BEGIN = '<!-- diagc:begin -->';
16
19
  export const AGENTS_END = '<!-- diagc:end -->';
17
20
  /** What `--agents` writes. Commands, not DSL: the guide is where the DSL lives, so
@@ -63,11 +66,6 @@ export class InitError extends Error {
63
66
  this.name = 'InitError';
64
67
  }
65
68
  }
66
- /** `shop.diagram.ts` and `.diagrams/src/shop` both mean `shop` — the trim `eject`
67
- * applies, so a name copied from a listing is not an "unsafe name". */
68
- export function diagramName(arg) {
69
- return arg.replace(/^\.diagrams\/src\//, '').replace(/\.diagram\.(ts|json)$/, '');
70
- }
71
69
  /** Which of `wanted` a `.gitignore` text still lacks. A line counts after trimming,
72
70
  * with or without a leading or trailing slash: `/.diagrams/html` already ignores
73
71
  * what `.diagrams/html/` would. */
@@ -79,13 +77,13 @@ export function missingIgnores(existing, wanted = IGNORED) {
79
77
  /** Step 1: the starter. Returns the file it wrote, or nothing when the step was
80
78
  * skipped. Every check comes before the write, so a refusal leaves no file. */
81
79
  async function starterStep(opts, io) {
82
- const srcDir = path.join(opts.cwd, SRC_DIR);
80
+ const { srcDir } = projectPaths(opts.cwd);
83
81
  if (opts.name === undefined && opts.type === undefined) {
84
82
  // A plain `diagc init` in a repository that already has diagrams is here for
85
83
  // the other steps (`--agents` after an upgrade): do not add an `example`.
86
84
  const existing = await fg('**/*.diagram.{ts,json}', { cwd: srcDir });
87
85
  if (existing.length > 0) {
88
- io.out(skipped(SRC_DIR, `already has ${existing.length} diagram(s) — starter skipped`));
86
+ io.out(skipped(RELATIVE_PATHS.srcDir, `already has ${existing.length} diagram(s) — starter skipped`));
89
87
  return undefined;
90
88
  }
91
89
  }
@@ -110,13 +108,13 @@ async function starterStep(opts, io) {
110
108
  }
111
109
  for (const ext of ['ts', 'json']) {
112
110
  if (existsSync(path.join(srcDir, `${name}.diagram.${ext}`))) {
113
- throw new InitError(`${SRC_DIR}/${name}.diagram.${ext} already exists — pick another name, or run 'diagc init' with no name and no --type to leave it alone.`);
111
+ throw new InitError(`${RELATIVE_PATHS.srcDir}/${name}.diagram.${ext} already exists — pick another name, or run 'diagc init' with no name and no --type to leave it alone.`);
114
112
  }
115
113
  }
116
114
  const file = path.join(srcDir, `${name}.diagram.ts`);
117
115
  await mkdir(path.dirname(file), { recursive: true });
118
116
  await writeFile(file, source);
119
- io.out(done(`${SRC_DIR}/${name}.diagram.ts`, `(${type} starter)`));
117
+ io.out(done(`${RELATIVE_PATHS.srcDir}/${name}.diagram.ts`, `(${type} starter)`));
120
118
  return file;
121
119
  }
122
120
  /** Step 2: `.gitignore`. Appends the missing lines; creates the file if there is none. */
@@ -186,10 +184,11 @@ async function skillStep(cwd, plan, io) {
186
184
  /** Step 5: compile what was written, so the user starts from a diagram that is
187
185
  * known to build and sees where the artifact went. */
188
186
  async function compileStep(file, opts, io) {
187
+ const { srcDir, artifactsDir } = projectPaths(opts.cwd);
189
188
  let artifact;
190
189
  try {
191
- artifact = await compileFile(file, path.join(opts.cwd, ARTIFACTS_DIR), {
192
- rootDir: path.join(opts.cwd, SRC_DIR),
190
+ artifact = await compileFile(file, artifactsDir, {
191
+ rootDir: srcDir,
193
192
  coreEntry: opts.coreEntry,
194
193
  ...(opts.resolver !== undefined ? { resolver: opts.resolver } : {}),
195
194
  });
package/dist/names.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  /** A diagram name the API, the CLI and the file tree all agree on: lowercase
2
2
  * letters, digits and `-`, with `/` between folders, every segment non-empty. */
3
3
  export declare function isSafeName(name: string): boolean;
4
+ /** `shop.diagram.ts` and `.diagrams/src/shop` both mean `shop` — the trim `eject`
5
+ * applies, so a name copied from a listing is not an "unsafe name". */
6
+ export declare function diagramName(arg: string): string;
package/dist/names.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { RELATIVE_PATHS } from './paths.js';
1
2
  /** Words the studio API's action routes put after a diagram's name
2
3
  * (`/api/diagrams/<name>/rename`). A name ending in `/<word>` would be read as
3
4
  * that action on its folder, so it could be created and never saved. Alone, the
@@ -11,3 +12,10 @@ export function isSafeName(name) {
11
12
  const slash = name.lastIndexOf('/');
12
13
  return slash < 0 || !ACTION_SEGMENTS.includes(name.slice(slash + 1));
13
14
  }
15
+ const SRC_PREFIX = `${RELATIVE_PATHS.srcDir}/`;
16
+ /** `shop.diagram.ts` and `.diagrams/src/shop` both mean `shop` — the trim `eject`
17
+ * applies, so a name copied from a listing is not an "unsafe name". */
18
+ export function diagramName(arg) {
19
+ const name = arg.startsWith(SRC_PREFIX) ? arg.slice(SRC_PREFIX.length) : arg;
20
+ return name.replace(/\.diagram\.(ts|json)$/, '');
21
+ }
@@ -0,0 +1,29 @@
1
+ /** Every place diagc reads or writes in a project, all under the one `.diagrams` folder
2
+ * at the project's root. */
3
+ export interface ProjectPaths {
4
+ /** the `.diagrams` folder itself */
5
+ readonly diagramsDir: string;
6
+ /** the sources, `*.diagram.ts` and `*.diagram.json`, with their sidecars */
7
+ readonly srcDir: string;
8
+ /** where compile writes artifacts without `--out`, and where the studio reads them */
9
+ readonly artifactsDir: string;
10
+ /** publish's pages and gallery */
11
+ readonly htmlDir: string;
12
+ /** publish's PNGs */
13
+ readonly staticDir: string;
14
+ /** the images the studio saves, beside the sources that show them */
15
+ readonly assetsDir: string;
16
+ /** diff's pages, a folder per range */
17
+ readonly diffDir: string;
18
+ /** the vendored snapshots of remote includes */
19
+ readonly includesDir: string;
20
+ /** the lock that pins each remote include to its vendored snapshot */
21
+ readonly lockFile: string;
22
+ }
23
+ /** The places in the project at `root`, joined as `path.join` joins them: `.` and `..`
24
+ * collapse, and an empty root is the current directory. */
25
+ export declare function projectPaths(root: string): ProjectPaths;
26
+ /** The same places relative to a project's root, spelled with `/` on every platform.
27
+ * The CLI runs at the root and names them this way: a user reads and types them so,
28
+ * and fast-glob patterns and `.gitignore` lines take a backslash for an escape. */
29
+ export declare const RELATIVE_PATHS: ProjectPaths;
package/dist/paths.js ADDED
@@ -0,0 +1,25 @@
1
+ import path from 'node:path';
2
+ function layout(root, join) {
3
+ const diagramsDir = join(root, '.diagrams');
4
+ const srcDir = join(diagramsDir, 'src');
5
+ return {
6
+ diagramsDir,
7
+ srcDir,
8
+ artifactsDir: join(diagramsDir, '.artifacts'),
9
+ htmlDir: join(diagramsDir, 'html'),
10
+ staticDir: join(diagramsDir, 'static'),
11
+ assetsDir: join(srcDir, 'assets'),
12
+ diffDir: join(diagramsDir, 'diff'),
13
+ includesDir: join(diagramsDir, 'includes'),
14
+ lockFile: join(diagramsDir, 'includes.lock.json'),
15
+ };
16
+ }
17
+ /** The places in the project at `root`, joined as `path.join` joins them: `.` and `..`
18
+ * collapse, and an empty root is the current directory. */
19
+ export function projectPaths(root) {
20
+ return layout(root, path.join);
21
+ }
22
+ /** The same places relative to a project's root, spelled with `/` on every platform.
23
+ * The CLI runs at the root and names them this way: a user reads and types them so,
24
+ * and fast-glob patterns and `.gitignore` lines take a backslash for an escape. */
25
+ export const RELATIVE_PATHS = layout('', path.posix.join);
@@ -5,7 +5,8 @@ import fg from 'fast-glob';
5
5
  * with its layout and drawings sidecars from the source tree (artifacts carry
6
6
  * neither — compile never touches a sidecar). */
7
7
  export async function discoverDiagrams(artifactsDir, srcDir) {
8
- const files = await fg('**/*.diagram.json', { cwd: artifactsDir, absolute: true });
8
+ // In path order: fast-glob's follows the file system's, which changes from run to run.
9
+ const files = (await fg('**/*.diagram.json', { cwd: artifactsDir, absolute: true })).sort();
9
10
  const out = [];
10
11
  const exists = async (p) => {
11
12
  try {
@@ -12,11 +12,16 @@ export interface PublishOptions {
12
12
  renderPng?: (htmlPath: string, pngPath: string) => Promise<void>;
13
13
  /** an http(s) address for the gallery's header — never put on a diagram page */
14
14
  link?: string;
15
+ /** where a warning goes, one line each: `console.warn` by default, so a caller with
16
+ * streams of its own (the CLI's) passes its stderr */
17
+ warn?: (line: string) => void;
15
18
  }
16
19
  export interface PublishResult {
17
20
  pages: string[];
18
21
  images: string[];
19
22
  gallery: string;
23
+ /** the diagrams it warned it was skipping, by name */
24
+ skipped: string[];
20
25
  }
21
26
  /**
22
27
  * The model with every image/shape ref it can read swapped for inline data, so
@@ -24,8 +29,5 @@ export interface PublishResult {
24
29
  * (refs are content hashes, so one read serves them all); `label` names the
25
30
  * diagram in the warnings for refs it has to leave as they are.
26
31
  */
27
- export declare function inlineAssets(model: DiagramModel, dirs: {
28
- libraryDir: string;
29
- assetsDir: string;
30
- }, cache: Map<string, Buffer>, label: string): Promise<DiagramModel>;
32
+ export declare function inlineAssets(model: DiagramModel, opts: Pick<PublishOptions, 'libraryDir' | 'assetsDir' | 'warn'>, cache: Map<string, Buffer>, label: string): Promise<DiagramModel>;
31
33
  export declare function publishDiagrams(opts: PublishOptions): Promise<PublishResult>;