@diagc/cli 1.5.0 → 1.6.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.
Files changed (73) hide show
  1. package/assets/guide/index.md +1 -1
  2. package/assets/skill/SKILL.md +1 -1
  3. package/dist/cli/io.d.ts +5 -0
  4. package/dist/cli/io.js +4 -0
  5. package/dist/cli/parse.d.ts +7 -0
  6. package/dist/cli/parse.js +25 -0
  7. package/dist/cli/run.js +4 -0
  8. package/dist/cli.js +23 -1
  9. package/dist/commands/shared.d.ts +4 -0
  10. package/dist/commands/shared.js +13 -0
  11. package/dist/commands/show.d.ts +5 -0
  12. package/dist/commands/show.js +115 -0
  13. package/dist/commands/tui.d.ts +3 -0
  14. package/dist/commands/tui.js +36 -0
  15. package/dist/init.d.ts +1 -1
  16. package/dist/init.js +1 -1
  17. package/dist/text/accents.d.ts +9 -0
  18. package/dist/text/accents.js +83 -0
  19. package/dist/text/ansi.d.ts +28 -0
  20. package/dist/text/ansi.js +111 -0
  21. package/dist/text/braille.d.ts +28 -0
  22. package/dist/text/braille.js +58 -0
  23. package/dist/text/canvas.d.ts +65 -0
  24. package/dist/text/canvas.js +155 -0
  25. package/dist/text/content.d.ts +32 -0
  26. package/dist/text/content.js +90 -0
  27. package/dist/text/fish.d.ts +27 -0
  28. package/dist/text/fish.js +209 -0
  29. package/dist/text/folds.d.ts +14 -0
  30. package/dist/text/folds.js +45 -0
  31. package/dist/text/glyphs.d.ts +31 -0
  32. package/dist/text/glyphs.js +84 -0
  33. package/dist/text/layout.d.ts +61 -0
  34. package/dist/text/layout.js +334 -0
  35. package/dist/text/legend.d.ts +44 -0
  36. package/dist/text/legend.js +252 -0
  37. package/dist/text/paint.d.ts +25 -0
  38. package/dist/text/paint.js +208 -0
  39. package/dist/text/render.d.ts +11 -0
  40. package/dist/text/render.js +28 -0
  41. package/dist/text/scene.d.ts +40 -0
  42. package/dist/text/scene.js +50 -0
  43. package/dist/text/vocabulary.d.ts +37 -0
  44. package/dist/text/vocabulary.js +211 -0
  45. package/dist/text/width.d.ts +15 -0
  46. package/dist/text/width.js +181 -0
  47. package/dist/tui/actions.d.ts +10 -0
  48. package/dist/tui/actions.js +297 -0
  49. package/dist/tui/app.d.ts +31 -0
  50. package/dist/tui/app.js +389 -0
  51. package/dist/tui/details.d.ts +3 -0
  52. package/dist/tui/details.js +54 -0
  53. package/dist/tui/keys.d.ts +33 -0
  54. package/dist/tui/keys.js +113 -0
  55. package/dist/tui/kitty.d.ts +36 -0
  56. package/dist/tui/kitty.js +65 -0
  57. package/dist/tui/legend.d.ts +14 -0
  58. package/dist/tui/legend.js +18 -0
  59. package/dist/tui/nav.d.ts +25 -0
  60. package/dist/tui/nav.js +79 -0
  61. package/dist/tui/overview.d.ts +46 -0
  62. package/dist/tui/overview.js +115 -0
  63. package/dist/tui/pixels.d.ts +28 -0
  64. package/dist/tui/pixels.js +80 -0
  65. package/dist/tui/screen.d.ts +44 -0
  66. package/dist/tui/screen.js +335 -0
  67. package/dist/tui/state.d.ts +100 -0
  68. package/dist/tui/state.js +72 -0
  69. package/dist/tui/terminal.d.ts +21 -0
  70. package/dist/tui/terminal.js +53 -0
  71. package/dist/watch.d.ts +2 -0
  72. package/dist/watch.js +1 -0
  73. package/package.json +3 -2
@@ -8,7 +8,7 @@ This guide is for diagc {{version}}.
8
8
 
9
9
  1. Write or edit `.diagrams/src/<name>.diagram.ts`. A folder is allowed: `.diagrams/src/team/app.diagram.ts` is the diagram `team/app`.
10
10
  2. Run `diagc lint --json`. It prints `[]` and exits 0 when everything is clean. Otherwise each finding has `file`, `severity`, `code` and `message`: fix it and run again. An `error` means the diagram does not compile. A `warning` compiles but is probably a mistake, such as a misspelled type.
11
- 3. Run `diagc publish <name>` and look at `.diagrams/static/<name>.png` to check the picture. It needs Chrome; set `CHROME_PATH` when none is found. The PNG shows the first plane with every group opened and only the layers that plane turns on; each further plane gets `.diagrams/static/<name>.<plane>.png`, and the other layers are on the page `.diagrams/html/<name>.html`.
11
+ 3. Run `diagc show <name>` to read the picture as text: the boxes, what sits inside what, and the arrows with their labels, every group open. It needs nothing else. Run `diagc publish <name>` and look at `.diagrams/static/<name>.png` to check the picture itself. It needs Chrome; set `CHROME_PATH` when none is found. The PNG shows the first plane with every group opened and only the layers that plane turns on; each further plane gets `.diagrams/static/<name>.<plane>.png`, and the other layers are on the page `.diagrams/html/<name>.html`.
12
12
 
