archidocs 1.3.0 → 1.3.1

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 (63) hide show
  1. package/dist/cli/commands.d.ts +8 -8
  2. package/dist/cli/commands.js +7 -7
  3. package/dist/cli/dev.d.ts +5 -6
  4. package/dist/cli/dev.js +12 -14
  5. package/dist/cli/diff-format.d.ts +1 -5
  6. package/dist/cli/main.js +2 -324
  7. package/dist/cli/run.d.ts +18 -0
  8. package/dist/cli/run.js +283 -0
  9. package/dist/commands/build.d.ts +51 -0
  10. package/dist/commands/build.js +39 -0
  11. package/dist/commands/check.d.ts +8 -0
  12. package/dist/commands/check.js +5 -0
  13. package/dist/commands/diff.d.ts +29 -0
  14. package/dist/commands/diff.js +25 -0
  15. package/dist/commands/export.d.ts +41 -0
  16. package/dist/commands/export.js +47 -0
  17. package/dist/commands/history.d.ts +18 -0
  18. package/dist/commands/history.js +9 -0
  19. package/dist/commands/index.d.ts +11 -0
  20. package/dist/commands/index.js +11 -0
  21. package/dist/core/index.d.ts +1 -1
  22. package/dist/core/index.js +1 -1
  23. package/dist/core/load.d.ts +0 -2
  24. package/dist/core/load.js +5 -6
  25. package/dist/core/workspace-files.d.ts +13 -0
  26. package/dist/core/workspace-files.js +20 -0
  27. package/dist/git.d.ts +2 -0
  28. package/dist/git.js +14 -4
  29. package/dist/history/git.d.ts +0 -10
  30. package/dist/history/git.js +1 -30
  31. package/dist/history/index.d.ts +15 -31
  32. package/dist/history/index.js +47 -43
  33. package/dist/history/points.d.ts +23 -0
  34. package/dist/history/points.js +28 -0
  35. package/dist/history/site.d.ts +30 -0
  36. package/dist/history/site.js +37 -0
  37. package/dist/mcp/history.d.ts +4 -4
  38. package/dist/mcp/history.js +56 -116
  39. package/dist/mcp/server.js +18 -17
  40. package/dist/mcp/site.d.ts +12 -0
  41. package/dist/mcp/site.js +46 -0
  42. package/dist/mcp/source.d.ts +14 -7
  43. package/dist/mcp/source.js +25 -99
  44. package/dist/revisions/find.d.ts +64 -0
  45. package/dist/revisions/find.js +85 -0
  46. package/dist/revisions/index.d.ts +57 -0
  47. package/dist/revisions/index.js +24 -0
  48. package/dist/revisions/site.d.ts +82 -0
  49. package/dist/revisions/site.js +157 -0
  50. package/dist/revisions/text.d.ts +8 -0
  51. package/dist/revisions/text.js +17 -0
  52. package/dist/revisions/touching.d.ts +7 -0
  53. package/dist/revisions/touching.js +7 -0
  54. package/dist/viewer/assets/index-C0lIIm8V.js +138 -0
  55. package/dist/viewer/assets/{png-CAaXWR-k.js → png-DMwnpRCt.js} +1 -1
  56. package/dist/viewer/assets/{svg-BPVHfD36.js → svg-DN6lMeZo.js} +1 -1
  57. package/dist/viewer/index.html +1 -1
  58. package/dist/workspace/index.d.ts +37 -0
  59. package/dist/workspace/index.js +52 -0
  60. package/package.json +1 -1
  61. package/dist/viewer/assets/index-BXa5R96a.js +0 -138
  62. /package/dist/{history → revisions}/migrate.d.ts +0 -0
  63. /package/dist/{history → revisions}/migrate.js +0 -0
