@intentius/chant 0.124.96 → 0.124.98

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 (237) hide show
  1. package/dist/audit/core.d.ts +29 -0
  2. package/dist/audit/core.d.ts.map +1 -1
  3. package/dist/audit/core.js +48 -11
  4. package/dist/audit/identity.d.ts +27 -0
  5. package/dist/audit/identity.d.ts.map +1 -0
  6. package/dist/audit/identity.js +36 -0
  7. package/dist/audit/report-html.d.ts +3 -1
  8. package/dist/audit/report-html.d.ts.map +1 -1
  9. package/dist/audit/report-html.js +1 -1
  10. package/dist/audit/report-model.d.ts +16 -0
  11. package/dist/audit/report-model.d.ts.map +1 -1
  12. package/dist/audit/report-model.js +5 -1
  13. package/dist/change-set-graph.d.ts +3 -1
  14. package/dist/change-set-graph.d.ts.map +1 -1
  15. package/dist/change-set-graph.js +7 -1
  16. package/dist/change-set.d.ts +5 -2
  17. package/dist/change-set.d.ts.map +1 -1
  18. package/dist/change-set.js +6 -3
  19. package/dist/ci-agent.d.ts +17 -0
  20. package/dist/ci-agent.d.ts.map +1 -1
  21. package/dist/ci-agent.js +32 -0
  22. package/dist/ci-comment-allow.d.ts +88 -0
  23. package/dist/ci-comment-allow.d.ts.map +1 -0
  24. package/dist/ci-comment-allow.js +178 -0
  25. package/dist/ci-comment-commands.d.ts +12 -0
  26. package/dist/ci-comment-commands.d.ts.map +1 -1
  27. package/dist/ci-comment-commands.js +22 -0
  28. package/dist/ci-control.d.ts +6 -1
  29. package/dist/ci-control.d.ts.map +1 -1
  30. package/dist/ci-control.js +6 -1
  31. package/dist/ci-product.d.ts +3 -0
  32. package/dist/ci-product.d.ts.map +1 -1
  33. package/dist/ci-product.js +3 -0
  34. package/dist/cli/commands/audit.d.ts +3 -1
  35. package/dist/cli/commands/audit.d.ts.map +1 -1
  36. package/dist/cli/commands/audit.js +23 -6
  37. package/dist/cli/commands/import.d.ts +8 -1
  38. package/dist/cli/commands/import.d.ts.map +1 -1
  39. package/dist/cli/commands/import.js +31 -6
  40. package/dist/cli/handlers/agent.d.ts.map +1 -1
  41. package/dist/cli/handlers/agent.js +12 -2
  42. package/dist/cli/handlers/pr-comment.d.ts +6 -0
  43. package/dist/cli/handlers/pr-comment.d.ts.map +1 -1
  44. package/dist/cli/handlers/pr-comment.js +12 -0
  45. package/dist/cli/handlers/promote.d.ts.map +1 -1
  46. package/dist/cli/handlers/promote.js +53 -6
  47. package/dist/cli/main.d.ts.map +1 -1
  48. package/dist/cli/main.js +29 -6
  49. package/dist/cli/parse-args.d.ts.map +1 -1
  50. package/dist/cli/parse-args.js +23 -0
  51. package/dist/cli/registry.d.ts +8 -0
  52. package/dist/cli/registry.d.ts.map +1 -1
  53. package/dist/cloud-lister/mask.d.ts +30 -1
  54. package/dist/cloud-lister/mask.d.ts.map +1 -1
  55. package/dist/cloud-lister/mask.js +66 -3
  56. package/dist/components/driver.d.ts +8 -1
  57. package/dist/components/driver.d.ts.map +1 -1
  58. package/dist/components/driver.js +1 -0
  59. package/dist/components/product-pipeline.d.ts +23 -1
  60. package/dist/components/product-pipeline.d.ts.map +1 -1
  61. package/dist/components/product-pipeline.js +40 -7
  62. package/dist/components/product-plan.d.ts +20 -0
  63. package/dist/components/product-plan.d.ts.map +1 -1
  64. package/dist/components/product-plan.js +11 -1
  65. package/dist/control/applied.d.ts +8 -1
  66. package/dist/control/applied.d.ts.map +1 -1
  67. package/dist/control/applied.js +18 -2
  68. package/dist/control/dispatch.d.ts +52 -0
  69. package/dist/control/dispatch.d.ts.map +1 -1
  70. package/dist/control/dispatch.js +140 -4
  71. package/dist/control/train.d.ts +198 -0
  72. package/dist/control/train.d.ts.map +1 -0
  73. package/dist/control/train.js +294 -0
  74. package/dist/deep-observation.js +2 -2
  75. package/dist/floor-table.data.d.ts.map +1 -1
  76. package/dist/floor-table.data.js +7 -1
  77. package/dist/graph-detail.d.ts +9 -0
  78. package/dist/graph-detail.d.ts.map +1 -1
  79. package/dist/graph-detail.js +38 -13
  80. package/dist/graph-refs.d.ts +233 -3
  81. package/dist/graph-refs.d.ts.map +1 -1
  82. package/dist/graph-refs.js +106 -15
  83. package/dist/lint/post-synth.d.ts +22 -0
  84. package/dist/lint/post-synth.d.ts.map +1 -1
  85. package/dist/lint/rules/declarable-naming-convention.d.ts +12 -0
  86. package/dist/lint/rules/declarable-naming-convention.d.ts.map +1 -1
  87. package/dist/lint/rules/declarable-naming-convention.js +38 -8
  88. package/dist/lint/rules/imported-source.d.ts +20 -0
  89. package/dist/lint/rules/imported-source.d.ts.map +1 -0
  90. package/dist/lint/rules/imported-source.js +27 -0
  91. package/dist/lint/rules/no-unused-declarable.d.ts.map +1 -1
  92. package/dist/lint/rules/no-unused-declarable.js +3 -0
  93. package/dist/op/gate.d.ts +2 -0
  94. package/dist/op/gate.d.ts.map +1 -1
  95. package/dist/op/gate.js +8 -1
  96. package/dist/pr-forge-reads.d.ts +17 -0
  97. package/dist/pr-forge-reads.d.ts.map +1 -1
  98. package/dist/pr-forge-reads.js +55 -0
  99. package/dist/reconcile.d.ts +9 -0
  100. package/dist/reconcile.d.ts.map +1 -1
  101. package/dist/release-floors.d.ts +9 -1
  102. package/dist/release-floors.d.ts.map +1 -1
  103. package/dist/release-floors.js +10 -2
  104. package/dist/repo-path.d.ts +29 -0
  105. package/dist/repo-path.d.ts.map +1 -0
  106. package/dist/repo-path.js +81 -0
  107. package/dist/sensitive-key.d.ts +23 -0
  108. package/dist/sensitive-key.d.ts.map +1 -1
  109. package/dist/sensitive-key.js +37 -0
  110. package/dist/terraform/hcl2json.d.ts +7 -0
  111. package/dist/terraform/hcl2json.d.ts.map +1 -1
  112. package/dist/terraform/hcl2json.js +7 -0
  113. package/dist/wave-runtime.mjs +352 -345
  114. package/dist/workspace/catalog-edges.d.ts +147 -0
  115. package/dist/workspace/catalog-edges.d.ts.map +1 -0
  116. package/dist/workspace/catalog-edges.js +461 -0
  117. package/dist/workspace/compose-graph.d.ts +73 -3
  118. package/dist/workspace/compose-graph.d.ts.map +1 -1
  119. package/dist/workspace/declaration.d.ts +2 -0
  120. package/dist/workspace/declaration.d.ts.map +1 -1
  121. package/dist/workspace/declaration.js +1 -0
  122. package/dist/workspace/declaration.schema.json +6 -0
  123. package/dist/workspace/discover.d.ts +134 -0
  124. package/dist/workspace/discover.d.ts.map +1 -0
  125. package/dist/workspace/discover.js +372 -0
  126. package/dist/workspace/graph-cli.d.ts +20 -0
  127. package/dist/workspace/graph-cli.d.ts.map +1 -1
  128. package/dist/workspace/graph-cli.js +178 -20
  129. package/dist/workspace/graph.schema.json +195 -2
  130. package/dist/workspace/release-train.d.ts +214 -3
  131. package/dist/workspace/release-train.d.ts.map +1 -1
  132. package/dist/workspace/release-train.js +552 -16
  133. package/dist/workspace/repo-ref.d.ts +14 -0
  134. package/dist/workspace/repo-ref.d.ts.map +1 -1
  135. package/dist/workspace/repo-ref.js +26 -1
  136. package/dist/workspace/workspace-gates.d.ts +24 -0
  137. package/dist/workspace/workspace-gates.d.ts.map +1 -1
  138. package/dist/workspace/workspace-gates.js +29 -5
  139. package/dist/workspace/workspace-ledger.d.ts +31 -5
  140. package/dist/workspace/workspace-ledger.d.ts.map +1 -1
  141. package/dist/workspace/workspace-ledger.js +2 -1
  142. package/dist/workspace/workspace-run.d.ts +14 -0
  143. package/dist/workspace/workspace-run.d.ts.map +1 -1
  144. package/dist/workspace/workspace-run.js +2 -2
  145. package/dist/yaml.d.ts.map +1 -1
  146. package/dist/yaml.js +33 -8
  147. package/package.json +1 -1
  148. package/src/audit/core.test.ts +64 -1
  149. package/src/audit/core.ts +75 -10
  150. package/src/audit/identity.test.ts +31 -0
  151. package/src/audit/identity.ts +43 -0
  152. package/src/audit/report-html.ts +4 -2
  153. package/src/audit/report-model.ts +21 -1
  154. package/src/change-set-graph.test.ts +33 -1
  155. package/src/change-set-graph.ts +7 -1
  156. package/src/change-set.ts +6 -3
  157. package/src/ci-agent.test.ts +32 -0
  158. package/src/ci-agent.ts +42 -0
  159. package/src/ci-comment-allow.test.ts +380 -0
  160. package/src/ci-comment-allow.ts +184 -0
  161. package/src/ci-comment-commands.ts +25 -0
  162. package/src/ci-control.ts +42 -0
  163. package/src/ci-product.ts +3 -0
  164. package/src/cli/commands/audit-parser-notice.test.ts +74 -0
  165. package/src/cli/commands/audit.test.ts +12 -0
  166. package/src/cli/commands/audit.ts +25 -7
  167. package/src/cli/commands/import-layout.test.ts +2 -1
  168. package/src/cli/commands/import.ts +29 -6
  169. package/src/cli/handlers/agent.ts +13 -2
  170. package/src/cli/handlers/pr-before-merge.test.ts +18 -0
  171. package/src/cli/handlers/pr-comment.ts +12 -0
  172. package/src/cli/handlers/promote.test.ts +68 -0
  173. package/src/cli/handlers/promote.ts +52 -6
  174. package/src/cli/main.test.ts +5 -0
  175. package/src/cli/main.ts +29 -6
  176. package/src/cli/parse-args.ts +18 -0
  177. package/src/cli/registry.ts +8 -0
  178. package/src/cloud-lister/kubernetes.k3d.e2e.test.ts +104 -0
  179. package/src/cloud-lister/mask-references.test.ts +132 -0
  180. package/src/cloud-lister/mask.ts +68 -3
  181. package/src/components/driver.ts +9 -1
  182. package/src/components/product-pipeline.ts +57 -7
  183. package/src/components/product-plan.ts +27 -2
  184. package/src/control/applied.ts +33 -3
  185. package/src/control/dispatch.ts +156 -5
  186. package/src/control/train.test.ts +215 -0
  187. package/src/control/train.ts +413 -0
  188. package/src/deep-observation.ts +2 -2
  189. package/src/floor-table.data.ts +7 -1
  190. package/src/graph-detail.ts +37 -12
  191. package/src/graph-refs.test.ts +45 -1
  192. package/src/graph-refs.ts +321 -14
  193. package/src/lint/post-synth.ts +20 -0
  194. package/src/lint/rules/declarable-naming-convention.test.ts +35 -1
  195. package/src/lint/rules/declarable-naming-convention.ts +35 -8
  196. package/src/lint/rules/imported-source.test.ts +22 -0
  197. package/src/lint/rules/imported-source.ts +31 -0
  198. package/src/lint/rules/no-unused-declarable.test.ts +16 -0
  199. package/src/lint/rules/no-unused-declarable.ts +7 -0
  200. package/src/op/gate.ts +10 -2
  201. package/src/pr-forge-reads.ts +62 -0
  202. package/src/reconcile.ts +9 -0
  203. package/src/release-floors.ts +14 -2
  204. package/src/repo-path.test.ts +72 -0
  205. package/src/repo-path.ts +103 -0
  206. package/src/sensitive-key.ts +38 -0
  207. package/src/terraform/hcl2json.ts +8 -0
  208. package/src/workspace/application-set.e2e.test.ts +405 -0
  209. package/src/workspace/catalog-edges.ts +507 -0
  210. package/src/workspace/ci-green-workflow.test.ts +2 -2
  211. package/src/workspace/cluster-join.e2e.test.ts +150 -0
  212. package/src/workspace/compose-graph.ts +74 -5
  213. package/src/workspace/declaration.schema.json +6 -0
  214. package/src/workspace/declaration.ts +3 -0
  215. package/src/workspace/discover.e2e.test.ts +122 -0
  216. package/src/workspace/discover.test.ts +225 -0
  217. package/src/workspace/discover.ts +406 -0
  218. package/src/workspace/drift-reader.test.ts +3 -3
  219. package/src/workspace/external-secret-catalog.e2e.test.ts +98 -0
  220. package/src/workspace/external-secret-catalog.test.ts +142 -0
  221. package/src/workspace/graph-cli.ts +207 -21
  222. package/src/workspace/graph-contract.test.ts +92 -0
  223. package/src/workspace/graph.schema.json +195 -2
  224. package/src/workspace/helm-references.e2e.test.ts +135 -0
  225. package/src/workspace/identity-annotation-catalog.e2e.test.ts +91 -0
  226. package/src/workspace/identity-annotation-catalog.test.ts +139 -0
  227. package/src/workspace/release-train-repos.test.ts +304 -0
  228. package/src/workspace/release-train.test.ts +296 -0
  229. package/src/workspace/release-train.ts +631 -16
  230. package/src/workspace/repo-ref.ts +26 -1
  231. package/src/workspace/runs-on.test.ts +45 -0
  232. package/src/workspace/workspace-gates.ts +48 -5
  233. package/src/workspace/workspace-ledger.ts +28 -5
  234. package/src/workspace/workspace-run.test.ts +1 -1
  235. package/src/workspace/workspace-run.ts +2 -2
  236. package/src/yaml.test.ts +96 -8
  237. package/src/yaml.ts +36 -8