13
13
  A person runs `diagc studio` to browse every diagram and to move boxes by hand.
14
14
 
@@ -17,7 +17,7 @@ A diagram is a TypeScript file under `.diagrams/src/`; `diagc` validates it, lay
17
17
 
18
18
  1. Write or edit `.diagrams/src/<name>.diagram.ts`.
19
19
  2. Run `diagc lint --json` until it prints `[]` and exits 0. Each finding has `file`, `severity`, `code` and `message`: an `error` does not compile, a `warning` compiles but is probably a mistake.
20
- 3. Run `diagc publish <name>` and look at `.diagrams/static/<name>.png`. It needs Chrome (set `CHROME_PATH` when none is found); without one it writes the HTML page only.
20
+ 3. Run `diagc show <name>` and read the picture as text: the boxes, the nesting and the arrows with their labels. Then run `diagc publish <name>` and look at `.diagrams/static/<name>.png`. It needs Chrome (set `CHROME_PATH` when none is found); without one it writes the HTML page only.
21
21
 
22
22
  ## Rules
23
23
 
package/dist/cli/io.d.ts CHANGED
@@ -7,6 +7,11 @@ export interface CliIo {
7
7
  err: (line: string) => void;
8
8
  /** text on stdout as it is */
9
9
  write: (text: string) => void;
10
+ /** set when stdout is a terminal, with its width: what a command that draws reads to
11
+ * colour its output and to say when a picture is wider than the screen */
12
+ readonly tty?: {
13
+ columns: number;
14
+ };
10
15
  }
11
16
  /** The process's own streams. `write` is a plain write, which, unlike console.log's, does
12
17
  * not swallow the error of a reader that has closed the pipe. */
package/dist/cli/io.js CHANGED
@@ -4,4 +4,8 @@ export const processIo = {
4
4
  out: (line) => console.log(line),
5
5
  err: (line) => console.error(line),
6
6
  write: (text) => void process.stdout.write(text),
7
+ // read when asked, not at startup: a terminal's width changes with its window
8
+ get tty() {
9
+ return process.stdout.isTTY ? { columns: process.stdout.columns ?? 80 } : undefined;
10
+ },
7
11
  };
@@ -11,6 +11,13 @@ export interface FlagValues {
11
11
  '--agents': true;
12
12
  '--style': string;
13
13
  '--theme': 'light' | 'dark';
14
+ '--plane': string;
15
+ '--layers': string[];
16
+ '--depth': number;
17
+ '--root': string;
18
+ '--ascii': true;
19
+ '--color': true;
20
+ '--no-color': true;
14
21
  }
15
22
  export type Flag = keyof FlagValues;
16
23
  /** What a command takes, as the parser checks it before the command runs. */
package/dist/cli/parse.js CHANGED
@@ -30,6 +30,13 @@ export const STYLE_IDS = [
30
30
  'ascii',
31
31
  'dos',
32
32
  ];
33
+ /** A flag's value that has to be there: no fallback, since a missing value would
34
+ * otherwise swallow the next flag as the value. */
35
+ const required = (flag, hint) => (next) => {
36
+ if (next === undefined || next.startsWith('--'))
37
+ throw badValue(flag, hint);
38
+ return next;
39
+ };
33
40
  /** Every flag, in the order the refusal of one a command does not take goes through them:
34
41
  * how it reads its value, or null for a flag that takes none. */
35
42
  const FLAGS = {
@@ -87,6 +94,24 @@ const FLAGS = {
87
94
  throw badValue('--theme', 'light or dark, e.g. --theme dark');
88
95
  return next;
89
96
  },
97
+ '--plane': required('--plane', 'needs a plane id, e.g. --plane logical'),
98
+ '--layers': (next) => {
99
+ // An empty value is a choice, not a missing one: no layers at all.
100
+ const value = required('--layers', "needs layer ids, e.g. --layers security,data ('' for none)")(next);
101
+ return value
102
+ .split(',')
103
+ .map((id) => id.trim())
104
+ .filter((id) => id !== '');
105
+ },
106
+ '--depth': (next) => {
107
+ if (next === undefined || !/^\d+$/.test(next))
108
+ throw badValue('--depth', 'a whole number of levels to open, e.g. --depth 1');
109
+ return Number(next);
110
+ },
111
+ '--root': required('--root', 'needs a node id, e.g. --root checkout'),
112
+ '--ascii': null,
113
+ '--color': null,
114
+ '--no-color': null,
90
115
  };
91
116
  const isFlag = (arg) => Object.hasOwn(FLAGS, arg);