@@ -249,7 +249,7 @@ export declare const commands: {
249
249
  readonly dev: {
250
250
  readonly name: "dev";
251
251
  readonly synopsis: readonly ["dev [--workspace <dir>] [--port <n>] [--host <host>]"];
252
- readonly description: "Serve the viewer locally and reload it as you edit the Workspace.";
252
+ readonly description: "Serve the viewer locally and reload it when a `.yaml` or `.md` file in the Workspace changes.";
253
253
  readonly arguments: readonly [];
254
254
  readonly flags: {
255
255
  readonly workspace: {
@@ -368,10 +368,10 @@ export declare const commands: {
368
368
  readonly description: "Show what changed in the Model between two points in the Workspace's history.";
369
369
  readonly arguments: readonly [{
370
370
  readonly name: "<from>";
371
- readonly description: "A git ref, or a date, which means the last default-branch commit at or before it.";
371
+ readonly description: "A git ref, or a date or time, which names the last Revision at or before it.";
372
372
  }, {
373
373
  readonly name: "[<to>]";
374
- readonly description: "A ref or date like `<from>`; with none, the working tree.";
374
+ readonly description: "A ref, date or time like `<from>`; with none, the working tree.";
375
375
  }];
376
376
  readonly flags: {
377
377
  readonly format: {
@@ -389,7 +389,7 @@ export declare const commands: {
389
389
  readonly description: "Show what a branch changes against the default branch, as a reviewer of its pull request will see it.";
390
390
  }, {
391
391
  readonly command: "archidocs diff 2026-01-01 2026-06-30";
392
- readonly description: "Show the Changes between two dates; each date means the last default-branch commit at or before it.";
392
+ readonly description: "Show the Changes between two dates; each date names the last Revision at or before it.";
393
393
  }, {
394
394
  readonly command: "archidocs diff origin/main HEAD --format markdown";
395
395
  readonly description: "Write the Changes as Markdown, to post as a pull request comment.";
@@ -399,20 +399,20 @@ export declare const commands: {
399
399
  readonly meaning: "The Changes were printed. It exits 0 whether or not anything changed, so a script that asks whether the Model changed must read the output, not the exit code.";
400
400
  }, {
401
401
  readonly code: 2;
402
- readonly meaning: "It could not run: an unknown flag, a flag missing its value, an unknown format, no point or more than two, an unknown ref or date, no Workspace found, or a Workspace outside git.";
402
+ readonly meaning: "It could not run: an unknown flag, a flag missing its value, an unknown format, no point or more than two, an unknown ref or date, a date before the first Revision, a sha prefix of several Revisions, no Workspace found, or a Workspace outside git.";
403
403
  }];
404
404
  };
405
405
  readonly "history build": {
406
406
  readonly name: "history build";
407
- readonly synopsis: readonly ["history build [--since <ref|date>]"];
407
+ readonly synopsis: readonly ["history build [--since <ref|date|time>]"];
408
408
  readonly description: "Build and cache the Bundle of every past Revision, so later builds and diffs don't have to. Safe to re-run.";
409
409
  readonly arguments: readonly [];
410
410
  readonly flags: {
411
411
  readonly since: {
412
412
  readonly type: "string";
413
- readonly value: "<ref|date>";
413
+ readonly value: "<ref|date|time>";
414
414
  readonly defaultText: "every Revision";
415
- readonly description: "Only build Revisions at or after this ref's commit time or the start of this date.";
415
+ readonly description: "Only build Revisions at or after this ref's commit time, the start of this date, or this time (UTC unless it gives a zone).";
416
416
  };
417
417
  };
418
418
  readonly examples: readonly [{
@@ -118,7 +118,7 @@ export const commands = {
118
118
  dev: {
119
119
  name: "dev",
120
120
  synopsis: ["dev [--workspace <dir>] [--port <n>] [--host <host>]"],
121
- description: "Serve the viewer locally and reload it as you edit the Workspace.",
121
+ description: "Serve the viewer locally and reload it when a `.yaml` or `.md` file in the Workspace changes.",
122
122
  arguments: [],
123
123
  flags: {
124
124
  workspace: { type: "string", value: "<dir>", defaultText: "the Workspace found from the current folder", description: "Where to look for the Workspace." },
@@ -174,8 +174,8 @@ export const commands = {
174
174
  synopsis: ["diff <from> [<to>] [--format text|json|markdown]"],
175
175
  description: "Show what changed in the Model between two points in the Workspace's history.",
176
176
  arguments: [
177
- { name: "<from>", description: "A git ref, or a date, which means the last default-branch commit at or before it." },
178
- { name: "[<to>]", description: "A ref or date like `<from>`; with none, the working tree." },
177
+ { name: "<from>", description: "A git ref, or a date or time, which names the last Revision at or before it." },
178
+ { name: "[<to>]", description: "A ref, date or time like `<from>`; with none, the working tree." },
179
179
  ],
180
180
  flags: {
181
181
  format: { type: "string", value: "text|json|markdown", default: "text", description: "Print the changes as text, JSON, or Markdown for a PR comment." },
@@ -183,21 +183,21 @@ export const commands = {
183
183
  examples: [
184
184
  { command: "archidocs diff HEAD", description: "Show what your uncommitted edits change, against the last commit." },
185
185
  { command: "archidocs diff origin/main HEAD", description: "Show what a branch changes against the default branch, as a reviewer of its pull request will see it." },
186
- { command: "archidocs diff 2026-01-01 2026-06-30", description: "Show the Changes between two dates; each date means the last default-branch commit at or before it." },
186
+ { command: "archidocs diff 2026-01-01 2026-06-30", description: "Show the Changes between two dates; each date names the last Revision at or before it." },
187
187
  { command: "archidocs diff origin/main HEAD --format markdown", description: "Write the Changes as Markdown, to post as a pull request comment." },
188
188
  ],
189
189
  exitCodes: [
190
190
  { code: EXIT.ok, meaning: "The Changes were printed. It exits 0 whether or not anything changed, so a script that asks whether the Model changed must read the output, not the exit code." },
191
- { code: EXIT.couldNotRun, meaning: `It could not run: ${USAGE_ERROR}, an unknown format, no point or more than two, an unknown ref or date, no Workspace found, or a Workspace outside git.` },
191
+ { code: EXIT.couldNotRun, meaning: `It could not run: ${USAGE_ERROR}, an unknown format, no point or more than two, an unknown ref or date, a date before the first Revision, a sha prefix of several Revisions, no Workspace found, or a Workspace outside git.` },
192
192
  ],
193
193
  },
194
194
  "history build": {
195
195
  name: "history build",
196
- synopsis: ["history build [--since <ref|date>]"],
196
+ synopsis: ["history build [--since <ref|date|time>]"],
197
197
  description: "Build and cache the Bundle of every past Revision, so later builds and diffs don't have to. Safe to re-run.",
198
198
  arguments: [],
199
199
  flags: {
200
- since: { type: "string", value: "<ref|date>", defaultText: "every Revision", description: "Only build Revisions at or after this ref's commit time or the start of this date." },
200
+ since: { type: "string", value: "<ref|date|time>", defaultText: "every Revision", description: "Only build Revisions at or after this ref's commit time, the start of this date, or this time (UTC unless it gives a zone)." },
201
201
  },
202
202
  examples: [
203
203
  { command: "archidocs history build", description: "Build and cache the Bundle of every past Revision, so the next `build` or `diff` reads them from the cache." },
package/dist/cli/dev.d.ts CHANGED
@@ -1,12 +1,11 @@
1
- import { type Issue } from "../core/index.ts";
1
+ import type { Issue } from "../core/index.ts";
2
+ import { type Checkout } from "../workspace/index.ts";
2
3
  export declare const DEFAULT_DEV_PORT = 4321;
3
4
  export interface DevOptions {
4
- /** The Workspace root, watched for changes. */
5
- root: string;
5
+ /** The Workspace to serve. Its root is watched for changes, and its name is how the viewer's exports name the Workspace, as `site.json` does in a built site. */
6
+ checkout: Checkout;
6
7
  /** The prebuilt viewer to serve. */
7
8
  viewerDir: string;
8
- /** How the viewer's exports name the Workspace, as `site.json` does in a built site. */
9
- workspace: string;
10
9
  host?: string;
11
10
  /** 0 picks a free port. */
12
11
  port?: number;
@@ -28,4 +27,4 @@ export interface DevServer {
28
27
  * the Workspace on every file change. A Workspace with errors keeps serving
29
28
  * its last good Bundle and shows the errors in the page instead.
30
29
  */
31
- export declare function serveDev({ root, viewerDir, workspace, host, port, onLoad }: DevOptions): Promise<DevServer>;
30
+ export declare function serveDev({ checkout, viewerDir, host, port, onLoad }: DevOptions): Promise<DevServer>;
package/dist/cli/dev.js CHANGED
@@ -2,10 +2,9 @@ import { watch } from "node:fs";
2
2
  import { readFile, stat } from "node:fs/promises";
3
3
  import { createServer } from "node:http";
4
4
  import { extname, join, normalize, sep } from "node:path";
5
- import { load, nodeFileSystem, serializeBundle } from "../core/index.js";
6
5
  import { formatText } from "./format.js";
7
- import { gitHead } from "../git.js";
8
- import { SCHEMA_VERSION } from "../schema/bundle.js";
6
+ import { isWorkspaceFile } from "../workspace/index.js";
7
+ import { INDEX_PATH, INDEX_VERSION, LATEST_BUNDLE_PATH, serializeBundle, serializeIndex, serializeSiteFile, SITE_FILE_PATH } from "../revisions/index.js";
9
8
  export const DEFAULT_DEV_PORT = 4321;
10
9
  /** The path the page listens on for reloads; under `__archidocs/` so it can't clash with a site file. */
11
10
  const EVENTS = "/__archidocs/events";
@@ -42,7 +41,7 @@ const CLIENT = `<script>
42
41
  * the Workspace on every file change. A Workspace with errors keeps serving
43
42
  * its last good Bundle and shows the errors in the page instead.
44
43
  */
45
- export async function serveDev({ root, viewerDir, workspace, host = "127.0.0.1", port = DEFAULT_DEV_PORT, onLoad }) {
44
+ export async function serveDev({ checkout, viewerDir, host = "127.0.0.1", port = DEFAULT_DEV_PORT, onLoad }) {
46
45
  let bundleJson;
47
46
  let errors;
48
47
  const clients = new Set();
@@ -52,8 +51,7 @@ export async function serveDev({ root, viewerDir, workspace, host = "127.0.0.1",
52
51
  };
53
52
  let first = true;
54
53
  const rebuild = async () => {
55
- const { commit, builtAt } = await gitHead(root);
56
- const { bundle, issues } = await load({ fs: nodeFileSystem(), root, commit, builtAt });
54
+ const { bundle, issues } = await checkout.load();
57
55
  const failed = issues.filter((i) => i.severity === "error");
58
56
  const kept = failed.length > 0 && bundleJson !== undefined;
59
57
  onLoad?.({ issues, kept, first });
@@ -89,8 +87,8 @@ export async function serveDev({ root, viewerDir, workspace, host = "127.0.0.1",
89
87
  };
90
88
  await rebuild();
91
89
  const index = (await readFile(join(viewerDir, "index.html"), "utf8")).replace("</body>", `${CLIENT}</body>`);
92
- const site = JSON.stringify({ workspace }) + "\n";
93
- const noHistory = JSON.stringify({ schemaVersion: SCHEMA_VERSION, revisions: [] }) + "\n";
90
+ const site = serializeSiteFile(await checkout.name());
91
+ const noHistory = serializeIndex({ schemaVersion: INDEX_VERSION, revisions: [] });
94
92
  const server = createServer((req, res) => {
95
93
  void (async () => {
96
94
  const path = decodeURIComponent(new URL(req.url ?? "/", "http://dev").pathname);
@@ -109,12 +107,12 @@ export async function serveDev({ root, viewerDir, workspace, host = "127.0.0.1",
109
107
  }
110
108
  if (path === "/" || path === "/index.html")
111
109
  return send(index, TYPES[".html"]);
112
- if (path === "/workspace.bundle.json")
110
+ if (path === `/${LATEST_BUNDLE_PATH}`)
113
111
  return send(bundleJson, TYPES[".json"]);
114
- if (path === "/site.json")
112
+ if (path === `/${SITE_FILE_PATH}`)
115
113
  return send(site, TYPES[".json"]);
116
114
  // Dev mode shows the working tree only; the viewer reads an empty index as no history.
117
- if (path === "/bundles/index.json")
115
+ if (path === `/${INDEX_PATH}`)
118
116
  return send(noHistory, TYPES[".json"]);
119
117
  const file = normalize(join(viewerDir, path));
120
118
  if (!file.startsWith(normalize(viewerDir + sep)) || !(await stat(file).catch(() => undefined))?.isFile()) {
@@ -132,9 +130,9 @@ export async function serveDev({ root, viewerDir, workspace, host = "127.0.0.1",
132
130
  server.once("error", fail);
133
131
  server.listen(port, host, () => done());
134
132
  });
135
- const watcher = watch(root, { recursive: true }, (_event, name) => {
136
- // Hidden folders (.git, editor swap files) and node_modules aren't Workspace files.
137
- if (name && name.split(/[\\/]/).some((part) => part.startsWith(".") || part === "node_modules"))
133
+ const watcher = watch(checkout.root, { recursive: true }, (_event, name) => {
134
+ // Only a Workspace file feeds the Bundle. Some platforms give no name, so reload then.
135
+ if (name && !isWorkspaceFile(name))
138
136
  return;
139
137
  schedule();
140
138
  });
@@ -1,9 +1,5 @@
1
1
  import { type Change } from "../core/index.ts";
2
+ import type { DiffSide } from "../commands/index.ts";
2
3
  export declare const diffFormats: readonly ["text", "json", "markdown"];
3
4
  export type DiffFormat = (typeof diffFormats)[number];
4
- /** One side of a diff: the point as given and the commit it resolved to (null for the working tree). */
5
- export interface DiffSide {
6
- point: string;
7
- commit: string | null;
8
- }
9
5
  export declare function formatDiff(changes: Change[], from: DiffSide, to: DiffSide, format: DiffFormat): string;
package/dist/cli/main.js CHANGED
@@ -1,325 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync } from "node:fs";
3
- import { cp, mkdir, readFile, realpath, writeFile } from "node:fs/promises";
4
- import { basename, join, resolve } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { findWorkspaceRoot, load, nodeFileSystem, resolveView, serializeBundle } from "../core/index.js";
7
- import { directions, layoutView, renderSequenceSvg, renderSvg, themes } from "../render/index.js";
8
- import { renderPngInNode } from "../render/node.js";
9
- import { serveStdio } from "@modelcontextprotocol/server/stdio";
10
- import { gitHead, gitTopLevel } from "../git.js";
11
- import { bundleSource, checkoutSource, createServer, DEFAULT_PORT, serveHttp } from "../mcp/index.js";
12
- import { authoringGuide } from "../guide/index.js";
13
- import { EXIT, NO_WORKSPACE, parseCommand, usageText } from "./commands.js";
14
- import { init } from "./init.js";
15
- import { DEFAULT_DEV_PORT, serveDev } from "./dev.js";
16
- import { exitCodeFor, formatIssues, formats, formatText } from "./format.js";
17
- import { diff } from "../core/index.js";
18
- import { bundleAt, buildHistory, DEFAULT_KEEP, defaultBaseBranch, history, previewSides, publishHistory, publishPreview, resolvePoint } from "../history/index.js";
19
- import { SCHEMA_VERSION } from "../schema/bundle.js";
20
- import { diffFormats, formatDiff } from "./diff-format.js";
21
- /** Exit codes, shared with the command definitions that document them: 0 no errors, 1 errors found (or any warning with `--strict`), 2 could not run. */
22
- const { ok: OK, foundErrors: FOUND_ERRORS, couldNotRun: COULD_NOT_RUN } = EXIT;
23
- class UsageError extends Error {
24
- }
25
- /**
26
- * The prebuilt viewer, which `build --out` copies as is. The CLI runs from
27
- * dist/cli/ when installed and from src/cli/ in this repo; both sit two
28
- * levels below the package root, whose dist/viewer/ holds the viewer.
29
- */
30
- const VIEWER_DIR = fileURLToPath(new URL("../../dist/viewer/", import.meta.url));
31
- /** The package's own package.json, two levels up from dist/cli/ or src/cli/ like the viewer. */
32
- const PACKAGE_JSON = fileURLToPath(new URL("../../package.json", import.meta.url));
33
- const usage = usageText();
34
- async function main(argv) {
35
- const [command, ...rest] = argv;
36
- if (command === "init") {
37
- const { values } = parseCommand("init", rest);
38
- if (values.workspace !== undefined && !values.skill)
39
- throw new UsageError("--workspace only applies with --skill; without it, init uses or creates this repo's Workspace.");
40
- const cwd = await realpath(process.cwd());
41
- const repoRoot = (await gitTopLevel(cwd)) ?? cwd;
42
- const lines = await init({ repoRoot, cwd, skillOnly: values.skill, ...(values.workspace === undefined ? {} : { workspace: values.workspace }) });
43
- process.stdout.write(lines.join("\n") + "\n");
44
- return OK;
45
- }
46
- if (command === "version") {
47
- const { values } = parseCommand("version", rest);
48
- if (values.format !== "text" && values.format !== "json")
49
- throw new UsageError(`Unknown format "${values.format}"; use text or json.`);
50
- const { version } = JSON.parse(await readFile(PACKAGE_JSON, "utf8"));
51
- process.stdout.write(values.format === "json" ? JSON.stringify({ version, schemaVersion: SCHEMA_VERSION }) + "\n" : `archidocs ${version} (Bundle schemaVersion ${SCHEMA_VERSION})\n`);
52
- return OK;
53
- }
54
- if (command === "guide") {
55
- const { positionals } = parseCommand("guide", rest);
56
- if (positionals.length > 1)
57
- throw new UsageError(`Give one topic at a time; got ${positionals.join(", ")}.`);
58
- const guide = await authoringGuide(positionals[0]);
59
- if (!guide.ok)
60
- throw new UsageError(guide.message);
61
- process.stdout.write(guide.text);
62
- return OK;
63
- }
64
- if (command === "check") {
65
- const { values } = parseCommand("check", rest);
66
- const format = values.format;
67
- if (!formats.includes(format))
68
- throw new UsageError(`Unknown format "${values.format}"; use ${formats.join(", ")}.`);
69
- const { issues } = await loadFromCwd();
70
- process.stdout.write(formatIssues(issues, format, { color: useColor() }));
71
- return exitCodeFor(issues, { strict: values.strict });
72
- }
73
- if (command === "build") {
74
- const { values } = parseCommand("build", rest);
75
- if (values.preview && values.keep !== undefined)
76
- throw new UsageError("--keep doesn't apply to --preview, whose site holds just the base and the PR head.");
77
- if (values.preview && values["bundle-only"])
78
- throw new UsageError("--bundle-only doesn't apply to --preview, which writes a site.");
79
- if (values.base !== undefined && !values.preview)
80
- throw new UsageError("--base only applies with --preview.");
81
- const keep = values.keep === undefined ? DEFAULT_KEEP : values.keep === "all" ? "all" : Number(values.keep);
82
- if (keep !== "all" && !(Number.isInteger(keep) && keep >= 0))
83
- throw new UsageError(`--keep "${values.keep}" is not a count or all.`);
84
- if (values["bundle-only"] && values.keep !== undefined)
85
- throw new UsageError("--keep only applies to a site; --bundle-only writes no past Bundles.");
86
- const { bundle, issues } = await loadFromCwd();
87
- if (issues.some((i) => i.severity === "error")) {
88
- process.stdout.write(formatText(issues, { color: useColor() }));
89
- process.stderr.write(`Not writing the ${values["bundle-only"] ? "Bundle" : "site"}: the Workspace has errors.\n`);
90
- return FOUND_ERRORS;
91
- }
92
- // A preview finds both sides before writing anything, so a missing base writes no site.
93
- let preview;
94
- if (values.preview) {
95
- const h = await historyFromCwd();
96
- preview = { h, sides: await previewSides(h, values.base ?? (await defaultBaseBranch(h.repoRoot))) };
97
- }
98
- const out = resolve(values.out);
99
- if (!values["bundle-only"]) {
100
- if (!existsSync(join(VIEWER_DIR, "index.html")))
101
- throw new Error(`The viewer is not built (no ${VIEWER_DIR}); run \`pnpm build\` first.`);
102
- await cp(VIEWER_DIR, out, { recursive: true });
103
- // The viewer's exports name the Workspace as `archidocs export` does: by its repo's folder.
104
- const root = await workspaceRoot(process.cwd());
105
- await writeFile(join(out, "site.json"), JSON.stringify({ workspace: await workspaceName(root) }) + "\n");
106
- }
107
- await mkdir(out, { recursive: true });
108
- await writeFile(join(out, "workspace.bundle.json"), serializeBundle(bundle));
109
- if (preview) {
110
- const { base, baseSha, headSha } = await publishPreview(preview.h, out, preview.sides, bundle);
111
- process.stdout.write(`Wrote the preview site to ${values.out}: Compare origin/${base} (${baseSha.slice(0, 7)}) → PR (${headSha.slice(0, 7)})\n`);
112
- return OK;
113
- }
114
- if (!values["bundle-only"])
115
- await writeSiteHistory(out, keep);
116
- process.stdout.write(values["bundle-only"] ? `Wrote ${join(values.out, "workspace.bundle.json")}\n` : `Wrote the site to ${values.out}\n`);
117
- return OK;
118
- }
119
- if (command === "dev") {
120
- const { values } = parseCommand("dev", rest);
121
- const port = values.port === undefined ? DEFAULT_DEV_PORT : Number(values.port);
122
- if (!Number.isInteger(port) || port < 0 || port > 65535)
123
- throw new UsageError(`--port "${values.port}" is not a port.`);
124
- if (!existsSync(join(VIEWER_DIR, "index.html")))
125
- throw new Error(`The viewer is not built (no ${VIEWER_DIR}); run \`pnpm build\` first.`);
126
- const root = await workspaceRoot(values.workspace === undefined ? process.cwd() : resolve(values.workspace));
127
- const color = useColor();
128
- const dev = await serveDev({
129
- root,
130
- viewerDir: VIEWER_DIR,
131
- workspace: await workspaceName(root),
132
- port,
133
- ...(values.host === undefined ? {} : { host: values.host }),
134
- onLoad: ({ issues, kept, first }) => {
135
- const shown = issues.filter((i) => i.severity === "error" || first);
136
- if (shown.length > 0)
137
- process.stdout.write(formatText(shown, { color }));
138
- if (kept)
139
- process.stderr.write("The Workspace has errors; still serving the last good Bundle.\n");
140
- else if (!first)
141
- process.stderr.write(`Reloaded the Workspace (${new Date().toLocaleTimeString()})\n`);
142
- },
143
- }).catch((e) => {
144
- if (e.code === "EADDRINUSE")
145
- throw new UsageError(`Port ${port} is in use; pick another with --port.`);
146
- throw e;
147
- });
148
- process.stderr.write(`Archidocs dev server on ${dev.url} (watching ${root}; Ctrl+C to stop)\n`);
149
- return OK;
150
- }
151
- if (command === "export") {
152
- const { values, positionals } = parseCommand("export", rest);
153
- const allSaved = values["all-saved"];
154
- const [viewId, ...extra] = positionals;
155
- if (allSaved && viewId !== undefined)
156
- throw new UsageError("Give a View or --all-saved, not both.");
157
- if (allSaved && values.out === undefined)
158
- throw new UsageError("--all-saved needs --out <dir> for the pictures.");
159
- if (!allSaved && viewId === undefined)
160
- throw new UsageError("Give the View to export, such as c1 or c2/<system>, or --all-saved.");
161
- if (extra.length > 0)
162
- throw new UsageError(`Export one View at a time; got ${positionals.join(", ")}.`);
163
- const format = values.format;
164
- if (format !== "svg" && format !== "png")
165
- throw new UsageError(`Unknown format "${format}"; use svg or png.`);
166
- const direction = values.direction;
167
- if (direction !== undefined && !directions.includes(direction))
168
- throw new UsageError(`Unknown direction "${direction}"; use ${directions.join(", ")}.`);
169
- const theme = values.theme;
170
- if (!themes.includes(theme))
171
- throw new UsageError(`Unknown theme "${values.theme}"; use ${themes.join(" or ")}.`);
172
- const { label } = values;
173
- const root = await workspaceRoot(process.cwd());
174
- const { bundle, issues } = await loadFromCwd();
175
- if (issues.some((i) => i.severity === "error")) {
176
- process.stdout.write(formatText(issues, { color: useColor() }));
177
- process.stderr.write("Not exporting: the Workspace has errors.\n");
178
- return FOUND_ERRORS;
179
- }
180
- const workspace = await workspaceName(root);
181
- const fileName = (id) => `${id.replace(/[/:]/g, "-")}.${format}`;
182
- const source = { workspace, commit: bundle.commit, date: bundle.builtAt };
183
- const write = async (svg, out) => {
184
- await writeFile(resolve(out), format === "svg" ? svg : await renderPngInNode(svg));
185
- process.stdout.write(`Wrote ${out}\n`);
186
- };
187
- /** Lays out and draws one View: a Dynamic View as a sequence chart, any other as a diagram; `--direction` wins over the View's own. */
188
- const draw = async (view, out) => {
189
- if (view.kind === "dynamic")
190
- return write(renderSequenceSvg({ bundle, view, source, theme, label }), out);
191
- const layout = await layoutView(view, direction === undefined ? {} : { direction });
192
- await write(renderSvg({ bundle, view, layout, source, theme, label }), out);
193
- };
194
- if (allSaved) {
195
- await mkdir(resolve(values.out), { recursive: true });
196
- for (const saved of bundle.views) {
197
- const view = resolveView(bundle, saved.id);
198
- if (view)
199
- await draw(view, join(values.out, fileName(saved.id)));
200
- }
201
- return OK;
202
- }
203
- const view = resolveView(bundle, viewId);
204
- if (!view)
205
- throw new UsageError(`Unknown View "${viewId}"; Views are c1, c2, c2/<system>, c3/<service with Components>, deployment/<environment> and Saved Views (project:view-id).`);
206
- await draw(view, values.out ?? fileName(viewId));
207
- return OK;
208
- }
209
- if (command === "diff") {
210
- const { values, positionals } = parseCommand("diff", rest);
211
- const format = values.format;
212
- if (!diffFormats.includes(format))
213
- throw new UsageError(`Unknown format "${values.format}"; use ${diffFormats.join(", ")}.`);
214
- const [fromPoint, toPoint, ...extra] = positionals;
215
- if (fromPoint === undefined)
216
- throw new UsageError("Give the point to diff from: a ref or a date.");
217
- if (extra.length > 0)
218
- throw new UsageError(`Give at most two points; got ${positionals.join(", ")}.`);
219
- const h = await historyFromCwd();
220
- /** A point's Bundle; with no point, the working tree's. */
221
- const side = async (point) => {
222
- if (point === undefined)
223
- return [{ point: "working tree", commit: null }, (await loadFromCwd()).bundle];
224
- const commit = await resolvePoint(h.repoRoot, point);
225
- if (!commit)
226
- throw new UsageError(`Unknown ref or date "${point}"; a date resolves to the last default-branch commit at or before it.`);
227
- return [{ point, commit }, (await bundleAt(h, commit)).bundle];
228
- };
229
- const [from, before] = await side(fromPoint);
230
- const [to, after] = await side(toPoint);
231
- process.stdout.write(formatDiff(diff(before, after), from, to, format));
232
- return OK;
233
- }
234
- if (command === "history") {
235
- const [sub, ...args] = rest;
236
- if (sub !== "build")
237
- throw new UsageError(sub ? `Unknown history command "${sub}".` : "Give a history command: build.");
238
- const { values } = parseCommand("history build", args);
239
- const h = await historyFromCwd();
240
- const { revisions, built } = await buildHistory(h, values.since === undefined ? {} : { since: values.since });
241
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
242
- process.stdout.write(`Built ${plural(built, "Revision")}; ${revisions - built} of ${revisions} already built.\n`);
243
- return OK;
244
- }
245
- if (command === "mcp") {
246
- const { values } = parseCommand("mcp", rest);
247
- const viewerUrl = values["viewer-url"];
248
- if (viewerUrl !== undefined && !URL.canParse(viewerUrl))
249
- throw new UsageError(`--viewer-url "${viewerUrl}" is not a URL.`);
250
- if (values.workspace !== undefined && values.bundle !== undefined)
251
- throw new UsageError("Give --workspace or --bundle, not both.");
252
- if (!values.http && values["allow-writes"])
253
- throw new UsageError("--allow-writes only applies with --http; over stdio a checkout already takes writes.");
254
- if (!values.http && (values.host !== undefined || values.port !== undefined))
255
- throw new UsageError("--host and --port only apply with --http.");
256
- const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
257
- if (!Number.isInteger(port) || port < 0 || port > 65535)
258
- throw new UsageError(`--port "${values.port}" is not a port.`);
259
- const source = values.bundle !== undefined
260
- ? bundleSource({ location: values.bundle })
261
- : checkoutSource({ root: await workspaceRoot(values.workspace === undefined ? process.cwd() : resolve(values.workspace)) });
262
- const options = { source, ...(viewerUrl === undefined ? {} : { viewerUrl }) };
263
- if (values.http) {
264
- const http = await serveHttp({ ...options, port, allowWrites: values["allow-writes"], ...(values.host === undefined ? {} : { host: values.host }) });
265
- process.stderr.write(`Archidocs MCP server on ${http.url} (writes ${values["allow-writes"] && source.writesAllowed ? "allowed" : "off"})\n`);
266
- return OK;
267
- }
268
- // stdout carries the protocol; the server runs until the client closes stdin.
269
- serveStdio(() => createServer(options));
270
- return OK;
271
- }
272
- throw new UsageError(command ? `Unknown command "${command}".` : "No command given.");
273
- }
274
- /** Colour only on a terminal; `NO_COLOR` turns it off and `FORCE_COLOR` on. */
275
- function useColor() {
276
- const { NO_COLOR, FORCE_COLOR } = process.env;
277
- if (NO_COLOR)
278
- return false;
279
- if (FORCE_COLOR !== undefined)
280
- return FORCE_COLOR !== "0";
281
- return process.stdout.isTTY === true;
282
- }
283
- /** How a picture's source line names the Workspace: its git repo's folder, else the Workspace root's. */
284
- async function workspaceName(root) {
285
- return basename((await gitTopLevel(root)) ?? root);
286
- }
287
- async function workspaceRoot(start) {
288
- const root = await findWorkspaceRoot(nodeFileSystem(), start);
289
- if (!root)
290
- throw new UsageError(NO_WORKSPACE);
291
- return root;
292
- }
293
- /** The history of the Workspace found from the current folder; it must be in a git repo. */
294
- async function historyFromCwd() {
295
- const root = await workspaceRoot(process.cwd());
296
- const repoRoot = await gitTopLevel(root);
297
- if (!repoRoot)
298
- throw new UsageError("History needs the Workspace in a git repository.");
299
- return history(repoRoot, await realpath(root));
300
- }
301
- /** The site's past Bundles and Revision index; outside git, an empty index, so the viewer knows there is no history. */
302
- async function writeSiteHistory(out, keep) {
303
- const root = await workspaceRoot(process.cwd());
304
- const repoRoot = await gitTopLevel(root);
305
- if (repoRoot)
306
- await publishHistory(history(repoRoot, await realpath(root)), out, { keep });
307
- else {
308
- await mkdir(join(out, "bundles"), { recursive: true });
309
- await writeFile(join(out, "bundles", "index.json"), JSON.stringify({ schemaVersion: SCHEMA_VERSION, revisions: [] }, null, 2) + "\n");
310
- }
311
- }
312
- async function loadFromCwd() {
313
- const root = await workspaceRoot(process.cwd());
314
- const { commit, builtAt } = await gitHead(root);
315
- return load({ fs: nodeFileSystem(), root, commit, builtAt });
316
- }
317
- main(process.argv.slice(2)).then((code) => {
318
- process.exitCode = code;
319
- }, (error) => {
320
- const message = error instanceof Error ? error.message : String(error);
321
- process.stderr.write(`archidocs: ${message}\n`);
322
- if (error instanceof UsageError || error.code?.startsWith("ERR_PARSE_ARGS"))
323
- process.stderr.write(usage);
324
- process.exitCode = COULD_NOT_RUN;
325
- });
2
+ import { run } from "./run.js";
3
+ process.exitCode = await run(process.argv.slice(2), { cwd: process.cwd(), env: process.env, stdout: process.stdout, stderr: process.stderr });
@@ -0,0 +1,18 @@
1
+ /** Where a run of the CLI writes and what it reads instead of `process`: its folder, environment and output streams. */
2
+ export interface Io {
3
+ cwd: string;
4
+ env: Record<string, string | undefined>;
5
+ stdout: {
6
+ write(chunk: string): unknown;
7
+ isTTY?: boolean;
8
+ };
9
+ stderr: {
10
+ write(chunk: string): unknown;
11
+ };
12
+ }
13
+ /**
14
+ * Runs one CLI command and returns its exit code. It never throws: an error is
15
+ * written to `io.stderr` as `archidocs: <message>`, with the usage text for a
16
+ * usage error, and returns the could-not-run code.
17
+ */
18
+ export declare function run(argv: string[], io: Io): Promise<number>;