@diagc/cli 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -12
- package/assets/guide/activity.md +27 -0
- package/assets/guide/c4.md +25 -0
- package/assets/guide/causal-loop.md +22 -0
- package/assets/guide/deployment.md +28 -0
- package/assets/guide/er.md +25 -0
- package/assets/guide/fishbone.md +28 -0
- package/assets/guide/git-graph.md +28 -0
- package/assets/guide/index.md +112 -0
- package/assets/guide/plan.md +28 -0
- package/assets/guide/second-order.md +26 -0
- package/assets/guide/threat-model.md +28 -0
- package/assets/starters/activity/starter.diagram.ts +22 -0
- package/assets/starters/basic/starter.diagram.ts +21 -0
- package/assets/starters/c4/starter.diagram.ts +19 -0
- package/assets/starters/causal-loop/starter.diagram.ts +16 -0
- package/assets/starters/deployment/starter.diagram.ts +19 -0
- package/assets/starters/er/starter.diagram.ts +23 -0
- package/assets/starters/fishbone/starter.diagram.ts +11 -0
- package/assets/starters/git-graph/starter.diagram.ts +15 -0
- package/assets/starters/plan/starter.diagram.ts +26 -0
- package/assets/starters/second-order/starter.diagram.ts +14 -0
- package/assets/starters/threat-model/starter.diagram.ts +16 -0
- package/assets/studio/assets/{index-DL_lrezG.js → index-C0LPHkb1.js} +1 -1
- package/assets/studio/index.html +1 -1
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +74 -6
- package/dist/compile.d.ts +26 -0
- package/dist/compile.js +50 -2
- package/dist/guide.d.ts +39 -0
- package/dist/guide.js +152 -0
- package/dist/home.d.ts +9 -0
- package/dist/home.js +19 -1
- package/dist/init.d.ts +54 -0
- package/dist/init.js +197 -0
- package/dist/lint.d.ts +3 -0
- package/dist/lint.js +14 -2
- package/dist/starters.d.ts +16 -0
- package/dist/starters.js +34 -0
- package/package.json +2 -2
package/dist/guide.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { NODE_TYPES, NOTATION_NODE_TYPES, NOTATION_RELATION_KINDS, RELATION_KINDS } from '@diagc/core';
|
|
4
|
+
import { UnknownStarterError, readStarter } from './starters.js';
|
|
5
|
+
const INDEX = 'index';
|
|
6
|
+
/** `diagc guide all`: the index, then every topic — for a reader who cannot ask
|
|
7
|
+
* for one (the copy published on the website). */
|
|
8
|
+
export const ALL_TOPIC = 'all';
|
|
9
|
+
/**
|
|
10
|
+
* Which node types a topic owns. Core's `NODE_TYPES` is one flat list — it only
|
|
11
|
+
* feeds the lint — so a diagram type's own ids are recognised by their prefix.
|
|
12
|
+
* The index prints whatever no topic claims. A test holds each prefix to at
|
|
13
|
+
* least one real type, so a renamed family cannot quietly empty a topic's list.
|
|
14
|
+
*/
|
|
15
|
+
export const TOPIC_TYPE_PREFIXES = {
|
|
16
|
+
c4: ['c4-'],
|
|
17
|
+
activity: ['activity-'],
|
|
18
|
+
'second-order': ['so-'],
|
|
19
|
+
fishbone: ['fb-'],
|
|
20
|
+
deployment: ['deploy-'],
|
|
21
|
+
'threat-model': ['tm-'],
|
|
22
|
+
plan: ['plan-'],
|
|
23
|
+
er: ['db-table'],
|
|
24
|
+
};
|
|
25
|
+
/** Thrown for a topic there is no page for; the message lists what there is. */
|
|
26
|
+
export class UnknownTopicError extends Error {
|
|
27
|
+
constructor(topic, topics) {
|
|
28
|
+
super(`No guide topic '${topic}'. Topics: ${[ALL_TOPIC, ...topics].join(', ')}`);
|
|
29
|
+
this.name = 'UnknownTopicError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Thrown when the guide's own files are not where the install says they are. */
|
|
33
|
+
export class GuideMissingError extends Error {
|
|
34
|
+
constructor(guideDir) {
|
|
35
|
+
super(`guide files missing from this install (${guideDir}) — reinstall diagc.`);
|
|
36
|
+
this.name = 'GuideMissingError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** The topics a guide directory holds: every page but the index, sorted. */
|
|
40
|
+
export function guideTopics(guideDir) {
|
|
41
|
+
if (!existsSync(path.join(guideDir, `${INDEX}.md`)))
|
|
42
|
+
throw new GuideMissingError(guideDir);
|
|
43
|
+
return readdirSync(guideDir)
|
|
44
|
+
.filter((f) => f.endsWith('.md') && f !== `${INDEX}.md`)
|
|
45
|
+
.map((f) => f.slice(0, -'.md'.length))
|
|
46
|
+
.sort();
|
|
47
|
+
}
|
|
48
|
+
const codeList = (ids) => ids.map((id) => `\`${id}\``).join(', ');
|
|
49
|
+
const fence = (src) => '```ts\n' + src.trimEnd() + '\n```';
|
|
50
|
+
/** What a notation adds to a shared list, for a page named after that notation. */
|
|
51
|
+
function notationOwn(map, page) {
|
|
52
|
+
return map[page] ?? [];
|
|
53
|
+
}
|
|
54
|
+
function nodeTypesFor(page) {
|
|
55
|
+
if (page === INDEX) {
|
|
56
|
+
const claimed = Object.values(TOPIC_TYPE_PREFIXES).flat();
|
|
57
|
+
return NODE_TYPES.filter((t) => !claimed.some((p) => t.startsWith(p)));
|
|
58
|
+
}
|
|
59
|
+
const own = TOPIC_TYPE_PREFIXES[page] ?? [];
|
|
60
|
+
return [...NODE_TYPES.filter((t) => own.some((p) => t.startsWith(p))), ...notationOwn(NOTATION_NODE_TYPES, page)];
|
|
61
|
+
}
|
|
62
|
+
function relationKindsFor(page) {
|
|
63
|
+
return [...new Set([...RELATION_KINDS, ...notationOwn(NOTATION_RELATION_KINDS, page)])];
|
|
64
|
+
}
|
|
65
|
+
/** One bullet per topic: the command that prints it, and its own title. */
|
|
66
|
+
function topicList(guideDir) {
|
|
67
|
+
return guideTopics(guideDir)
|
|
68
|
+
.map((topic) => {
|
|
69
|
+
const file = path.join(guideDir, `${topic}.md`);
|
|
70
|
+
const title = /^# (.+)$/m.exec(readFileSync(file, 'utf8'))?.[1];
|
|
71
|
+
if (title === undefined)
|
|
72
|
+
throw new Error(`${file}: a topic starts with a '# Title' line`);
|
|
73
|
+
return `- \`diagc guide ${topic}\` — ${title.trim()}`;
|
|
74
|
+
})
|
|
75
|
+
.join('\n');
|
|
76
|
+
}
|
|
77
|
+
/** One page with its placeholders filled. The replacer is a function, so what it
|
|
78
|
+
* returns is taken literally: a starter holding `$&` or a `{{…}}` of its own is
|
|
79
|
+
* printed as written. */
|
|
80
|
+
function renderPage(page, ctx) {
|
|
81
|
+
const file = path.join(ctx.guideDir, `${page}.md`);
|
|
82
|
+
return readFileSync(file, 'utf8')
|
|
83
|
+
.replace(/\{\{([a-z-]+)(?::([a-z0-9-]+))?\}\}/g, (whole, name, arg) => {
|
|
84
|
+
switch (name) {
|
|
85
|
+
case 'starter': {
|
|
86
|
+
const type = arg ?? (page === INDEX ? undefined : page);
|
|
87
|
+
if (type === undefined)
|
|
88
|
+
throw new Error(`${file}: {{starter}} needs a type here — write {{starter:basic}}`);
|
|
89
|
+
return fence(readStarter(ctx.startersDir, type));
|
|
90
|
+
}
|
|
91
|
+
case 'node-types': {
|
|
92
|
+
const ids = nodeTypesFor(page);
|
|
93
|
+
if (ids.length === 0)
|
|
94
|
+
throw new Error(`${file}: {{node-types}} is empty for '${page}' — this diagram type has no node types of its own`);
|
|
95
|
+
return codeList(ids);
|
|
96
|
+
}
|
|
97
|
+
case 'relation-kinds':
|
|
98
|
+
return codeList(relationKindsFor(page));
|
|
99
|
+
case 'topics':
|
|
100
|
+
return topicList(ctx.guideDir);
|
|
101
|
+
case 'version':
|
|
102
|
+
return ctx.version;
|
|
103
|
+
default:
|
|
104
|
+
throw new Error(`${file}: unknown placeholder ${whole}`);
|
|
105
|
+
}
|
|
106
|
+
})
|
|
107
|
+
.trimEnd();
|
|
108
|
+
}
|
|
109
|
+
/** The guide as Markdown: the index, one topic, or (`all`) everything. A topic is
|
|
110
|
+
* looked up in the listing and never joined into a path first, so `../x` is an
|
|
111
|
+
* unknown topic like any other. */
|
|
112
|
+
export function renderGuide(topic, ctx) {
|
|
113
|
+
const topics = guideTopics(ctx.guideDir);
|
|
114
|
+
if (topic === undefined)
|
|
115
|
+
return renderPage(INDEX, ctx);
|
|
116
|
+
if (topic === ALL_TOPIC)
|
|
117
|
+
return [INDEX, ...topics].map((p) => renderPage(p, ctx)).join('\n\n---\n\n');
|
|
118
|
+
if (!topics.includes(topic))
|
|
119
|
+
throw new UnknownTopicError(topic, topics);
|
|
120
|
+
return renderPage(topic, ctx);
|
|
121
|
+
}
|
|
122
|
+
const stdio = {
|
|
123
|
+
out: (text) => void process.stdout.write(`${text}\n`),
|
|
124
|
+
err: (text) => console.error(text),
|
|
125
|
+
};
|
|
126
|
+
/** `diagc guide [topic]`: print, and return the exit code. The errors a user can
|
|
127
|
+
* cause or meet — a topic that does not exist, an install with no guide, an
|
|
128
|
+
* install with no starter files — are one line on stderr; anything else is a bug
|
|
129
|
+
* in the guide's own files and is left to throw. */
|
|
130
|
+
export function runGuide(topics, ctx, io = stdio) {
|
|
131
|
+
if (topics.length > 1) {
|
|
132
|
+
io.err(`diagc: guide takes one topic, got ${topics.length} — run it once per topic, or 'diagc guide ${ALL_TOPIC}'.`);
|
|
133
|
+
return 1;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
io.out(renderGuide(topics[0], ctx));
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
|
139
|
+
catch (e) {
|
|
140
|
+
if (e instanceof UnknownTopicError || e instanceof GuideMissingError) {
|
|
141
|
+
io.err(`diagc: ${e.message}`);
|
|
142
|
+
return 1;
|
|
143
|
+
}
|
|
144
|
+
// No starter type at all means the starters directory is gone, not that the
|
|
145
|
+
// guide names a misspelt one: that case has a non-empty list and stays a bug.
|
|
146
|
+
if (e instanceof UnknownStarterError && e.types.length === 0) {
|
|
147
|
+
io.err(`diagc: starter files missing from this install (${ctx.startersDir}) — reinstall diagc.`);
|
|
148
|
+
return 1;
|
|
149
|
+
}
|
|
150
|
+
throw e;
|
|
151
|
+
}
|
|
152
|
+
}
|
package/dist/home.d.ts
CHANGED
|
@@ -17,6 +17,10 @@ export interface HomePaths {
|
|
|
17
17
|
coreEntry: string;
|
|
18
18
|
/** monorepo: the studio's Vite root; packaged: the prebuilt studio bundle */
|
|
19
19
|
studioDir: string;
|
|
20
|
+
/** the authoring guide `diagc guide` prints: `index.md` plus one file per topic */
|
|
21
|
+
guideDir: string;
|
|
22
|
+
/** `<type>/starter.diagram.ts`, one folder per diagram type */
|
|
23
|
+
startersDir: string;
|
|
20
24
|
}
|
|
21
25
|
export interface Home {
|
|
22
26
|
root: string;
|
|
@@ -34,3 +38,8 @@ export declare function findHome(startPath: string): Home;
|
|
|
34
38
|
* Injectable for tests; the default is the real resolver. */
|
|
35
39
|
export declare function resolveCoreEntry(resolve?: (id: string) => string): string;
|
|
36
40
|
export declare function homePaths(home: Home, coreEntry?: typeof resolveCoreEntry): HomePaths;
|
|
41
|
+
/** The release this CLI is, read from the home's own `package.json`. release-please
|
|
42
|
+
* keeps the workspace root and the published manifest on one number, so the same
|
|
43
|
+
* read is right in both layouts. Not a `HomePaths` field: `homePaths` touches no
|
|
44
|
+
* file, and only the commands that print a version should pay for the read. */
|
|
45
|
+
export declare function cliVersion(root: string): string;
|
package/dist/home.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, realpathSync } from 'node:fs';
|
|
1
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
/** Marker that identifies a packaged install: the staged viewer shell. It is
|
|
@@ -62,6 +62,8 @@ export function homePaths(home, coreEntry = resolveCoreEntry) {
|
|
|
62
62
|
libraryDir: path.join(studioDir, 'library'),
|
|
63
63
|
coreEntry: coreEntry(),
|
|
64
64
|
studioDir,
|
|
65
|
+
guideDir: path.join(root, 'assets', 'guide'),
|
|
66
|
+
startersDir: path.join(root, 'assets', 'starters'),
|
|
65
67
|
};
|
|
66
68
|
}
|
|
67
69
|
return {
|
|
@@ -71,5 +73,21 @@ export function homePaths(home, coreEntry = resolveCoreEntry) {
|
|
|
71
73
|
libraryDir: path.join(root, 'apps', 'studio', 'public', 'library'),
|
|
72
74
|
coreEntry: path.join(root, 'packages', 'core', 'src', 'index.ts'),
|
|
73
75
|
studioDir: path.join(root, 'apps', 'studio'),
|
|
76
|
+
guideDir: path.join(root, 'packages', 'diagc', 'guide'),
|
|
77
|
+
// A checkout reads the starters where the examples keep them; `stage-assets`
|
|
78
|
+
// copies only the starter files out, into the same `<type>/` shape.
|
|
79
|
+
startersDir: path.join(root, '.diagrams', 'src', 'examples'),
|
|
74
80
|
};
|
|
75
81
|
}
|
|
82
|
+
/** The release this CLI is, read from the home's own `package.json`. release-please
|
|
83
|
+
* keeps the workspace root and the published manifest on one number, so the same
|
|
84
|
+
* read is right in both layouts. Not a `HomePaths` field: `homePaths` touches no
|
|
85
|
+
* file, and only the commands that print a version should pay for the read. */
|
|
86
|
+
export function cliVersion(root) {
|
|
87
|
+
const manifest = path.join(root, 'package.json');
|
|
88
|
+
const version = JSON.parse(readFileSync(manifest, 'utf8')).version;
|
|
89
|
+
if (typeof version !== 'string' || version === '') {
|
|
90
|
+
throw new Error(`no version in ${manifest} — reinstall diagc.`);
|
|
91
|
+
}
|
|
92
|
+
return version;
|
|
93
|
+
}
|
package/dist/init.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type IncludeResolver } from '@diagc/core';
|
|
2
|
+
/** What `diagc init` works with. `cwd` is the directory being set up — the
|
|
3
|
+
* current directory in the CLI, a temp dir in tests — and every path is built
|
|
4
|
+
* from it, so nothing here reads `process.cwd()`. */
|
|
5
|
+
export interface InitOptions {
|
|
6
|
+
cwd: string;
|
|
7
|
+
/** the diagram's name, folders allowed (`team/app`); `example` when omitted */
|
|
8
|
+
name?: string;
|
|
9
|
+
/** the starter to copy; `basic` when omitted */
|
|
10
|
+
type?: string;
|
|
11
|
+
/** write the coding-agent block into AGENTS.md / CLAUDE.md */
|
|
12
|
+
agents: boolean;
|
|
13
|
+
startersDir: string;
|
|
14
|
+
/** what the `npm i -D @diagc/core@…` hint names */
|
|
15
|
+
version: string;
|
|
16
|
+
coreEntry: string;
|
|
17
|
+
resolver?: IncludeResolver;
|
|
18
|
+
}
|
|
19
|
+
export interface InitIo {
|
|
20
|
+
out(text: string): void;
|
|
21
|
+
err(text: string): void;
|
|
22
|
+
}
|
|
23
|
+
export declare const DEFAULT_NAME = "example";
|
|
24
|
+
export declare const DEFAULT_TYPE = "basic";
|
|
25
|
+
/** build output a repository should not commit; `init` adds what is missing */
|
|
26
|
+
export declare const IGNORED: readonly string[];
|
|
27
|
+
export declare const AGENTS_BEGIN = "<!-- diagc:begin -->";
|
|
28
|
+
export declare const AGENTS_END = "<!-- diagc:end -->";
|
|
29
|
+
/** What `--agents` writes. Commands, not DSL: the guide is where the DSL lives, so
|
|
30
|
+
* this block does not go stale when the DSL grows. The markers let a later run
|
|
31
|
+
* replace it in place. */
|
|
32
|
+
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";
|
|
33
|
+
/** `existing` with the block added at the end, or — when both markers are there —
|
|
34
|
+
* with the earlier block replaced where it stands, so a second run never
|
|
35
|
+
* duplicates it and a run after an upgrade refreshes it. */
|
|
36
|
+
export declare function withAgentsBlock(existing: string): {
|
|
37
|
+
text: string;
|
|
38
|
+
replaced: boolean;
|
|
39
|
+
};
|
|
40
|
+
/** A one-line failure on stderr with exit 1. A refusal leaves the tree untouched;
|
|
41
|
+
* a compile failure comes after the writes, so the starter and `.gitignore` stay. */
|
|
42
|
+
export declare class InitError extends Error {
|
|
43
|
+
constructor(message: string);
|
|
44
|
+
}
|
|
45
|
+
/** `shop.diagram.ts` and `.diagrams/src/shop` both mean `shop` — the trim `eject`
|
|
46
|
+
* applies, so a name copied from a listing is not an "unsafe name". */
|
|
47
|
+
export declare function diagramName(arg: string): string;
|
|
48
|
+
/** Which of `wanted` a `.gitignore` text still lacks. A line counts after trimming,
|
|
49
|
+
* with or without a leading or trailing slash: `/.diagrams/html` already ignores
|
|
50
|
+
* what `.diagrams/html/` would. */
|
|
51
|
+
export declare function missingIgnores(existing: string, wanted?: readonly string[]): string[];
|
|
52
|
+
/** `diagc init`: run the steps in order and return the exit code. A refusal is one
|
|
53
|
+
* line on stderr; anything else is a bug and is left to throw. */
|
|
54
|
+
export declare function runInit(opts: InitOptions, io?: InitIo): Promise<number>;
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import fg from 'fast-glob';
|
|
5
|
+
import { errMessage } from '@diagc/core';
|
|
6
|
+
import { isSafeName } from './api/handlers.js';
|
|
7
|
+
import { compileFile } from './compile.js';
|
|
8
|
+
import { readStarter, UnknownStarterError } from './starters.js';
|
|
9
|
+
export const DEFAULT_NAME = 'example';
|
|
10
|
+
export const DEFAULT_TYPE = 'basic';
|
|
11
|
+
const SRC_DIR = '.diagrams/src';
|
|
12
|
+
const ARTIFACTS_DIR = '.diagrams/.artifacts';
|
|
13
|
+
/** build output a repository should not commit; `init` adds what is missing */
|
|
14
|
+
export const IGNORED = ['.diagrams/.artifacts/', '.diagrams/html/', '.diagrams/diff/'];
|
|
15
|
+
export const AGENTS_BEGIN = '<!-- diagc:begin -->';
|
|
16
|
+
export const AGENTS_END = '<!-- diagc:end -->';
|
|
17
|
+
/** What `--agents` writes. Commands, not DSL: the guide is where the DSL lives, so
|
|
18
|
+
* this block does not go stale when the DSL grows. The markers let a later run
|
|
19
|
+
* replace it in place. */
|
|
20
|
+
export const AGENTS_BLOCK = `${AGENTS_BEGIN}
|
|
21
|
+
## Diagrams
|
|
22
|
+
|
|
23
|
+
Diagrams live in \`.diagrams/src/*.diagram.ts\` and are built with \`diagc\`.
|
|
24
|
+
|
|
25
|
+
- Run \`diagc guide\` before writing or changing one; \`diagc guide <type>\` covers one diagram type.
|
|
26
|
+
- Run \`diagc lint --json\` until it reports nothing.
|
|
27
|
+
- Run \`diagc publish <name>\` and look at \`.diagrams/static/<name>.png\` to check the picture.
|
|
28
|
+
${AGENTS_END}
|
|
29
|
+
`;
|
|
30
|
+
/** `existing` with the block added at the end, or — when both markers are there —
|
|
31
|
+
* with the earlier block replaced where it stands, so a second run never
|
|
32
|
+
* duplicates it and a run after an upgrade refreshes it. */
|
|
33
|
+
export function withAgentsBlock(existing) {
|
|
34
|
+
const begin = existing.indexOf(AGENTS_BEGIN);
|
|
35
|
+
const end = begin === -1 ? -1 : existing.indexOf(AGENTS_END, begin);
|
|
36
|
+
if (begin !== -1 && end !== -1) {
|
|
37
|
+
let after = end + AGENTS_END.length;
|
|
38
|
+
// The block carries its own closing newline; take the old one with the old block.
|
|
39
|
+
if (existing.startsWith('\n', after))
|
|
40
|
+
after += 1;
|
|
41
|
+
return { text: existing.slice(0, begin) + AGENTS_BLOCK + existing.slice(after), replaced: true };
|
|
42
|
+
}
|
|
43
|
+
if (existing === '')
|
|
44
|
+
return { text: AGENTS_BLOCK, replaced: false };
|
|
45
|
+
const sep = existing.endsWith('\n\n') ? '' : existing.endsWith('\n') ? '\n' : '\n\n';
|
|
46
|
+
return { text: `${existing}${sep}${AGENTS_BLOCK}`, replaced: false };
|
|
47
|
+
}
|
|
48
|
+
const COL = 38;
|
|
49
|
+
const done = (left, right) => `✓ ${left.padEnd(COL)}${right}`;
|
|
50
|
+
const skipped = (left, right) => `· ${left.padEnd(COL)}${right}`;
|
|
51
|
+
/** A one-line failure on stderr with exit 1. A refusal leaves the tree untouched;
|
|
52
|
+
* a compile failure comes after the writes, so the starter and `.gitignore` stay. */
|
|
53
|
+
export class InitError extends Error {
|
|
54
|
+
constructor(message) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.name = 'InitError';
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** `shop.diagram.ts` and `.diagrams/src/shop` both mean `shop` — the trim `eject`
|
|
60
|
+
* applies, so a name copied from a listing is not an "unsafe name". */
|
|
61
|
+
export function diagramName(arg) {
|
|
62
|
+
return arg.replace(/^\.diagrams\/src\//, '').replace(/\.diagram\.(ts|json)$/, '');
|
|
63
|
+
}
|
|
64
|
+
/** Which of `wanted` a `.gitignore` text still lacks. A line counts after trimming,
|
|
65
|
+
* with or without a leading or trailing slash: `/.diagrams/html` already ignores
|
|
66
|
+
* what `.diagrams/html/` would. */
|
|
67
|
+
export function missingIgnores(existing, wanted = IGNORED) {
|
|
68
|
+
const norm = (l) => l.trim().replace(/^\//, '').replace(/\/$/, '');
|
|
69
|
+
const have = new Set(existing.split(/\r?\n/).map(norm));
|
|
70
|
+
return wanted.filter((w) => !have.has(norm(w)));
|
|
71
|
+
}
|
|
72
|
+
/** Step 1: the starter. Returns the file it wrote, or nothing when the step was
|
|
73
|
+
* skipped. Every check comes before the write, so a refusal leaves no file. */
|
|
74
|
+
async function starterStep(opts, io) {
|
|
75
|
+
const srcDir = path.join(opts.cwd, SRC_DIR);
|
|
76
|
+
if (opts.name === undefined && opts.type === undefined) {
|
|
77
|
+
// A plain `diagc init` in a repository that already has diagrams is here for
|
|
78
|
+
// the other steps (`--agents` after an upgrade): do not add an `example`.
|
|
79
|
+
const existing = await fg('**/*.diagram.{ts,json}', { cwd: srcDir });
|
|
80
|
+
if (existing.length > 0) {
|
|
81
|
+
io.out(skipped(SRC_DIR, `already has ${existing.length} diagram(s) — starter skipped`));
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const name = diagramName(opts.name ?? DEFAULT_NAME);
|
|
86
|
+
if (!isSafeName(name) || name.endsWith('/')) {
|
|
87
|
+
throw new InitError(`'${name}' is not a diagram name — use lowercase letters, digits and '-', with '/' for a folder (shop, team/app).`);
|
|
88
|
+
}
|
|
89
|
+
// The type is checked before the name clash: a wrong `--type` is the more useful
|
|
90
|
+
// thing to hear, and it too is checked before anything is written.
|
|
91
|
+
const type = opts.type ?? DEFAULT_TYPE;
|
|
92
|
+
let source;
|
|
93
|
+
try {
|
|
94
|
+
source = readStarter(opts.startersDir, type);
|
|
95
|
+
}
|
|
96
|
+
catch (e) {
|
|
97
|
+
if (!(e instanceof UnknownStarterError))
|
|
98
|
+
throw e;
|
|
99
|
+
// No types at all is not a wrong `--type`: the install lost its files.
|
|
100
|
+
throw new InitError(e.types.length === 0
|
|
101
|
+
? `starter files missing from this install (${opts.startersDir}) — reinstall diagc.`
|
|
102
|
+
: `${e.message} — e.g. diagc init ${name} --type ${e.types[0]}`);
|
|
103
|
+
}
|
|
104
|
+
for (const ext of ['ts', 'json']) {
|
|
105
|
+
if (existsSync(path.join(srcDir, `${name}.diagram.${ext}`))) {
|
|
106
|
+
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.`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const file = path.join(srcDir, `${name}.diagram.ts`);
|
|
110
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
111
|
+
await writeFile(file, source);
|
|
112
|
+
io.out(done(`${SRC_DIR}/${name}.diagram.ts`, `(${type} starter)`));
|
|
113
|
+
return file;
|
|
114
|
+
}
|
|
115
|
+
/** Step 2: `.gitignore`. Appends the missing lines; creates the file if there is none. */
|
|
116
|
+
async function gitignoreStep(cwd, io) {
|
|
117
|
+
const file = path.join(cwd, '.gitignore');
|
|
118
|
+
const existing = existsSync(file) ? await readFile(file, 'utf8') : '';
|
|
119
|
+
const missing = missingIgnores(existing);
|
|
120
|
+
if (missing.length === 0) {
|
|
121
|
+
io.out(skipped('.gitignore', 'already ignores the build output'));
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
// A file whose last line has no newline gets one first, or the first new entry
|
|
125
|
+
// would be glued onto it.
|
|
126
|
+
const sep = existing === '' || existing.endsWith('\n') ? '' : '\n';
|
|
127
|
+
await writeFile(file, `${existing}${sep}${missing.join('\n')}\n`);
|
|
128
|
+
io.out(done('.gitignore', `(+ ${missing.join(', ')})`));
|
|
129
|
+
}
|
|
130
|
+
/** Step 3: the coding-agent block, only with `--agents`. Into whichever of
|
|
131
|
+
* AGENTS.md and CLAUDE.md exist; into a new AGENTS.md when neither does. */
|
|
132
|
+
async function agentsStep(cwd, io) {
|
|
133
|
+
const targets = ['AGENTS.md', 'CLAUDE.md'].filter((f) => existsSync(path.join(cwd, f)));
|
|
134
|
+
if (targets.length === 0)
|
|
135
|
+
targets.push('AGENTS.md');
|
|
136
|
+
for (const name of targets) {
|
|
137
|
+
const file = path.join(cwd, name);
|
|
138
|
+
const existing = existsSync(file) ? await readFile(file, 'utf8') : '';
|
|
139
|
+
const { text, replaced } = withAgentsBlock(existing);
|
|
140
|
+
await writeFile(file, text);
|
|
141
|
+
io.out(done(name, replaced ? '(diagc block refreshed)' : '(diagc block added)'));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** Step 4: compile what was written, so the user starts from a diagram that is
|
|
145
|
+
* known to build and sees where the artifact went. */
|
|
146
|
+
async function compileStep(file, opts, io) {
|
|
147
|
+
let artifact;
|
|
148
|
+
try {
|
|
149
|
+
artifact = await compileFile(file, path.join(opts.cwd, ARTIFACTS_DIR), {
|
|
150
|
+
rootDir: path.join(opts.cwd, SRC_DIR),
|
|
151
|
+
coreEntry: opts.coreEntry,
|
|
152
|
+
...(opts.resolver !== undefined ? { resolver: opts.resolver } : {}),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
catch (e) {
|
|
156
|
+
throw new InitError(`compile failed — ${errMessage(e)}`);
|
|
157
|
+
}
|
|
158
|
+
io.out(done('compiled', `-> ${path.relative(opts.cwd, artifact).split(path.sep).join('/')}`));
|
|
159
|
+
}
|
|
160
|
+
/** Step 5: what to do now. The `--agents` line goes when `--agents` was given; the
|
|
161
|
+
* install hint only where there is a `package.json` to install into. */
|
|
162
|
+
function nextSteps(opts) {
|
|
163
|
+
const lines = [
|
|
164
|
+
['diagc studio', 'look at it'],
|
|
165
|
+
['diagc guide', 'how to write diagrams (for you or your agent)'],
|
|
166
|
+
];
|
|
167
|
+
if (!opts.agents)
|
|
168
|
+
lines.push(['diagc init --agents', 'point coding agents at the guide (AGENTS.md)']);
|
|
169
|
+
if (existsSync(path.join(opts.cwd, 'package.json')))
|
|
170
|
+
lines.push([`npm i -D @diagc/core@${opts.version}`, 'editor types for .diagram.ts']);
|
|
171
|
+
return `\nNext:\n${lines.map(([cmd, what]) => ` ${cmd.padEnd(COL)}${what}`).join('\n')}`;
|
|
172
|
+
}
|
|
173
|
+
const stdio = {
|
|
174
|
+
out: (text) => console.log(text),
|
|
175
|
+
err: (text) => console.error(text),
|
|
176
|
+
};
|
|
177
|
+
/** `diagc init`: run the steps in order and return the exit code. A refusal is one
|
|
178
|
+
* line on stderr; anything else is a bug and is left to throw. */
|
|
179
|
+
export async function runInit(opts, io = stdio) {
|
|
180
|
+
try {
|
|
181
|
+
const written = await starterStep(opts, io);
|
|
182
|
+
await gitignoreStep(opts.cwd, io);
|
|
183
|
+
if (opts.agents)
|
|
184
|
+
await agentsStep(opts.cwd, io);
|
|
185
|
+
if (written !== undefined)
|
|
186
|
+
await compileStep(written, opts, io);
|
|
187
|
+
io.out(nextSteps(opts));
|
|
188
|
+
return 0;
|
|
189
|
+
}
|
|
190
|
+
catch (e) {
|
|
191
|
+
if (e instanceof InitError) {
|
|
192
|
+
io.err(`diagc: ${e.message}`);
|
|
193
|
+
return 1;
|
|
194
|
+
}
|
|
195
|
+
throw e;
|
|
196
|
+
}
|
|
197
|
+
}
|
package/dist/lint.d.ts
CHANGED
|
@@ -7,6 +7,9 @@ export interface LintReport {
|
|
|
7
7
|
code: string;
|
|
8
8
|
message: string;
|
|
9
9
|
ref?: string;
|
|
10
|
+
/** where a `load` finding happened in the source, when the stack placed it */
|
|
11
|
+
line?: number;
|
|
12
|
+
column?: number;
|
|
10
13
|
}
|
|
11
14
|
/** Every finding for one source: its validation errors when it does not load,
|
|
12
15
|
* otherwise its warnings (core's lint included). */
|
package/dist/lint.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { diagramWarnings, errMessage } from '@diagc/core';
|
|
2
|
-
import { loadModel } from './compile.js';
|
|
2
|
+
import { LoadError, loadModel } from './compile.js';
|
|
3
3
|
const report = (file, severity, i) => ({
|
|
4
4
|
file,
|
|
5
5
|
severity,
|
|
@@ -19,9 +19,21 @@ export async function lintFile(file, opts) {
|
|
|
19
19
|
if (e instanceof Error && e.name === 'DiagramValidationError' && Array.isArray(e.issues)) {
|
|
20
20
|
return e.issues.map((i) => report(file, 'error', i));
|
|
21
21
|
}
|
|
22
|
+
if (e instanceof LoadError) {
|
|
23
|
+
return [
|
|
24
|
+
{
|
|
25
|
+
file,
|
|
26
|
+
severity: 'error',
|
|
27
|
+
code: 'load',
|
|
28
|
+
message: e.reason,
|
|
29
|
+
...(e.line !== undefined && e.column !== undefined ? { line: e.line, column: e.column } : {}),
|
|
30
|
+
},
|
|
31
|
+
];
|
|
32
|
+
}
|
|
22
33
|
return [report(file, 'error', { code: 'load', message: errMessage(e) })];
|
|
23
34
|
}
|
|
24
35
|
}
|
|
25
36
|
export function formatLintReport(r) {
|
|
26
|
-
|
|
37
|
+
const where = r.line !== undefined && r.column !== undefined ? `${r.file}:${r.line}:${r.column}` : r.file;
|
|
38
|
+
return `${where}: ${r.severity} ${r.code}: ${r.message}`;
|
|
27
39
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** The file every starter folder holds. One name in both layouts — a checkout's
|
|
2
|
+
* `.diagrams/src/examples/<type>/` and a package's `assets/starters/<type>/` — so
|
|
3
|
+
* one lookup serves both (see home.ts). */
|
|
4
|
+
export declare const STARTER_FILE = "starter.diagram.ts";
|
|
5
|
+
/** The diagram types a starter exists for: each folder under `startersDir` that
|
|
6
|
+
* holds one. In a checkout the folder also carries the realistic examples and a
|
|
7
|
+
* few loose diagrams, which is why this tests for the file and not just the folder. */
|
|
8
|
+
export declare function starterTypes(startersDir: string): string[];
|
|
9
|
+
/** Thrown for a type no starter exists for; `types` is what there is. */
|
|
10
|
+
export declare class UnknownStarterError extends Error {
|
|
11
|
+
readonly types: string[];
|
|
12
|
+
constructor(type: string, types: string[]);
|
|
13
|
+
}
|
|
14
|
+
/** One starter's source, byte for byte. The type is checked against the listing,
|
|
15
|
+
* never joined into a path first, so a type that is itself a path reads nothing. */
|
|
16
|
+
export declare function readStarter(startersDir: string, type: string): string;
|
package/dist/starters.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
/** The file every starter folder holds. One name in both layouts — a checkout's
|
|
4
|
+
* `.diagrams/src/examples/<type>/` and a package's `assets/starters/<type>/` — so
|
|
5
|
+
* one lookup serves both (see home.ts). */
|
|
6
|
+
export const STARTER_FILE = 'starter.diagram.ts';
|
|
7
|
+
/** The diagram types a starter exists for: each folder under `startersDir` that
|
|
8
|
+
* holds one. In a checkout the folder also carries the realistic examples and a
|
|
9
|
+
* few loose diagrams, which is why this tests for the file and not just the folder. */
|
|
10
|
+
export function starterTypes(startersDir) {
|
|
11
|
+
if (!existsSync(startersDir))
|
|
12
|
+
return [];
|
|
13
|
+
return readdirSync(startersDir, { withFileTypes: true })
|
|
14
|
+
.filter((e) => e.isDirectory() && existsSync(path.join(startersDir, e.name, STARTER_FILE)))
|
|
15
|
+
.map((e) => e.name)
|
|
16
|
+
.sort();
|
|
17
|
+
}
|
|
18
|
+
/** Thrown for a type no starter exists for; `types` is what there is. */
|
|
19
|
+
export class UnknownStarterError extends Error {
|
|
20
|
+
types;
|
|
21
|
+
constructor(type, types) {
|
|
22
|
+
super(`No starter '${type}'. Types: ${types.join(', ')}`);
|
|
23
|
+
this.types = types;
|
|
24
|
+
this.name = 'UnknownStarterError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** One starter's source, byte for byte. The type is checked against the listing,
|
|
28
|
+
* never joined into a path first, so a type that is itself a path reads nothing. */
|
|
29
|
+
export function readStarter(startersDir, type) {
|
|
30
|
+
const types = starterTypes(startersDir);
|
|
31
|
+
if (!types.includes(type))
|
|
32
|
+
throw new UnknownStarterError(type, types);
|
|
33
|
+
return readFileSync(path.join(startersDir, type, STARTER_FILE), 'utf8');
|
|
34
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@diagc/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Author software-architecture diagrams as code, compile them to a validated model, edit them in a local studio, and publish pages and images.",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
6
|
"author": "Bogdan Frankovskyi",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"fast-glob": "^3.3.0",
|
|
45
45
|
"jiti": "^2.0.0",
|
|
46
46
|
"playwright-core": "^1.62.0",
|
|
47
|
-
"@diagc/core": "0.
|
|
47
|
+
"@diagc/core": "0.12.0"
|
|
48
48
|
},
|
|
49
49
|
"publishConfig": {
|
|
50
50
|
"access": "public"
|