92
117
  /** Read argv against every flag there is, whichever command it names: which arguments
package/dist/cli/run.js CHANGED
@@ -7,7 +7,9 @@ import { guide } from '../commands/guide.js';
7
7
  import { init } from '../commands/init.js';
8
8
  import { lint } from '../commands/lint.js';
9
9
  import { publish } from '../commands/publish.js';
10
+ import { show } from '../commands/show.js';
10
11
  import { studio } from '../commands/studio.js';
12
+ import { tui } from '../commands/tui.js';
11
13
  import { watch } from '../commands/watch.js';
12
14
  import { findHome, homePaths } from '../home.js';
13
15
  import { resolveInclude } from '../includes.js';
@@ -21,7 +23,9 @@ export const COMMANDS = {
21
23
  lint,
22
24
  watch,
23
25
  publish,
26
+ show,
24
27
  studio,
28
+ tui,
25
29
  eject,
26
30
  diff,
27
31
  guide,
package/dist/cli.js CHANGED
@@ -21,7 +21,7 @@
21
21
  */
22
22
  import { processIo } from './cli/io.js';
23
23
  import { run } from './cli/run.js';
24
- const USAGE = `Usage: diagc <init|compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
24
+ const USAGE = `Usage: diagc <init|compile|lint|watch|publish|show|studio|tui|eject|diff|guide> [files...] [--out dir]
25
25
 
26
26
  Commands:
27
27
  init init [name] [--type <type>] [--agents]: set a repository up — a starter
@@ -32,7 +32,11 @@ Commands:
32
32
  lint Report suspicious diagrams (typos, duplicates, unused or undrawn parts); exit 1 on any
33
33
  watch Recompile — and live-recompile — a directory of sources
34
34
  publish Compile and render an HTML/PNG site under .diagrams/
35
+ show show <name>: print the diagram as text — boxes, lines and labels in the
36
+ terminal or a pipe, every container open (--depth folds deeper levels)
35
37
  studio Run the visual studio against the current directory
38
+ tui tui [name]: look at the diagrams in the terminal — fold and unfold,
39
+ go into boxes, switch planes and layers, search; redraws as sources change
36
40
  eject Promote a JSON diagram to a generated TypeScript source (verified)
37
41
  diff diff <from>[..<to>] [names...]: what changed in the diagrams between two git
38
42
  refs (or a ref and the working tree), with before/after pages and PNGs
@@ -47,6 +51,12 @@ Options:
47
51
  --style id Publish: take the PNGs in this style preset (clean, sketch, …) in
48
52
  place of each diagram's own
49
53
  --theme t Publish: take the PNGs light (the default) or dark
54
+ --plane id show: draw this plane (default: the first)
55
+ --layers a,b show: draw these layers in place of the plane's own ('' for none)
56
+ --depth n show: open only the top n levels of containers
57
+ --root id show: draw this container's inside only
58
+ --ascii show: plain ASCII in place of box-drawing characters
59
+ --color, --no-color show: colour or not, whatever stdout is (default: a terminal is)
50
60
  --json lint: print the findings as a JSON array; diff: the changes as JSON
51
61
  --labels a,b diff: name the two sides (default: the refs)
52
62
  --image-url t diff: summary.md's image links as t, {path} standing for each PNG
@@ -65,8 +75,20 @@ async function exit(code) {
65
75
  await Promise.all([process.stdout, process.stderr].map((s) => new Promise((done) => s.write('', done))));
66
76
  process.exit(code);
67
77
  }
78
+ /** A reader that stops early (`diagc show big | head`, quitting `less`) closes the
79
+ * pipe, and what is left to write has nowhere to go. That is the reader's choice, not
80
+ * the command failing: end quietly, as other tools do, rather than with a stack trace. */
81
+ function quietOnClosedPipe(stream) {
82
+ stream.on('error', (e) => {
83
+ if (e.code === 'EPIPE')
84
+ process.exit(0);
85
+ throw e;
86
+ });
87
+ }
68
88
  /** The binary: argv through the process's own streams, then exit with the code. */
69
89
  async function main() {
90
+ quietOnClosedPipe(process.stdout);
91
+ quietOnClosedPipe(process.stderr);
70
92
  return exit(await run(process.argv.slice(2), processIo, USAGE));
71
93
  }
72
94
  void main();
@@ -17,3 +17,7 @@ export declare function diagramNames(io: CliIo, files: readonly string[], known:
17
17
  * says so on stderr, and the pages go out as HTML only. Playwright loads only when a
18
18
  * picture is wanted. */
19
19
  export declare function pngRenderer(io: CliIo, images: boolean): Promise<NonNullable<PublishOptions['renderPng']> | undefined>;
20
+ /** The source a diagram name reads from: its `.diagram.ts`, else its `.diagram.json`;
21
+ * undefined when it has neither. TypeScript first, as the hand-written one of the two
22
+ * (a `.diagram.json` beside it is the studio's, or a leftover from an eject). */
23
+ export declare function sourceOf(name: string, srcDir?: string): string | undefined;
@@ -1,3 +1,5 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
1
3
  import { diagramName } from '../names.js';
2
4
  import { RELATIVE_PATHS } from '../paths.js';
3
5
  /** The sources compile and lint read when they are named none. */
@@ -32,3 +34,14 @@ export async function pngRenderer(io, images) {
32
34
  }
33
35
  return snapshot.renderPng;
34
36
  }