@@ -0,0 +1,406 @@
1
+ /**
2
+ * `chant workspace graph <dir> --discover` (#5095): the graph of a directory
3
+ * that has no `chant.workspace.json`, read as if a declaration listed what
4
+ * the kinds' probes find there. Nothing is written inside the directory.
5
+ *
6
+ * The walk visits every directory under `<dir>`, leaving out `node_modules`
7
+ * and directories whose names start with a dot (`.git` among them), and
8
+ * resolves each with {@link resolveKind}, by probe and precedence. What it
9
+ * finds becomes a declaration held in memory, which {@link discoveredTree}
10
+ * lays over the files as `chant.workspace.json` at the root. The read then
11
+ * goes through the same path as a declared one: the same plan, reader
12
+ * projects, member cache and composition.
13
+ *
14
+ * A claimed directory is a member unless one of these holds, and each case is
15
+ * listed in `discovered` with its outcome:
16
+ *
17
+ * - `tie`: two or more kinds share the highest precedence. It is not read.
18
+ * - `module`: a `.tf` file under `<dir>` calls it through a local `source`
19
+ * (`./` or `../`) in a `module` block, so it is a module, read with the root
20
+ * that calls it.
21
+ * - `inside-member`: it sits inside another member's directory. Members don't
22
+ * nest (#2524 D2), except inside the root member `.`.
23
+ *
24
+ * Kinds come from the built-in kinds and from the `@intentius` packages that
25
+ * publish a `./workspace-kinds` file and are installed beside the running
26
+ * chant ({@link discoveryKinds}). A `node_modules` inside `<dir>` supplies
27
+ * none, so discovering a directory loads no package it carries.
28
+ *
29
+ * A member's name comes from its path relative to `<dir>`
30
+ * ({@link discoveredMemberNames}), so it stays the same across revisions.
31
+ */
32
+
33
+ import { createHash } from "node:crypto";
34
+ import { lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
35
+ import { basename, dirname, join, posix, relative, resolve } from "node:path";
36
+ import { CHANT_INSTALL, dataExportTarget } from "./class-data";
37
+ import { DECLARATION_FILES, isInside, WorkspaceReadError } from "./declaration";
38
+ import { createKindRegistry, KINDS_SUBPATH, readPackageKinds, resolveKind, type KindProbe, type KindRegistry, type MemberKind } from "./kinds";
39
+ import { gitTop, gitTree, joinPath, resolveCommit, skippedDir, workingTree, type WorkspaceTree } from "./tree";
40
+ import type { LocatedWorkspace } from "./which-chant";
41
+
42
+ /** What became of one claimed directory. */
43
+ export type DiscoveryOutcome = "member" | "tie" | "module" | "inside-member";
44
+
45
+ /** One directory a kind's probe claims: an entry of the graph document's `discovered` list. */
46
+ export interface DiscoveredEntry {
47
+ /** Relative to `<dir>`, with `/` separators; `"."` for `<dir>` itself. */
48
+ dir: string;
49
+ /** The member's name when `outcome` is `member`, else null. */
50
+ member: string | null;
51
+ /** The kind the precedence order picks; null for a tie. */
52
+ kind: string | null;
53
+ /** Where that kind comes from: `builtin`, or the package that supplies it; null for a tie. */
54
+ source: string | null;
55
+ /** That kind's probe, as its kinds file states it; null for a tie. */
56
+ probe: KindProbe | null;
57
+ outcome: DiscoveryOutcome;
58
+ /** Every kind whose probe claims the directory, highest precedence first. */
59
+ claims: { kind: string; precedence: number; source: string }[];
60
+ /** Why the directory is not a member, in one line; null for a member. */
61
+ note: string | null;
62
+ }
63
+
64
+ /** A package beside the running chant that supplies member kinds. */
65
+ export interface KindPackage {
66
+ package: string;
67
+ version: string;
68
+ dir: string;
69
+ }
70
+
71
+ /** The kinds a discovery reads with, and the packages they came from. */
72
+ export interface DiscoveryKinds {
73
+ registry: KindRegistry;
74
+ packages: KindPackage[];
75
+ /** Why a package's kinds couldn't be used, one line each. */
76
+ problems: string[];
77
+ }
78
+
79
+ /** Paths are kept with `/`, as a tree's are. */
80
+ const toPosix = (p: string) => p.split("\\").join("/");
81
+
82
+ /**
83
+ * Every `@intentius` package that publishes `./workspace-kinds`, found the way
84
+ * Node resolves a bare import from `from`: in `node_modules/@intentius` of
85
+ * `from` and each directory above it, the nearest copy of a name winning.
86
+ * Sorted by name.
87
+ */
88
+ export function kindPackagesBeside(from: string = CHANT_INSTALL): KindPackage[] {
89
+ const found = new Map<string, KindPackage>();
90
+ for (let at = resolve(from); ; at = dirname(at)) {
91
+ const scope = join(at, "node_modules", "@intentius");
92
+ let names: string[] = [];
93
+ try {
94
+ names = readdirSync(scope);
95
+ } catch {
96
+ // No scope here.
97
+ }
98
+ for (const n of names.sort()) {
99
+ const dir = join(scope, n);
100
+ try {
101
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8")) as Record<string, unknown>;
102
+ if (typeof pkg.name !== "string" || typeof pkg.version !== "string" || found.has(pkg.name)) continue;
103
+ if (typeof dataExportTarget(pkg, KINDS_SUBPATH) !== "string") continue;
104
+ found.set(pkg.name, { package: pkg.name, version: pkg.version, dir });
105
+ } catch {
106
+ // Not a package, or not readable: it supplies nothing.
107
+ }
108
+ }
109
+ if (dirname(at) === at) break;
110
+ }
111
+ return [...found.values()].sort((a, b) => (a.package < b.package ? -1 : 1));
112
+ }
113
+
114
+ /**
115
+ * The registry a discovery reads with: the built-in kinds and every kind the
116
+ * packages beside the running chant supply. A name two packages both supply
117
+ * is left out, as `loadKindRegistry` leaves it out. Never throws.
118
+ */
119
+ export function discoveryKinds(from: string = CHANT_INSTALL): DiscoveryKinds {
120
+ const packages = kindPackagesBeside(from);
121
+ const problems: string[] = [];
122
+ const owner = new Map<string, string>();
123
+ const clashing = new Set<string>();
124
+ const extra: MemberKind[] = [];
125
+ for (const p of packages) {
126
+ const read = readPackageKinds(p.dir, p.package);
127
+ problems.push(...read.problems);
128
+ for (const k of read.kinds) {
129
+ const first = owner.get(k.name);
130
+ if (first) {
131
+ clashing.add(k.name);
132
+ problems.push(`kind ${k.name} is supplied by both ${first} and ${p.package}; a kind name has one source`);
133
+ continue;
134
+ }
135
+ owner.set(k.name, p.package);
136
+ extra.push(k);
137
+ }
138
+ }
139
+ return { registry: createKindRegistry(extra.filter((k) => !clashing.has(k.name))), packages, problems };
140
+ }
141
+
142
+ /** Text with HCL comments removed and string contents kept, so a brace in a comment doesn't count. */
143
+ function withoutComments(text: string): string {
144
+ let out = "";
145
+ for (let i = 0; i < text.length; i++) {
146
+ const c = text[i];
147
+ if (c === '"') {
148
+ const start = i;
149
+ for (i++; i < text.length && text[i] !== '"' && text[i] !== "\n"; i++) if (text[i] === "\\") i++;
150
+ out += text.slice(start, i + 1);
151
+ } else if (c === "#" || (c === "/" && text[i + 1] === "/")) {
152
+ while (i < text.length && text[i] !== "\n") i++;
153
+ out += "\n";
154
+ } else if (c === "/" && text[i + 1] === "*") {
155
+ const end = text.indexOf("*/", i + 2);
156
+ i = end < 0 ? text.length : end + 1;
157
+ out += " ";
158
+ } else {
159
+ out += c;
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+
165
+ /**
166
+ * The local `source` of every `module` block in HCL `text`: the ones that
167
+ * start with `./` or `../`, as written. A registry or git source is not
168
+ * local. HCL is not parsed: a `module "<name>" {` opener is found, its body
169
+ * runs to the matching brace, and `source = "<path>"` is read at the body's
170
+ * own level.
171
+ */
172
+ export function localModuleSources(text: string): string[] {
173
+ const src = withoutComments(text);
174
+ const out: string[] = [];
175
+ const opener = /(^|\n)\s*module\s+"[^"\n]*"\s*\{/g;
176
+ for (let m = opener.exec(src); m; m = opener.exec(src)) {
177
+ let depth = 1;
178
+ let i = m.index + m[0].length;
179
+ let body = "";
180
+ for (; i < src.length && depth > 0; i++) {
181
+ const c = src[i];
182
+ if (c === '"') {
183
+ const start = i;
184
+ for (i++; i < src.length && src[i] !== '"' && src[i] !== "\n"; i++) if (src[i] === "\\") i++;
185
+ if (depth === 1) body += src.slice(start, i + 1);
186
+ continue;
187
+ }
188
+ if (c === "{") depth++;
189
+ else if (c === "}") depth--;
190
+ if (depth === 1 && c !== "}") body += c;
191
+ }
192
+ const source = /(?:^|\n)\s*source\s*=\s*"([^"\n]*)"/.exec(body)?.[1];
193
+ if (source && (source.startsWith("./") || source.startsWith("../"))) out.push(source);
194
+ opener.lastIndex = i;
195
+ }
196
+ return out;
197
+ }
198
+
199
+ /** Lowercase letters, digits and hyphens, as a member name allows. */
200
+ function nameOf(dir: string): string {
201
+ return (
202
+ dir
203
+ .toLowerCase()
204
+ .replace(/[^a-z0-9]+/g, "-")
205
+ .replace(/^-+|-+$/g, "") || "member"
206
+ );
207
+ }
208
+
209
+ const NAME_MAX = 40;
210
+
211
+ function hashed(dir: string, base: string, length = 6): string {
212
+ const digest = createHash("sha256").update(dir).digest("hex").slice(0, length);
213
+ return `${base.slice(0, NAME_MAX - length - 1).replace(/-+$/, "")}-${digest}`;
214
+ }
215
+
216
+ /**
217
+ * A member name for each directory, from its path relative to `<dir>`. Every
218
+ * run of characters a name can't hold, `/` among them, becomes one `-`, and
219
+ * letters are lowercased: `infra/net` is `infra-net`. `.` is `root`. A name
220
+ * longer than 40 characters, or one that two directories would share, keeps
221
+ * its first characters and ends in `-` and six hex digits of the SHA-256 of
222
+ * the path, so it still depends on the path alone.
223
+ */
224
+ export function discoveredMemberNames(dirs: readonly string[]): Map<string, string> {
225
+ const plain = new Map(dirs.map((d) => [d, d === "." ? "root" : nameOf(d)]));
226
+ const count = new Map<string, number>();
227
+ for (const n of plain.values()) count.set(n, (count.get(n) ?? 0) + 1);
228
+ const out = new Map<string, string>();
229
+ const taken = new Set<string>();
230
+ for (const d of dirs) {
231
+ const n = plain.get(d)!;
232
+ let name = n.length > NAME_MAX || count.get(n)! > 1 ? hashed(d, n) : n;
233
+ // Two paths whose digests share a prefix: take more of the digest.
234
+ for (let length = 7; taken.has(name) && length <= 16; length++) name = hashed(d, n, length);
235
+ taken.add(name);
236
+ out.set(d, name);
237
+ }
238
+ return out;
239
+ }
240
+
241
+ export interface Discovery {
242
+ /** The declaration the read uses, as JSON text. */
243
+ declaration: string;
244
+ entries: DiscoveredEntry[];
245
+ }
246
+
247
+ const claimOf = (k: MemberKind) => ({ kind: k.name, precedence: k.precedence, source: k.source });
248
+
249
+ /** The parts of a probe its kinds file states, without what chant adds. */
250
+ function probeOf(k: MemberKind): KindProbe {
251
+ return structuredClone(k.probe);
252
+ }
253
+
254
+ /**
255
+ * Walk `tree` and work out the members a declaration for it would list, the
256
+ * `discovered` entries, and the declaration itself. `name` is the workspace's
257
+ * name. `runsOn` sets a discovered member's `runsOn` field by member name
258
+ * (#5101), as `--runs-on` does. Reads the tree only.
259
+ */
260
+ export function discover(tree: WorkspaceTree, kinds: DiscoveryKinds, name: string, runsOn: Readonly<Record<string, string>> = {}): Discovery {
261
+ const claimed: { dir: string; claims: MemberKind[]; winner: MemberKind | undefined }[] = [];
262
+ const modules = new Map<string, Set<string>>();
263
+ const walk = (dir: string) => {
264
+ const entries = tree.list(dir) ?? [];
265
+ // The root's own declaration would make it a nested workspace of itself; a declared root never gets here, but --at may hold one below.
266
+ const r = resolveKind(kinds.registry, tree, dir, dir === "" ? ["workspace"] : []);
267
+ if (r.claims.length > 0) claimed.push({ dir, claims: r.claims, winner: r.winner });
268
+ for (const e of entries) {
269
+ if (e.type !== "file" || !e.name.endsWith(".tf")) continue;
270
+ let text: string;
271
+ try {
272
+ text = tree.read(joinPath(dir, e.name));
273
+ } catch {
274
+ continue;
275
+ }
276
+ for (const source of localModuleSources(text)) {
277
+ const target = posix.normalize(posix.join(dir || ".", source)).replace(/\/+$/, "");
278
+ if (target === ".." || target.startsWith("../")) continue;
279
+ const key = target === "." ? "" : target;
280
+ if (key === dir) continue;
281
+ const callers = modules.get(key) ?? new Set<string>();
282
+ callers.add(dir || ".");
283
+ modules.set(key, callers);
284
+ }
285
+ }
286
+ for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
287
+ if (e.type === "dir" && !skippedDir(e.name)) walk(joinPath(dir, e.name));
288
+ }
289
+ };
290
+ walk("");
291
+ claimed.sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0));
292
+
293
+ const shown = (d: string) => d || ".";
294
+ const entries: DiscoveredEntry[] = [];
295
+ const memberDirs: string[] = [];
296
+ for (const c of claimed) {
297
+ const base = {
298
+ dir: shown(c.dir),
299
+ member: null,
300
+ kind: c.winner?.name ?? null,
301
+ source: c.winner?.source ?? null,
302
+ probe: c.winner ? probeOf(c.winner) : null,
303
+ claims: c.claims.map(claimOf),
304
+ };
305
+ const callers = modules.get(c.dir);
306
+ if (callers) {
307
+ entries.push({ ...base, outcome: "module", note: `called as a module through a local source by ${[...callers].sort().join(", ")}` });
308
+ continue;
309
+ }
310
+ if (!c.winner) {
311
+ const tied = c.claims.filter((k) => k.precedence === c.claims[0].precedence);
312
+ entries.push({ ...base, outcome: "tie", note: `kinds ${tied.map((k) => k.name).join(" and ")} claim it at precedence ${tied[0].precedence}; name its kind in a declaration to read it` });
313
+ continue;
314
+ }
315
+ const outer = memberDirs.find((m) => m !== "" && isInside(c.dir, m));
316
+ if (outer !== undefined) {
317
+ entries.push({ ...base, outcome: "inside-member", note: `inside member directory ${outer}; members don't nest, except inside the root member .` });
318
+ continue;
319
+ }
320
+ memberDirs.push(c.dir);
321
+ entries.push({ ...base, outcome: "member", note: null });
322
+ }
323
+
324
+ const names = discoveredMemberNames(memberDirs.map(shown));
325
+ for (const e of entries) if (e.outcome === "member") e.member = names.get(e.dir)!;
326
+ const known = [...names.values()].sort();
327
+ const unknown = Object.keys(runsOn).filter((m) => !known.includes(m));
328
+ if (unknown.length > 0) {
329
+ throw new WorkspaceReadError("declaration-invalid", `--runs-on names ${unknown.map((m) => JSON.stringify(m)).join(", ")}, which is not a discovered member${known.length > 0 ? ` (the members are ${known.join(", ")})` : ""}`);
330
+ }
331
+ const members = entries.filter((e) => e.outcome === "member").map((e) => ({ name: e.member!, dir: e.dir, kind: e.kind!, ...(runsOn[e.member!] !== undefined ? { runsOn: runsOn[e.member!] } : {}) }));
332
+ const used = new Set(entries.filter((e) => e.outcome === "member").map((e) => e.source));
333
+ const pins = kinds.packages.filter((p) => used.has(p.package)).map((p) => ({ package: p.package, version: p.version }));
334
+ const declaration = { name, schema: 1, ...(pins.length > 0 ? { pins } : {}), members };
335
+ return { declaration: `${JSON.stringify(declaration, null, 2)}\n`, entries };
336
+ }
337
+
338
+ /** The file the in-memory declaration is shown as. */
339
+ export const DISCOVERED_DECLARATION = DECLARATION_FILES[0];
340
+
341
+ /**
342
+ * `base` with the in-memory declaration shown as `chant.workspace.json` at
343
+ * its root. Every other path reads through to `base`. Nothing is written.
344
+ */
345
+ export function discoveredTree(base: WorkspaceTree, declaration: string): WorkspaceTree {
346
+ const file = DISCOVERED_DECLARATION;
347
+ return {
348
+ label: base.label,
349
+ stat: (path) => (path === file ? "file" : base.stat(path)),
350
+ list: (path) => {
351
+ const entries = base.list(path);
352
+ if (path !== "" || !entries) return entries;
353
+ return [...entries.filter((e) => e.name !== file), { name: file, type: "file" }];
354
+ },
355
+ read: (path) => (path === file ? declaration : base.read(path)),
356
+ bytes: (path) => (path === file ? new TextEncoder().encode(declaration) : base.bytes ? base.bytes(path) : new TextEncoder().encode(base.read(path))),
357
+ };
358
+ }
359
+
360
+ /** Whether `tree` holds a declaration at its root. */
361
+ export function declares(tree: WorkspaceTree): boolean {
362
+ return DECLARATION_FILES.some((f) => tree.stat(f) === "file");
363
+ }
364
+
365
+ /** The workspace name a discovered read gives `dir`: its base name, made a valid name. */
366
+ export function discoveredWorkspaceName(dir: string): string {
367
+ return nameOf(basename(dir)).slice(0, NAME_MAX).replace(/-+$/, "") || "workspace";
368
+ }
369
+
370
+ /**
371
+ * The working tree under `root` without the symbolic links to directories, so
372
+ * the walk stays inside `root` and can't go round a loop. A link to a file is
373
+ * kept.
374
+ */
375
+ function withoutDirLinks(tree: WorkspaceTree, root: string): WorkspaceTree {
376
+ return {
377
+ ...tree,
378
+ list: (path) =>
379
+ tree.list(path)?.filter((e) => {
380
+ if (e.type !== "dir") return true;
381
+ try {
382
+ return !lstatSync(join(root, ...joinPath(path, e.name).split("/"))).isSymbolicLink();
383
+ } catch {
384
+ return false;
385
+ }
386
+ }),
387
+ };
388
+ }
389
+
390
+ /**
391
+ * Where a discovered read of `dir` reads: the working tree, or for `at` the
392
+ * commit's tree under `dir`, before the declaration is laid over it. Throws
393
+ * a {@link WorkspaceReadError}: for `at`, `not-a-git-repository` and
394
+ * `revision-unknown`.
395
+ */
396
+ export function locateDiscovered(dir: string, at?: string): Omit<LocatedWorkspace, "tree"> & { base: WorkspaceTree } {
397
+ const rootOnDisk = resolve(dir);
398
+ const top = gitTop(rootOnDisk);
399
+ const rel = top ? toPosix(relative(top, realpathSync(rootOnDisk))) : undefined;
400
+ const root = rel === undefined || rel.startsWith("..") ? rootOnDisk : rel === "" ? "." : rel;
401
+ if (at === undefined) return { base: withoutDirLinks(workingTree(rootOnDisk), rootOnDisk), root, rootOnDisk, at: null, top };
402
+ if (!top) throw new WorkspaceReadError("not-a-git-repository", "--at reads git objects, and this directory is not in a git repository");
403
+ const commit = resolveCommit(top, at);
404
+ if (!commit) throw new WorkspaceReadError("revision-unknown", `--at ${at} names no commit in this repository`);
405
+ return { base: gitTree(top, commit, root === "." ? "" : root), root, rootOnDisk, at: commit, top };
406
+ }
@@ -10,7 +10,7 @@ import Ajv2020 from "ajv/dist/2020";
10
10
  import { join } from "node:path";
