@krizaka/architecture 0.3.1 → 0.4.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 CHANGED
@@ -53,6 +53,24 @@ npx krizaka-architecture layout ../my-repo --out views.json # a directory: i
53
53
 
54
54
  Exit 0 when laid out, 1 with the rule when the model is refused, 2 on a bad call.
55
55
 
56
+ ### In another language, and proving a committed layout is current
57
+
58
+ `translations: { fr: { path, text } }` lays the views out once and returns them in each language too
59
+ (`translations.fr = { path, sha256, views }`): the same geometry, every title, technology, description and edge label replaced
60
+ by its words from a JSON object. A string the views draw without its translation, or a translation no view draws, is refused
61
+ (rule `translations`), so the words follow the model.
62
+
63
+ A site that commits its layout proves it current with `staleSources(layout, { model, base, translations })`: the list of files
64
+ whose sha256 differs from the one the layout was made from, that it was not made from, or that it was made from and are not
65
+ passed (empty: current). No parser, no network: a check in CI needs only the files.
66
+
67
+ ```bash
68
+ npx krizaka-architecture layout agents.c4 --out lib/architecture.json --base specification.c4 --base org.c4 --system agents \
69
+ --translations fr=agents.fr.json
70
+ npx krizaka-architecture check lib/architecture.json --model agents.c4 --base specification.c4 --base org.c4 \
71
+ --translations fr=agents.fr.json # 0 current, 1 stale (names the file), 2 a bad call
72
+ ```
73
+
56
74
  ## The units and their versions (`unitsOf`)
57
75
 