37
+ /** The source a diagram name reads from: its `.diagram.ts`, else its `.diagram.json`;
38
+ * undefined when it has neither. TypeScript first, as the hand-written one of the two
39
+ * (a `.diagram.json` beside it is the studio's, or a leftover from an eject). */
40
+ export function sourceOf(name, srcDir = RELATIVE_PATHS.srcDir) {
41
+ for (const ext of ['.diagram.ts', '.diagram.json']) {
42
+ const file = path.posix.join(srcDir, `${name}${ext}`);
43
+ if (existsSync(file))
44
+ return file;
45
+ }
46
+ return undefined;
47
+ }
@@ -0,0 +1,5 @@
1
+ import type { Command } from '../cli/command.js';
2
+ type ShowFlag = '--plane' | '--layers' | '--depth' | '--root' | '--ascii' | '--color' | '--no-color';
3
+ /** `diagc show <name>`: the diagram as text on stdout. */
4
+ export declare const show: Command<ShowFlag>;
5
+ export {};
@@ -0,0 +1,115 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { buildHierarchy, defined, errMessage, isLayoutOverlay, } from '@diagc/core/internal';
4
+ import { loadModel } from '../compile.js';
5
+ import { diagramName } from '../names.js';
6
+ import { RELATIVE_PATHS } from '../paths.js';
7
+ import { colorModeFor } from '../text/ansi.js';
8
+ import { depthPins, exportPins } from '../text/folds.js';
9
+ import { renderToLines } from '../text/render.js';
10
+ import { cellWidth } from '../text/width.js';
11
+ import { LOCKED, sourceOf } from './shared.js';
12
+ const listOf = (what, ids) => ids.length === 0 ? `it has no ${what}` : `its ${what}: ${ids.join(', ')}`;
13
+ /** What is wrong with the view the flags ask for, or undefined when it can be drawn:
14
+ * a plane, a layer or a root the model does not have, or a root with no inside. */
15
+ function viewProblem(name, model, flags) {
16
+ const plane = flags['--plane'];
17
+ if (plane !== undefined && !model.planes.some((p) => p.id === plane)) {
18
+ return `no plane '${plane}' in ${name}; ${listOf('planes', model.planes.map((p) => p.id))}`;
19
+ }
20
+ const layer = flags['--layers']?.find((id) => !model.layers.some((l) => l.id === id));
21
+ if (layer !== undefined)
22
+ return `no layer '${layer}' in ${name}; ${listOf('layers', model.layers.map((l) => l.id))}`;
23
+ const root = flags['--root'];
24
+ if (root === undefined)
25
+ return undefined;
26
+ const hierarchy = buildHierarchy(model, plane);
27
+ if ((hierarchy.childrenOf.get(root)?.length ?? 0) > 0)
28
+ return undefined;
29
+ const containers = [...hierarchy.childrenOf].filter(([, kids]) => kids.length > 0).map(([id]) => id);
30
+ const which = containers.length === 0 ? ', and it has none' : `: ${containers.join(', ')}`;
31
+ const what = model.nodes.some((n) => n.id === root)
32
+ ? `'${root}' holds nothing to draw`
33
+ : `no node '${root}' in ${name}`;
34
+ return `${what}; --root takes a container${which}`;
35
+ }
36
+ /** The layout beside the source, when there is one that reads as a layout. One that
37
+ * does not is said on stderr and drawn without: the layout only steers the flow. */
38
+ async function readOverlay(source, io) {
39
+ const file = source.replace(/\.diagram\.(ts|json)$/, '.layout.json');
40
+ if (!existsSync(file))
41
+ return undefined;
42
+ try {
43
+ const parsed = JSON.parse(await readFile(file, 'utf8'));
44
+ if (isLayoutOverlay(parsed))
45
+ return parsed;
46
+ }
47
+ catch {
48
+ // reported below, as a layout that does not read
49
+ }
50
+ io.err(`diagc: ignoring ${file}: not a layout file`);
51
+ return undefined;
52
+ }
53
+ const colorFlag = (flags) => flags['--no-color'] === true ? 'no-color' : flags['--color'] === true ? 'color' : undefined;
54
+ /** A terminal wraps a line wider than itself, which takes a picture apart: say so,
55
+ * once, on stderr, where the picture on stdout stays as it is. */
56
+ function widthHint(io, lines, name) {
57
+ if (io.tty === undefined)
58
+ return;
59
+ // eslint-disable-next-line no-control-regex -- the escapes are what is stripped
60
+ const width = Math.max(...lines.map((l) => cellWidth(l.replace(/\x1b\[[0-9;]*m/g, ''))));
61
+ if (width <= io.tty.columns)
62
+ return;
63
+ io.err(`diagc: the picture is ${width} columns wide and the terminal ${io.tty.columns}; pipe it through 'less -S' or use 'diagc tui ${name}'.`);
64
+ }
65
+ /** `diagc show <name>`: the diagram as text on stdout. */
66
+ export const show = {
67
+ flags: ['--plane', '--layers', '--depth', '--root', '--ascii', '--color', '--no-color'],
68
+ positionals: { max: 1, what: 'one diagram name' },
69
+ whyNot: LOCKED,
70
+ async run({ positionals, flags }, { io, usage, home, snapshots }) {
71
+ const name = positionals[0] === undefined ? '' : diagramName(positionals[0]);
72
+ if (name === '' || (flags['--color'] === true && flags['--no-color'] === true)) {
73
+ io.err(name === '' ? 'diagc: show needs a diagram name.' : 'diagc: --color and --no-color contradict each other.');
74
+ io.err(usage);
75
+ return 1;
76
+ }
77
+ const source = sourceOf(name);
78
+ if (source === undefined) {
79
+ io.err(`diagc: no diagram '${name}'`);
80
+ return 1;
81
+ }
82
+ let model;
83
+ try {
84
+ // The source, not its artifact: the picture is of the diagram as it is now,
85
+ // compiled or not, the way lint reads it.
86
+ model = await loadModel(source, {
87
+ rootDir: RELATIVE_PATHS.srcDir,
88
+ coreEntry: home.coreEntry,
89
+ resolver: snapshots.resolver,
90
+ warn: io.err,
91
+ });
92
+ }
93
+ catch (e) {
94
+ io.err(errMessage(e));
95
+ return 1;
96
+ }
97
+ const problem = viewProblem(name, model, flags);
98
+ if (problem !== undefined) {
99
+ io.err(`diagc: ${problem}`);
100
+ return 1;
101
+ }
102
+ const overlay = await readOverlay(source, io);
103
+ const plane = flags['--plane'];
104
+ // A printed picture folds as the PNG does; --depth trades that for the top levels.
105
+ const pins = flags['--depth'] !== undefined ? depthPins(model, plane, flags['--depth']) : exportPins(model, overlay);
106
+ const lines = await renderToLines({ model, pins, ...defined({ overlay, plane, layers: flags['--layers'], root: flags['--root'] }) }, { ascii: flags['--ascii'] === true, color: colorModeFor(process.env, io.tty !== undefined, colorFlag(flags)) });
107
+ if (lines.length === 0) {
108
+ io.err(`diagc: nothing to draw in ${name}`);
109
+ return 0;
110
+ }
111
+ io.write(`${lines.join('\n')}\n`);
112
+ widthHint(io, lines, name);
113
+ return 0;
114
+ },
115
+ };
@@ -0,0 +1,3 @@
1
+ import type { Command } from '../cli/command.js';
2
+ /** `diagc tui [name]`: the diagrams in the terminal, live, until it is quit. */
3
+ export declare const tui: Command<never>;
@@ -0,0 +1,36 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { diagramName } from '../names.js';
3
+ import { RELATIVE_PATHS } from '../paths.js';
4
+ import { screenColorMode } from '../text/ansi.js';
5
+ import { runTui, watchSources } from '../tui/app.js';
6
+ import { processTerminal } from '../tui/terminal.js';
7
+ import { LOCKED, sourceOf } from './shared.js';
8
+ /** `diagc tui [name]`: the diagrams in the terminal, live, until it is quit. */
9
+ export const tui = {
10
+ flags: [],
11
+ positionals: { max: 1, what: 'one diagram name' },
12
+ // Its compile-watch loop resolves includes locked, as the studio's does.
13
+ whyNot: LOCKED,
14
+ async run({ positionals }, { io, home }) {
15
+ const name = positionals[0] === undefined ? undefined : diagramName(positionals[0]);
16
+ if (name !== undefined && sourceOf(name) === undefined) {
17
+ io.err(`diagc: no diagram '${name}'`);
18
+ return 1;
19
+ }
20
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
21
+ io.err("diagc: tui needs a terminal; use 'diagc show <name>' to print a diagram.");
22
+ return 1;
23
+ }
24
+ const { srcDir, artifactsDir } = RELATIVE_PATHS;
25
+ await mkdir(srcDir, { recursive: true });
26
+ await runTui({
27
+ terminal: processTerminal(process.stdin, process.stdout),
28
+ srcDir,
29
+ artifactsDir,
30
+ ...(name !== undefined ? { name } : {}),
31
+ watch: watchSources(srcDir, artifactsDir, home.coreEntry),
32
+ color: screenColorMode(process.env),
33
+ });
34
+ return 0;
35
+ },
36
+ };
package/dist/init.d.ts CHANGED
@@ -31,7 +31,7 @@ export declare const AGENTS_END = "<!-- diagc:end -->";
31
31
  /** What `--agents` writes. Commands, not DSL: the guide is where the DSL lives, so
32
32
  * this block does not go stale when the DSL grows. The markers let a later run
33
33
  * replace it in place. */