11
11
  import { afterAll, describe, expect, test } from "vitest";
12
12
  import { driftRecord, driftRecordLine, driftSettle, driftStart } from "../drift-record";
13
- import { KIND_DRIFT_READER_FLOOR, NEXT_RELEASE } from "../release-floors";
13
+ import { KIND_DRIFT_READER_FLOOR } from "../release-floors";
14
14
  import { cleanScratch, declaration, repo } from "./__fixtures__/contract-repo";
15
15
  import { driftReadDocument, readWorkspaceDrift } from "./drift-cli";
16
16
  import { checkDriftReaderOutput, DRIFT_READER_SCHEMA_ID } from "./drift-reader";
@@ -107,9 +107,9 @@ describe("the drift reader's output schema", () => {
107
107
  ajv.addSchema(driftSchema);
108
108
  const validate = ajv.compile(driftReaderSchema);
109
109
 
110
- test("names its $id, and the floor is the next release", () => {
110
+ test("names its $id, and the floor is the release that shipped it", () => {
111
111
  expect(driftReaderSchema.$id).toBe(DRIFT_READER_SCHEMA_ID);
112
- expect(KIND_DRIFT_READER_FLOOR).toBe(NEXT_RELEASE);
112
+ expect(KIND_DRIFT_READER_FLOOR).toBe("0.124.96");
113
113
  });
114
114
 
115
115
  test("takes the lines of a read and a refusal, and nothing else", () => {
@@ -0,0 +1,98 @@
1
+ /**
2
+ * An ExternalSecret to its store and to the cloud secret, through
3
+ * `chant workspace graph --discover` end to end (#5098): a manifests member
4
+ * `k8s` and a terraform member `tf`, read through the k8s and terraform
5
+ * lexicons installed in this checkout.
6
+ */
7
+
8
+ import { afterAll, beforeAll, describe, expect, test } from "vitest";
9
+ import { cleanScratch, scratchDir, writeFiles } from "./__fixtures__/contract-repo";
10
+ import { CACHE_DIR_ENV } from "./graph-cache";
11
+ import { workspaceGraph, type GraphDocument } from "./graph-cli";
12
+
13
+ const TIMEOUT = 240_000;
14
+
15
+ let cacheBefore: string | undefined;
16
+ beforeAll(() => {
17
+ cacheBefore = process.env[CACHE_DIR_ENV];
18
+ process.env[CACHE_DIR_ENV] = scratchDir("chant-es-cache-");
19
+ });
20
+ afterAll(() => {
21
+ if (cacheBefore === undefined) delete process.env[CACHE_DIR_ENV];
22
+ else process.env[CACHE_DIR_ENV] = cacheBefore;
23
+ cleanScratch();
24
+ });
25
+
26
+ const store = (kind: string, namespace?: string) =>
27
+ `apiVersion: external-secrets.io/v1\nkind: ${kind}\nmetadata:\n name: gcp\n${namespace ? ` namespace: ${namespace}\n` : ""}spec:\n provider:\n gcpsm:\n projectID: demo-proj\n`;
28
+
29
+ const externalSecret = (name: string, key: string) =>
30
+ `apiVersion: external-secrets.io/v1\nkind: ExternalSecret\nmetadata:\n name: ${name}\n namespace: app\nspec:\n secretStoreRef:\n kind: ClusterSecretStore\n name: gcp\n target:\n name: ${name}\n data:\n - secretKey: token\n remoteRef:\n key: ${key}\n`;
31
+
32
+ const FX = {
33
+ "k8s/stores.yaml": `${store("ClusterSecretStore")}---\n${store("SecretStore", "elsewhere")}`,
34
+ "k8s/app-creds.yaml": externalSecret("app-creds", "app-token"),
35
+ "k8s/app-extra.yaml": externalSecret("app-extra", "other-token"),
36
+ "tf/main.tf": [
37
+ 'resource "google_secret_manager_secret" "token" {',
38
+ ' secret_id = "app-token"',
39
+ ' project = "demo-proj"',
40
+ " replication {\n auto {}\n }",
41
+ "}",
42
+ "",
43
+ 'variable "name" {}',
44
+ "",
45
+ 'resource "google_secret_manager_secret" "named" {',
46
+ " secret_id = var.name",
47
+ ' project = "demo-proj"',
48
+ " replication {\n auto {}\n }",
49
+ "}",
50
+ "",
51
+ ].join("\n"),
52
+ };
53
+
54
+ function result(doc: GraphDocument): Extract<GraphDocument, { nodes: unknown }> {
55
+ if ("error" in doc) throw new Error(`${doc.error.code}: ${doc.error.message}`);
56
+ return doc;
57
+ }
58
+
59
+ describe("workspace graph: ExternalSecret rules (#5098)", () => {
60
+ test(
61
+ "draws the edges to the store and the cloud secret, and reports a key no secret has and an argument it could not read",
62
+ async () => {
63
+ const root = scratchDir("chant-es-fx-");
64
+ writeFiles(root, FX);
65
+ const { doc, failed } = await workspaceGraph({ cwd: root, discover: true, noCache: false, catalog: true });
66
+ const g = result(doc);
67
+ expect(failed).toBe(false);
68
+
69
+ const es = g.nodes.filter((n) => n.kind === "K8s::ExternalSecrets::ExternalSecret").map((n) => n.id);
70
+ expect(es).toHaveLength(2);
71
+ const creds = es.find((id) => id.endsWith("AppCreds"))!;
72
+ const extra = es.find((id) => id.endsWith("AppExtra"))!;
73
+ const clusterStore = g.nodes.find((n) => n.kind === "K8s::ExternalSecrets::ClusterSecretStore")!.id;
74
+ const secret = g.nodes.find((n) => n.id.endsWith("/google_secret_manager_secret.token"))!.id;
75
+ const named = g.nodes.find((n) => n.id.endsWith("/google_secret_manager_secret.named"))!.id;
76
+
77
+ const derived = g.edges.filter((e) => e.origin === "derived" && e.rule?.includes("ExternalSecret"));
78
+ // Reads from the store, then the secret: app-creds, and app-extra's store only.
79
+ expect(derived.map((e) => `${e.from} -> ${e.to} [${e.viaAttr}]`).sort()).toEqual(
80
+ [
81
+ `${creds} -> ${clusterStore} [secretStoreRef]`,
82
+ `${creds} -> ${secret} [remoteRef.key via gcp]`,
83
+ `${extra} -> ${clusterStore} [secretStoreRef]`,
84
+ ].sort(),
85
+ );
86
+ // The SecretStore of that name in another namespace is joined to nothing.
87
+ const namespaced = g.nodes.find((n) => n.kind === "K8s::ExternalSecrets::SecretStore")!.id;
88
+ expect(g.edges.filter((e) => e.to === namespaced && e.relation === "reference")).toEqual([]);
89
+
90
+ const dangling = (g.dangling ?? []).filter((d) => d.rule?.includes("remoteRef.key"));
91
+ expect(dangling).toEqual([
92
+ expect.objectContaining({ from: extra, value: "other-token", through: clusterStore, targetKind: "google_secret_manager_secret" }),
93
+ ]);
94
+ expect(g.catalog?.nonLiteral?.[named]).toBe(1);
95
+ },
96
+ TIMEOUT,
97
+ );
98
+ });
@@ -0,0 +1,142 @@
1
+ /**
2
+ * #5098: an ExternalSecret to its store and to the cloud secret the store
3
+ * reads it from, over a composed workspace graph with the k8s catalog and
4
+ * the terraform catalog together. Members `k8s` and `tf` stand for a manifest
5
+ * directory and a terraform root.
6
+ */
7
+ import { describe, expect, it } from "vitest";
8
+ import { k8sReferenceCatalog } from "../../../../lexicons/k8s/src/reference-catalog";
9
+ import { TERRAFORM_REFERENCE_CATALOG } from "../../../../lexicons/terraform/src/behaviour/reference-catalog";
10
+ import { placeCatalogPass, runCatalogPass } from "./catalog-edges";
11
+ import type { ComposedNode, WorkspaceGraph } from "./compose-graph";
12
+
13
+ const ES = "K8s::ExternalSecrets::ExternalSecret";
14
+ const CSS = "K8s::ExternalSecrets::ClusterSecretStore";
15
+ const SS = "K8s::ExternalSecrets::SecretStore";
16
+ const STORE_RULE = `k8s:${ES}:spec.secretStoreRef.name`;
17
+ const KEY_RULE = `k8s:${ES}:spec.data[].remoteRef.key`;
18
+ const FROM_RULE = `k8s:${ES}:spec.dataFrom[].extract.key`;
19
+
20
+ const k8s = (id: string, kind: string, attrs: Record<string, unknown>, member = "k8s"): ComposedNode => ({ id: `${member}/${id}`, kind, lexicon: "k8s", attrs, member });
21
+ const tf = (address: string, body: Record<string, unknown>, member = "tf"): ComposedNode => ({
22
+ id: `${member}/r/${address}`,
23
+ kind: "Terraform::Resource",
24
+ lexicon: "terraform",
25
+ member,
26
+ attrs: { address, type: address.split(".")[0], name: address.split(".")[1], body, source: "main.tf" },
27
+ });
28
+
29
+ const gcpStore = (name = "gcp", projectID = "demo-proj") => k8s(`cs-${name}`, CSS, { metadata: { name }, spec: { provider: { gcpsm: { projectID } } } });
30
+ const externalSecret = (spec: Record<string, unknown>, namespace: string | null = "app") =>
31
+ k8s("es-app-creds", ES, { metadata: { name: "app-creds", ...(namespace ? { namespace } : {}) }, spec });
32
+ const gcpSecret = (secretId: string, project: string | null = "demo-proj", address = "google_secret_manager_secret.token") =>
33
+ tf(address, { secret_id: secretId, ...(project ? { project } : {}), replication: [{ auto: {} }] });
34
+
35
+ const pass = (nodes: ComposedNode[]) =>
36
+ runCatalogPass(nodes, [
37
+ { lexicon: "k8s", catalog: k8sReferenceCatalog },
38
+ { lexicon: "terraform", catalog: TERRAFORM_REFERENCE_CATALOG },
39
+ ]);
40
+
41
+ const uses = (store: string, key: string, kind = "ClusterSecretStore") => ({ secretStoreRef: { kind, name: store }, data: [{ secretKey: "token", remoteRef: { key } }] });
42
+ const refEdges = (out: ReturnType<typeof pass>) => out.edges.filter((e) => e.relation === "reference").map((e) => `${e.from} -> ${e.to} [${e.viaAttr}] ${e.rule}`);
43
+
44
+ describe("an ExternalSecret and its store (#5098)", () => {
45
+ it("draws the edge to the store and the edge to the cloud secret", () => {
46
+ const out = pass([gcpStore(), externalSecret(uses("gcp", "app-token")), gcpSecret("app-token")]);
47
+ expect(refEdges(out)).toEqual([
48
+ `k8s/es-app-creds -> k8s/cs-gcp [secretStoreRef] ${STORE_RULE}`,
49
+ `k8s/es-app-creds -> tf/r/google_secret_manager_secret.token [remoteRef.key via gcp] ${KEY_RULE}`,
50
+ ]);
51
+ expect(out.edges.every((e) => e.origin === "derived" && e.grain === "property")).toBe(true);
52
+ expect(out.dangling.filter((d) => d.rule?.includes("ExternalSecret"))).toEqual([]);
53
+ expect(out.ambiguous).toEqual([]);
54
+ });
55
+
56
+ it("names both rules, with the store kinds and the secret kind they look for, once placed", () => {
57
+ const graph = { version: 1, workspace: { name: "w", root: "." }, members: [], nodes: [], edges: [], groups: { byMember: {} }, exports: [], imports: [], links: [], collectors: [], records: [] } as unknown as WorkspaceGraph;
58
+ placeCatalogPass(graph, pass([gcpStore(), externalSecret(uses("gcp", "app-token")), gcpSecret("app-token")]));
59
+ expect(graph.catalog?.rules[STORE_RULE]).toMatchObject({ from: ES, path: "spec.secretStoreRef.name", targetKinds: [CSS, SS], label: "reads through" });
60
+ expect(graph.catalog?.rules[KEY_RULE]).toMatchObject({ from: ES, path: "spec.data[].remoteRef.key", targetKinds: ["aws_secretsmanager_secret", "google_secret_manager_secret"], label: "reads secret" });
61
+ });
62
+
63
+ it("gives a SecretStore of that name in another namespace no edge", () => {
64
+ const other = k8s("ss-gcp", SS, { metadata: { name: "gcp", namespace: "elsewhere" }, spec: { provider: { gcpsm: { projectID: "demo-proj" } } } });
65
+ const out = pass([other, externalSecret(uses("gcp", "app-token", "SecretStore")), gcpSecret("app-token")]);
66
+ expect(refEdges(out)).toEqual([]);
67
+ expect(out.dangling.filter((d) => d.rule === STORE_RULE)).toEqual([
68
+ expect.objectContaining({ from: "k8s/es-app-creds", value: "gcp", targetKind: SS }),
69
+ ]);
70
+ // A store that is not found leaves its keys unread: the store entry says what is missing.
71
+ expect(out.dangling.filter((d) => d.rule === KEY_RULE)).toEqual([]);
72
+ });
73
+
74
+ it("reads a store with no kind as a SecretStore in the namespace", () => {
75
+ const store = k8s("ss-gcp", SS, { metadata: { name: "gcp", namespace: "app" }, spec: { provider: { gcpsm: { projectID: "demo-proj" } } } });
76
+ const out = pass([store, externalSecret({ secretStoreRef: { name: "gcp" }, data: [{ secretKey: "t", remoteRef: { key: "app-token" } }] }), gcpSecret("app-token")]);
77
+ expect(refEdges(out).map((e) => e.split(" ")[2])).toEqual(["k8s/ss-gcp", "tf/r/google_secret_manager_secret.token"]);
78
+ });
79
+
80
+ it("puts the key in dangling, with the holder and the store it was read through, when no secret has it", () => {
81
+ const out = pass([gcpStore(), externalSecret(uses("gcp", "other-token")), gcpSecret("app-token")]);
82
+ expect(refEdges(out)).toEqual([`k8s/es-app-creds -> k8s/cs-gcp [secretStoreRef] ${STORE_RULE}`]);
83
+ expect(out.dangling).toEqual([
84
+ expect.objectContaining({ from: "k8s/es-app-creds", path: "spec.data[].remoteRef.key", value: "other-token", rule: KEY_RULE, targetKind: "google_secret_manager_secret", through: "k8s/cs-gcp", member: "k8s" }),
85
+ ]);
86
+ });
87
+
88
+ it("does not join a key to a secret of the same id in another project", () => {
89
+ const out = pass([gcpStore(), externalSecret(uses("gcp", "app-token")), gcpSecret("app-token", "other-proj")]);
90
+ expect(refEdges(out).filter((e) => e.includes(KEY_RULE))).toEqual([]);
91
+ expect(out.dangling.map((d) => d.value)).toEqual(["app-token"]);
92
+ });
93
+
94
+ it("gives a secret whose id is a variable no edge, and counts the argument it could not read", () => {
95
+ const secret = tf("google_secret_manager_secret.token", { secret_id: "${var.name}", project: "demo-proj" });
96
+ const out = pass([gcpStore(), externalSecret(uses("gcp", "app-token")), secret]);
97
+ expect(refEdges(out).filter((e) => e.includes(KEY_RULE))).toEqual([]);
98
+ expect(out.nonLiteral).toEqual({ "tf/r/google_secret_manager_secret.token": 1 });
99
+ expect(out.dangling.map((d) => d.value)).toEqual(["app-token"]);
100
+ });
101
+
102
+ it("gives a secret whose project is a variable no edge, and counts it", () => {
103
+ const secret = tf("google_secret_manager_secret.token", { secret_id: "app-token", project: "${var.project}" });
104
+ const out = pass([gcpStore(), externalSecret(uses("gcp", "app-token")), secret]);
105
+ expect(refEdges(out).filter((e) => e.includes(KEY_RULE))).toEqual([]);
106
+ expect(out.nonLiteral).toEqual({ "tf/r/google_secret_manager_secret.token": 1 });
107
+ });
108
+
109
+ it("reads dataFrom extract keys too, and each key once", () => {
110
+ const spec = { secretStoreRef: { kind: "ClusterSecretStore", name: "gcp" }, data: [{ secretKey: "a", remoteRef: { key: "app-token" } }, { secretKey: "b", remoteRef: { key: "app-token" } }], dataFrom: [{ extract: { key: "more" } }] };
111
+ const out = pass([gcpStore(), externalSecret(spec), gcpSecret("app-token"), gcpSecret("more", "demo-proj", "google_secret_manager_secret.more")]);
112
+ expect(refEdges(out).filter((e) => !e.includes(STORE_RULE)).map((e) => e.split(" ").slice(2).join(" "))).toEqual([
113
+ `tf/r/google_secret_manager_secret.more [remoteRef.key via gcp] ${FROM_RULE}`,
114
+ `tf/r/google_secret_manager_secret.token [remoteRef.key via gcp] ${KEY_RULE}`,
115
+ ]);
116
+ });
117
+
118
+ it("joins an AWS Secrets Manager store to aws_secretsmanager_secret by name, and by region when the secret sets one", () => {
119
+ const store = k8s("cs-aws", CSS, { metadata: { name: "aws" }, spec: { provider: { aws: { service: "SecretsManager", region: "eu-west-1" } } } });
120
+ const es = externalSecret(uses("aws", "prod/db"));
121
+ const bare = tf("aws_secretsmanager_secret.db", { name: "prod/db" });
122
+ const keyed = (out: ReturnType<typeof pass>) => refEdges(out).filter((e) => e.includes(KEY_RULE)).map((e) => e.split(" ")[2]);
123
+ expect(keyed(pass([store, es, bare]))).toEqual(["tf/r/aws_secretsmanager_secret.db"]);
124
+ expect(keyed(pass([store, es, tf("aws_secretsmanager_secret.db", { name: "prod/db", region: "eu-west-1" })]))).toEqual(["tf/r/aws_secretsmanager_secret.db"]);
125
+ expect(keyed(pass([store, es, tf("aws_secretsmanager_secret.db", { name: "prod/db", region: "us-east-1" })]))).toEqual([]);
126
+ const parameterStore = k8s("cs-aws", CSS, { metadata: { name: "aws" }, spec: { provider: { aws: { service: "ParameterStore", region: "eu-west-1" } } } });
127
+ expect(keyed(pass([parameterStore, es, bare]))).toEqual([]);
128
+ });
129
+
130
+ it("reads no key through a store whose provider it does not know, and still draws the store edge", () => {
131
+ const vault = k8s("cs-vault", CSS, { metadata: { name: "vault" }, spec: { provider: { vault: { server: "https://vault" } } } });
132
+ const out = pass([vault, externalSecret(uses("vault", "app-token")), gcpSecret("app-token")]);
133
+ expect(refEdges(out).map((e) => e.split(" ")[2])).toEqual(["k8s/cs-vault"]);
134
+ expect(out.dangling).toEqual([]);
135
+ });
136
+
137
+ it("reports a store two members both declare as ambiguous, and reads no key through it", () => {
138
+ const out = pass([gcpStore(), { ...gcpStore(), id: "other/cs-gcp", member: "other" }, externalSecret(uses("gcp", "app-token")), gcpSecret("app-token")]);
139
+ expect(refEdges(out)).toEqual([]);
140
+ expect(out.ambiguous).toEqual([expect.objectContaining({ rule: STORE_RULE, value: "gcp", candidates: ["k8s/cs-gcp", "other/cs-gcp"] })]);
141
+ });
142
+ });