@intentius/behold 0.30.2 → 0.32.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 (102) hide show
  1. package/AGENTS.md +791 -16
  2. package/README.md +78 -23
  3. package/THIRD_PARTY.md +6 -5
  4. package/demos.json +14 -9
  5. package/dist/cli.js +51926 -20221
  6. package/example-carve/README.md +19 -23
  7. package/example-carve/app/package.json +1 -1
  8. package/example-carve/app/src/carved.ts +3 -3
  9. package/example-carve/carve-report.json +1 -1
  10. package/example-carve/{legacy-tf → tf-root}/terraform.tfstate +1 -1
  11. package/example-choudoufu-estate/README.md +7 -0
  12. package/example-choudoufu-estate/chant.workspace.json +1 -1
  13. package/example-choudoufu-estate/scripts/choudoufu-down.sh +2 -1
  14. package/example-choudoufu-estate/scripts/choudoufu-up.sh +10 -3
  15. package/example-terraform-estate/README.md +32 -5
  16. package/example-terraform-estate/chant.workspace.json +1 -1
  17. package/example-terraform-estate/recorded/adoption/platform.json +72 -0
  18. package/example-terraform-estate/recorded/adoption/prod.json +224 -0
  19. package/example-three-cloud/README.md +111 -18
  20. package/example-three-cloud/aws/Pulumi.yaml +15 -0
  21. package/example-three-cloud/aws/index.ts +174 -0
  22. package/example-three-cloud/aws/package-lock.json +2725 -0
  23. package/example-three-cloud/aws/package.json +14 -0
  24. package/example-three-cloud/aws/tsconfig.json +17 -0
  25. package/example-three-cloud/azure/main.tf +48 -0
  26. package/example-three-cloud/azure/site.tf +104 -0
  27. package/example-three-cloud/chant.config.json +9 -0
  28. package/example-three-cloud/chant.workspace.json +30 -4
  29. package/example-three-cloud/dns/chant.config.ts +26 -1
  30. package/example-three-cloud/dns/src/records.component.ts +32 -6
  31. package/example-three-cloud/package-lock.json +48 -27
  32. package/example-three-cloud/package.json +8 -6
  33. package/example-three-cloud/scripts/emulators-up.sh +28 -1
  34. package/example-three-cloud/scripts/front-door.ts +679 -86
  35. package/package.json +26 -8
  36. package/schemas/graph/v1/graph.schema.json +140 -0
  37. package/web/adopt-pulumi.js +114 -0
  38. package/web/adopt-pulumi.test.js +28 -0
  39. package/web/adopt.js +203 -0
  40. package/web/adopt.test.js +27 -0
  41. package/web/app.js +367 -14
  42. package/web/boot-motion.js +6 -0
  43. package/web/carve-steps.js +1 -1
  44. package/web/carve-steps.test.js +2 -2
  45. package/web/change-set-overlay.js +12 -5
  46. package/web/change-set-overlay.test.js +22 -0
  47. package/web/cut-around.d.ts +30 -0
  48. package/web/cut-around.js +138 -0
  49. package/web/drift-stream.js +241 -0
  50. package/web/drift-stream.test.js +146 -0
  51. package/web/edge-weight.d.ts +8 -2
  52. package/web/edge-weight.js +38 -4
  53. package/web/edge-weight.test.js +55 -1
  54. package/web/graph-query.js +180 -0
  55. package/web/graph-query.test.js +49 -0
  56. package/web/graph.html +107 -0
  57. package/web/index-diff.js +109 -0
  58. package/web/index-diff.test.js +39 -0
  59. package/web/index.html +45 -20
  60. package/web/kiosk-ask-tips.js +15 -5
  61. package/web/kiosk-ask-tips.test.js +14 -1
  62. package/web/kiosk-estate-scene.js +72 -8
  63. package/web/kiosk-light-frame.js +1 -0
  64. package/web/kiosk-light.js +41 -3
  65. package/web/kiosk-member-kind.test.js +140 -0
  66. package/web/kiosk-popover.js +4 -1
  67. package/web/kiosk-side.js +296 -0
  68. package/web/kiosk-side.test.js +249 -0
  69. package/web/kiosk-watch.js +12 -0
  70. package/web/kiosk-watch.test.js +15 -1
  71. package/web/kiosk.html +47 -1
  72. package/web/kiosk.js +106 -7
  73. package/web/member-kind.js +31 -0
  74. package/web/neighbourhood.js +105 -0
  75. package/web/neighbourhood.test.js +131 -0
  76. package/web/outside-refs.js +515 -0
  77. package/web/outside-refs.test.js +249 -0
  78. package/web/template-apps.js +245 -0
  79. package/web/template-apps.test.js +252 -0
  80. package/web/templates.js +285 -0
  81. package/web/templates.test.js +155 -0
  82. package/web/terragucci-lifecycle.js +112 -62
  83. package/web/terragucci-lifecycle.test.js +29 -1
  84. package/web/terragucci-timeline.js +39 -2
  85. package/web/terragucci-timeline.test.js +42 -1
  86. package/web/theme-paint.js +14 -0
  87. package/example-three-cloud/aws/chant.config.ts +0 -8
  88. package/example-three-cloud/aws/site.component.ts +0 -13
  89. package/example-three-cloud/aws/src/site.ts +0 -27
  90. package/example-three-cloud/azure/chant.config.ts +0 -1
  91. package/example-three-cloud/azure/src/site.component.ts +0 -13
  92. package/example-three-cloud/azure/src/site.ts +0 -18
  93. /package/example-carve/{legacy-tf → tf-root}/cdn.tf +0 -0
  94. /package/example-carve/{legacy-tf → tf-root}/compute.tf +0 -0
  95. /package/example-carve/{legacy-tf → tf-root}/floci-override.tf.disabled +0 -0
  96. /package/example-carve/{legacy-tf → tf-root}/modules/cdn/main.tf +0 -0
  97. /package/example-carve/{legacy-tf → tf-root}/naming.tf +0 -0
  98. /package/example-carve/{legacy-tf → tf-root}/network.tf +0 -0
  99. /package/example-carve/{legacy-tf → tf-root}/observability.tf +0 -0
  100. /package/example-carve/{legacy-tf → tf-root}/outputs.tf +0 -0
  101. /package/example-carve/{legacy-tf → tf-root}/storage.tf +0 -0
  102. /package/example-carve/{legacy-tf → tf-root}/versions.tf +0 -0