34
- export declare const AGENTS_BLOCK = "<!-- diagc:begin -->\n## Diagrams\n\nDiagrams live in `.diagrams/src/*.diagram.ts` and are built with `diagc`.\n\n- Run `diagc guide` before writing or changing one; `diagc guide <type>` covers one diagram type.\n- Run `diagc lint --json` until it reports nothing.\n- Run `diagc publish <name>` and look at `.diagrams/static/<name>.png` to check the picture.\n<!-- diagc:end -->\n";
34
+ export declare const AGENTS_BLOCK = "<!-- diagc:begin -->\n## Diagrams\n\nDiagrams live in `.diagrams/src/*.diagram.ts` and are built with `diagc`.\n\n- Run `diagc guide` before writing or changing one; `diagc guide <type>` covers one diagram type.\n- Run `diagc lint --json` until it reports nothing.\n- Run `diagc show <name>` to read the picture as text, and `diagc publish <name>` to look at `.diagrams/static/<name>.png`.\n<!-- diagc:end -->\n";
35
35
  /** Where the skill goes: the folder Claude Code reads a repository's skills from. */
36
36
  export declare const SKILL_PATH = ".claude/skills/diagc/SKILL.md";
37
37
  /** `existing` with `block` added at the end, or — when an earlier block is there —
package/dist/init.js CHANGED
@@ -27,7 +27,7 @@ Diagrams live in \`.diagrams/src/*.diagram.ts\` and are built with \`diagc\`.
27
27
 
28
28
  - Run \`diagc guide\` before writing or changing one; \`diagc guide <type>\` covers one diagram type.
29
29
  - Run \`diagc lint --json\` until it reports nothing.
30
- - Run \`diagc publish <name>\` and look at \`.diagrams/static/<name>.png\` to check the picture.
30
+ - Run \`diagc show <name>\` to read the picture as text, and \`diagc publish <name>\` to look at \`.diagrams/static/<name>.png\`.
31
31
  ${AGENTS_END}
32
32
  `;
33
33
  /** Where the skill goes: the folder Claude Code reads a repository's skills from. */
