archidocs 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -2
  3. package/dist/cli/commands.d.ts +322 -0
  4. package/dist/cli/commands.js +174 -0
  5. package/dist/cli/dev.d.ts +31 -0
  6. package/dist/cli/dev.js +156 -0
  7. package/dist/cli/diff-format.d.ts +9 -0
  8. package/dist/cli/diff-format.js +50 -0
  9. package/dist/cli/format.d.ts +15 -0
  10. package/dist/cli/format.js +64 -0
  11. package/dist/cli/init.d.ts +17 -0
  12. package/dist/cli/init.js +82 -0
  13. package/dist/cli/main.d.ts +2 -0
  14. package/dist/cli/main.js +330 -0
  15. package/dist/core/adr.d.ts +28 -0
  16. package/dist/core/adr.js +88 -0
  17. package/dist/core/adrs.d.ts +20 -0
  18. package/dist/core/adrs.js +86 -0
  19. package/dist/core/catalogue.d.ts +7 -0
  20. package/dist/core/catalogue.js +35 -0
  21. package/dist/core/compare.d.ts +21 -0
  22. package/dist/core/compare.js +62 -0
  23. package/dist/core/deployment-views.d.ts +28 -0
  24. package/dist/core/deployment-views.js +108 -0
  25. package/dist/core/deployments.d.ts +18 -0
  26. package/dist/core/deployments.js +21 -0
  27. package/dist/core/diff.d.ts +44 -0
  28. package/dist/core/diff.js +138 -0
  29. package/dist/core/dynamic-views.d.ts +73 -0
  30. package/dist/core/dynamic-views.js +162 -0
  31. package/dist/core/files.d.ts +2 -0
  32. package/dist/core/files.js +1 -0
  33. package/dist/core/fs.d.ts +19 -0
  34. package/dist/core/fs.js +21 -0
  35. package/dist/core/history-scope.d.ts +40 -0
  36. package/dist/core/history-scope.js +63 -0
  37. package/dist/core/impact.d.ts +34 -0
  38. package/dist/core/impact.js +62 -0
  39. package/dist/core/index.d.ts +20 -0
  40. package/dist/core/index.js +18 -0
  41. package/dist/core/load.d.ts +32 -0
  42. package/dist/core/load.js +465 -0
  43. package/dist/core/model.d.ts +150 -0
  44. package/dist/core/model.js +1 -0
  45. package/dist/core/ownership.d.ts +34 -0
  46. package/dist/core/ownership.js +65 -0
  47. package/dist/core/paths.d.ts +47 -0
  48. package/dist/core/paths.js +115 -0
  49. package/dist/core/query.d.ts +51 -0
  50. package/dist/core/query.js +77 -0
  51. package/dist/core/refs.d.ts +31 -0
  52. package/dist/core/refs.js +50 -0
  53. package/dist/core/rules.d.ts +41 -0
  54. package/dist/core/rules.js +1033 -0
  55. package/dist/core/save-as-view.d.ts +45 -0
  56. package/dist/core/save-as-view.js +114 -0
  57. package/dist/core/saved-views.d.ts +48 -0
  58. package/dist/core/saved-views.js +243 -0
  59. package/dist/core/schema-check.d.ts +13 -0
  60. package/dist/core/schema-check.js +79 -0
  61. package/dist/core/search.d.ts +27 -0
  62. package/dist/core/search.js +63 -0
  63. package/dist/core/suggest.d.ts +3 -0
  64. package/dist/core/suggest.js +30 -0
  65. package/dist/core/views.d.ts +126 -0
  66. package/dist/core/views.js +217 -0
  67. package/dist/core/yaml.d.ts +16 -0
  68. package/dist/core/yaml.js +52 -0
  69. package/dist/git.d.ts +7 -0
  70. package/dist/git.js +23 -0
  71. package/dist/guide/index.d.ts +53 -0
  72. package/dist/guide/index.js +57 -0
  73. package/dist/history/git.d.ts +39 -0
  74. package/dist/history/git.js +126 -0
  75. package/dist/history/index.d.ts +118 -0
  76. package/dist/history/index.js +223 -0
  77. package/dist/history/migrate.d.ts +16 -0
  78. package/dist/history/migrate.js +30 -0
  79. package/dist/mcp/history.d.ts +36 -0
  80. package/dist/mcp/history.js +175 -0
  81. package/dist/mcp/http.d.ts +23 -0
  82. package/dist/mcp/http.js +85 -0
  83. package/dist/mcp/index.d.ts +3 -0
  84. package/dist/mcp/index.js +3 -0
  85. package/dist/mcp/server.d.ts +54 -0
  86. package/dist/mcp/server.js +824 -0
  87. package/dist/mcp/source.d.ts +50 -0
  88. package/dist/mcp/source.js +132 -0
  89. package/dist/mcp/writes.d.ts +10 -0
  90. package/dist/mcp/writes.js +267 -0
  91. package/dist/render/font.d.ts +14 -0
  92. package/dist/render/font.js +11 -0
  93. package/dist/render/index.d.ts +8 -0
  94. package/dist/render/index.js +8 -0
  95. package/dist/render/layout.d.ts +53 -0
  96. package/dist/render/layout.js +199 -0
  97. package/dist/render/node.d.ts +3 -0
  98. package/dist/render/node.js +8 -0
  99. package/dist/render/png.d.ts +11 -0
  100. package/dist/render/png.js +29 -0
  101. package/dist/render/sequence-svg.d.ts +33 -0
  102. package/dist/render/sequence-svg.js +98 -0
  103. package/dist/render/sequence.d.ts +103 -0
  104. package/dist/render/sequence.js +142 -0
  105. package/dist/render/svg.d.ts +36 -0
  106. package/dist/render/svg.js +222 -0
  107. package/dist/render/teams.d.ts +12 -0
  108. package/dist/render/teams.js +31 -0
  109. package/dist/render/text.d.ts +15 -0
  110. package/dist/render/text.js +29 -0
  111. package/dist/render/tokens.d.ts +53 -0
  112. package/dist/render/tokens.js +71 -0
  113. package/dist/schema/adr.d.ts +36 -0
  114. package/dist/schema/adr.js +27 -0
  115. package/dist/schema/bundle.d.ts +726 -0
  116. package/dist/schema/bundle.js +171 -0
  117. package/dist/schema/index.d.ts +4 -0
  118. package/dist/schema/index.js +4 -0
  119. package/dist/schema/json-schema.d.ts +8 -0
  120. package/dist/schema/json-schema.js +19 -0
  121. package/dist/schema/workspace.d.ts +1066 -0
  122. package/dist/schema/workspace.js +271 -0
  123. package/dist/viewer/assets/index-DvKgCpBr.css +1 -0
  124. package/dist/viewer/assets/index-gucix3xm.js +113 -0
  125. package/dist/viewer/assets/index_bg-Blvrv-U2.wasm +0 -0
  126. package/dist/viewer/assets/index_bg-D3t31u3-.js +1 -0
  127. package/dist/viewer/assets/layout.worker-Bg-OaLVN.js +26 -0
  128. package/dist/viewer/assets/overpass-latin-QyaMbcmi.woff2 +0 -0
  129. package/dist/viewer/assets/overpass-latin-ext-DSRhPfzW.woff2 +0 -0
  130. package/dist/viewer/assets/overpass-mono-latin-BTquVRaO.woff2 +0 -0
  131. package/dist/viewer/assets/overpass-mono-latin-ext-D47EiU4_.woff2 +0 -0
  132. package/dist/viewer/assets/png-BDKIXtm5.js +1 -0
  133. package/dist/viewer/assets/svg-Bulv5YWn.js +2 -0
  134. package/dist/viewer/favicon.svg +1 -0
  135. package/dist/viewer/index.html +53 -0
  136. package/dist/writer/adrs.d.ts +21 -0
  137. package/dist/writer/adrs.js +72 -0
  138. package/dist/writer/deployments.d.ts +51 -0
  139. package/dist/writer/deployments.js +145 -0
  140. package/dist/writer/diff.d.ts +6 -0
  141. package/dist/writer/diff.js +77 -0
  142. package/dist/writer/document.d.ts +25 -0
  143. package/dist/writer/document.js +79 -0
  144. package/dist/writer/edit.d.ts +78 -0
  145. package/dist/writer/edit.js +63 -0
  146. package/dist/writer/index.d.ts +67 -0
  147. package/dist/writer/index.js +310 -0
  148. package/dist/writer/overlay.d.ts +7 -0
  149. package/dist/writer/overlay.js +26 -0
  150. package/dist/writer/views.d.ts +29 -0
  151. package/dist/writer/views.js +78 -0
  152. package/dist/writer/workspace.d.ts +25 -0
  153. package/dist/writer/workspace.js +56 -0
  154. package/guide/SKILL.md +36 -0
  155. package/guide/topics/add-service.md +30 -0
  156. package/guide/topics/bootstrap.md +28 -0
  157. package/guide/topics/change.md +32 -0
  158. package/guide/topics/deployments.md +36 -0
  159. package/guide/topics/dynamic-view.md +39 -0
  160. package/guide/topics/propose-adr.md +12 -0
  161. package/guide/topics/relationships.md +39 -0
  162. package/guide/topics/saved-view.md +36 -0
  163. package/package.json +75 -4
  164. package/schemas/adr.schema.json +82 -0
  165. package/schemas/model.schema.json +1381 -0
  166. package/schemas/project.schema.json +24 -0
  167. package/schemas/workspace.schema.json +72 -0