58
76
  A unit is what a manifest declares, each with `path`, `manifest`, `ecosystem`, `language`, `name`, `version`, `published` (an org
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krizaka/architecture",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "The C4 view of a repository, generated from its code and manifests: containers from the workspaces (with their version and the org dependencies that build them, from the lockfile), Maven modules, crates and Python projects, components from the folders, the imports between them, the external services from the env declarations. Runs on a local checkout or a map of files, writes JSON and a text version.",
5
5
  "keywords": [
6
6
  "krizaka",
@@ -46,7 +46,7 @@
46
46
  "devDependencies": {
47
47
  "@types/node": "^22.10.0",
48
48
  "eslint": "^9.39.0",
49
- "@krizaka/config": "^0.26.2"
49
+ "@krizaka/config": "^0.29.0"
50
50
  },
51
51
  "engines": {
52
52
  "node": ">=22"
package/src/cli.mjs CHANGED
@@ -1,17 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  // krizaka-architecture <repo-path> [--out c4.json] [--level context|containers|components] [--text [file]]
3
3
  // krizaka-architecture layout <model.c4 | repo-path> [--out views.json] [--base f.c4]... [--system id] [--view id]...
4
+ // [--translations <locale>=file.json]...
5
+ // krizaka-architecture check <views.json> --model f.c4... [--base f.c4]... [--translations <locale>=file.json]...
4
6
  // Without --out the JSON goes to stdout. With --level the file holds that level only: { level, nodes, edges }.
5
7
  import { existsSync, writeFileSync } from "node:fs";
6
8
  import { resolve } from "node:path";
7
9
 
8
10
  import { buildC4, toText } from "./index.mjs";
9
- import { runLayout } from "./layout-cli.mjs";
11
+ import { runCheck, runLayout } from "./layout-cli.mjs";
10
12
 
11
13
  const args = process.argv.slice(2);
12
- if (args[0] === "layout") {
14
+ const SUBCOMMANDS = { layout: runLayout, check: runCheck };
15
+ if (Object.hasOwn(SUBCOMMANDS, args[0])) {
13
16
  // exitCode, not exit(): a large JSON on a pipe must be flushed first
14
- process.exitCode = await runLayout(args.slice(1));
17
+ process.exitCode = await SUBCOMMANDS[args[0]](args.slice(1));
15
18
  await new Promise((done) => process.stdout.write("", done));
16
19
  process.exit(process.exitCode);
17
20
  }
@@ -0,0 +1,50 @@
1
+ // Whether a committed layout was made from the files as they are now (krizaka-internal#4184). A layout carries the sha256 of
2
+ // every source it was made from — the model, the base, each translation — so a repository that commits its layout proves it
3
+ // is current without laying it out again: no parser, no network.
4
+ import { createHash } from "node:crypto";
5
+
6
+ import { LAYOUT_SCHEMA } from "./layout.mjs";
7
+
8
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
9
+ const stale = (path, message) => ({ path, message });
10
+
11
+ /** The problems of one group of hashed sources against the files given now (both ways: changed, absent, not passed). */
12
+ function groupProblems(recorded, files) {
13
+ const out = [];
14
+ for (const f of files) {
15
+ const was = recorded.find((r) => r.path === f.path);
16
+ if (!was) out.push(stale(f.path, `the layout was not made from ${f.path}`));
17
+ else if (was.sha256 !== sha256(f.text))
18
+ out.push(stale(f.path, `the layout was made from another ${f.path}: lay it out again`));
19
+ }
20
+ for (const r of recorded)
21
+ if (!files.some((f) => f.path === r.path))
22
+ out.push(stale(r.path, `the layout was made from ${r.path} too: pass it`));
23
+ return out;
24
+ }
25
+
26
+ function translationProblems(recorded, translations) {
27
+ const out = [];
28
+ for (const [locale, file] of Object.entries(translations)) {
29
+ const was = recorded[locale];
30
+ if (!was) out.push(stale(file.path, `the layout has no ${locale} translation`));
31
+ else if (was.path !== file.path || was.sha256 !== sha256(file.text))
32
+ out.push(stale(file.path, `the layout was made from another ${file.path}: lay it out again`));
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /**
38
+ * What makes a committed layout stale, given the files now: `{ model, base?, translations? }` (`base` and `translations` are
39
+ * compared only when passed). An empty list means the layout was made from exactly these files.
40
+ * @returns {{ path: string, message: string }[]}
41
+ */
42
+ export function staleSources(layout, { model, base, translations }) {
43
+ if (layout?.schema !== LAYOUT_SCHEMA || !layout.sources)
44
+ return [stale("", `the file is not a ${LAYOUT_SCHEMA} layout`)];
45
+ return [
46
+ ...groupProblems(layout.sources.model, model),
47
+ ...(base ? groupProblems(layout.sources.base, base) : []),
48
+ ...(translations ? translationProblems(layout.translations ?? {}, translations) : []),
49
+ ];
50
+ }
package/src/index.d.ts CHANGED
@@ -144,7 +144,7 @@ export interface HashedFile {
144
144
  sha256: string;
145
145
  }
146
146
 
147
- export type ModelRule = "model" | "no-specification" | "home" | "views";
147
+ export type ModelRule = "model" | "no-specification" | "home" | "views" | "translations";
148
148
 
149
149
  export interface ModelProblem {
150
150
  rule: ModelRule;
@@ -160,6 +160,17 @@ export interface LayoutOptions {
160
160
  system?: string;
161
161
  /** The view ids to return, in this order; each must exist. Default: every view LikeC4 does not add by itself (not the implicit `index`), the containers view for a C4. */
162
162
  views?: string[];
163
+ /**
164
+ * Each language's words, by locale (`{ fr: { path, text } }`): a JSON object from every string the returned views draw (titles,
165
+ * technologies, descriptions, edge labels) to its translation. A string without one, or a translation no view draws, is
166
+ * refused (rule `translations`). The layout then holds `translations`.
167
+ */
168
+ translations?: Record<string, ModelFile>;
169
+ }
170
+
171
+ /** The views in one language: the layout's geometry, every string translated, and the hash of the file it came from. */
172
+ export interface TranslatedViews extends HashedFile {
173
+ views: ArchView[];
163
174
  }
164
175
 
165
176
  export interface Layout {
@@ -170,10 +181,12 @@ export interface Layout {
170
181
  /** The check's verdict: `ok` (a refused model throws), the system it was checked against, the elements the model adds. */
171
182
  check: { status: "ok"; system: string | null; errors: []; elements: string[] };
172
183
  views: ArchView[];
184
+ /** Present when `translations` were passed: each language's views, keyed by locale. */
185
+ translations?: Record<string, TranslatedViews>;
173
186
  }
174
187
 
175
188
  export const LAYOUT_SCHEMA: "krizaka.layout/1";
176
- export const RULES: Readonly<Record<"model" | "specification" | "home" | "views", ModelRule>>;
189
+ export const RULES: Readonly<Record<"model" | "specification" | "home" | "views" | "translations", ModelRule>>;
177
190
 
178
191
  /** A model the check refuses. `rule` is the first rule that failed; `problems` lists every one. */
179
192
  export class ArchitectureModelError extends Error {
@@ -190,3 +203,19 @@ export class ArchitectureModelError extends Error {
190
203
  export function layoutViews(model: string | ModelFile[] | C4, options?: LayoutOptions): Promise<Layout>;
191
204
  /** The LikeC4 files of a C4's containers level (a specification, the containers, their relations, a `containers` view). */
192
205
  export function modelOfC4(c4: C4): ModelFile[];
206
+
207
+ /** One reason a committed layout is not made from the files given now. */
208
+ export interface StaleSource {
209
+ path: string;
210
+ message: string;
211
+ }
212
+
213
+ /**
214
+ * What makes a committed layout stale: a model, base or translation file whose sha256 differs from the one it was made from, one
215
+ * it was not made from, or one it was made from that is not passed. `base` and `translations` are compared only when passed.
216
+ * An empty list: the layout was made from exactly these files. Reads no parser and no network.
217
+ */
218
+ export function staleSources(
219
+ layout: unknown,
220
+ sources: { model: ModelFile[]; base?: ModelFile[]; translations?: Record<string, ModelFile> },
221
+ ): StaleSource[];
package/src/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  export { buildC4, buildC4FromFiles, SCHEMA } from "./c4.mjs";
2
+ export { staleSources } from "./freshness.mjs";
2
3
  export { ArchitectureModelError, LAYOUT_SCHEMA, layoutViews, RULES } from "./layout.mjs";
3
4
  export { modelOfC4 } from "./model.mjs";
4
5
  export { toText } from "./text.mjs";
@@ -1,13 +1,24 @@
1
1
  // krizaka-architecture layout <model.c4 | repo-path> [--out views.json] [--base file.c4]... [--system id] [--view id]...
2
- // A .c4 file is checked and laid out; a directory is read with buildC4 and its containers view is laid out.
2
+ // [--translations <locale>=file.json]...
3
+ // krizaka-architecture check <views.json> --model file.c4... [--base file.c4]... [--translations <locale>=file.json]...
4
+ // A .c4 file is checked and laid out; a directory is read with buildC4 and its containers view is laid out. `check` proves a
5
+ // committed layout was made from these files as they are now.
3
6
  import { readFileSync, statSync, writeFileSync } from "node:fs";
4
7
  import { basename, resolve } from "node:path";
5
8
 
6
9
  import { buildC4 } from "./c4.mjs";
10
+ import { staleSources } from "./freshness.mjs";
7
11
  import { ArchitectureModelError, layoutViews } from "./layout.mjs";
8
12
 
9
- const USAGE =
10
- "usage: krizaka-architecture layout <model.c4 | repo-path> [--out views.json] [--base file.c4]... [--system id] [--view id]...";
13
+ const USAGE = [
14
+ "usage: krizaka-architecture layout <model.c4 | repo-path> [--out views.json] [--base file.c4]... [--system id] [--view id]...",
15
+ " [--translations <locale>=file.json]...",
16
+ " krizaka-architecture check <views.json> --model file.c4... [--base file.c4]... [--translations <locale>=file.json]...",
17
+ ].join("\n");
18
+ const FLAGS = ["out", "base", "system", "view", "translations", "model"];
19
+
20
+ /** A bad call: the usage on stderr, exit 2. */
21
+ class UsageError extends Error {}
11
22
 
12
23
  /** Every value of a repeatable flag (`--base a --base b`), a single one for the others. */
13
24
  function valuesOf(args, name) {
@@ -18,40 +29,115 @@ function valuesOf(args, name) {
18
29
  return out;
19
30
  }
20
31
 
21
- /** Runs the subcommand; returns the exit code. */
22
- export async function runLayout(args, { stdout = process.stdout, stderr = process.stderr } = {}) {
23
- const flagValues = new Set(["out", "base", "system", "view"].flatMap((n) => valuesOf(args, n)));
32
+ /** The first argument that is neither a flag nor a flag's value. */
33
+ function inputOf(args) {
34
+ const flagValues = new Set(FLAGS.flatMap((n) => valuesOf(args, n)));
24
35
  const input = args.find((a) => !a.startsWith("--") && !flagValues.has(a));
25
- if (!input) {
26
- stderr.write(`${USAGE}\n`);
27
- return 2;
36
+ if (!input) throw new UsageError();
37
+ return input;
38
+ }
39
+
40
+ /** A file as the API takes it: its name (what the layout records and `check` compares) and its text. */
41
+ function fileOf(path) {
42
+ try {
43
+ return { path: basename(path), text: readFileSync(resolve(path), "utf8") };
44
+ } catch {
45
+ throw new UsageError();
28
46
  }
47
+ }
48
+
49
+ const filesOf = (args, name) => valuesOf(args, name).map(fileOf);
50
+
51
+ /** `--translations fr=words.fr.json` → `{ fr: { path, text } }`; null when none is passed. */
52
+ function translationsOf(args) {
53
+ const pairs = valuesOf(args, "translations");
54
+ if (!pairs.length) return null;
55
+ return Object.fromEntries(
56
+ pairs.map((pair) => {
57
+ const [, locale, path] = pair.match(/^([a-z]{2}(?:-[A-Z]{2})?)=(.+)$/) ?? [];
58
+ if (!locale) throw new UsageError();
59
+ return [locale, fileOf(path)];
60
+ }),
61
+ );
62
+ }
63
+
64
+ function modelOf(input) {
29
65
  const path = resolve(input);
30
- let model;
31
66
  try {
32
- model = statSync(path).isDirectory() ? buildC4(path) : [{ path: basename(path), text: readFileSync(path, "utf8") }];
67
+ return statSync(path).isDirectory() ? buildC4(path) : [fileOf(path)];
33
68
  } catch {
34
- stderr.write(`${USAGE}\n`);
35
- return 2;
69
+ throw new UsageError();
36
70
  }
37
- const base = valuesOf(args, "base").map((f) => ({ path: basename(f), text: readFileSync(resolve(f), "utf8") }));
71
+ }
72
+
73
+ async function layout(args, stdout) {
38
74
  const views = valuesOf(args, "view");
39
- try {
40
- const layout = await layoutViews(model, {
41
- base,
42
- system: valuesOf(args, "system")[0],
43
- views: views.length ? views : undefined,
44
- });
45
- const json = `${JSON.stringify(layout, null, 2)}\n`;
46
- const [out] = valuesOf(args, "out");
47
- if (out) {
48
- writeFileSync(resolve(out), json);
49
- stdout.write(`${layout.views.length} view(s), check ${layout.check.status} -> ${out}\n`);
50
- } else stdout.write(json);
75
+ const result = await layoutViews(modelOf(inputOf(args)), {
76
+ base: filesOf(args, "base"),
77
+ system: valuesOf(args, "system")[0],
78
+ views: views.length ? views : undefined,
79
+ translations: translationsOf(args) ?? undefined,
80
+ });
81
+ const json = `${JSON.stringify(result, null, 2)}\n`;
82
+ const [out] = valuesOf(args, "out");
83
+ if (!out) {
84
+ stdout.write(json);
51
85
  return 0;
86
+ }
87
+ writeFileSync(resolve(out), json);
88
+ const languages = Object.keys(result.translations ?? {});
89
+ const said = languages.length ? `, translated to ${languages.join(", ")}` : "";
90
+ stdout.write(`${result.views.length} view(s), check ${result.check.status}${said} -> ${out}\n`);
91
+ return 0;
92
+ }
93
+
94
+ /** The value of a JSON text; null when it is not JSON (`check` then says the file is not a layout). */
95
+ function jsonOrNull(text) {
96
+ try {
97
+ return JSON.parse(text);
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ function check(args, stdout, stderr) {
104
+ const input = inputOf(args);
105
+ const model = filesOf(args, "model");
106
+ if (!model.length) throw new UsageError();
107
+ const data = jsonOrNull(fileOf(input).text);
108
+ const base = filesOf(args, "base");
109
+ const problems = staleSources(data, {
110
+ model,
111
+ base: base.length ? base : undefined,
112
+ translations: translationsOf(args) ?? undefined,
113
+ });
114
+ if (problems.length) {
115
+ const lines = problems.map((p) => input + ": " + p.message);
116
+ stderr.write(lines.join("\n") + "\n");
117
+ return 1;
118
+ }
119
+ stdout.write(`${input} matches ${[...model, ...base].map((f) => f.path).join(", ")} and its translations\n`);
120
+ return 0;
121
+ }
122
+
123
+ async function guarded(run, stderr) {
124
+ try {
125
+ return await run();
52
126
  } catch (error) {
127
+ if (error instanceof UsageError) {
128
+ stderr.write(`${USAGE}\n`);
129
+ return 2;
130
+ }
53
131
  if (!(error instanceof ArchitectureModelError)) throw error;
54
132
  stderr.write(`${error.message}\n`);
55
133
  return 1;
56
134
  }
57
135
  }
136
+
137
+ /** Runs `layout`; returns the exit code (0 laid out, 1 refused, 2 a bad call). */
138
+ export const runLayout = (args, { stdout = process.stdout, stderr = process.stderr } = {}) =>
139
+ guarded(() => layout(args, stdout), stderr);
140
+
141
+ /** Runs `check`; returns the exit code (0 current, 1 stale, 2 a bad call). */
142
+ export const runCheck = (args, { stdout = process.stdout, stderr = process.stderr } = {}) =>
143
+ guarded(() => check(args, stdout, stderr), stderr);
package/src/layout.mjs CHANGED
@@ -6,6 +6,7 @@ import { createHash } from "node:crypto";
6
6
  import { fromSources } from "@likec4/language-services/node";
7
7
 
8
8
  import { CONTAINERS_VIEW, isC4, modelOfC4 } from "./model.mjs";
9
+ import { translateViews } from "./translations.mjs";
9
10
 
10
11
  export const LAYOUT_SCHEMA = "krizaka.layout/1";
11
12
 
@@ -15,6 +16,7 @@ export const RULES = Object.freeze({
15
16
  specification: "no-specification",
16
17
  home: "home",
17
18
  views: "views",
19
+ translations: "translations",
18
20
  });
19
21
 
20
22
  const describe = (p) => " " + p.path + ":" + p.line + " [" + p.rule + "] " + p.message;
@@ -111,7 +113,9 @@ function sourcesOf(model) {
111
113
  * @param model a LikeC4 text, `[{ path, text }]`, or the C4 `buildC4` returns (its containers view is drawn)
112
114
  * @param options `base`: the org's files the model is written against (`specification.c4`, `org.c4`), a model then writes
113
115
  * no specification of its own; `system`: the id of the system a model may only extend (every element it adds lives inside);
114
- * `views`: the view ids to return, in this order (each must exist), default all but LikeC4's implicit `index`
116
+ * `views`: the view ids to return, in this order (each must exist), default all but LikeC4's implicit `index`;
117
+ * `translations`: `{ <locale>: { path, text } }`, each a JSON object from every string the returned views draw to its words
118
+ * in that language (none missing, none unused); the result then holds `translations: { <locale>: { path, sha256, views } }`
115
119
  * @throws {ArchitectureModelError} when a rule fails; `rule` and `problems` say which
116
120
  */
117
121
  export async function layoutViews(model, options = {}) {
@@ -169,6 +173,8 @@ export async function layoutViews(model, options = {}) {
169
173
  if (!problems.length && absent.length)
170
174
  problems.push(problemOf(RULES.views, files[0]?.path ?? "", 1, `the model has no view ${absent.join(", ")}`));
171
175
  if (problems.length) throw new ArchitectureModelError(problems);
176
+ const returned = wanted ? wanted.map((id) => laid.find((v) => v.id === id)) : laid;
177
+ const translations = options.translations ? translated(returned, options.translations) : null;
172
178
 
173
179
  const likec4Version = (await import("@likec4/language-services/package.json", { with: { type: "json" } })).default
174
180
  .version;
@@ -180,10 +186,25 @@ export async function layoutViews(model, options = {}) {
180
186
  base: base.map(({ path, sha256: hash }) => ({ path, sha256: hash })),
181
187
  },
182
188
  check: { status: "ok", system, errors: [], elements },
183
- views: wanted ? wanted.map((id) => laid.find((v) => v.id === id)) : laid,
189
+ views: returned,
190
+ ...(translations ? { translations } : {}),
184
191
  };
185
192
  }
186
193
 
194
+ /** Every language's views, with the hash of its file; throws with every string a translation lacks or has too many. */
195
+ function translated(views, files) {
196
+ const problem = (path, message) => problemOf(RULES.translations, path, 1, message);
197
+ const out = {};
198
+ const problems = [];
199
+ for (const [locale, file] of Object.entries(files)) {
200
+ const result = translateViews(views, file, problem);
201
+ problems.push(...result.problems);
202
+ out[locale] = { path: file.path, sha256: sha256(file.text), views: result.views };
203
+ }
204
+ if (problems.length) throw new ArchitectureModelError(problems);
205
+ return out;
206
+ }
207
+
187
208
  async function elementIds(base) {
188
209
  return withModel(
189
210
  virtualFiles(base, BASE_ROOT),
@@ -0,0 +1,60 @@
1
+ // The laid-out views in another language (krizaka-internal#4184). A translation is a JSON object from every string the views
2
+ // draw (titles, technologies, descriptions, edge labels) to its words in that language; the geometry is the layout's own, so a
3
+ // drawing is the same in every language. A string without its translation, or a translation no view draws, is refused: the
4
+ // words stay in step with the model.
5
+
6
+ /** Every string a list of views draws or says, once each, in the order the views meet them. */
7
+ export function stringsOf(views) {
8
+ const out = new Set();
9
+ for (const v of views) {
10
+ out.add(v.title);
11
+ for (const n of v.nodes) for (const s of [n.title, n.technology, n.description]) if (s !== null) out.add(s);
12
+ for (const e of v.edges) if (e.label !== null) out.add(e.label);
13
+ }
14
+ return [...out];
15
+ }
16
+
17
+ const isWords = (value) =>
18
+ value !== null &&
19
+ typeof value === "object" &&
20
+ !Array.isArray(value) &&
21
+ Object.values(value).every((s) => typeof s === "string");
22
+
23
+ function parseWords(text) {
24
+ try {
25
+ const value = JSON.parse(text);
26
+ return isWords(value) ? value : null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ const viewIn = (view, say) => ({
33
+ ...view,
34
+ title: say(view.title),
35
+ nodes: view.nodes.map((n) => ({
36
+ ...n,
37
+ title: say(n.title),
38
+ technology: say(n.technology),
39
+ description: say(n.description),
40
+ })),
41
+ edges: view.edges.map((e) => ({ ...e, label: say(e.label) })),
42
+ });
43
+
44
+ /**
45
+ * The views in one language. `file` is `{ path, text }` (a JSON object of strings); `problem(path, message)` builds one refusal.
46
+ * Returns `{ views, problems }`: the problems name every missing and every unused string, or the file that is not an object.
47
+ */
48
+ export function translateViews(views, file, problem) {
49
+ const words = parseWords(file.text);
50
+ if (words === null) return { views: [], problems: [problem(file.path, "a translation is an object of strings")] };
51
+ const drawn = stringsOf(views);
52
+ const missing = drawn.filter((s) => !Object.hasOwn(words, s));
53
+ const unused = Object.keys(words).filter((s) => !drawn.includes(s));
54
+ const problems = [
55
+ ...missing.map((s) => problem(file.path, `« ${s} » has no translation`)),
56
+ ...unused.map((s) => problem(file.path, `« ${s} » is translated but no view draws it`)),
57
+ ];
58
+ const say = (s) => (s === null ? null : words[s]);
59
+ return { views: problems.length ? [] : views.map((v) => viewIn(v, say)), problems };
60
+ }