@diagc/cli 1.1.3 → 1.1.5

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.
@@ -12,6 +12,15 @@ function send(res, status, body) {
12
12
  res.setHeader('content-type', 'application/json');
13
13
  res.end(JSON.stringify(body));
14
14
  }
15
+ function decodes(s) {
16
+ try {
17
+ decodeURIComponent(s);
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
15
24
  /** Run the matching route with plain values — no HTTP anywhere. undefined means
16
25
  * no route matched (the HTTP wrapper falls through to static serving; the
17
26
  * Obsidian host answers 404). Errors become envelopes; this boundary never
@@ -23,6 +32,11 @@ export async function runRoute(request, ctx, handlers) {
23
32
  try {
24
33
  // matchRoute already proved the match; re-running exposes the captures.
25
34
  const match = request.url.match(route.pattern);
35
+ // The routes decode their captures; one that cannot be decoded is the
36
+ // client's mistake, answered here rather than thrown as a server error.
37
+ if (!match.slice(1).every((c) => c === undefined || decodes(c))) {
38
+ return { status: 400, body: { issues: [{ message: 'Malformed name' }] } };
39
+ }
26
40
  let body = undefined;
27
41
  if (route.bodyMode === 'json') {
28
42
  try {
@@ -1,9 +1,10 @@
1
1
  import { type DiagramModel } from '@diagc/core/internal';
2
+ import { isSafeName } from '../names.js';
2
3
  export interface HandlerResult {
3
4
  status: number;
4
5
  body: unknown;
5
6
  }
6
- export declare function isSafeName(name: string): boolean;
7
+ export { isSafeName };
7
8
  /** Recursively collect every file under `dir` whose name ends in `suffix`,
8
9
  * posix-joined relative to `dir` with the suffix stripped. Missing dir → [].
9
10
  * Shared by the diagram-source and layout-overlay walks. */
@@ -37,7 +38,7 @@ export declare function readDiagram(diagramsDir: string, name: string): Promise<
37
38
  export declare function readComposedDiagram(diagramsDir: string, name: string): Promise<HandlerResult>;
38
39
  export declare function saveDiagram(diagramsDir: string, name: string, payload: unknown): Promise<HandlerResult>;
39
40
  /** Move a designer-owned diagram (and its sibling layout, if any) to a new name,
40
- * rewriting the model's internal id/name to match so the file stays self-consistent. */
41
+ * rewriting the model's id to match so the file stays self-consistent. */
41
42
  export declare function renameDiagram(diagramsDir: string, from: string, to: string): Promise<HandlerResult>;
42
43
  /** Promote a JSON-owned diagram to a generated `.diagram.ts`. See `ejectDiagram`
43
44
  * for the round-trip guarantee; this just maps its failure codes to statuses. */
@@ -5,10 +5,10 @@ import { IMAGE_REF, composeIncludes, errMessage, isDrawings, isLayoutOverlay, va
5
5
  import { writeFileAtomic } from '../atomic-write.js';
6
6
  import { EjectError, ejectDiagram } from '../eject.js';
7
7
  import { resolveInclude } from '../includes.js';
8
+ import { isSafeName } from '../names.js';
8
9
  import { snapshotSession } from '../snapshots.js';
9
- export function isSafeName(name) {
10
- return /^[a-z0-9][a-z0-9/-]*$/.test(name) && !name.includes('..') && !name.includes('//');
11
- }
10
+ // The name rule every route checks, for the hosts and tests that reach it here.
11
+ export { isSafeName };
12
12
  // path.dirname(diagramsDir) is the .diagrams root when diagramsDir is
13
13
  // .diagrams/src — the same rootDir a locked session uses elsewhere (eject.ts).
14
14
  // 'locked' because the boot/refresh path must never fetch or vendor a remote
@@ -52,19 +52,26 @@ export async function listDiagramModels(diagramsDir, artifactsDir) {
52
52
  const all = [...new Set([...sourceNames, ...artifactNames])].sort();
53
53
  const diagrams = [];
54
54
  for (const name of all) {
55
- const editable = sourceNames.has(name);
56
- const file = editable
55
+ const isSource = sourceNames.has(name);
56
+ // Every read and save refuses a name isSafeName refuses, so such a source is shown but not offered for editing.
57
+ const editable = isSource && isSafeName(name);
58
+ const file = isSource
57
59
  ? path.join(diagramsDir, `${name}.diagram.json`)
58
60
  : path.join(artifactsDir, `${name}.diagram.json`);
59
61
  let model = null;
60
62
  const issues = [];
63
+ if (isSource && !editable) {
64
+ issues.push({
65
+ message: `'${name}' is read-only here: the studio saves names of lowercase letters, digits, '-' and '/', none ending in /rename, /eject or /composed. Rename the file to edit it.`,
66
+ });
67
+ }
61
68
  try {
62
69
  model = JSON.parse(await readFile(file, 'utf8'));
63
70
  }
64
71
  catch {
65
72
  issues.push({ message: `Could not read model for '${name}'` });
66
73
  }
67
- if (editable && hasIncludes(model)) {
74
+ if (isSource && hasIncludes(model)) {
68
75
  try {
69
76
  const { model: composed, warnings } = await composeIncludes(model, path.resolve(file), lockedResolver(diagramsDir));
70
77
  // compileFile refuses an invalid composed result outright, because the
@@ -208,7 +215,7 @@ export async function saveDiagram(diagramsDir, name, payload) {
208
215
  return { status: 200, body: { ok: true } };
209
216
  }
210
217
  /** Move a designer-owned diagram (and its sibling layout, if any) to a new name,
211
- * rewriting the model's internal id/name to match so the file stays self-consistent. */
218
+ * rewriting the model's id to match so the file stays self-consistent. */
212
219
  export async function renameDiagram(diagramsDir, from, to) {
213
220
  if (!isSafeName(from) || !isSafeName(to)) {
214
221
  return { status: 400, body: { issues: [{ message: `Unsafe name '${isSafeName(from) ? to : from}'` }] } };
@@ -238,25 +245,51 @@ export async function renameDiagram(diagramsDir, from, to) {
238
245
  catch {
239
246
  return { status: 400, body: { issues: [{ message: `Corrupt diagram source '${from}'` }] } };
240
247
  }
248
+ // The id follows the file. The name is the diagram's title, so it follows only
249
+ // when it was the id, a title nobody set.
250
+ if (model['name'] === model['id'])
251
+ model['name'] = to;
241
252
  model['id'] = to;
242
- model['name'] = to;
243
253
  await mkdir(path.dirname(toDiagram), { recursive: true });
244
- await writeFileAtomic(toDiagram, `${JSON.stringify(model, null, 2)}\n`);
245
- await unlink(fromDiagram);
246
- // Carry the layout over when it exists; its absence is not an error.
254
+ // Sidecars first, the source last, so the old name keeps its source until every
255
+ // other step has worked. A failure undoes the steps before it, in reverse, and
256
+ // the error answers 500.
257
+ const moved = [];
258
+ let written = false;
247
259
  try {
248
- await rename(path.join(diagramsDir, `${from}.layout.json`), path.join(diagramsDir, `${to}.layout.json`));
260
+ for (const sidecar of ['layout', 'drawings']) {
261
+ const move = [
262
+ path.join(diagramsDir, `${from}.${sidecar}.json`),
263
+ path.join(diagramsDir, `${to}.${sidecar}.json`),
264
+ ];
265
+ if (await moveIfPresent(...move))
266
+ moved.push(move);
267
+ }
268
+ await writeFileAtomic(toDiagram, `${JSON.stringify(model, null, 2)}\n`);
269
+ written = true;
270
+ await unlink(fromDiagram);
249
271
  }
250
- catch {
251
- /* no layout to move */
272
+ catch (e) {
273
+ if (written)
274
+ await unlink(toDiagram).catch(() => { });
275
+ for (const [src, dst] of moved.reverse())
276
+ await rename(dst, src).catch(() => { });
277
+ throw e;
252
278
  }
279
+ return { status: 200, body: { ok: true } };
280
+ }
281
+ /** `rename(src, dst)`, false when there is no `src` to move: a diagram need not have
282
+ * a sidecar. Any other failure throws. */
283
+ async function moveIfPresent(src, dst) {
253
284
  try {
254
- await rename(path.join(diagramsDir, `${from}.drawings.json`), path.join(diagramsDir, `${to}.drawings.json`));
285
+ await rename(src, dst);
286
+ return true;
255
287
  }
256
- catch {
257
- /* no drawings to move */
288
+ catch (e) {
289
+ if (e.code === 'ENOENT')
290
+ return false;
291
+ throw e;
258
292
  }
259
- return { status: 200, body: { ok: true } };
260
293
  }
261
294
  /** Promote a JSON-owned diagram to a generated `.diagram.ts`. See `ejectDiagram`
262
295
  * for the round-trip guarantee; this just maps its failure codes to statuses. */
@@ -66,8 +66,6 @@ export const ROUTES = [
66
66
  pattern: /^\/api\/(diagrams|layouts|drawings)\/(.+)$/,
67
67
  bodyMode: 'json',
68
68
  handler: (h, c) => {
69
- // decodeURIComponent throws on malformed percent-encoding — kept
70
- // inside the boundary so a bad name yields 500, never a crash.
71
69
  const name = decodeURIComponent(c.match[2] ?? '');
72
70
  return c.match[1] === 'diagrams'
73
71
  ? h.saveDiagram(c.diagramsDir, name, c.body)
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type PublishOptions } from './publish/publish.js';
2
- interface Args {
2
+ export interface Args {
3
3
  command: string;
4
4
  files: string[];
5
5
  out: string;
@@ -50,4 +50,3 @@ export declare function parseRange(range: string): {
50
50
  };
51
51
  /** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
52
52
  export declare function diffOutDir(from: string, to: string | undefined): string;
53
- export {};
package/dist/cli.js CHANGED
@@ -38,6 +38,7 @@ import { formatCompileEvent, startWatch } from './watch.js';
38
38
  import { galleryLink } from './publish/gallery.js';
39
39
  import { publishDiagrams } from './publish/publish.js';
40
40
  import { runStudio } from './studio.js';
41
+ import { ArgNotTakenError, checkCommandArgs } from './command-args.js';
41
42
  const USAGE = `Usage: diagc <init|compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
42
43
 
43
44
  Commands:
@@ -228,13 +229,14 @@ async function main() {
228
229
  let args;
229
230
  try {
230
231
  args = parseArgs(process.argv.slice(2));
232
+ checkCommandArgs(args);
231
233
  }
232
234
  catch (e) {
233
235
  if (e instanceof HelpRequested) {
234
236
  console.log(USAGE);
235
237
  process.exit(0);
236
238
  }
237
- if (e instanceof UnknownFlagError || e instanceof BadFlagValueError) {
239
+ if (e instanceof UnknownFlagError || e instanceof BadFlagValueError || e instanceof ArgNotTakenError) {
238
240
  console.error(`diagc: ${e.message}\n`);
239
241
  console.error(USAGE);
240
242
  process.exit(1);
@@ -290,12 +292,10 @@ async function main() {
290
292
  process.exit(reports.length > 0 ? 1 : 0);
291
293
  }
292
294
  else if (args.command === 'watch') {
293
- // Always locked, independent of args.updateIncludes: watch is a long-running
295
+ // Always locked, and --update-includes is refused here: watch is a long-running
294
296
  // live loop with no point at which "refetch and rewrite the lock" makes
295
- // sense, so it ignores the flag by design rather than inheriting the shared
296
- // session's mode (mirrors studio.ts's own hardcoded 'locked' session).
297
- if (args.updateIncludes)
298
- console.error('ignoring --update-includes: watch always runs locked');
297
+ // sense, so it has its own session rather than the shared one (mirrors
298
+ // studio.ts's own hardcoded 'locked' session).
299
299
  const dir = args.files[0] ?? '.diagrams/src';
300
300
  if (existsSync(dir) &&
301
301
  statSync(dir).isDirectory() &&
@@ -331,6 +331,7 @@ async function main() {
331
331
  const sources = await fg('**/*.diagram.{ts,json}', { cwd: dirs.srcDir, absolute: true });
332
332
  if (sources.length === 0)
333
333
  warnNoSources(dirs.srcDir);
334
+ let failed = false;
334
335
  for (const f of sources) {
335
336
  try {
336
337
  await compileFile(f, dirs.artifactsDir, {
@@ -340,13 +341,14 @@ async function main() {
340
341
  });
341
342
  }
342
343
  catch (e) {
344
+ failed = true;
343
345
  console.error(`✗ ${f}\n${errMessage(e)}`);
344
346
  }
345
347
  }
346
348
  // publish's glob above ignores args.files (that only scopes which rendered
347
- // pages come out below), so it always compiles the whole source tree —
348
- // an update run here is always full-tree, so the prune is unguarded.
349
- if (args.updateIncludes)
349
+ // pages come out below), so an update run here is always full-tree; like
350
+ // compile's, its prune waits until every source compiles.
351
+ if (args.updateIncludes && !failed)
350
352
  await snap.prune();
351
353
  let images = args.images;
352
354
  let renderPng;
@@ -378,16 +380,12 @@ async function main() {
378
380
  else if (args.command === 'studio') {
379
381
  // Studio's own compile-watch loop always resolves includes locked (see
380
382
  // studio.ts) — same reasoning as watch above.
381
- if (args.updateIncludes)
382
- console.error('ignoring --update-includes: studio always runs locked');
383
383
  await runStudio(home, process.cwd());
384
384
  return;
385
385
  }
386
386
  else if (args.command === 'eject') {
387
387
  // ejectDiagram's post-swap recompile always resolves includes locked (see
388
388
  // eject.ts) — same reasoning as watch above.
389
- if (args.updateIncludes)
390
- console.error('ignoring --update-includes: eject always runs locked');
391
389
  const name = args.files[0] === undefined ? undefined : diagramName(args.files[0]);
392
390
  if (name === undefined || name === '') {
393
391
  console.error('diagc: eject needs a diagram name.');
@@ -0,0 +1,9 @@
1
+ import type { Args } from './cli.js';
2
+ /** Thrown by {@link checkCommandArgs} for a flag or an argument the command does not
3
+ * take; `main` reports it the same way as an unknown flag. */
4
+ export declare class ArgNotTakenError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ /** Refuse a flag or an argument `args.command` does not take. Ignored, it would be a
8
+ * wrong file set or an output the user never sees (`init --out build`). */
9
+ export declare function checkCommandArgs(args: Args): void;
@@ -0,0 +1,56 @@
1
+ /** Thrown by {@link checkCommandArgs} for a flag or an argument the command does not
2
+ * take; `main` reports it the same way as an unknown flag. */
3
+ export class ArgNotTakenError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'ArgNotTakenError';
7
+ }
8
+ }
9
+ const LOCKED = { '--update-includes': 'it always resolves includes locked' };
10
+ /** What each command takes: the flags the reference's flag table lists for it, and a
11
+ * cap on positional arguments where the command has no message of its own for extra
12
+ * ones. `why` says why a flag another command takes means nothing here. */
13
+ const TAKES = {
14
+ compile: { flags: ['--out', '--update-includes'] },
15
+ lint: { flags: ['--json'] },
16
+ watch: { flags: ['--out'], max: [1, 'one directory'], why: LOCKED },
17
+ publish: { flags: ['--out', '--no-images', '--link', '--update-includes'] },
18
+ studio: { flags: [], max: [0, 'no arguments'], why: LOCKED },
19
+ eject: { flags: ['--out'], max: [1, 'one diagram name'], why: LOCKED },
20
+ diff: { flags: ['--out', '--no-images', '--json', '--labels', '--image-url'] },
21
+ guide: { flags: [] },
22
+ init: { flags: ['--type', '--agents'] },
23
+ };
24
+ /** The flags `args` says were passed. */
25
+ function flagsGiven(args) {
26
+ const given = [
27
+ [args.outGiven, '--out'],
28
+ [!args.images, '--no-images'],
29
+ [args.link !== undefined, '--link'],
30
+ [args.json, '--json'],
31
+ [args.labels !== undefined, '--labels'],
32
+ [args.imageUrl !== undefined, '--image-url'],
33
+ [args.updateIncludes, '--update-includes'],
34
+ [args.type !== undefined, '--type'],
35
+ [args.agents, '--agents'],
36
+ ];
37
+ return given.filter(([on]) => on).map(([, flag]) => flag);
38
+ }
39
+ /** Refuse a flag or an argument `args.command` does not take. Ignored, it would be a
40
+ * wrong file set or an output the user never sees (`init --out build`). */
41
+ export function checkCommandArgs(args) {
42
+ const takes = TAKES[args.command];
43
+ if (takes === undefined)
44
+ return; // an unknown command has its own message
45
+ for (const flag of flagsGiven(args)) {
46
+ if (takes.flags.includes(flag))
47
+ continue;
48
+ const takers = Object.keys(TAKES).filter((c) => TAKES[c].flags.includes(flag));
49
+ const list = takers.length === 1 ? takers[0] : `${takers.slice(0, -1).join(', ')} and ${takers.at(-1)}`;
50
+ const why = takes.why?.[flag] === undefined ? '' : ` (${takes.why[flag]})`;
51
+ throw new ArgNotTakenError(`${args.command} does not take ${flag}${why}; ${list} ${takers.length === 1 ? 'does' : 'do'}.`);
52
+ }
53
+ const extra = takes.max === undefined ? undefined : args.files[takes.max[0]];
54
+ if (extra !== undefined)
55
+ throw new ArgNotTakenError(`${args.command} takes ${takes.max[1]}; '${extra}' is one too many.`);
56
+ }
package/dist/compile.d.ts CHANGED
@@ -34,6 +34,9 @@ export interface LoadOptions {
34
34
  rootDir?: string;
35
35
  coreEntry?: string;
36
36
  resolver?: IncludeResolver;
37
+ /** what composing the includes warns about, one warning at a time; by default each
38
+ * is printed on stderr as `<file>: <warning>` */
39
+ onWarning?: (warning: string) => void;
37
40
  }
38
41
  /**
39
42
  * Read a source, validate it, expand its includes and validate the result: the
package/dist/compile.js CHANGED
@@ -142,8 +142,12 @@ export async function loadModel(file, opts) {
142
142
  ? snapshotSession(resolveInclude, path.dirname(path.resolve(opts.rootDir)), 'locked').resolver
143
143
  : resolveInclude);
144
144
  const { model: composed, warnings } = await composeIncludes(model, path.resolve(file), resolver);
145
- for (const w of warnings)
146
- console.warn(`${file}: ${w}`);
145
+ for (const w of warnings) {
146
+ if (opts?.onWarning !== undefined)
147
+ opts.onWarning(w);
148
+ else
149
+ console.warn(`${file}: ${w}`);
150
+ }
147
151
  model = composed;
148
152
  const issues = validate(model);
149
153
  if (issues.length > 0)
package/dist/init.js CHANGED
@@ -3,7 +3,7 @@ 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 './api/handlers.js';
6
+ import { isSafeName } from './names.js';
7
7
  import { compileFile } from './compile.js';
8
8
  import { readStarter, UnknownStarterError } from './starters.js';
9
9
  export const DEFAULT_NAME = 'example';
@@ -90,7 +90,7 @@ async function starterStep(opts, io) {
90
90
  }
91
91
  }
92
92
  const name = diagramName(opts.name ?? DEFAULT_NAME);
93
- if (!isSafeName(name) || name.endsWith('/')) {
93
+ if (!isSafeName(name)) {
94
94
  throw new InitError(`'${name}' is not a diagram name — use lowercase letters, digits and '-', with '/' for a folder (shop, team/app).`);
95
95
  }
96
96
  // The type is checked before the name clash: a wrong `--type` is the more useful
package/dist/lint.d.ts CHANGED
@@ -12,6 +12,7 @@ export interface LintReport {
12
12
  column?: number;
13
13
  }
14
14
  /** Every finding for one source: its validation errors when it does not load,
15
- * otherwise its warnings (core's lint included). */
15
+ * otherwise its warnings (core's lint included), and in both cases what composing
16
+ * its includes warned about. */
16
17
  export declare function lintFile(file: string, opts?: LoadOptions): Promise<LintReport[]>;
17
18
  export declare function formatLintReport(r: LintReport): string;
package/dist/lint.js CHANGED
@@ -8,18 +8,22 @@ const report = (file, severity, i) => ({
8
8
  ...(i.ref !== undefined ? { ref: i.ref } : {}),
9
9
  });
10
10
  /** Every finding for one source: its validation errors when it does not load,
11
- * otherwise its warnings (core's lint included). */
11
+ * otherwise its warnings (core's lint included), and in both cases what composing
12
+ * its includes warned about. */
12
13
  export async function lintFile(file, opts) {
14
+ // Findings rather than lines on stderr, so `--json` carries them and they fail the lint.
15
+ const included = [];
16
+ const onWarning = (message) => included.push(report(file, 'warning', { code: 'include', message }));
13
17
  try {
14
- const model = await loadModel(file, opts);
15
- return diagramWarnings(model).map((w) => report(file, 'warning', w));
18
+ const model = await loadModel(file, { ...opts, onWarning });
19
+ return [...included, ...diagramWarnings(model).map((w) => report(file, 'warning', w))];
16
20
  }
17
21
  catch (e) {
18
22
  // By name, not instanceof: a builder diagram throws from jiti's own copy of core.
19
23
  if (e instanceof Error &&
20
24
  e.name === 'DiagramValidationError' &&
21
25
  Array.isArray(e.issues)) {
22
- return e.issues.map((i) => report(file, 'error', i));
26
+ return [...included, ...e.issues.map((i) => report(file, 'error', i))];
23
27
  }
24
28
  if (e instanceof LoadError) {
25
29
  return [
@@ -0,0 +1,3 @@
1
+ /** A diagram name the API, the CLI and the file tree all agree on: lowercase
2
+ * letters, digits and `-`, with `/` between folders, every segment non-empty. */
3
+ export declare function isSafeName(name: string): boolean;
package/dist/names.js ADDED
@@ -0,0 +1,13 @@
1
+ /** Words the studio API's action routes put after a diagram's name
2
+ * (`/api/diagrams/<name>/rename`). A name ending in `/<word>` would be read as
3
+ * that action on its folder, so it could be created and never saved. Alone, the
4
+ * word is the plain route's name and is served like any other. */
5
+ const ACTION_SEGMENTS = ['rename', 'eject', 'composed'];
6
+ /** A diagram name the API, the CLI and the file tree all agree on: lowercase
7
+ * letters, digits and `-`, with `/` between folders, every segment non-empty. */
8
+ export function isSafeName(name) {
9
+ if (!/^[a-z0-9][a-z0-9/-]*$/.test(name) || name.includes('..') || name.includes('//') || name.endsWith('/'))
10
+ return false;
11
+ const slash = name.lastIndexOf('/');
12
+ return slash < 0 || !ACTION_SEGMENTS.includes(name.slice(slash + 1));
13
+ }
@@ -1,3 +1,4 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
3
  import path from 'node:path';
3
4
  import { errMessage, isDrawings } from '@diagc/core/internal';
@@ -5,6 +6,16 @@ import { classifyAssetRef, rewriteAssetRefs, safeAssetPath } from './assets.js';
5
6
  import { buildGallery } from './gallery.js';
6
7
  import { discoverDiagrams } from './discover.js';
7
8
  import { stampHtml } from './html.js';
9
+ /** The model's display name from its artifact, for a diagram this run did not read. */
10
+ async function titleOf(modelPath) {
11
+ try {
12
+ const name = JSON.parse(await readFile(modelPath, 'utf8')).name;
13
+ return typeof name === 'string' ? name : undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
8
19
  async function readMaybe(p) {
9
20
  try {
10
21
  return await readFile(p);
@@ -54,16 +65,17 @@ export async function publishDiagrams(opts) {
54
65
  if (opts.images)
55
66
  await mkdir(opts.staticDir, { recursive: true });
56
67
  const cache = new Map();
57
- let all = await discoverDiagrams(opts.artifactsDir, opts.srcDir);
68
+ const all = await discoverDiagrams(opts.artifactsDir, opts.srcDir);
69
+ let chosen = all;
58
70
  if (opts.names !== undefined && opts.names.length > 0) {
59
71
  const want = new Set(opts.names);
60
- all = all.filter((d) => want.has(d.name));
72
+ chosen = all.filter((d) => want.has(d.name));
61
73
  }
62
74
  const pages = [];
63
75
  const images = [];
64
76
  // diagram name → the model's display name, for the index cards
65
77
  const titles = new Map();
66
- for (const d of all) {
78
+ for (const d of chosen) {
67
79
  try {
68
80
  const modelRaw = JSON.parse(await readFile(d.modelPath, 'utf8'));
69
81
  titles.set(d.name, modelRaw.name);
@@ -98,16 +110,29 @@ export async function publishDiagrams(opts) {
98
110
  continue;
99
111
  }
100
112
  }
101
- // Only diagrams whose page was actually written belong in the gallery — a
102
- // source that failed before its HTML wrote would otherwise get a dead link.
113
+ // A diagram this run published gets a card for the page it wrote now and a thumbnail
114
+ // for the image it rendered now: what an earlier run left must not stand in for it
115
+ // (the Pages workflow counts thumbnails to catch a run with no usable Chrome), and a
116
+ // diagram that failed gets no card. A run scoped by name leaves the other pages in
117
+ // place, so the index keeps those diagrams as they are on disk. A page whose diagram
118
+ // is not discovered (its artifact is gone) gets no card.
103
119
  const written = new Set(pages);
120
+ const rendered = new Set(images);
121
+ const inRun = new Set(chosen.map((d) => d.name));
122
+ const entries = [];
123
+ for (const d of all) {
124
+ const pagePath = path.join(opts.htmlDir, `${d.name}.html`);
125
+ const pngPath = path.join(opts.staticDir, `${d.name}.png`);
126
+ const thisRun = inRun.has(d.name);
127
+ if (!(thisRun ? written.has(pagePath) : existsSync(pagePath)))
128
+ continue;
129
+ entries.push({
130
+ name: d.name,
131
+ title: titles.get(d.name) ?? (await titleOf(d.modelPath)) ?? d.name,
132
+ hasImage: thisRun ? rendered.has(pngPath) : existsSync(pngPath),
133
+ });
134
+ }
104
135
  const galleryPath = path.join(opts.htmlDir, 'index.html');
105
- await writeFile(galleryPath, buildGallery(all
106
- .filter((d) => written.has(path.join(opts.htmlDir, `${d.name}.html`)))
107
- .map((d) => ({
108
- name: d.name,
109
- title: titles.get(d.name) ?? d.name,
110
- hasImage: images.includes(path.join(opts.staticDir, `${d.name}.png`)),
111
- })), opts.link !== undefined ? { link: opts.link } : {}));
136
+ await writeFile(galleryPath, buildGallery(entries, opts.link !== undefined ? { link: opts.link } : {}));
112
137
  return { pages, images, gallery: galleryPath };
113
138
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagc/cli",
3
- "version": "1.1.3",
3
+ "version": "1.1.5",
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": "1.1.3"
47
+ "@diagc/core": "1.1.5"
48
48
  },
49
49
  "publishConfig": {
50
50
  "access": "public"