@@ -0,0 +1,9 @@
1
+ import { type DiagramModel, type NotationId, type ViewEdge } from '@diagc/core/internal';
2
+ export interface Accents {
3
+ /** node id → its notation's colour: below the node's own, above the model's typeColors */
4
+ nodes: ReadonlyMap<string, string>;
5
+ /** edge id → its notation's colour: below the relation's own and its layer's tint */
6
+ edges: ReadonlyMap<string, string>;
7
+ }
8
+ /** What `notation` colours on the plane, of its nodes and of the drawn `edges`. */
9
+ export declare function notationAccents(model: DiagramModel, plane: string | undefined, notation: NotationId | undefined, edges: readonly ViewEdge[]): Accents;
@@ -0,0 +1,83 @@
1
+ import { FB_CATEGORY_TYPE, FISHBONE_NOTATION, fishboneTree, GIT_NOTATION, gitGraph, isGitKind, TM_BOUNDARY_TYPE, TM_NOTATION, } from '@diagc/core/internal';
2
+ // The colours a notation gives its boxes and lines, as the browser gives them: a git
3
+ // graph's lanes and a fishbone's bones from one palette, a threat model's trust
4
+ // boundaries red. The CLI cannot import the renderer, so this is a copy of its notation
5
+ // colour hooks, which accents.test.ts holds to them. The renderer's other hooks give a
6
+ // theme's colours, one for a light page and one for a dark: a text picture cannot know
7
+ // the background it will be read on, so those notations draw without them.
8
+ /** A lane's or a bone's colour where it sets none, in turn. */
9
+ const PALETTE = ['#7ba7d9', '#d9534f', '#e0a030', '#7bbf7b', '#b08ad9', '#8a8f96'];
10
+ const BOUNDARY_COLOR = '#c62828';
11
+ const NONE = { nodes: new Map(), edges: new Map() };
12
+ const paletteAt = (i) => PALETTE[i % PALETTE.length];
13
+ /** Each category in its colour, and every cause and sub-cause hanging from it: its
14
+ * own colour, else the model's for a category, else the palette by column, a column
15
+ * being the two categories that meet the spine at one point, which read as one rib. */
16
+ function boneColors(model) {
17
+ const byType = model.typeColors?.[FB_CATEGORY_TYPE] ?? model.typeColors?.['*'];
18
+ const own = new Map(model.nodes.map((n) => [n.id, n.color]));
19
+ const colors = new Map();
20
+ fishboneTree(model).categories.forEach((category, i) => {
21
+ const color = own.get(category.id) ?? byType ?? paletteAt(Math.floor(i / 2));
22
+ colors.set(category.id, color);
23
+ for (const cause of category.causes) {
24
+ colors.set(cause.id, color);
25
+ for (const sub of cause.subs)
26
+ colors.set(sub, color);
27
+ }
28
+ });
29
+ return colors;
30
+ }
31
+ /** Each lane in its colour: its own, else the model's for a branch, else the palette
32
+ * by lane; and each commit in its own colour, else its lane's. */
33
+ function laneColors(model, graph) {
34
+ const byType = model.typeColors?.['branch'] ?? model.typeColors?.['*'];
35
+ const colors = new Map();
36
+ graph.lanes.forEach((lane, i) => {
37
+ const color = lane.node.color ?? byType ?? paletteAt(i);
38
+ colors.set(lane.id, color);
39
+ for (const commit of lane.commits)
40
+ colors.set(commit.id, commit.color ?? color);
41
+ });
42
+ return colors;
43
+ }
44
+ /** A git link in a lane's colour: a branch in the new lane's, a commit in its own
45
+ * lane's, a merge in the lower lane's, so a feature merging up keeps its colour and a
46
+ * trunk merging down takes the lane's. */
47
+ function linkColor(edge, graph, lanes) {
48
+ if (!isGitKind(edge.kind))
49
+ return undefined;
50
+ const [from, to] = [graph.laneOf.get(edge.from), graph.laneOf.get(edge.to)];
51
+ if (from === undefined || to === undefined)
52
+ return undefined;
53
+ const index = (id) => graph.lanes.findIndex((l) => l.id === id);
54
+ const lane = edge.kind === 'branch' ? to : edge.kind === 'commit' ? from : index(from) >= index(to) ? from : to;
55
+ return lanes.get(lane);
56
+ }
57
+ function byEdge(edges, colorOf) {
58
+ const colors = new Map();
59
+ for (const e of edges) {
60
+ const color = colorOf(e);
61
+ if (color !== undefined)
62
+ colors.set(e.id, color);
63
+ }
64
+ return colors;
65
+ }
66
+ /** What `notation` colours on the plane, of its nodes and of the drawn `edges`. */
67
+ export function notationAccents(model, plane, notation, edges) {
68
+ if (notation === FISHBONE_NOTATION) {
69
+ const nodes = boneColors(model);
70
+ // a bone, a cause line or a tick takes the colour of the node it starts from
71
+ return { nodes, edges: byEdge(edges, (e) => nodes.get(e.from)) };
72
+ }
73
+ if (notation === GIT_NOTATION) {
74
+ const graph = gitGraph(model, plane);
75
+ const nodes = laneColors(model, graph);
76
+ return { nodes, edges: byEdge(edges, (e) => linkColor(e, graph, nodes)) };
77
+ }
78
+ if (notation === TM_NOTATION) {
79
+ const boundaries = model.nodes.filter((n) => n.type === TM_BOUNDARY_TYPE);
80
+ return { nodes: new Map(boundaries.map((n) => [n.id, BOUNDARY_COLOR])), edges: new Map() };
81
+ }
82
+ return NONE;
83
+ }
@@ -0,0 +1,28 @@
1
+ import type { Cell, Style } from './canvas.js';
2
+ /** How much colour the output may use: none (a pipe, NO_COLOR), the 256-colour
3
+ * palette every modern terminal has, or 24-bit where the terminal says it has it.
4
+ * `mono` is the TUI's no-colour: bold, dim and inverse but no colours, because a
5
+ * screen without inverse has no way to show where the reader is. */
6
+ export type ColorMode = 'none' | 'mono' | 'ansi256' | 'truecolor';
7
+ /** A CSS colour as RGB, for the forms a diagram writes literally (`#rgb`, `#rrggbb`,
8
+ * `rgb(r, g, b)`). Anything else — a theme variable, a colour name — has no value
9
+ * outside a browser, and the cell keeps the terminal's own colour. */
10
+ export declare function parseColor(css: string): [number, number, number] | undefined;
11
+ /**
12
+ * The colour mode for an output, by the usual conventions in their usual order: a
13
+ * flag beats the environment, NO_COLOR (when non-empty) turns colour off, a dumb
14
+ * terminal gets none, FORCE_COLOR turns it on for a pipe, and otherwise a terminal
15
+ * is coloured and a pipe is not.
16
+ */
17
+ export declare function colorModeFor(env: Readonly<Record<string, string | undefined>>, tty: boolean, flag?: 'color' | 'no-color'): ColorMode;
18
+ /** The TUI's mode: colour as for a terminal `show` prints to, but the attributes
19
+ * kept where colour is off. NO_COLOR is about colour, not about bold and inverse. */
20
+ export declare function screenColorMode(env: Readonly<Record<string, string | undefined>>): ColorMode;
21
+ /** The escape that sets `style`, or `''` for the plain style. */
22
+ export declare function sgr(style: Style, mode: ColorMode): string;
23
+ /**
24
+ * The picture as text, one string per row. Trailing blanks are trimmed unless `trim`
25
+ * is false (a full-screen frame keeps its width). A row that set a style ends with a
26
+ * reset, so no colour leaks into the next line or the shell.
27
+ */
28
+ export declare function serialize(rows: readonly Cell[][], mode: ColorMode, trim?: boolean): string[];
@@ -0,0 +1,111 @@
1
+ /** A CSS colour as RGB, for the forms a diagram writes literally (`#rgb`, `#rrggbb`,
2
+ * `rgb(r, g, b)`). Anything else — a theme variable, a colour name — has no value
3
+ * outside a browser, and the cell keeps the terminal's own colour. */
4
+ export function parseColor(css) {
5
+ const s = css.trim().toLowerCase();
6
+ const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(s);
7
+ if (short !== null)
8
+ return [1, 2, 3].map((i) => parseInt(short[i].repeat(2), 16));
9
+ const long = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(s);
10
+ if (long !== null)
11
+ return [1, 2, 3].map((i) => parseInt(long[i], 16));
12
+ const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,[^)]*)?\)$/.exec(s);
13
+ if (rgb !== null)
14
+ return [1, 2, 3].map((i) => Math.min(255, Number(rgb[i])));
15
+ return undefined;
16
+ }
17
+ /**
18
+ * The colour mode for an output, by the usual conventions in their usual order: a
19
+ * flag beats the environment, NO_COLOR (when non-empty) turns colour off, a dumb
20
+ * terminal gets none, FORCE_COLOR turns it on for a pipe, and otherwise a terminal
21
+ * is coloured and a pipe is not.
22
+ */
23
+ export function colorModeFor(env, tty, flag) {
24
+ const depth = env.COLORTERM === 'truecolor' || env.COLORTERM === '24bit' ? 'truecolor' : 'ansi256';
25
+ if (flag === 'no-color')
26
+ return 'none';
27
+ if (flag === 'color')
28
+ return depth;
29
+ if (env.NO_COLOR !== undefined && env.NO_COLOR !== '')
30
+ return 'none';
31
+ if (env.TERM === 'dumb')
32
+ return 'none';
33
+ if (env.FORCE_COLOR !== undefined)
34
+ return env.FORCE_COLOR === '0' ? 'none' : depth;
35
+ return tty ? depth : 'none';
36
+ }
37
+ /** The TUI's mode: colour as for a terminal `show` prints to, but the attributes
38
+ * kept where colour is off. NO_COLOR is about colour, not about bold and inverse. */
39
+ export function screenColorMode(env) {
40
+ const mode = colorModeFor(env, true);
41
+ return mode === 'none' ? 'mono' : mode;
42
+ }
43
+ const CUBE = [0, 95, 135, 175, 215, 255];
44
+ const nearestLevel = (v) => {
45
+ let best = 0;
46
+ for (let i = 1; i < CUBE.length; i++)
47
+ if (Math.abs(CUBE[i] - v) < Math.abs(CUBE[best] - v))
48
+ best = i;
49
+ return best;
50
+ };
51
+ const distance = (a, b) => a.reduce((sum, v, i) => sum + (v - b[i]) ** 2, 0);
52
+ /** The 256-colour palette entry nearest `rgb`: the 6×6×6 cube or the 24 greys. */
53
+ function palette256([r, g, b]) {
54
+ const [ri, gi, bi] = [r, g, b].map(nearestLevel);
55
+ const cube = [CUBE[ri], CUBE[gi], CUBE[bi]];
56
+ const grey = Math.max(0, Math.min(23, Math.round(((r + g + b) / 3 - 8) / 10)));
57
+ const greyValue = 8 + grey * 10;
58
+ return distance([r, g, b], [greyValue, greyValue, greyValue]) < distance([r, g, b], cube)
59
+ ? 232 + grey
60
+ : 16 + 36 * ri + 6 * gi + bi;
61
+ }
62
+ function colorCode(color, mode) {
63
+ if ('ansi' in color)
64
+ return String(color.ansi < 8 ? 30 + color.ansi : 90 + color.ansi - 8);
65
+ return mode === 'truecolor' ? `38;2;${color.rgb.join(';')}` : `38;5;${palette256(color.rgb)}`;
66
+ }
67
+ /** The escape that sets `style`, or `''` for the plain style. */
68
+ export function sgr(style, mode) {
69
+ if (mode === 'none')
70
+ return '';
71
+ const codes = [];
72
+ if (style.bold === true)
73
+ codes.push('1');
74
+ if (style.dim === true)
75
+ codes.push('2');
76
+ if (style.inverse === true)
77
+ codes.push('7');
78
+ if (style.fg !== undefined && mode !== 'mono')
79
+ codes.push(colorCode(style.fg, mode));
80
+ return codes.length === 0 ? '' : `\x1b[${codes.join(';')}m`;
81
+ }
82
+ const RESET = '\x1b[0m';
83
+ /** A blank that shows nothing: trailing ones can go. An inverse blank is a bar. */
84
+ const invisible = (cell) => cell.ch === ' ' && cell.style.inverse !== true;
85
+ /**
86
+ * The picture as text, one string per row. Trailing blanks are trimmed unless `trim`
87
+ * is false (a full-screen frame keeps its width). A row that set a style ends with a
88
+ * reset, so no colour leaks into the next line or the shell.
89
+ */
90
+ export function serialize(rows, mode, trim = true) {
91
+ return rows.map((row) => {
92
+ let end = row.length;
93
+ if (trim)
94
+ while (end > 0 && (invisible(row[end - 1]) || row[end - 1].ch === ''))
95
+ end--;
96
+ let out = '';
97
+ let current = '';
98
+ for (let i = 0; i < end; i++) {
99
+ const cell = row[i];
100
+ if (cell.ch === '')
101
+ continue;
102
+ const code = sgr(cell.style, mode);
103
+ if (code !== current) {
104
+ out += current === '' ? code : `${RESET}${code}`;
105
+ current = code;
106
+ }
107
+ out += cell.ch;
108
+ }
109
+ return current === '' ? out : `${out}${RESET}`;
110
+ });
111
+ }