@@ -0,0 +1,62 @@
1
+ import { diff } from "./diff.js";
2
+ import { ModelIndex, resolveView } from "./views.js";
3
+ const withoutSource = (item) => JSON.stringify({ ...item, source: undefined });
4
+ /** Items of both sides, each once: the later side's where both have it. */
5
+ function union(before, after, key) {
6
+ const keys = new Set(after.map(key));
7
+ return [...after, ...before.filter((item) => !keys.has(key(item)))];
8
+ }
9
+ const byId = (item) => item.id;
10
+ const deploymentKey = (d) => `${d.service}\0${d.environment}\0${d.target}`;
11
+ /**
12
+ * One Bundle holding everything either side holds, the later side's version
13
+ * where both do, so a View drawn from it keeps removed things in place.
14
+ * Relationships are matched by their whole content, so a changed one shows
15
+ * at both sides; each lands on the same edge.
16
+ */
17
+ export function unionBundle(before, after) {
18
+ return {
19
+ ...after,
20
+ teams: union(before.teams, after.teams, byId),
21
+ environments: union(before.environments, after.environments, byId),
22
+ projects: union(before.projects, after.projects, byId),
23
+ elements: union(before.elements, after.elements, byId),
24
+ relationships: union(before.relationships, after.relationships, withoutSource),
25
+ targets: union(before.targets, after.targets, byId),
26
+ deployments: union(before.deployments, after.deployments, deploymentKey),
27
+ views: union(before.views, after.views, byId),
28
+ adrs: union(before.adrs, after.adrs, byId),
29
+ };
30
+ }
31
+ /**
32
+ * A View for Compare: laid out over the union of both sides, with every node
33
+ * and edge marked. A node or edge only the later side's View shows is
34
+ * added, one only the earlier side's shows is removed. One both show is
35
+ * changed when its Element changed, or for a collapsed box when anything
36
+ * inside it was added, removed or changed; an edge when its Relationships
37
+ * did. A View that exists at one side only is drawn from that side.
38
+ * Undefined when neither side has the View.
39
+ */
40
+ export function compareView(before, after, id, options = {}) {
41
+ const view = resolveView(unionBundle(before, after), id, options);
42
+ if (!view)
43
+ return undefined;
44
+ const [b, a] = [resolveView(before, id, options), resolveView(after, id, options)];
45
+ const changed = new Set(diff(before, after).filter((c) => c.kind === "element").map((c) => c.id));
46
+ const model = new ModelIndex(unionBundle(before, after));
47
+ const holdsChange = (nodeId) => [...changed].some((c) => c !== nodeId && model.ancestry(c).includes(nodeId));
48
+ const sides = (list, key) => [b, a].map((v) => new Map((v ? list(v) : []).map((x) => [key(x), x])));
49
+ const [bNodes, aNodes] = sides((v) => v.nodes, (n) => n.id);
50
+ const edgeKey = (e) => `${e.from}\0${e.to}`;
51
+ const [bEdges, aEdges] = sides((v) => v.edges, edgeKey);
52
+ const mark = (inBefore, inAfter, isChanged) => inAfter && !inBefore ? "added" : inBefore && !inAfter ? "removed" : isChanged() ? "changed" : "unchanged";
53
+ for (const node of view.nodes) {
54
+ node.change = mark(bNodes.has(node.id), aNodes.has(node.id), () => changed.has(node.id) || (node.collapsed && holdsChange(node.id)));
55
+ }
56
+ const relationships = (e) => (e?.relationships.map(withoutSource).sort() ?? []).join("\n");
57
+ for (const edge of view.edges) {
58
+ const key = edgeKey(edge);
59
+ edge.change = mark(bEdges.has(key), aEdges.has(key), () => relationships(bEdges.get(key)) !== relationships(aEdges.get(key)));
60
+ }
61
+ return view;
62
+ }
@@ -0,0 +1,28 @@
1
+ import type { Bundle, BundleDeployment } from "../schema/bundle.ts";
2
+ import { type ResolvedView } from "./views.ts";
3
+ /** Which Deployments a Deployment View draws, and which Services it leaves out altogether. */
4
+ export interface DeploymentScope {
5
+ /** A Deployment of the Environment is drawn when this accepts it; one that isn't counts as absent from the View. */
6
+ deployed?: (d: BundleDeployment) => boolean;
7
+ /** A Service this rejects is left out, with its Relationships. */
8
+ keep?: (service: string) => boolean;
9
+ }
10
+ /** A Deployment's node id: its Service and Target, as `<service>@<target>`. */
11
+ export declare const deploymentNodeId: (d: Pick<BundleDeployment, "service" | "target">) => string;
12
+ /**
13
+ * Resolves the Deployment View of one Environment:
14
+ * - every Target holding a drawn Deployment is a container, nested in its parent Targets;
15
+ * - inside each Target, a System's Deployments sit in a box for that System
16
+ * (`<system>@<target>`, drawing only); a Deployment of a Service outside any
17
+ * System sits in the Target itself;
18
+ * - Relationships are lifted to Service level. A consumer Deployment connects to
19
+ * the provider's Deployments under their deepest shared Target, or to all of
20
+ * them when no Target is shared;
21
+ * - a related Service with no drawn Deployment (such as an External provider) is a
22
+ * logical node outside every Target. Persons are not drawn.
23
+ * Nodes are sorted by id, edges by `from`, then `to`.
24
+ */
25
+ export declare function resolveDeployment(bundle: Bundle, head: {
26
+ id: string;
27
+ title: string;
28
+ }, environment: string, scope?: DeploymentScope): ResolvedView;
@@ -0,0 +1,108 @@
1
+ import { lifter } from "./query.js";
2
+ import { ModelIndex } from "./views.js";
3
+ /** A Deployment's node id: its Service and Target, as `<service>@<target>`. */
4
+ export const deploymentNodeId = (d) => `${d.service}@${d.target}`;
5
+ /**
6
+ * Resolves the Deployment View of one Environment:
7
+ * - every Target holding a drawn Deployment is a container, nested in its parent Targets;
8
+ * - inside each Target, a System's Deployments sit in a box for that System
9
+ * (`<system>@<target>`, drawing only); a Deployment of a Service outside any
10
+ * System sits in the Target itself;
11
+ * - Relationships are lifted to Service level. A consumer Deployment connects to
12
+ * the provider's Deployments under their deepest shared Target, or to all of
13
+ * them when no Target is shared;
14
+ * - a related Service with no drawn Deployment (such as an External provider) is a
15
+ * logical node outside every Target. Persons are not drawn.
16
+ * Nodes are sorted by id, edges by `from`, then `to`.
17
+ */
18
+ export function resolveDeployment(bundle, head, environment, scope = {}) {
19
+ const model = new ModelIndex(bundle);
20
+ const targets = new Map(bundle.targets.map((t) => [t.id, t]));
21
+ const keep = scope.keep ?? (() => true);
22
+ const deployed = scope.deployed ?? (() => true);
23
+ const drawn = bundle.deployments.filter((d) => d.environment === environment && model.byId.get(d.service)?.kind === "service" && targets.has(d.target) && keep(d.service) && deployed(d));
24
+ const nodes = new Map();
25
+ const plain = { collapsed: false, external: false };
26
+ const byService = new Map();
27
+ for (const d of drawn) {
28
+ const chain = chainOf(targets, d.target);
29
+ chain.forEach((t, i) => {
30
+ if (!nodes.has(t))
31
+ nodes.set(t, { id: t, kind: "target", name: targets.get(t).name, parent: chain[i - 1] ?? null, ...plain });
32
+ });
33
+ const system = model.ancestry(d.service).find((a) => model.byId.get(a)?.kind === "system");
34
+ let parent = d.target;
35
+ if (system !== undefined) {
36
+ parent = `${system}@${d.target}`;
37
+ const s = model.byId.get(system);
38
+ nodes.set(parent, { id: parent, kind: "system", name: s.name, parent: d.target, element: system, collapsed: false, external: "external" in s && s.external });
39
+ }
40
+ const service = model.byId.get(d.service);
41
+ nodes.set(deploymentNodeId(d), { id: deploymentNodeId(d), kind: "deployment", name: service.name, parent, element: d.service, collapsed: false, external: "external" in service && service.external });
42
+ byService.set(d.service, [...(byService.get(d.service) ?? []), { d, chain }]);
43
+ }
44
+ const lift = lifter(bundle, "service");
45
+ const edges = new Map();
46
+ const connect = (from, to, r) => {
47
+ const key = `${from}\0${to}`;
48
+ const edge = edges.get(key) ?? { from, to, relationships: [] };
49
+ edge.relationships.push(r);
50
+ edges.set(key, edge);
51
+ };
52
+ const logical = (id) => {
53
+ const e = model.byId.get(id);
54
+ if (!nodes.has(id))
55
+ nodes.set(id, { id, kind: e.kind, name: e.name, parent: null, collapsed: false, external: "external" in e && e.external });
56
+ return id;
57
+ };
58
+ for (const r of model.relationships) {
59
+ const [from, to] = [lift(r.from), lift(r.to)];
60
+ if (from === to || !keep(from) || !keep(to))
61
+ continue;
62
+ if ([from, to].some((id) => !model.byId.has(id) || model.byId.get(id).kind === "person"))
63
+ continue;
64
+ const consumers = byService.get(from) ?? [];
65
+ const providers = byService.get(to) ?? [];
66
+ if (consumers.length === 0 && providers.length === 0)
67
+ continue;
68
+ if (consumers.length === 0) {
69
+ for (const p of providers)
70
+ connect(logical(from), deploymentNodeId(p.d), r);
71
+ continue;
72
+ }
73
+ for (const c of consumers) {
74
+ if (providers.length === 0) {
75
+ connect(deploymentNodeId(c.d), logical(to), r);
76
+ continue;
77
+ }
78
+ const shared = providers.map((p) => sharedDepth(c.chain, p.chain));
79
+ const deepest = Math.max(...shared);
80
+ providers.forEach((p, i) => {
81
+ if (deepest === 0 || shared[i] === deepest)
82
+ connect(deploymentNodeId(c.d), deploymentNodeId(p.d), r);
83
+ });
84
+ }
85
+ }
86
+ return {
87
+ ...head,
88
+ kind: "deployment",
89
+ direction: "TB",
90
+ nodes: [...nodes.values()].sort((a, b) => cmp(a.id, b.id)),
91
+ edges: [...edges.values()].sort((a, b) => cmp(a.from, b.from) || cmp(a.to, b.to)),
92
+ };
93
+ }
94
+ /** A Target's chain, outermost first, ending at the Target itself. */
95
+ function chainOf(targets, id) {
96
+ const chain = [];
97
+ for (let t = targets.get(id); t && !chain.includes(t.id); t = t.parent === null ? undefined : targets.get(t.parent))
98
+ chain.unshift(t.id);
99
+ return chain;
100
+ }
101
+ /** How many Targets two chains share from the outside in. */
102
+ function sharedDepth(a, b) {
103
+ let i = 0;
104
+ while (i < a.length && i < b.length && a[i] === b[i])
105
+ i++;
106
+ return i;
107
+ }
108
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
@@ -0,0 +1,18 @@
1
+ import type { Bundle, BundleDeployment } from "../schema/bundle.ts";
2
+ /** One Deployment Target in a chain: enough to name it. */
3
+ export interface TargetStep {
4
+ id: string;
5
+ name: string;
6
+ kind: string;
7
+ }
8
+ /** A Deployment with its full Deployment Target chain, outermost first, ending at its own Target. */
9
+ export interface DeploymentDetail extends BundleDeployment {
10
+ targetPath: TargetStep[];
11
+ }
12
+ /**
13
+ * A Service's Deployments, optionally in one Environment, each with the chain
14
+ * of Deployment Targets it sits in (e.g. region › cluster). Ordered as in the
15
+ * Bundle: by Environment, then Target. A Target the Bundle does not know
16
+ * leaves the chain empty.
17
+ */
18
+ export declare function getDeployments(bundle: Bundle, service: string, environment?: string): DeploymentDetail[];
@@ -0,0 +1,21 @@
1
+ /**
2
+ * A Service's Deployments, optionally in one Environment, each with the chain
3
+ * of Deployment Targets it sits in (e.g. region › cluster). Ordered as in the
4
+ * Bundle: by Environment, then Target. A Target the Bundle does not know
5
+ * leaves the chain empty.
6
+ */
7
+ export function getDeployments(bundle, service, environment) {
8
+ const targets = new Map(bundle.targets.map((t) => [t.id, t]));
9
+ return bundle.deployments
10
+ .filter((d) => d.service === service && (environment === undefined || d.environment === environment))
11
+ .map((d) => ({ ...d, targetPath: chain(targets, d.target) }));
12
+ }
13
+ function chain(targets, id) {
14
+ const path = [];
15
+ const seen = new Set();
16
+ for (let t = targets.get(id); t && !seen.has(t.id); t = t.parent === null ? undefined : targets.get(t.parent)) {
17
+ seen.add(t.id);
18
+ path.unshift({ id: t.id, name: t.name, kind: t.kind });
19
+ }
20
+ return path;
21
+ }
@@ -0,0 +1,44 @@
1
+ import type { Bundle } from "../schema/bundle.ts";
2
+ /** The kinds of Model item a Change can be about, in the order Changes are listed. */
3
+ export declare const changeKinds: readonly ["team", "environment", "project", "element", "relationship", "target", "deployment", "view", "adr"];
4
+ export type ChangeKind = (typeof changeKinds)[number];
5
+ export type ChangeType = "added" | "removed" | "changed";
6
+ /** One Model item as diffed: the Bundle item without its `source`. */
7
+ export type ChangeItem = Record<string, unknown>;
8
+ /**
9
+ * One item of the Model added, removed or changed between two Bundles.
10
+ * `before` and `after` are the whole item at each side (null where it is
11
+ * missing); `fields` names the fields that differ, in the item's key order,
12
+ * and is empty for an added or removed item.
13
+ */
14
+ export interface Change {
15
+ type: ChangeType;
16
+ kind: ChangeKind;
17
+ /** The item's id; a Relationship without one is `from -> to`, a Deployment `service in environment on target`. */
18
+ id: string;
19
+ fields: string[];
20
+ before: ChangeItem | null;
21
+ after: ChangeItem | null;
22
+ }
23
+ /** Counts of Changes by type. */
24
+ export interface ChangeCounts {
25
+ added: number;
26
+ removed: number;
27
+ changed: number;
28
+ }
29
+ /**
30
+ * The Changes from one Bundle to another: a flat list ordered by kind, then
31
+ * id. Items match by (qualified) id, Deployments by their triple, and
32
+ * Relationships by id, else by a pair with one Relationship at each side,
33
+ * else by (pair, technology, interaction); anything unmatched is removed
34
+ * plus added. `source`, key order, `commit` and `builtAt` are ignored, and
35
+ * derived edges are never compared. Owners in a Bundle are already effective.
36
+ */
37
+ export declare function diff(before: Bundle, after: Bundle): Change[];
38
+ export declare function countChanges(changes: Change[]): ChangeCounts;
39
+ /**
40
+ * The ids a list of Changes touches: each item's own id, plus the Elements
41
+ * and Deployment Targets a Relationship, Deployment or ADR names at either
42
+ * side. Sorted and unique; this is what a Revision index entry records.
43
+ */
44
+ export declare function changedIds(changes: Change[]): string[];
@@ -0,0 +1,138 @@
1
+ /** The kinds of Model item a Change can be about, in the order Changes are listed. */
2
+ export const changeKinds = ["team", "environment", "project", "element", "relationship", "target", "deployment", "view", "adr"];
3
+ /**
4
+ * The Changes from one Bundle to another: a flat list ordered by kind, then
5
+ * id. Items match by (qualified) id, Deployments by their triple, and
6
+ * Relationships by id, else by a pair with one Relationship at each side,
7
+ * else by (pair, technology, interaction); anything unmatched is removed
8
+ * plus added. `source`, key order, `commit` and `builtAt` are ignored, and
9
+ * derived edges are never compared. Owners in a Bundle are already effective.
10
+ */
11
+ export function diff(before, after) {
12
+ const changes = [];
13
+ const byId = (kind, a, b) => compareMatched(kind, matchBy(a, b, (x) => x.id), (x) => x.id, changes);
14
+ byId("team", before.teams, after.teams);
15
+ byId("environment", before.environments, after.environments);
16
+ byId("project", before.projects, after.projects);
17
+ byId("element", before.elements, after.elements);
18
+ compareMatched("relationship", matchRelationships(before.relationships, after.relationships), relationshipId, changes);
19
+ byId("target", before.targets, after.targets);
20
+ compareMatched("deployment", matchBy(before.deployments, after.deployments, deploymentId), deploymentId, changes);
21
+ byId("view", before.views, after.views);
22
+ byId("adr", before.adrs, after.adrs);
23
+ const typeOrder = { changed: 0, removed: 1, added: 2 };
24
+ return changes.sort((a, b) => changeKinds.indexOf(a.kind) - changeKinds.indexOf(b.kind) || cmp(a.id, b.id) || typeOrder[a.type] - typeOrder[b.type]);
25
+ }
26
+ export function countChanges(changes) {
27
+ const counts = { added: 0, removed: 0, changed: 0 };
28
+ for (const c of changes)
29
+ counts[c.type]++;
30
+ return counts;
31
+ }
32
+ /**
33
+ * The ids a list of Changes touches: each item's own id, plus the Elements
34
+ * and Deployment Targets a Relationship, Deployment or ADR names at either
35
+ * side. Sorted and unique; this is what a Revision index entry records.
36
+ */
37
+ export function changedIds(changes) {
38
+ const ids = new Set();
39
+ for (const c of changes) {
40
+ if (c.kind !== "relationship" && c.kind !== "deployment")
41
+ ids.add(c.id);
42
+ for (const item of [c.before, c.after]) {
43
+ if (!item)
44
+ continue;
45
+ if (c.kind === "relationship")
46
+ for (const key of ["from", "to"])
47
+ ids.add(item[key]);
48
+ if (c.kind === "deployment")
49
+ for (const key of ["service", "target"])
50
+ ids.add(item[key]);
51
+ if (c.kind === "adr")
52
+ for (const id of item.elements)
53
+ ids.add(id);
54
+ }
55
+ }
56
+ return [...ids].sort(cmp);
57
+ }
58
+ const relationshipId = (r) => r.id ?? `${r.from} -> ${r.to}`;
59
+ const deploymentId = (d) => `${d.service} in ${d.environment} on ${d.target}`;
60
+ /** Pairs items whose key is unique at both sides; the rest are left over. */
61
+ function matchBy(before, after, key) {
62
+ const groups = (xs) => {
63
+ const map = new Map();
64
+ for (const x of xs)
65
+ map.set(key(x), [...(map.get(key(x)) ?? []), x]);
66
+ return map;
67
+ };
68
+ const a = groups(before);
69
+ const b = groups(after);
70
+ const paired = new Set();
71
+ const pairs = [];
72
+ for (const [k, xs] of a) {
73
+ const ys = b.get(k);
74
+ if (xs.length === 1 && ys?.length === 1) {
75
+ pairs.push([xs[0], ys[0]]);
76
+ paired.add(xs[0]).add(ys[0]);
77
+ }
78
+ }
79
+ return { pairs, removed: before.filter((x) => !paired.has(x)), added: after.filter((x) => !paired.has(x)) };
80
+ }
81
+ /**
82
+ * Relationships: by id where both sides have one, then by a pair with
83
+ * exactly one Relationship at each side, then by a (pair, technology,
84
+ * interaction) that is unique at each side. Uniqueness is counted over all
85
+ * Relationships not matched by id. Relationships identical at both sides are
86
+ * set aside first, so an unchanged one never shows as removed plus added.
87
+ */
88
+ function matchRelationships(before, after) {
89
+ const withId = (xs) => xs.filter((r) => r.id !== null);
90
+ const byId = matchBy(withId(before), withId(after), (r) => r.id);
91
+ const idMatched = new Set(byId.pairs.flat());
92
+ const restBefore = before.filter((r) => !idMatched.has(r));
93
+ const restAfter = after.filter((r) => !idMatched.has(r));
94
+ const pairs = [...byId.pairs];
95
+ const matched = new Set(idMatched);
96
+ const pairUp = (key, unique) => {
97
+ const count = (xs) => xs.reduce((m, r) => m.set(key(r), (m.get(key(r)) ?? 0) + 1), new Map());
98
+ const [inBefore, inAfter] = [count(restBefore), count(restAfter)];
99
+ const waiting = new Map();
100
+ for (const r of restAfter)
101
+ if (!matched.has(r))
102
+ waiting.set(key(r), [...(waiting.get(key(r)) ?? []), r]);
103
+ for (const r of restBefore) {
104
+ if (matched.has(r) || (unique && (inBefore.get(key(r)) !== 1 || inAfter.get(key(r)) !== 1)))
105
+ continue;
106
+ const other = waiting.get(key(r))?.shift();
107
+ if (!other)
108
+ continue;
109
+ pairs.push([r, other]);
110
+ matched.add(r).add(other);
111
+ }
112
+ };
113
+ pairUp((r) => canonical(item(r)), false);
114
+ pairUp((r) => JSON.stringify([r.from, r.to]), true);
115
+ pairUp((r) => JSON.stringify([r.from, r.to, r.technology, r.interaction]), true);
116
+ return { pairs, removed: before.filter((r) => !matched.has(r)), added: after.filter((r) => !matched.has(r)) };
117
+ }
118
+ function compareMatched(kind, matched, id, changes) {
119
+ for (const [a, b] of matched.pairs) {
120
+ const before = item(a);
121
+ const after = item(b);
122
+ const fields = [...new Set([...Object.keys(before), ...Object.keys(after)])].filter((f) => canonical(before[f]) !== canonical(after[f]));
123
+ if (fields.length > 0)
124
+ changes.push({ type: "changed", kind, id: id(b), fields, before, after });
125
+ }
126
+ for (const x of matched.removed)
127
+ changes.push({ type: "removed", kind, id: id(x), fields: [], before: item(x), after: null });
128
+ for (const x of matched.added)
129
+ changes.push({ type: "added", kind, id: id(x), fields: [], before: null, after: item(x) });
130
+ }
131
+ function item(x) {
132
+ return Object.fromEntries(Object.entries(x).filter(([key]) => key !== "source"));
133
+ }
134
+ /** JSON with object keys sorted, so key order never counts as a change. */
135
+ function canonical(value) {
136
+ return JSON.stringify(value, (_key, v) => v !== null && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => cmp(a, b))) : v);
137
+ }
138
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
@@ -0,0 +1,73 @@
1
+ import type { Bundle, BundleDynamicView, BundleRelationship } from "../schema/bundle.ts";
2
+ /** How a Step reads: a consumer calling its provider, the provider's reply, or an event a publisher sends one subscriber. */
3
+ export type StepKind = "call" | "return" | "event";
4
+ /**
5
+ * One Step resolved to the Relationship it takes. `from` and `to` are as
6
+ * drawn: for an event, publisher → subscriber, while `relationship` is the
7
+ * stored subscriber → publisher subscription. `via` and `channel` are copied
8
+ * from the Relationship when it has them.
9
+ */
10
+ export interface ResolvedStep {
11
+ /** The Step's position in the View, from 1. */
12
+ n: number;
13
+ kind: StepKind;
14
+ from: string;
15
+ to: string;
16
+ relationship: BundleRelationship;
17
+ interaction: "sync" | "async";
18
+ via?: string;
19
+ channel?: string;
20
+ /** The author's description, else the channel for an event, else the Relationship's description. */
21
+ description: string;
22
+ note?: string;
23
+ }
24
+ /** A Dynamic View resolved: its participants in drawing order and the Steps that resolve, numbered by position. */
25
+ export interface ResolvedDynamicView {
26
+ id: string;
27
+ kind: "dynamic";
28
+ title: string;
29
+ participants: string[];
30
+ steps: ResolvedStep[];
31
+ }
32
+ /** A problem `check` reports about a Dynamic View, at a path relative to the View. */
33
+ export interface DynamicProblem {
34
+ rule: "missing-step" | "ambiguous-step" | "return-without-relationship" | "return-on-async" | "ancestor-descendant-participants";
35
+ at: (string | number)[];
36
+ message: string;
37
+ }
38
+ export interface DynamicResolution {
39
+ view: ResolvedDynamicView;
40
+ problems: DynamicProblem[];
41
+ }
42
+ /**
43
+ * Resolves a Dynamic View's Steps against the Model. Each Step's ends may be
44
+ * any Elements; a Relationship between their descendants (a derived edge)
45
+ * counts as between them.
46
+ * - A non-return Step collects the forward Relationships `from` → `to`
47
+ * without `via` (calls) and the `via` subscriptions `to` → `from` (events).
48
+ * Exactly one match is the Step; more is ambiguous unless `relationship`
49
+ * names one.
50
+ * - A return Step needs a Relationship `to` → `from`, and it must be sync.
51
+ * Steps naming an unknown Element, or an Element and its own ancestor, are
52
+ * left out without a Step problem (`unknown-element` and
53
+ * `ancestor-descendant-participants` report them).
54
+ */
55
+ export declare function resolveDynamic(bundle: Bundle, def: BundleDynamicView): DynamicResolution;
56
+ /** Resolves a Saved Dynamic View by id; undefined for any other id. */
57
+ export declare function resolveDynamicView(bundle: Bundle, id: string): ResolvedDynamicView | undefined;
58
+ /** Whether an Element takes part in a Dynamic View: as a participant, or as the broker an event Step runs via. */
59
+ export declare function takesPart(view: ResolvedDynamicView, element: string): boolean;
60
+ /**
61
+ * The Generated Views holding a Step's Relationship, most specific first:
62
+ * `c3/<service>` when both ends are Components of one Service; the consumer's
63
+ * `c2/<system>`, then the provider's; for an event Step the broker's
64
+ * `c2/<system>`; then `c2`; and `c1` when the ends are under different
65
+ * top-level Elements. The consumer of an event Step is its subscriber.
66
+ */
67
+ export declare function stepViews(bundle: Bundle, step: ResolvedStep): string[];
68
+ /** The Dynamic Views with a Step that takes this Relationship, in Bundle order. */
69
+ export declare function dynamicViewsUsing(bundle: Bundle, relationship: BundleRelationship): {
70
+ id: string;
71
+ kind: "dynamic";
72
+ title: string;
73
+ }[];
@@ -0,0 +1,162 @@
1
+ import { within } from "./query.js";
2
+ const kindName = { person: "Person", system: "System", service: "Service", component: "Component" };
3
+ const nameOf = (r) => r.id ?? `${r.from} → ${r.to}`;
4
+ const names = (rs) => rs.map(nameOf).join(", ");
5
+ /**
6
+ * Resolves a Dynamic View's Steps against the Model. Each Step's ends may be
7
+ * any Elements; a Relationship between their descendants (a derived edge)
8
+ * counts as between them.
9
+ * - A non-return Step collects the forward Relationships `from` → `to`
10
+ * without `via` (calls) and the `via` subscriptions `to` → `from` (events).
11
+ * Exactly one match is the Step; more is ambiguous unless `relationship`
12
+ * names one.
13
+ * - A return Step needs a Relationship `to` → `from`, and it must be sync.
14
+ * Steps naming an unknown Element, or an Element and its own ancestor, are
15
+ * left out without a Step problem (`unknown-element` and
16
+ * `ancestor-descendant-participants` report them).
17
+ */
18
+ export function resolveDynamic(bundle, def) {
19
+ const byId = new Map(bundle.elements.map((e) => [e.id, e]));
20
+ const under = within(bundle);
21
+ const problems = [];
22
+ const steps = [];
23
+ def.steps.forEach((s, index) => {
24
+ const result = resolveStep(bundle, s, under, byId);
25
+ if (result === undefined)
26
+ return;
27
+ if ("rule" in result)
28
+ problems.push({ rule: result.rule, at: ["steps", index], message: result.message });
29
+ else
30
+ steps.push(toStep(index + 1, s, result.kind, result.relationship));
31
+ });
32
+ // Participants in the order they first appear: the fixed list first, then each Step's ends.
33
+ const appearances = [
34
+ ...(def.participants ?? []).map((id, i) => ({ id, at: ["participants", i] })),
35
+ ...def.steps.flatMap((s, i) => ["from", "to"].map((end) => ({ id: s[end], at: ["steps", i, end] }))),
36
+ ].filter((a) => byId.has(a.id));
37
+ const first = new Map();
38
+ for (const a of appearances)
39
+ if (!first.has(a.id))
40
+ first.set(a.id, a.at);
41
+ const participants = [...first.keys()];
42
+ // An ancestor and its descendant both taking part is reported once, where the later of the two first appears.
43
+ participants.forEach((later, j) => {
44
+ for (const earlier of participants.slice(0, j)) {
45
+ const [ancestor, descendant] = under(later, earlier) ? [earlier, later] : under(earlier, later) ? [later, earlier] : [];
46
+ if (ancestor === undefined || descendant === undefined)
47
+ continue;
48
+ problems.push({
49
+ rule: "ancestor-descendant-participants",
50
+ at: first.get(later),
51
+ message: `${kindName[byId.get(ancestor).kind]} "${ancestor}" and its descendant "${descendant}" are both participants`,
52
+ });
53
+ }
54
+ });
55
+ return { view: { id: def.id, kind: "dynamic", title: def.title, participants, steps }, problems };
56
+ }
57
+ /** Resolves a Saved Dynamic View by id; undefined for any other id. */
58
+ export function resolveDynamicView(bundle, id) {
59
+ const def = bundle.views.find((v) => v.id === id);
60
+ return def?.kind === "dynamic" ? resolveDynamic(bundle, def).view : undefined;
61
+ }
62
+ /** Whether an Element takes part in a Dynamic View: as a participant, or as the broker an event Step runs via. */
63
+ export function takesPart(view, element) {
64
+ return view.participants.includes(element) || view.steps.some((s) => s.via === element);
65
+ }
66
+ function resolveStep(bundle, s, under, byId) {
67
+ const { from, to } = s;
68
+ if (!byId.has(from) || !byId.has(to))
69
+ return undefined;
70
+ if (from === to)
71
+ return { rule: "missing-step", message: `A Step goes from one Element to another, not from "${from}" to itself` };
72
+ if (under(from, to) || under(to, from))
73
+ return undefined;
74
+ const named = s.relationship === null ? undefined : bundle.relationships.filter((r) => r.id === s.relationship);
75
+ if (named !== undefined && named.length === 0)
76
+ return { rule: "missing-step", message: `No Relationship "${s.relationship}"` };
77
+ if (s.return) {
78
+ const opposite = bundle.relationships.filter((r) => under(r.from, to) && under(r.to, from));
79
+ const pick = pickOne(opposite, named, s, () => ({ rule: "return-without-relationship", message: `A return from "${from}" to "${to}" needs a Relationship from "${to}" to "${from}"` }), (n) => `${n} Relationships match the return "${from}" → "${to}"`);
80
+ if (!("relationship" in pick))
81
+ return pick;
82
+ if (pick.relationship.interaction === "async") {
83
+ return { rule: "return-on-async", message: `Relationship "${nameOf(pick.relationship)}" is async, so it has no return; model a callback as its own Relationship` };
84
+ }
85
+ return { kind: "return", relationship: pick.relationship };
86
+ }
87
+ const calls = bundle.relationships.filter((r) => r.via === null && under(r.from, from) && under(r.to, to));
88
+ const events = bundle.relationships.filter((r) => r.via !== null && under(r.from, to) && under(r.to, from));
89
+ if (named === undefined && calls.length > 0 && events.length > 0) {
90
+ return { rule: "ambiguous-step", message: `"${from}" → "${to}" matches both a call (${names(calls)}) and an event (${names(events)}); name one with \`relationship\`` };
91
+ }
92
+ const pick = pickOne([...calls, ...events], named, s, () => ({ rule: "missing-step", message: `No Relationship from "${from}" to "${to}", nor a \`via\` subscription of "${to}" to it` }), (n) => `${n} Relationships match "${from}" → "${to}"`);
93
+ if (!("relationship" in pick))
94
+ return pick;
95
+ return { kind: events.includes(pick.relationship) ? "event" : "call", relationship: pick.relationship };
96
+ }
97
+ /** The one candidate a Step takes: the named one if it is a candidate, else the only candidate. */
98
+ function pickOne(candidates, named, s, none, several) {
99
+ if (named !== undefined) {
100
+ const hit = candidates.find((r) => named.includes(r));
101
+ const [a, b] = s.return ? [s.to, s.from] : [s.from, s.to];
102
+ return hit ? { relationship: hit } : { rule: "missing-step", message: `Relationship "${s.relationship}" doesn't connect "${a}" to "${b}"` };
103
+ }
104
+ if (candidates.length === 0)
105
+ return none();
106
+ if (candidates.length > 1)
107
+ return { rule: "ambiguous-step", message: `${several(candidates.length)} (${names(candidates)}); name one with \`relationship\`` };
108
+ return { relationship: candidates[0] };
109
+ }
110
+ function toStep(n, s, kind, r) {
111
+ const label = kind === "event" ? (r.channel ?? r.description) : r.description;
112
+ return {
113
+ n,
114
+ kind,
115
+ from: s.from,
116
+ to: s.to,
117
+ relationship: r,
118
+ interaction: r.interaction,
119
+ ...(r.via === null ? {} : { via: r.via }),
120
+ ...(r.channel === null ? {} : { channel: r.channel }),
121
+ description: s.description ?? label ?? "",
122
+ ...(s.note === null ? {} : { note: s.note }),
123
+ };
124
+ }
125
+ /**
126
+ * The Generated Views holding a Step's Relationship, most specific first:
127
+ * `c3/<service>` when both ends are Components of one Service; the consumer's
128
+ * `c2/<system>`, then the provider's; for an event Step the broker's
129
+ * `c2/<system>`; then `c2`; and `c1` when the ends are under different
130
+ * top-level Elements. The consumer of an event Step is its subscriber.
131
+ */
132
+ export function stepViews(bundle, step) {
133
+ const byId = new Map(bundle.elements.map((e) => [e.id, e]));
134
+ const ancestry = (id) => {
135
+ const out = [];
136
+ for (let e = byId.get(id); e !== undefined && !out.includes(e); e = e.parent === null ? undefined : byId.get(e.parent))
137
+ out.unshift(e);
138
+ return out;
139
+ };
140
+ const system = (id) => ancestry(id).find((e) => e.kind === "system");
141
+ const { from, to } = step.relationship;
142
+ const [a, b] = [byId.get(from), byId.get(to)];
143
+ const views = [];
144
+ if (a?.kind === "component" && b?.kind === "component" && a.parent === b.parent && a.parent !== null)
145
+ views.push(`c3/${a.parent}`);
146
+ for (const id of [from, to, ...(step.via === undefined ? [] : [step.via])]) {
147
+ const s = system(id);
148
+ if (s)
149
+ views.push(`c2/${s.id}`);
150
+ }
151
+ views.push("c2");
152
+ if (ancestry(from)[0] !== ancestry(to)[0])
153
+ views.push("c1");
154
+ return [...new Set(views)];
155
+ }
156
+ /** The Dynamic Views with a Step that takes this Relationship, in Bundle order. */
157
+ export function dynamicViewsUsing(bundle, relationship) {
158
+ return bundle.views
159
+ .filter((v) => v.kind === "dynamic")
160
+ .filter((v) => resolveDynamic(bundle, v).view.steps.some((s) => s.relationship === relationship))
161
+ .map((v) => ({ id: v.id, kind: "dynamic", title: v.title }));
162
+ }
@@ -0,0 +1,2 @@
1
+ /** A set of files keyed by path; used for rule examples. */
2
+ export type Files = Record<string, string>;