@@ -0,0 +1,249 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { readFileSync } from "node:fs";
3
+ import { outsideRefs, normalizeUrl } from "./outside-refs.js";
4
+
5
+ const sa = (name, annotations, namespace = "ci") => ({ apiVersion: "v1", kind: "ServiceAccount", metadata: { name, namespace, annotations } });
6
+ const clusterStore = (name, provider) => ({ apiVersion: "external-secrets.io/v1", kind: "ClusterSecretStore", metadata: { name }, spec: { provider } });
7
+ const store = (name, namespace, provider) => ({ apiVersion: "external-secrets.io/v1", kind: "SecretStore", metadata: { name, namespace }, spec: { provider } });
8
+ const externalSecret = (name, namespace, storeRef, keys, extra = {}) => ({
9
+ apiVersion: "external-secrets.io/v1",
10
+ kind: "ExternalSecret",
11
+ metadata: { name, namespace },
12
+ spec: { secretStoreRef: storeRef, data: keys.map((key) => ({ secretKey: "v", remoteRef: { key } })), ...extra },
13
+ });
14
+ const tf = (id, kind, body) => ({ id, kind, lexicon: "terraform", attrs: { address: id, body } });
15
+
16
+ const ARN = "arn:aws:iam::111122223333:role/ci-runner";
17
+ const GCP_STORE = clusterStore("gcp", { gcpsm: { projectID: "demo-proj" } });
18
+
19
+ describe("ServiceAccount annotations", () => {
20
+ it("gives an IRSA role one card labelled with the role and an edge from the account", () => {
21
+ const out = outsideRefs([sa("runner", { "eks.amazonaws.com/role-arn": ARN })]);
22
+ expect(out.cards).toEqual([
23
+ { id: `outside:identity:aws:${ARN}`, kind: "CloudIdentity", label: ARN, placeholder: true, attrs: { cloud: "aws", arn: ARN, account: "111122223333", role: "ci-runner" } },
24
+ ]);
25
+ expect(out.edges).toEqual([
26
+ {
27
+ from: "/ServiceAccount/ci/runner",
28
+ fromRef: { group: "", kind: "ServiceAccount", namespace: "ci", name: "runner" },
29
+ to: `outside:identity:aws:${ARN}`,
30
+ kind: "ref",
31
+ viaAttr: "metadata.annotations[eks.amazonaws.com/role-arn]",
32
+ inferred: true,
33
+ placeholder: true,
34
+ },
35
+ ]);
36
+ expect(out.notes).toEqual([]);
37
+ });
38
+
39
+ it("shares one card between two accounts with the same annotation", () => {
40
+ const out = outsideRefs([sa("a", { "eks.amazonaws.com/role-arn": ARN }), sa("b", { "eks.amazonaws.com/role-arn": ARN }, "other")]);
41
+ expect(out.cards).toHaveLength(1);
42
+ expect(out.edges.map((e) => e.from)).toEqual(["/ServiceAccount/ci/a", "/ServiceAccount/other/b"]);
43
+ });
44
+
45
+ it("reads the GKE and Azure annotations", () => {
46
+ const out = outsideRefs([
47
+ sa("g", { "iam.gke.io/gcp-service-account": "runner@demo-proj.iam.gserviceaccount.com" }),
48
+ sa("z", { "azure.workload.identity/client-id": "AAAA-BBBB" }),
49
+ ]);
50
+ expect(out.cards.map((c) => c.id)).toEqual(["outside:identity:azure:aaaa-bbbb", "outside:identity:gcp:runner@demo-proj.iam.gserviceaccount.com"]);
51
+ expect(out.cards[1].attrs).toEqual({ cloud: "gcp", email: "runner@demo-proj.iam.gserviceaccount.com", project: "demo-proj" });
52
+ });
53
+
54
+ it("returns no card for a role the graph already holds", () => {
55
+ const graph = { nodes: [tf("tf/aws_iam_role.ci", "aws_iam_role", { name: "ci-runner" })] };
56
+ expect(outsideRefs([sa("runner", { "eks.amazonaws.com/role-arn": ARN })], { graph })).toEqual({ cards: [], edges: [], notes: [] });
57
+ });
58
+
59
+ it("holds a role by an address in the node id and a service account by account_id and project", () => {
60
+ const graph = {
61
+ nodes: [
62
+ { id: "tf/module.x.aws_iam_role.ci[0]", kind: "Terraform::Resource", lexicon: "terraform", attrs: { arn: ARN } },
63
+ tf("tf/google_service_account.r", "google_service_account", { account_id: "runner", project: "demo-proj" }),
64
+ ],
65
+ };
66
+ const out = outsideRefs([sa("a", { "eks.amazonaws.com/role-arn": ARN }), sa("b", { "iam.gke.io/gcp-service-account": "runner@demo-proj.iam.gserviceaccount.com" })], { graph });
67
+ expect(out.cards).toEqual([]);
68
+ });
69
+
70
+ it("does not take a service account in another project as the held one", () => {
71
+ const graph = { nodes: [tf("tf/google_service_account.r", "google_service_account", { account_id: "runner", project: "other-proj" })] };
72
+ const out = outsideRefs([sa("b", { "iam.gke.io/gcp-service-account": "runner@demo-proj.iam.gserviceaccount.com" })], { graph });
73
+ expect(out.cards).toHaveLength(1);
74
+ });
75
+
76
+ it("puts an annotation it cannot read in notes", () => {
77
+ const out = outsideRefs([sa("a", { "eks.amazonaws.com/role-arn": "not-an-arn" }), sa("b", { "iam.gke.io/gcp-service-account": "<masked>" })]);
78
+ expect(out.cards).toEqual([]);
79
+ expect(out.notes.map((n) => [n.code, n.path])).toEqual([
80
+ ["unrecognised", "metadata.annotations[eks.amazonaws.com/role-arn]"],
81
+ ["masked", "metadata.annotations[iam.gke.io/gcp-service-account]"],
82
+ ]);
83
+ });
84
+ });
85
+
86
+ describe("ExternalSecret and its store", () => {
87
+ const es = externalSecret("app-creds", "app", { name: "gcp", kind: "ClusterSecretStore" }, ["app-token"]);
88
+
89
+ it("gives a store card and a provider card naming the project and the key", () => {
90
+ const out = outsideRefs([GCP_STORE, es]);
91
+ expect(out.cards).toEqual([
92
+ {
93
+ id: "outside:provider:gcpsm:demo-proj",
94
+ kind: "SecretProvider",
95
+ label: "GCP Secret Manager demo-proj",
96
+ placeholder: true,
97
+ attrs: { provider: "gcpsm", projectID: "demo-proj", keys: ["app-token"] },
98
+ },
99
+ { id: "outside:store:ClusterSecretStore/gcp", kind: "SecretStore", label: "ClusterSecretStore gcp", placeholder: true, attrs: { storeKind: "ClusterSecretStore", name: "gcp", read: true } },
100
+ ]);
101
+ expect(out.edges.map((e) => [e.from, e.to, e.viaAttr])).toEqual([
102
+ ["external-secrets.io/ClusterSecretStore//gcp", "outside:provider:gcpsm:demo-proj", "spec.provider.gcpsm"],
103
+ ["external-secrets.io/ExternalSecret/app/app-creds", "outside:store:ClusterSecretStore/gcp", "spec.secretStoreRef"],
104
+ ]);
105
+ expect(out.notes).toEqual([]);
106
+ });
107
+
108
+ it("collects the keys of every secret that uses the store, and dataFrom extract keys", () => {
109
+ const more = externalSecret("db", "app", { name: "gcp", kind: "ClusterSecretStore" }, ["db-pass"], { dataFrom: [{ extract: { key: "bulk" } }] });
110
+ const out = outsideRefs([GCP_STORE, es, more]);
111
+ expect(out.cards.find((c) => c.kind === "SecretProvider").attrs.keys).toEqual(["app-token", "bulk", "db-pass"]);
112
+ });
113
+
114
+ it("looks a SecretStore up in the secret's own namespace", () => {
115
+ const other = store("gcp", "elsewhere", { gcpsm: { projectID: "other-proj" } });
116
+ const ns = externalSecret("app-creds", "app", { name: "gcp" }, ["k"]);
117
+ const out = outsideRefs([other, ns]);
118
+ expect(out.cards.map((c) => c.id)).toEqual(["outside:provider:gcpsm:other-proj", "outside:store:SecretStore/app/gcp"]);
119
+ // the store in "elsewhere" is not the one "app" uses: its card says it was not read, and a note says why
120
+ expect(out.cards[1].attrs.read).toBe(false);
121
+ expect(out.notes.map((n) => n.code)).toEqual(["unresolved"]);
122
+ // and the key went nowhere
123
+ expect(out.cards[0].attrs.keys).toEqual([]);
124
+ });
125
+
126
+ it("reads AWS and Vault providers", () => {
127
+ const out = outsideRefs([
128
+ clusterStore("aws", { aws: { service: "SecretsManager", region: "eu-west-1" } }),
129
+ clusterStore("vault", { vault: { server: "https://vault.example.com", path: "secret" } }),
130
+ externalSecret("a", "app", { name: "aws", kind: "ClusterSecretStore" }, ["prod/db"]),
131
+ ]);
132
+ expect(out.cards.map((c) => [c.id, c.label])).toEqual([
133
+ ["outside:provider:aws:SecretsManager:eu-west-1", "AWS Secrets Manager eu-west-1"],
134
+ ["outside:provider:vault:https://vault.example.com/secret", "Vault https://vault.example.com/secret"],
135
+ ["outside:store:ClusterSecretStore/aws", "ClusterSecretStore aws"],
136
+ ]);
137
+ expect(out.cards[0].attrs.keys).toEqual(["prod/db"]);
138
+ });
139
+
140
+ it("drops a key the graph holds from the provider card, and the store card when the graph holds the store", () => {
141
+ const graph = {
142
+ nodes: [
143
+ tf("tf/google_secret_manager_secret.t", "google_secret_manager_secret", { secret_id: "app-token", project: "demo-proj" }),
144
+ { id: "k/gcp", kind: "K8s::Core::ClusterSecretStore", lexicon: "k8s", attrs: { kind: "ClusterSecretStore", metadata: { name: "gcp" } } },
145
+ ],
146
+ };
147
+ const out = outsideRefs([GCP_STORE, es, externalSecret("b", "app", { name: "gcp", kind: "ClusterSecretStore" }, ["other-token"])], { graph });
148
+ expect(out.cards.map((c) => c.id)).toEqual(["outside:provider:gcpsm:demo-proj"]);
149
+ expect(out.cards[0].attrs.keys).toEqual(["other-token"]);
150
+ expect(out.edges.map((e) => e.to)).toEqual(["outside:provider:gcpsm:demo-proj"]);
151
+ });
152
+
153
+ it("puts a provider with no rule and a dataFrom with no key in notes", () => {
154
+ const out = outsideRefs([
155
+ clusterStore("ibm", { ibm: { serviceUrl: "https://x" } }),
156
+ externalSecret("a", "app", { name: "ibm", kind: "ClusterSecretStore" }, [], { dataFrom: [{ find: { name: { regexp: "x" } } }] }),
157
+ ]);
158
+ expect(out.cards.map((c) => c.id)).toEqual(["outside:store:ClusterSecretStore/ibm"]);
159
+ expect(out.notes.map((n) => n.path).sort()).toEqual(["spec.dataFrom[0]", "spec.provider.ibm"]);
160
+ });
161
+
162
+ it("notes a masked secretStoreRef and names the ruling it waits on, joining nothing", () => {
163
+ // what chant's live read hands back: any key matching /secret/i is masked whole
164
+ const live = { ...externalSecret("app-creds", "app", "<masked>", ["app-token"]) };
165
+ live.spec.secretStoreRef = "<masked>";
166
+ const out = outsideRefs([GCP_STORE, live]);
167
+ expect(out.notes).toEqual([
168
+ {
169
+ code: "masked",
170
+ from: "external-secrets.io/ExternalSecret/app/app-creds",
171
+ path: "spec.secretStoreRef",
172
+ message: "the live read masked secretStoreRef, so the store and the keys cannot be joined",
173
+ waitsOn: "INTENTIUS/chant#5116",
174
+ },
175
+ ]);
176
+ // the store object still gives its provider card, with no keys
177
+ expect(out.cards.map((c) => [c.id, c.attrs.keys])).toEqual([["outside:provider:gcpsm:demo-proj", []]]);
178
+ });
179
+ });
180
+
181
+ describe("sources", () => {
182
+ const app = (name, spec) => ({ apiVersion: "argoproj.io/v1alpha1", kind: "Application", metadata: { name, namespace: "argocd" }, spec });
183
+
184
+ it("gives an Application source a card for the repo and path, and one per entry of sources", () => {
185
+ const out = outsideRefs([
186
+ app("one", { source: { repoURL: "https://GitHub.com/acme/infra.git", path: "./apps/web", targetRevision: "main" } }),
187
+ app("two", { sources: [{ repoURL: "https://charts.example.com", chart: "nginx" }, { repoURL: "https://github.com/acme/infra/", path: "apps/web" }] }),
188
+ ]);
189
+ expect(out.cards.map((c) => c.id)).toEqual(["outside:source:https://charts.example.com#chart=nginx", "outside:source:https://github.com/acme/infra#apps/web"]);
190
+ expect(out.cards[1].attrs).toEqual({ repoURL: "https://github.com/acme/infra", path: "apps/web" });
191
+ expect(out.edges.map((e) => [e.from, e.viaAttr, e.revision])).toEqual([
192
+ ["argoproj.io/Application/argocd/one", "spec.source", "main"],
193
+ ["argoproj.io/Application/argocd/two", "spec.sources[0]", undefined],
194
+ ["argoproj.io/Application/argocd/two", "spec.sources[1]", undefined],
195
+ ]);
196
+ });
197
+
198
+ it("notes an Application source with no repoURL", () => {
199
+ const out = outsideRefs([app("x", { source: { path: "a" } })]);
200
+ expect(out.cards).toEqual([]);
201
+ expect(out.notes[0]).toMatchObject({ code: "unrecognised", path: "spec.source.repoURL" });
202
+ });
203
+
204
+ it("takes a Kustomization's repo from its source object and its path from spec.path", () => {
205
+ const git = { apiVersion: "source.toolkit.fluxcd.io/v1", kind: "GitRepository", metadata: { name: "fleet", namespace: "flux-system" }, spec: { url: "ssh://git@github.com/acme/fleet.git" } };
206
+ const ks = { apiVersion: "kustomize.toolkit.fluxcd.io/v1", kind: "Kustomization", metadata: { name: "apps", namespace: "flux-system" }, spec: { path: "./clusters/prod", sourceRef: { kind: "GitRepository", name: "fleet" } } };
207
+ const out = outsideRefs([git, ks]);
208
+ expect(out.cards.map((c) => [c.id, c.attrs.sourceKind])).toEqual([["outside:source:ssh://git@github.com/acme/fleet#clusters/prod", "GitRepository"]]);
209
+ expect(out.edges[0]).toMatchObject({ from: "kustomize.toolkit.fluxcd.io/Kustomization/flux-system/apps", viaAttr: "spec.sourceRef" });
210
+ });
211
+
212
+ it("notes a Kustomization whose source object was not read", () => {
213
+ const ks = { apiVersion: "kustomize.toolkit.fluxcd.io/v1", kind: "Kustomization", metadata: { name: "apps", namespace: "flux-system" }, spec: { sourceRef: { kind: "GitRepository", name: "fleet" } } };
214
+ expect(outsideRefs([ks]).notes[0]).toMatchObject({ code: "unresolved", path: "spec.sourceRef" });
215
+ });
216
+
217
+ it("returns no card for a repo the graph holds", () => {
218
+ const graph = { nodes: [{ id: "g", kind: "github_repository", attrs: { clone_url: "https://github.com/acme/infra.git" } }] };
219
+ expect(outsideRefs([app("one", { source: { repoURL: "https://github.com/acme/infra", path: "x" } })], { graph }).cards).toEqual([]);
220
+ });
221
+
222
+ it("normalizes a URL the same whichever way it is written", () => {
223
+ expect(normalizeUrl("https://GitHub.com/acme/infra.git/")).toBe("https://github.com/acme/infra");
224
+ expect(normalizeUrl("git@github.com:acme/infra.git")).toBe("git@github.com:acme/infra");
225
+ });
226
+ });
227
+
228
+ describe("input shapes", () => {
229
+ it("opens a List and skips what it has no rule for", () => {
230
+ const list = { apiVersion: "v1", kind: "List", items: [sa("r", { "eks.amazonaws.com/role-arn": ARN }), { apiVersion: "apps/v1", kind: "Deployment", metadata: { name: "web" } }] };
231
+ expect(outsideRefs([list, null, "x"]).cards).toHaveLength(1);
232
+ });
233
+
234
+ it("gives the same answer whatever order the objects arrive in", () => {
235
+ const objs = [GCP_STORE, externalSecret("a", "app", { name: "gcp", kind: "ClusterSecretStore" }, ["k"]), sa("r", { "eks.amazonaws.com/role-arn": ARN })];
236
+ expect(outsideRefs([...objs].reverse())).toEqual(outsideRefs(objs));
237
+ });
238
+ });
239
+
240
+ describe("browser safety", () => {
241
+ it("imports nothing", () => {
242
+ const text = readFileSync(new URL("./outside-refs.js", import.meta.url), "utf8")
243
+ .split("\n")
244
+ .filter((l) => !l.trimStart().startsWith("//"))
245
+ .join("\n");
246
+ expect(text).not.toMatch(/(^|\n)\s*import\b/);
247
+ expect(text).not.toMatch(/\brequire\s*\(|\bnode:|\bprocess\./);
248
+ });
249
+ });
@@ -0,0 +1,245 @@
1
+ // behold#1036: an app made from a template, the way its owner thinks of it.
2
+ // GET /api/templates/apps (terragucci templates apps --json) names each app's
3
+ // root, its template and version, and its add-ons. An app and its add-ons are
4
+ // one root, planned and applied together (ruling C of INTENTIUS/chant#4642):
5
+ // `module "app"` is the app's template and each `module "<addon>"` an add-on.
6
+ // So on the graph their cards draw inside one frame, titled with the app's
7
+ // name and template, and the frame's header counts the cards terragucci's
8
+ // reports mark as drifted. The marks stay on the cards themselves.
9
+ //
10
+ // The app's inspect pane offers the requests that change it: Add an add-on
11
+ // (the Templates form, filtered to add-on templates, with the app set) and
12
+ // Upgrade to <version> when the catalog has a newer active version, which
13
+ // dispatches terragucci's rollout workflow. behold applies nothing. Neither
14
+ // button is drawn in a public view, an embed or a static export.
15
+ //
16
+ // behold#1037: the pane also lists the actions the app's templates offer
17
+ // (`actions` in the apps read), one button each, named by the action. A
18
+ // button dispatches terragucci's action workflow and nothing more: the run
19
+ // asks for an approval, the gate card below shows the digest, the waiting
20
+ // state and the `terragucci approve action` line for a person other than the
21
+ // one who asked, and the history lists each request, who approved it and how
22
+ // it ended. On a root whose engine has no action invocation (OpenTofu,
23
+ // choudoufu) the buttons stay, disabled, with the refusal beside them.
24
+ //
25
+ // Pure, apart from renderAppSection, which draws into the document it is handed.
26
+
27
+ import { laneActionCards } from "./terragucci-lifecycle.js";
28
+ import { laneRows } from "./terragucci-timeline.js";
29
+
30
+ /** The apps from the envelope GET /api/templates/apps answers, or []. */
31
+ export function appRows(answer) {
32
+ return (answer && Array.isArray(answer.results) && answer.results) || [];
33
+ }
34
+
35
+ /** A template's short name, as a request branch names it: `bucket` for `acme/bucket/aws`. */
36
+ export function templateShort(template) {
37
+ const parts = String(template || "").split("/").filter(Boolean);
38
+ return (parts.length >= 3 ? parts[parts.length - 2] : parts[parts.length - 1]) || String(template || "");
39
+ }
40
+
41
+ /** The frame's title: `orders (bucket 1.2.0)`. */
42
+ export function frameTitle(app) {
43
+ return `${app.app} (${templateShort(app.template)}${app.version ? ` ${app.version}` : ""})`;
44
+ }
45
+
46
+ /** The module calls of an app's root: `module.app` and each add-on's. */
47
+ export function appModules(app) {
48
+ return ["app", ...(app.addons || []).map((a) => a.name)].map((n) => `module.${n}`);
49
+ }
50
+
51
+ /**
52
+ * The card-id prefix of an app's root: `<member>/<root name>/`. The roots
53
+ * table (/api/terragucci's `roots`, each `{member, name, path}`) names it when
54
+ * there is one; else a card whose `attrs.root` is the root's last path
55
+ * segment, or its path with `-` for `/`, as behold names a root it discovers.
56
+ */
57
+ export function rootPrefix(app, roots, nodes) {
58
+ const hit = (roots || []).find((r) => r.path === app.root);
59
+ if (hit) return `${hit.member}/${hit.name}/`;
60
+ const names = [app.root.split("/").pop(), app.root.split("/").join("-")];
61
+ for (const n of nodes || []) {
62
+ const root = n.attrs && n.attrs.root;
63
+ if (typeof root !== "string" || !names.includes(root)) continue;
64
+ const at = n.id.indexOf(`/${root}/`);
65
+ if (at >= 0) return n.id.slice(0, at + root.length + 2);
66
+ }
67
+ return null;
68
+ }
69
+
70
+ /** Whether a card mark says drift. */
71
+ const drifted = (marks) => (marks || []).some((m) => m.verdict === "drift");
72
+
73
+ /**
74
+ * One frame per app whose cards are on the graph: the app, its title, the
75
+ * card ids of `module.app` and its add-ons, how many of them carry a drift
76
+ * mark (`cards` is /api/terragucci's marks by card id), and the header's
77
+ * words. An app none of whose cards is drawn gets no frame.
78
+ */
79
+ export function appFrames(apps, nodes, { roots = [], cards = {} } = {}) {
80
+ const out = [];
81
+ for (const app of apps || []) {
82
+ const prefix = rootPrefix(app, roots, nodes);
83
+ if (!prefix) continue;
84
+ const modules = appModules(app);
85
+ const ids = (nodes || [])
86
+ .map((n) => n.id)
87
+ .filter((id) => id.startsWith(prefix) && modules.some((m) => id.slice(prefix.length) === m || id.slice(prefix.length).startsWith(`${m}/`)));
88
+ if (!ids.length) continue;
89
+ const drift = ids.filter((id) => drifted(cards[id])).length;
90
+ const title = frameTitle(app);
91
+ out.push({ app, title, prefix, ids, drifted: drift, header: drift ? `${title} · ${drift} drifted` : title, ...(drift ? { drift: `${drift} drifted` } : {}) });
92
+ }
93
+ return out;
94
+ }
95
+
96
+ /** The frame a card is in, or null. */
97
+ export function frameOf(frames, id) {
98
+ return (frames || []).find((f) => f.ids.includes(id)) || null;
99
+ }
100
+
101
+ /**
102
+ * The buttons an app's inspect pane draws, in order: Add an add-on, then
103
+ * Upgrade to <version> when the catalog offers one, then one per action the
104
+ * app's templates offer (behold#1037). None in a public view, an embed or a
105
+ * static export. Each is `{id, label, title}`, plus what its request sends.
106
+ * With `actionRefusal` (ruling E) an action button is `disabled` and its
107
+ * title is the refusal.
108
+ */
109
+ export function appButtons(app, { publicMode = false, embed = false, staticMode = false, actionRefusal = null } = {}) {
110
+ if (publicMode || embed || staticMode || !app) return [];
111
+ const out = [{ id: "addon", label: "Add an add-on", title: `Open the Templates form with only add-on templates, for ${app.app}. terragucci opens the pull request that adds the add-on to ${app.root}.` }];
112
+ if (typeof app.upgrade === "string" && app.upgrade) {
113
+ out.push({
114
+ id: "upgrade",
115
+ label: `Upgrade to ${app.upgrade}`,
116
+ title: `Start the rollout of ${app.template} ${app.upgrade}: terragucci opens one pull request per wave, and every app on ${templateShort(app.template)} moves with it. Each wave is planned, reviewed and applied by the pipeline.`,
117
+ body: { app: app.app, version: app.upgrade },
118
+ });
119
+ }
120
+ for (const a of app.actions || []) {
121
+ if (!a || typeof a.address !== "string") continue;
122
+ const name = a.name || a.address.split(".").pop();
123
+ out.push({
124
+ id: "action",
125
+ label: name,
126
+ title: actionRefusal
127
+ ? actionRefusal
128
+ : `Ask terragucci to run ${name} (${a.address}) on ${app.root}. The run asks for an approval; a person other than you approves it with terragucci approve action, and only then does it run. behold approves nothing.`,
129
+ body: { root: app.root, address: a.address },
130
+ ...(actionRefusal ? { disabled: true } : {}),
131
+ });
132
+ }
133
+ return out;
134
+ }
135
+
136
+ /** What the pane says once an action button was pressed: the POST's answer, or a refusal's code and words. */
137
+ export function actionWords(answer) {
138
+ if (!answer) return { text: "" };
139
+ if (answer.error) return { text: `${answer.code ? `${answer.code}: ` : ""}${answer.error}${answer.command ? ` Run: ${answer.command}` : ""}`, refused: true };
140
+ return { text: `${answer.action} asked for on ${answer.root}: terragucci's run asks for an approval, and the gate card shows its digest and the line a person other than you runs.` };
141
+ }
142
+
143
+ /** The app root's action gate cards and action history: `lane` is /api/terragucci/lifecycle, `timeline` /api/terragucci/timeline. */
144
+ export function appActions(app, { lane = null, timeline = null, now = new Date() } = {}) {
145
+ const cards = laneActionCards(lane, now, { root: app.root });
146
+ const history = timeline && Array.isArray(timeline.entries) ? laneRows({ ...timeline, entries: timeline.entries.filter((e) => e.kind === "action" || e.kind === "action-requested") }, { root: app.root, now }) : [];
147
+ return { cards, history };
148
+ }
149
+
150
+ /** The app's facts, one line each: template and version, add-ons, drift, a yanked pin. */
151
+ export function appFacts(frame) {
152
+ const a = frame.app;
153
+ const lines = [`${a.template} ${a.version || "unpinned"}${a.yanked ? " (yanked)" : ""} · ${a.root}`];
154
+ const addons = (a.addons || []).map((x) => `${x.name} (${templateShort(x.template)}${x.version ? ` ${x.version}` : ""})`);
155
+ lines.push(addons.length ? `add-ons: ${addons.join(", ")}` : "no add-ons");
156
+ if (frame.drifted) lines.push(`${frame.drifted} card${frame.drifted === 1 ? "" : "s"} drifted, from terragucci's reports`);
157
+ return lines;
158
+ }
159
+
160
+ /** What the pane says once Upgrade was pressed: the POST's answer, or a refusal's code and words. */
161
+ export function upgradeWords(answer) {
162
+ if (!answer) return { text: "" };
163
+ if (answer.error) return { text: `${answer.code ? `${answer.code}: ` : ""}${answer.error}${answer.command ? ` Run: ${answer.command}` : ""}`, refused: true };
164
+ return { text: `Upgrade started: terragucci opens the first wave's pull request for ${answer.template} ${answer.version}, and the rollout carries the rest wave by wave.` };
165
+ }
166
+
167
+ /**
168
+ * Draw the app's part of the inspect pane into `host`: its title, facts and
169
+ * buttons. `ui.addAddon(app)` and `ui.upgrade(app, body)` are what the buttons
170
+ * call; `said` is the last upgrade's answer, for its words. `doc` is the
171
+ * document (a test hands in its own).
172
+ */
173
+ export function renderAppSection(host, frame, ui, opts = {}, doc = document) {
174
+ const el = (tag, cls, text) => {
175
+ const n = doc.createElement(tag);
176
+ if (cls) n.className = cls;
177
+ if (text !== undefined) n.textContent = text;
178
+ return n;
179
+ };
180
+ const box = el("section", "tpl-app");
181
+ box.appendChild(el("h3", null, `app ${frame.title}`));
182
+ for (const line of appFacts(frame)) box.appendChild(el("p", "tpl-app-fact", line));
183
+ const buttons = appButtons(frame.app, opts);
184
+ if (buttons.length) {
185
+ const row = el("div", "tpl-app-buttons");
186
+ for (const b of buttons) {
187
+ const n = el("button", `tpl-app-${b.id}`, b.label);
188
+ n.type = "button";
189
+ n.title = b.title;
190
+ if (b.disabled) n.disabled = true;
191
+ n.setAttribute("data-action", b.id);
192
+ n.addEventListener("click", () => {
193
+ if (b.id === "addon") ui.addAddon(frame.app);
194
+ else if (b.id === "upgrade") ui.upgrade(frame.app, b.body);
195
+ else if (ui.action) ui.action(frame.app, b);
196
+ });
197
+ row.appendChild(n);
198
+ }
199
+ box.appendChild(row);
200
+ }
201
+ const words = upgradeWords(opts.said);
202
+ if (words.text) box.appendChild(el("p", words.refused ? "tg-refusal tpl-app-result" : "tg-legend tpl-app-result", words.text));
203
+ // behold#1037: ruling E said beside the buttons, then what the last action press answered.
204
+ if (opts.actionRefusal && buttons.some((b) => b.id === "action")) box.appendChild(el("p", "tg-refusal tpl-app-action-refusal", opts.actionRefusal));
205
+ const asked = actionWords(opts.actionSaid);
206
+ if (asked.text) box.appendChild(el("p", asked.refused ? "tg-refusal tpl-app-result" : "tg-legend tpl-app-result", asked.text));
207
+ // The action gate cards and the action history for this app's root.
208
+ if (!opts.publicMode && !opts.embed && !opts.staticMode && (opts.lane || opts.timeline)) {
209
+ const { cards, history } = appActions(frame.app, { lane: opts.lane, timeline: opts.timeline, now: opts.now || new Date() });
210
+ if (cards.length && ui.gateCard) {
211
+ box.appendChild(el("h4", null, "actions waiting or run"));
212
+ for (const c of cards) box.appendChild(ui.gateCard(c));
213
+ }
214
+ if (history.length) {
215
+ box.appendChild(el("h4", null, "action history"));
216
+ for (const r of history) {
217
+ const p = el("p", `tg-entry tg-${r.tone} tpl-app-history`);
218
+ p.title = r.title;
219
+ p.appendChild(el("span", "tg-when", r.when));
220
+ p.appendChild(el("span", null, ` ${r.text}`));
221
+ for (const l of r.links) {
222
+ const a = el("a", null, l.text);
223
+ a.href = l.href;
224
+ a.target = "_blank";
225
+ a.rel = "noopener";
226
+ p.appendChild(el("span", null, " · "));
227
+ p.appendChild(a);
228
+ }
229
+ box.appendChild(p);
230
+ }
231
+ }
232
+ }
233
+ host.appendChild(box);
234
+ return box;
235
+ }
236
+
237
+ /** Press an action button: POST /api/templates/action with the root and address. `fetchJson(url, init)` answers parsed JSON. */
238
+ export function postAction(fetchJson, body) {
239
+ return fetchJson("/api/templates/action", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).catch((e) => ({ error: String(e) }));
240
+ }
241
+
242
+ /** Press Upgrade: POST /api/templates/upgrade with the app and the version the pane showed. `fetchJson(url, init)` answers parsed JSON. */
243
+ export function postUpgrade(fetchJson, body) {
244
+ return fetchJson("/api/templates/upgrade", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).catch((e) => ({ error: String(e) }));
245
+ }