@intentius/behold 0.32.0 → 0.33.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.
@@ -0,0 +1,1019 @@
1
+ import {
2
+ CHANGED_NODE_BUDGET,
3
+ FORGES,
4
+ FlatLayoutTooLarge,
5
+ GRAPH_FORMATS,
6
+ PENDING_FORMATS,
7
+ ReadGraphError,
8
+ RevisionError,
9
+ SVG_THEMES,
10
+ clusterView,
11
+ cutChanged,
12
+ cutDocument,
13
+ documentOptions,
14
+ documentScrubber,
15
+ emptyDocument,
16
+ gitRoot,
17
+ graphFormat,
18
+ graphView,
19
+ isForge,
20
+ isSvgTheme,
21
+ parseRange,
22
+ readAtRevision,
23
+ readComposed,
24
+ resolveRange
25
+ } from "./chunk-XKWCGNT2.js";
26
+ import {
27
+ parseYAML
28
+ } from "./chunk-OY4EF7ZO.js";
29
+
30
+ // src/graph-cli.ts
31
+ import { existsSync as existsSync2, statSync, writeFileSync } from "node:fs";
32
+ import { resolve as resolve3 } from "node:path";
33
+
34
+ // src/read-cluster.ts
35
+ import { existsSync, readFileSync } from "node:fs";
36
+ import { homedir } from "node:os";
37
+ import { delimiter, dirname, join, resolve as resolve2 } from "node:path";
38
+
39
+ // src/kube-exec.ts
40
+ import { execFile } from "node:child_process";
41
+ import { isAbsolute, resolve } from "node:path";
42
+ var ExecPluginError = class extends Error {
43
+ constructor(message) {
44
+ super(message);
45
+ this.name = "ExecPluginError";
46
+ }
47
+ };
48
+ var defaultRunner = (command, args, env, timeoutMs) => new Promise((resolveRun, reject) => {
49
+ const child = execFile(command, args, { env, timeout: timeoutMs, maxBuffer: 1 << 20, encoding: "utf8" }, (err, stdout, stderr) => {
50
+ if (err) reject(new ExecPluginError(`${command} failed: ${String(stderr || err.message).trim().slice(0, 400)}`));
51
+ else resolveRun({ stdout });
52
+ });
53
+ child.stdin?.end();
54
+ });
55
+ async function runExecPlugin(user, cluster, opts = {}) {
56
+ if (!user.command) throw new ExecPluginError("the exec entry names no command");
57
+ const apiVersion = user.apiVersion ?? "client.authentication.k8s.io/v1";
58
+ const command = !isAbsolute(user.command) && user.command.includes("/") && opts.baseDir ? resolve(opts.baseDir, user.command) : user.command;
59
+ const env = {};
60
+ for (const [k, v] of Object.entries(opts.env ?? process.env)) if (v !== void 0) env[k] = v;
61
+ for (const e of user.env ?? []) env[e.name] = e.value;
62
+ env.KUBERNETES_EXEC_INFO = JSON.stringify({
63
+ apiVersion,
64
+ kind: "ExecCredential",
65
+ spec: {
66
+ interactive: false,
67
+ ...user.provideClusterInfo ? { cluster: { server: cluster.server, ...cluster.caData ? { "certificate-authority-data": cluster.caData } : {}, ...cluster.insecureSkipVerify ? { "insecure-skip-tls-verify": true } : {} } } : {}
68
+ }
69
+ });
70
+ const { stdout } = await (opts.run ?? defaultRunner)(command, user.args ?? [], env, opts.timeoutMs ?? 3e4);
71
+ let doc;
72
+ try {
73
+ doc = JSON.parse(stdout);
74
+ } catch {
75
+ throw new ExecPluginError(`${user.command} printed no ExecCredential JSON`);
76
+ }
77
+ const status = doc.status ?? {};
78
+ const out = {};
79
+ if (typeof status.token === "string" && status.token) out.token = status.token;
80
+ if (typeof status.clientCertificateData === "string" && status.clientCertificateData) out.clientCertificateData = status.clientCertificateData;
81
+ if (typeof status.clientKeyData === "string" && status.clientKeyData) out.clientKeyData = status.clientKeyData;
82
+ if (!out.token && !(out.clientCertificateData && out.clientKeyData)) throw new ExecPluginError(`${user.command} printed an ExecCredential with no token and no client certificate`);
83
+ return out;
84
+ }
85
+
86
+ // web/outside-refs.js
87
+ var MASKED = "<masked>";
88
+ var WAITS_ON_MASK = "INTENTIUS/chant#5116";
89
+ var ANNOTATION_GCP = "iam.gke.io/gcp-service-account";
90
+ var ANNOTATION_AWS = "eks.amazonaws.com/role-arn";
91
+ var ANNOTATION_AZURE = "azure.workload.identity/client-id";
92
+ var ESO_GROUP = "external-secrets.io";
93
+ var FLUX_SOURCE_GROUP = "source.toolkit.fluxcd.io";
94
+ var FLUX_KUSTOMIZE_GROUP = "kustomize.toolkit.fluxcd.io";
95
+ var ARGO_GROUP = "argoproj.io";
96
+ var CLUSTER_SCOPED = /* @__PURE__ */ new Set(["ClusterSecretStore"]);
97
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
98
+ var str = (v) => typeof v === "string" && v.length > 0 ? v : void 0;
99
+ var arr = (v) => Array.isArray(v) ? v : [];
100
+ function refOf(obj) {
101
+ const apiVersion = str(obj.apiVersion) || "";
102
+ const group = apiVersion.includes("/") ? apiVersion.slice(0, apiVersion.indexOf("/")) : "";
103
+ const meta = isObject(obj.metadata) ? obj.metadata : {};
104
+ const kind = str(obj.kind);
105
+ const name = str(meta.name);
106
+ const namespace = CLUSTER_SCOPED.has(kind) ? "" : str(meta.namespace) || "default";
107
+ return { group, kind, namespace, name };
108
+ }
109
+ var idOf = (r) => `${r.group}/${r.kind}/${r.namespace}/${r.name}`;
110
+ function flatten(objects) {
111
+ const out = [];
112
+ for (const o of arr(objects)) {
113
+ if (!isObject(o)) continue;
114
+ if (Array.isArray(o.items) && typeof o.kind === "string" && o.kind.endsWith("List")) out.push(...flatten(o.items));
115
+ else out.push(o);
116
+ }
117
+ return out;
118
+ }
119
+ var CHANT_AWS_TYPES = {
120
+ "AWS::IAM::Role": "aws_iam_role",
121
+ "AWS::SecretsManager::Secret": "aws_secretsmanager_secret",
122
+ "AWS::SSM::Parameter": "aws_ssm_parameter"
123
+ };
124
+ function typeOfNode(node) {
125
+ const kind = str(node && node.kind);
126
+ if (kind && CHANT_AWS_TYPES[kind]) return CHANT_AWS_TYPES[kind];
127
+ if (kind && /^[a-z][a-z0-9]*_[a-z0-9_]+$/.test(kind)) return kind;
128
+ const attrs = node && node.attrs || {};
129
+ const address = str(attrs.address) || str(node && node.id);
130
+ if (!address) return void 0;
131
+ const parts = address.replace(/\[[^\]]*\]/g, "").split(".");
132
+ if (parts[0] === "data" || parts.length < 2) return void 0;
133
+ const type = parts[parts.length - 2];
134
+ return /^[a-z][a-z0-9]*_[a-z0-9_]+$/.test(type) ? type : void 0;
135
+ }
136
+ function argOf(node, ...names) {
137
+ const attrs = node && node.attrs || {};
138
+ const layers = [attrs, attrs.body, attrs.values, attrs.properties, attrs.Properties].filter(isObject);
139
+ for (const layer of layers) {
140
+ for (const n of names) if (str(layer[n])) return layer[n];
141
+ }
142
+ return void 0;
143
+ }
144
+ function nodesOfType(graph, ...types) {
145
+ return arr(graph && graph.nodes).filter((n) => types.includes(typeOfNode(n)));
146
+ }
147
+ function holdsIdentity(graph, identity) {
148
+ if (identity.cloud === "aws") {
149
+ return nodesOfType(graph, "aws_iam_role").some((n) => argOf(n, "arn") === identity.arn || argOf(n, "name", "RoleName", "role_name") === identity.role);
150
+ }
151
+ if (identity.cloud === "gcp") {
152
+ return nodesOfType(graph, "google_service_account").some((n) => {
153
+ if (argOf(n, "email") === identity.email) return true;
154
+ const id = argOf(n, "account_id");
155
+ const project = argOf(n, "project");
156
+ return !!id && !!project && `${id}@${project}.iam.gserviceaccount.com` === identity.email;
157
+ });
158
+ }
159
+ return nodesOfType(graph, "azuread_application", "azuread_application_registration", "azuread_service_principal", "azurerm_user_assigned_identity").some(
160
+ (n) => String(argOf(n, "client_id", "application_id") || "").toLowerCase() === identity.clientId
161
+ );
162
+ }
163
+ function holdsSecret(graph, provider, key) {
164
+ if (provider.provider === "gcpsm") {
165
+ return nodesOfType(graph, "google_secret_manager_secret").some((n) => argOf(n, "secret_id") === key && argOf(n, "project") === provider.projectID);
166
+ }
167
+ if (provider.provider === "aws") {
168
+ const types = provider.service === "ParameterStore" ? ["aws_ssm_parameter"] : ["aws_secretsmanager_secret"];
169
+ return nodesOfType(graph, ...types).some((n) => argOf(n, "name", "Name") === key);
170
+ }
171
+ return false;
172
+ }
173
+ function holdsK8s(graph, ref) {
174
+ return arr(graph && graph.nodes).some((n) => {
175
+ const attrs = n && n.attrs || {};
176
+ const meta = isObject(attrs.metadata) ? attrs.metadata : {};
177
+ const parts = typeof n.kind === "string" ? n.kind.split("::") : [];
178
+ const kind = str(attrs.kind) || (parts[0] === "K8s" ? parts[parts.length - 1] : void 0);
179
+ if (kind !== ref.kind || str(meta.name) !== ref.name) return false;
180
+ return CLUSTER_SCOPED.has(ref.kind) || (str(meta.namespace) || "default") === ref.namespace;
181
+ });
182
+ }
183
+ function holdsSource(graph, url) {
184
+ return arr(graph && graph.nodes).some((n) => {
185
+ const v = argOf(n, "repoURL", "url", "clone_url");
186
+ return !!v && normalizeUrl(v) === url;
187
+ });
188
+ }
189
+ function normalizeUrl(raw) {
190
+ let s = String(raw).trim().replace(/\/+$/, "").replace(/\.git$/, "");
191
+ const m = /^([a-z][a-z0-9+.-]*:\/\/)([^/]+)(.*)$/i.exec(s);
192
+ if (m) s = m[1].toLowerCase() + m[2].toLowerCase() + m[3];
193
+ return s;
194
+ }
195
+ var cleanPath = (p) => String(p).trim().replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
196
+ var PROVIDER_LABEL = {
197
+ gcpsm: "GCP Secret Manager",
198
+ aws: "AWS Secrets Manager",
199
+ awsParameterStore: "AWS Parameter Store",
200
+ vault: "Vault"
201
+ };
202
+ function builder(graph) {
203
+ const cards = /* @__PURE__ */ new Map();
204
+ const edges = /* @__PURE__ */ new Map();
205
+ const notes = [];
206
+ return {
207
+ graph,
208
+ cards,
209
+ notes,
210
+ card(c) {
211
+ const have = cards.get(c.id);
212
+ if (!have) cards.set(c.id, { ...c, placeholder: true });
213
+ return cards.get(c.id);
214
+ },
215
+ edge(from, fromRef, to, viaAttr, extra) {
216
+ const e = { from, to, kind: "ref", viaAttr, inferred: true, placeholder: true, ...extra || {} };
217
+ if (fromRef) e.fromRef = fromRef;
218
+ edges.set(`${from}>${to}>${viaAttr}`, e);
219
+ },
220
+ note(from, path, code, message, extra) {
221
+ notes.push({ code, from, path, message, ...extra || {} });
222
+ },
223
+ result() {
224
+ const byId = (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
225
+ return {
226
+ cards: [...cards.values()].sort(byId),
227
+ edges: [...edges.values()].sort((a, b) => `${a.from}>${a.to}>${a.viaAttr}`.localeCompare(`${b.from}>${b.to}>${b.viaAttr}`)),
228
+ notes
229
+ };
230
+ }
231
+ };
232
+ }
233
+ var isMasked = (v) => v === MASKED;
234
+ function identityFor(annotation, value) {
235
+ if (annotation === ANNOTATION_GCP) {
236
+ const m = /^[^@\s]+@([^@\s]+)\.iam\.gserviceaccount\.com$/.exec(value);
237
+ return {
238
+ id: `outside:identity:gcp:${value}`,
239
+ identity: { cloud: "gcp", email: value, ...m ? { project: m[1] } : {} },
240
+ label: value,
241
+ ok: true
242
+ };
243
+ }
244
+ if (annotation === ANNOTATION_AWS) {
245
+ const m = /^arn:aws[a-z-]*:iam::(\d{12}):role\/(.+)$/.exec(value);
246
+ if (!m) return { ok: false, why: "not an IAM role ARN" };
247
+ const role = m[2].slice(m[2].lastIndexOf("/") + 1);
248
+ return { id: `outside:identity:aws:${value}`, identity: { cloud: "aws", arn: value, account: m[1], role }, label: value, ok: true };
249
+ }
250
+ const clientId = value.toLowerCase();
251
+ return { id: `outside:identity:azure:${clientId}`, identity: { cloud: "azure", clientId }, label: `Azure identity ${clientId}`, ok: true };
252
+ }
253
+ function serviceAccount(b, obj, ref) {
254
+ const annotations = isObject(obj.metadata) && isObject(obj.metadata.annotations) ? obj.metadata.annotations : {};
255
+ for (const annotation of [ANNOTATION_GCP, ANNOTATION_AWS, ANNOTATION_AZURE]) {
256
+ if (!(annotation in annotations)) continue;
257
+ const path = `metadata.annotations[${annotation}]`;
258
+ const value = annotations[annotation];
259
+ if (isMasked(value)) {
260
+ b.note(idOf(ref), path, "masked", "the live read masked this annotation", { waitsOn: WAITS_ON_MASK });
261
+ continue;
262
+ }
263
+ if (!str(value)) {
264
+ b.note(idOf(ref), path, "unrecognised", "the annotation is empty or not a string");
265
+ continue;
266
+ }
267
+ const found = identityFor(annotation, value.trim());
268
+ if (!found.ok) {
269
+ b.note(idOf(ref), path, "unrecognised", `${found.why}: ${value}`);
270
+ continue;
271
+ }
272
+ if (holdsIdentity(b.graph, found.identity)) continue;
273
+ const cardAttrs = { ...found.identity };
274
+ b.card({ id: found.id, kind: "CloudIdentity", label: found.label, attrs: cardAttrs });
275
+ b.edge(idOf(ref), ref, found.id, path);
276
+ }
277
+ }
278
+ function providerOf(store, ref, b) {
279
+ const provider = isObject(store.spec) && isObject(store.spec.provider) ? store.spec.provider : void 0;
280
+ if (!provider) {
281
+ b.note(idOf(ref), "spec.provider", "unrecognised", "the store has no provider");
282
+ return void 0;
283
+ }
284
+ const kinds = Object.keys(provider);
285
+ const known = kinds.filter((k2) => k2 === "gcpsm" || k2 === "aws" || k2 === "vault");
286
+ for (const k2 of kinds) {
287
+ if (!known.includes(k2)) b.note(idOf(ref), `spec.provider.${k2}`, "unrecognised", `no placeholder rule for the ${k2} provider`);
288
+ }
289
+ if (known.length === 0) return void 0;
290
+ const k = known[0];
291
+ const spec = isObject(provider[k]) ? provider[k] : {};
292
+ if (k === "gcpsm") {
293
+ const projectID = str(spec.projectID);
294
+ if (!projectID || isMasked(projectID)) {
295
+ b.note(idOf(ref), "spec.provider.gcpsm.projectID", "unrecognised", "no readable projectID");
296
+ return void 0;
297
+ }
298
+ return { provider: "gcpsm", projectID, id: `outside:provider:gcpsm:${projectID}`, label: `${PROVIDER_LABEL.gcpsm} ${projectID}`, path: "spec.provider.gcpsm" };
299
+ }
300
+ if (k === "aws") {
301
+ const region = str(spec.region);
302
+ const service = str(spec.service) || "SecretsManager";
303
+ if (!region || isMasked(region)) {
304
+ b.note(idOf(ref), "spec.provider.aws.region", "unrecognised", "no readable region");
305
+ return void 0;
306
+ }
307
+ const label = service === "ParameterStore" ? PROVIDER_LABEL.awsParameterStore : PROVIDER_LABEL.aws;
308
+ return { provider: "aws", service, region, id: `outside:provider:aws:${service}:${region}`, label: `${label} ${region}`, path: "spec.provider.aws" };
309
+ }
310
+ const server = str(spec.server);
311
+ if (!server || isMasked(server)) {
312
+ b.note(idOf(ref), "spec.provider.vault.server", "unrecognised", "no readable server");
313
+ return void 0;
314
+ }
315
+ const path = str(spec.path) || "";
316
+ return {
317
+ provider: "vault",
318
+ server,
319
+ ...path ? { path } : {},
320
+ id: `outside:provider:vault:${server}/${path}`,
321
+ label: `${PROVIDER_LABEL.vault} ${server}${path ? `/${path}` : ""}`,
322
+ path: "spec.provider.vault"
323
+ };
324
+ }
325
+ function keysOf(obj, ref, b) {
326
+ const spec = isObject(obj.spec) ? obj.spec : {};
327
+ const keys = [];
328
+ arr(spec.data).forEach((d, i) => {
329
+ const key = isObject(d) && isObject(d.remoteRef) ? d.remoteRef.key : void 0;
330
+ if (str(key) && !isMasked(key)) keys.push(key);
331
+ else b.note(idOf(ref), `spec.data[${i}].remoteRef.key`, "unrecognised", "no readable key");
332
+ });
333
+ arr(spec.dataFrom).forEach((d, i) => {
334
+ const key = isObject(d) && isObject(d.extract) ? d.extract.key : void 0;
335
+ if (str(key) && !isMasked(key)) keys.push(key);
336
+ else b.note(idOf(ref), `spec.dataFrom[${i}]`, "unrecognised", "only extract.key is read; find, sourceRef and the rest name no single secret");
337
+ });
338
+ return keys;
339
+ }
340
+ function externalSecrets(b, all) {
341
+ const stores = /* @__PURE__ */ new Map();
342
+ for (const o of all) {
343
+ const r = refOf(o);
344
+ if (r.group === ESO_GROUP && (r.kind === "SecretStore" || r.kind === "ClusterSecretStore") && r.name) stores.set(idOf(r), { obj: o, ref: r });
345
+ }
346
+ const providers = /* @__PURE__ */ new Map();
347
+ const touch = (storeKey) => {
348
+ const s = stores.get(storeKey);
349
+ if (!s || s.provider !== void 0) return s;
350
+ s.provider = providerOf(s.obj, s.ref, b) || null;
351
+ if (s.provider && !providers.has(s.provider.id)) providers.set(s.provider.id, { provider: s.provider, keys: /* @__PURE__ */ new Set(), stores: [] });
352
+ if (s.provider) providers.get(s.provider.id).stores.push(s);
353
+ return s;
354
+ };
355
+ for (const key of stores.keys()) touch(key);
356
+ for (const o of all) {
357
+ const ref = refOf(o);
358
+ if (ref.group !== ESO_GROUP || ref.kind !== "ExternalSecret" || !ref.name) continue;
359
+ const from = idOf(ref);
360
+ const spec = isObject(o.spec) ? o.spec : {};
361
+ const sref = spec.secretStoreRef;
362
+ if (isMasked(sref) || isObject(sref) && (isMasked(sref.name) || isMasked(sref.kind))) {
363
+ b.note(from, "spec.secretStoreRef", "masked", "the live read masked secretStoreRef, so the store and the keys cannot be joined", { waitsOn: WAITS_ON_MASK });
364
+ continue;
365
+ }
366
+ if (!isObject(sref) || !str(sref.name)) {
367
+ b.note(from, "spec.secretStoreRef", "unrecognised", "no store named");
368
+ continue;
369
+ }
370
+ const storeKind = str(sref.kind) || "SecretStore";
371
+ if (storeKind !== "SecretStore" && storeKind !== "ClusterSecretStore") {
372
+ b.note(from, "spec.secretStoreRef.kind", "unrecognised", `no placeholder rule for a ${storeKind} store`);
373
+ continue;
374
+ }
375
+ const storeRef = { group: ESO_GROUP, kind: storeKind, namespace: storeKind === "ClusterSecretStore" ? "" : ref.namespace, name: sref.name };
376
+ const keys = keysOf(o, ref, b);
377
+ const held = holdsK8s(b.graph, storeRef);
378
+ const found = touch(idOf(storeRef));
379
+ if (!held) {
380
+ const id = `outside:store:${storeKind}/${storeKind === "SecretStore" ? `${storeRef.namespace}/` : ""}${storeRef.name}`;
381
+ b.card({
382
+ id,
383
+ kind: "SecretStore",
384
+ label: storeKind === "SecretStore" ? `SecretStore ${storeRef.namespace}/${storeRef.name}` : `ClusterSecretStore ${storeRef.name}`,
385
+ attrs: { storeKind, name: storeRef.name, ...storeRef.namespace ? { namespace: storeRef.namespace } : {}, read: !!found }
386
+ });
387
+ b.edge(from, ref, id, "spec.secretStoreRef");
388
+ }
389
+ if (!found) {
390
+ b.note(from, "spec.secretStoreRef", "unresolved", `${storeKind} ${storeRef.name} is not among the objects read, so its provider is not known`);
391
+ continue;
392
+ }
393
+ if (found.provider) for (const k of keys) providers.get(found.provider.id).keys.add(k);
394
+ }
395
+ for (const { provider, keys, stores: viaStores } of providers.values()) {
396
+ const kept = [...keys].filter((k) => !holdsSecret(b.graph, provider, k)).sort();
397
+ const { id, label, path, ...attrs } = provider;
398
+ b.card({ id, kind: "SecretProvider", label, attrs: { ...attrs, keys: kept } });
399
+ for (const s of viaStores) b.edge(idOf(s.ref), s.ref, id, path);
400
+ }
401
+ }
402
+ function sourceCard(b, ref, from, via, { url, path, chart, revision, kindOfSource }) {
403
+ const repo = normalizeUrl(url);
404
+ if (holdsSource(b.graph, repo)) return;
405
+ const where = chart ? `chart=${chart}` : path ? cleanPath(path) : "";
406
+ const id = `outside:source:${repo}#${where}`;
407
+ const label = chart ? `${repo} chart ${chart}` : where ? `${repo} ${where}` : repo;
408
+ b.card({
409
+ id,
410
+ kind: "Source",
411
+ label,
412
+ attrs: { repoURL: repo, ...path ? { path: cleanPath(path) } : {}, ...chart ? { chart } : {}, ...kindOfSource ? { sourceKind: kindOfSource } : {} }
413
+ });
414
+ b.edge(from, ref, id, via, revision ? { revision } : void 0);
415
+ }
416
+ function application(b, obj, ref) {
417
+ const from = idOf(ref);
418
+ const spec = isObject(obj.spec) ? obj.spec : {};
419
+ const entries = [];
420
+ if (isObject(spec.source)) entries.push([spec.source, "spec.source"]);
421
+ arr(spec.sources).forEach((s, i) => entries.push([s, `spec.sources[${i}]`]));
422
+ for (const [s, via] of entries) {
423
+ if (!isObject(s)) continue;
424
+ const url = str(s.repoURL);
425
+ if (!url || isMasked(url)) {
426
+ b.note(from, `${via}.repoURL`, "unrecognised", "no readable repoURL");
427
+ continue;
428
+ }
429
+ sourceCard(b, ref, from, via, { url, path: str(s.path), chart: str(s.chart), revision: str(s.targetRevision) });
430
+ }
431
+ }
432
+ var FLUX_SOURCE_KINDS = /* @__PURE__ */ new Set(["GitRepository", "OCIRepository", "Bucket"]);
433
+ function kustomization(b, obj, ref, all) {
434
+ const from = idOf(ref);
435
+ const spec = isObject(obj.spec) ? obj.spec : {};
436
+ const sref = spec.sourceRef;
437
+ if (!isObject(sref) || !str(sref.name)) {
438
+ b.note(from, "spec.sourceRef", "unrecognised", "no source named");
439
+ return;
440
+ }
441
+ const kind = str(sref.kind) || "GitRepository";
442
+ if (!FLUX_SOURCE_KINDS.has(kind)) {
443
+ b.note(from, "spec.sourceRef.kind", "unrecognised", `no placeholder rule for a ${kind} source`);
444
+ return;
445
+ }
446
+ const namespace = str(sref.namespace) || ref.namespace;
447
+ const source = all.find((o) => {
448
+ const r = refOf(o);
449
+ return r.group === FLUX_SOURCE_GROUP && r.kind === kind && r.name === sref.name && r.namespace === namespace;
450
+ });
451
+ if (!source) {
452
+ b.note(from, "spec.sourceRef", "unresolved", `${kind} ${namespace}/${sref.name} is not among the objects read, so the repo is not known`);
453
+ return;
454
+ }
455
+ const sspec = isObject(source.spec) ? source.spec : {};
456
+ const url = kind === "Bucket" ? str(sspec.endpoint) && str(sspec.bucketName) ? `${sspec.endpoint}/${sspec.bucketName}` : void 0 : str(sspec.url);
457
+ if (!url || isMasked(url)) {
458
+ b.note(from, "spec.sourceRef", "unrecognised", `${kind} ${namespace}/${sref.name} has no readable url`);
459
+ return;
460
+ }
461
+ sourceCard(b, ref, from, "spec.sourceRef", { url, path: str(spec.path), kindOfSource: kind });
462
+ }
463
+ function outsideRefs(objects, opts = {}) {
464
+ const all = flatten(objects);
465
+ const b = builder(opts.graph);
466
+ for (const o of all) {
467
+ const ref = refOf(o);
468
+ if (!ref.kind || !ref.name) continue;
469
+ if (ref.group === "" && ref.kind === "ServiceAccount") serviceAccount(b, o, ref);
470
+ else if (ref.group === ARGO_GROUP && ref.kind === "Application") application(b, o, ref);
471
+ else if (ref.group === FLUX_KUSTOMIZE_GROUP && ref.kind === "Kustomization") kustomization(b, o, ref, all);
472
+ }
473
+ externalSecrets(b, all);
474
+ return b.result();
475
+ }
476
+
477
+ // src/read-cluster.ts
478
+ var CHANT_CLOUD_INDEX = "@intentius/chant/lifecycle/cloud-index";
479
+ var CHANT_LISTER = "@intentius/chant/cloud-lister/index";
480
+ var ClusterReadRefusal = class extends Error {
481
+ constructor(code, message, remedy) {
482
+ super(message);
483
+ this.code = code;
484
+ this.remedy = remedy;
485
+ this.name = "ClusterReadRefusal";
486
+ }
487
+ code;
488
+ remedy;
489
+ };
490
+ async function chantLister() {
491
+ const index = CHANT_CLOUD_INDEX;
492
+ const lister = CHANT_LISTER;
493
+ let mod;
494
+ let listerMod;
495
+ try {
496
+ mod = await import(
497
+ /* @vite-ignore */
498
+ index
499
+ );
500
+ listerMod = await import(
501
+ /* @vite-ignore */
502
+ lister
503
+ );
504
+ } catch (e) {
505
+ throw new ClusterReadRefusal("chant", `the chant beside behold has no cloud lister (${CHANT_CLOUD_INDEX}) or could not load it: ${e.message}`, "install chant 0.124.54 or newer beside behold and run behold under tsx. Nothing was listed.");
506
+ }
507
+ if (typeof mod.indexCloud !== "function" || typeof listerMod.kubeTargetFromKubeconfig !== "function") {
508
+ throw new ClusterReadRefusal("chant", "the chant beside behold lacks indexCloud or kubeTargetFromKubeconfig", "install chant 0.124.54 or newer beside behold. Nothing was listed.");
509
+ }
510
+ const lexiconsOf = mod.substrateLexicons;
511
+ const planStore = mod.planIndexStore;
512
+ const openStore = mod.openIndexStore;
513
+ return {
514
+ indexCloud: mod.indexCloud,
515
+ noneStore: () => openStore(planStore({ store: "none", cwd: process.cwd(), env: {}, defaultStoreDir: () => process.cwd(), command: "behold graph" }), process.cwd()),
516
+ lexicons: async () => (await lexiconsOf("kubernetes")).lexicons,
517
+ kubeTarget: listerMod.kubeTargetFromKubeconfig
518
+ };
519
+ }
520
+ function kubeconfigPath(opts = {}) {
521
+ if (opts.kubeconfig) return resolve2(opts.kubeconfig);
522
+ const env = opts.env ?? process.env;
523
+ const first = (env.KUBECONFIG ?? "").split(delimiter).find(Boolean);
524
+ return first ? resolve2(first) : join(opts.home ?? homedir(), ".kube", "config");
525
+ }
526
+ var named = (list, name, field) => {
527
+ for (const e of Array.isArray(list) ? list : []) {
528
+ const o = e;
529
+ if (o?.name === name) return o[field] ?? {};
530
+ }
531
+ return void 0;
532
+ };
533
+ function inspect(text, path, wanted) {
534
+ let doc;
535
+ try {
536
+ doc = parseYAML(text);
537
+ } catch (e) {
538
+ throw new ClusterReadRefusal("kubeconfig", `${path} is not a kubeconfig: ${e.message}`, "name a kubeconfig file with --kubeconfig. Nothing was listed.");
539
+ }
540
+ if (!doc || typeof doc !== "object") throw new ClusterReadRefusal("kubeconfig", `${path} is not a kubeconfig`, "name a kubeconfig file with --kubeconfig. Nothing was listed.");
541
+ const context = wanted ?? (typeof doc["current-context"] === "string" ? doc["current-context"] : void 0);
542
+ if (!context) throw new ClusterReadRefusal("context", `${path} names no current context and none was given`, "pass --context <name>. Nothing was listed.");
543
+ const ctx = named(doc.contexts, context, "context");
544
+ if (!ctx) throw new ClusterReadRefusal("context", `${path} has no context ${context}`, "pass the name of a context the kubeconfig has. Nothing was listed.");
545
+ const userName = String(ctx.user ?? "");
546
+ const clusterName = String(ctx.cluster ?? "");
547
+ const user = named(doc.users, userName, "user") ?? {};
548
+ const cluster = named(doc.clusters, clusterName, "cluster") ?? {};
549
+ return { doc, context, user, userName, cluster, clusterName };
550
+ }
551
+ async function withExecCredential(doc, found, baseDir, opts) {
552
+ const exec = found.user.exec;
553
+ const b64 = (v) => typeof v === "string" && v ? v : void 0;
554
+ const cred = await runExecPlugin(
555
+ exec,
556
+ { server: String(found.cluster.server ?? ""), ...b64(found.cluster["certificate-authority-data"]) ? { caData: b64(found.cluster["certificate-authority-data"]) } : {}, ...found.cluster["insecure-skip-tls-verify"] === true ? { insecureSkipVerify: true } : {} },
557
+ { baseDir, ...opts.env ? { env: opts.env } : {}, ...opts.runExec ? { run: opts.runExec } : {} }
558
+ );
559
+ const swapped = JSON.parse(JSON.stringify(doc));
560
+ const users = swapped.users;
561
+ const entry = users.find((u) => u.name === found.userName);
562
+ entry.user = {
563
+ ...cred.token ? { token: cred.token } : {},
564
+ ...cred.clientCertificateData && cred.clientKeyData ? { "client-certificate-data": Buffer.from(cred.clientCertificateData).toString("base64"), "client-key-data": Buffer.from(cred.clientKeyData).toString("base64") } : {}
565
+ };
566
+ return JSON.stringify(swapped);
567
+ }
568
+ function execRefusal(context, userName, command) {
569
+ return new ClusterReadRefusal(
570
+ "exec-plugin",
571
+ `context ${context}: user ${userName} authenticates through an exec plugin${command ? ` (${command})` : ""}, and behold does not run a command a kubeconfig names unless you say so`,
572
+ "use a context with a token, a token file or a client certificate (k3d and kind write those), or pass --allow-exec-plugin to let behold run the plugin once and read with the credential it prints. Nothing was listed."
573
+ );
574
+ }
575
+ function drawnIds(nodes) {
576
+ const parts = (n) => {
577
+ const type = (n.listedType ?? "").split("/");
578
+ const kind = type[type.length - 1] || "Object";
579
+ const group = type.length === 3 ? type[0] : "";
580
+ const name = n.attrs?.metadata?.name ?? n.id.split("/").pop() ?? n.id;
581
+ return { place: n.location || "cluster", group, kind, name };
582
+ };
583
+ const plain = (p) => `${p.place}/${p.kind}/${p.name}`;
584
+ const count = /* @__PURE__ */ new Map();
585
+ for (const n of nodes) count.set(plain(parts(n)), (count.get(plain(parts(n))) ?? 0) + 1);
586
+ const out = /* @__PURE__ */ new Map();
587
+ for (const n of nodes) {
588
+ const p = parts(n);
589
+ out.set(n.id, (count.get(plain(p)) ?? 0) > 1 && p.group ? `${p.place}/${p.group}/${p.kind}/${p.name}` : plain(p));
590
+ }
591
+ return out;
592
+ }
593
+ function drawIr(graph) {
594
+ const ids = drawnIds(graph.nodes);
595
+ const idOf2 = (id) => ids.get(id);
596
+ const nodes = graph.nodes.map((n) => ({ ...n, id: idOf2(n.id) }));
597
+ const edges = graph.edges.filter((e) => idOf2(e.from) && idOf2(e.to)).map((e) => ({ ...e, from: idOf2(e.from), to: idOf2(e.to) }));
598
+ const byStack = {};
599
+ for (const n of graph.nodes) (byStack[n.location || "cluster"] ??= []).push(idOf2(n.id));
600
+ const groups = { byStack };
601
+ for (const [k, v] of Object.entries(graph.groups ?? {})) {
602
+ if (k !== "byStack") groups[k] = Object.fromEntries(Object.entries(v).map(([key, list]) => [key, list.map((id) => idOf2(id)).filter((x) => !!x)]));
603
+ }
604
+ const dangling = (graph.dangling ?? []).filter((d) => !(d.path === "metadata.namespace") && idOf2(d.from)).map((d) => ({ ...d, from: idOf2(d.from) }));
605
+ return { ir: { ...graph, nodes, edges, groups, dangling }, dropped: graph.edges.length - edges.length };
606
+ }
607
+ function maskedAsListed(v) {
608
+ if (v === "[REDACTED]") return "<masked>";
609
+ if (Array.isArray(v)) return v.map(maskedAsListed);
610
+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, maskedAsListed(x)]));
611
+ return v;
612
+ }
613
+ var OUTSIDE_BOX = "Outside the cluster";
614
+ function addOutsideCards(ir) {
615
+ const listed = ir.nodes;
616
+ const key = (group, kind, ns, name) => `${group}/${kind}/${ns}/${name}`;
617
+ const idByRef = /* @__PURE__ */ new Map();
618
+ const manifests = [];
619
+ for (const n of listed) {
620
+ if (!n.listedType) continue;
621
+ const type = n.listedType.split("/");
622
+ const kind = type[type.length - 1];
623
+ const group = type.length === 3 ? type[0] : "";
624
+ const version = type[type.length - 2];
625
+ const meta = n.attrs?.metadata ?? {};
626
+ manifests.push({ ...maskedAsListed(n.attrs ?? {}), apiVersion: group ? `${group}/${version}` : version, kind });
627
+ idByRef.set(key(group, kind, kind === "ClusterSecretStore" ? "" : meta.namespace || "default", meta.name ?? ""), n.id);
628
+ }
629
+ const out = outsideRefs(manifests, { graph: { nodes: ir.nodes } });
630
+ const masked = out.notes.filter((n) => n.code === "masked").length;
631
+ if (!out.cards.length) return { ir, cards: 0, masked };
632
+ const cards = out.cards.map((c) => ({ id: c.id, kind: c.kind, lexicon: "outside", attrs: { ...c.attrs ?? {}, ...c.label ? { label: c.label } : {} } }));
633
+ const edges = out.edges.flatMap((e) => {
634
+ const from = idByRef.get(e.from);
635
+ return from ? [{ from, to: e.to, kind: "ref", viaAttr: e.viaAttr, inferred: true }] : [];
636
+ });
637
+ const groups = { ...ir.groups ?? {}, byStack: { ...ir.groups?.byStack ?? {}, [OUTSIDE_BOX]: cards.map((c) => c.id) } };
638
+ return { ir: { ...ir, nodes: [...ir.nodes, ...cards], edges: [...ir.edges, ...edges], groups }, cards: cards.length, masked };
639
+ }
640
+ async function readCluster(opts = {}) {
641
+ const path = kubeconfigPath(opts);
642
+ if (!existsSync(path)) throw new ClusterReadRefusal("kubeconfig", `no kubeconfig at ${path}`, "pass --kubeconfig <file> or set KUBECONFIG. Nothing was listed.");
643
+ const text = readFileSync(path, "utf8");
644
+ const baseDir = dirname(path);
645
+ const found = inspect(text, path, opts.context);
646
+ let kubeconfigText = text;
647
+ if (found.user["auth-provider"]) {
648
+ throw new ClusterReadRefusal("auth-provider", `context ${found.context}: user ${found.userName} authenticates through an auth-provider, which kubectl no longer supports`, "use a context with a token, a token file or a client certificate, or an exec plugin with --allow-exec-plugin. Nothing was listed.");
649
+ }
650
+ const exec = found.user.exec;
651
+ if (exec && !opts.allowExecPlugin) throw execRefusal(found.context, found.userName, exec.command);
652
+ const chant = opts.chant ?? await chantLister();
653
+ if (exec) {
654
+ try {
655
+ kubeconfigText = await withExecCredential(found.doc, found, baseDir, opts);
656
+ } catch (e) {
657
+ if (e instanceof ExecPluginError) throw new ClusterReadRefusal("exec-plugin", `context ${found.context}: the exec plugin gave no credential: ${e.message}`, "run the plugin's command yourself to see its error. Nothing was listed.");
658
+ throw e;
659
+ }
660
+ }
661
+ const target = chant.kubeTarget(kubeconfigText, { context: found.context, baseDir });
662
+ const namespaces = opts.namespaces?.length ? [...opts.namespaces] : void 0;
663
+ let doc;
664
+ try {
665
+ ({ doc } = await chant.indexCloud({
666
+ scope: { substrate: "kubernetes", scopeId: target.clusterName, locations: namespaces ?? "*", types: opts.types?.length ? [...opts.types] : "*" },
667
+ target: { substrate: "kubernetes", kubernetes: { server: target.server, ...target.token ? { token: target.token } : {}, ...target.tls ? { tls: target.tls } : {} } },
668
+ store: await chant.noneStore(),
669
+ lexicons: await chant.lexicons(),
670
+ ...opts.version ? { version: opts.version } : {}
671
+ }));
672
+ } catch (e) {
673
+ throw new ClusterReadRefusal("read", `context ${found.context}: ${e.message}`, "check that the cluster is reachable and the credential is accepted. Nothing was written.");
674
+ }
675
+ const { ir: drawn, dropped } = drawIr(doc.graph);
676
+ const members = [{ name: found.context, dir: "", kind: "chant" }];
677
+ const composed = await readComposed(drawn, members, [], { k8sContext: found.context });
678
+ const outside = addOutsideCards(composed.ir);
679
+ const read = { ...composed, ir: outside.ir };
680
+ const notListed = doc.coverage.filter((c) => c.verdict !== "listed").map((c) => ({ listedType: c.listedType, verdict: c.verdict, ...c.detail ? { detail: c.detail } : {} }));
681
+ const clauses = [
682
+ `read from cluster ${found.context}, ${drawn.nodes.length} objects`,
683
+ notListed.length ? `${new Set(notListed.map((n) => n.listedType)).size} kinds not listed (${[...new Set(notListed.map((n) => n.verdict))].join(", ")})` : void 0,
684
+ dropped ? `${dropped} edges to objects outside the read are left out` : void 0,
685
+ outside.cards ? `${outside.cards} ${outside.cards === 1 ? "card" : "cards"} for what the objects name outside the cluster` : void 0,
686
+ outside.masked ? `${outside.masked} reference ${outside.masked === 1 ? "field is masked by the live read and draws" : "fields are masked by the live read and draw"} no card (chant#5116)` : void 0
687
+ ].filter(Boolean);
688
+ const note = [read.meta.note, clauses.join(" \xB7 ")].filter(Boolean).join(" \xB7 ");
689
+ return {
690
+ ...read,
691
+ meta: { estate: 1, note },
692
+ cluster: { context: found.context, cluster: target.clusterName, kubeconfig: path, observedAt: doc.stamp.observedAt, notListed }
693
+ };
694
+ }
695
+
696
+ // src/graph-cli.ts
697
+ function graphUsage(prog = "behold graph") {
698
+ const flags = [...GRAPH_FORMATS.map((f) => f.name), ...Object.keys(PENDING_FORMATS)].map((n) => `--${n}`).join(" | ");
699
+ return `Usage: ${prog} [dir] [${flags}] [--theme light|dark] [-o <file>] [--detail 0..3] [--source] [--every-card]
700
+ ${prog} [dir] --changed <base>..<head> [--depth n] [--budget n]
701
+ ${prog} --context <name> [--kubeconfig <file>] [--namespace <ns,...>] [--types <t,...>] [--allow-exec-plugin]
702
+ ${prog} [dir] --around <id>[,<id>...] [--depth n] [--up | --down]
703
+
704
+ Read a directory into behold's graph and print it. Starts no server.
705
+
706
+ dir A folder of .tf files, a chant workspace root, a choudoufu
707
+ estate or a chant project. Default: the current directory.
708
+ ${GRAPH_FORMATS.map((f) => ` --${f.name.padEnd(13)}${f.summary}`).join("\n")}
709
+ ${Object.keys(PENDING_FORMATS).map((n) => ` --${n.padEnd(13)}not in this version yet`).join("\n")}
710
+ --forge <name> With --mermaid: fit that forge's character budget, one of
711
+ ${FORGES.join(", ")} (default github). Over budget, neighbours go
712
+ first, then whole boxes, and a line says how many cards are
713
+ not shown.
714
+ --theme <name> With --svg: ${SVG_THEMES.join(" or ")} (default dark).
715
+ -o <file> Write to <file> instead of stdout.
716
+ --detail <n> 0 to 3, as the zoom levels read (default 2, resources;
717
+ 3 adds attributes, and a Kubernetes object's spec).
718
+ --source Keep each card's source text (attrs.source), which is left
719
+ out by default: a Terraform root's whole file rides on every
720
+ card from it.
721
+ --every-card Draw every card: no stacking of alike cards in a box.
722
+ --changed <base>..<head>
723
+ Cut to what changed between two commits, plus the cards
724
+ within --depth hops of it (default 1), each marked added,
725
+ removed, changed or neighbour. Both are read from git
726
+ archive into a temporary directory: the checkout is not
727
+ touched, and a shallow clone works once the two commits are
728
+ fetched. <base>...<head> starts from their merge base. The
729
+ read is at --detail 3 unless you give another, since below
730
+ it a card holds no attributes to compare. Past --budget
731
+ cards (default ${CHANGED_NODE_BUDGET}) the neighbours fold into a count per box, then
732
+ the cut becomes a table of counts per box.
733
+ --around <id>[,<id>...]
734
+ Cut to the cards (or boxes) named and what is within --depth
735
+ hops of them (default 1). --up follows what they depend on,
736
+ --down what depends on them; the default is both. Exit 1
737
+ when an id is not in the graph.
738
+ --context <name>
739
+ Draw the cluster that kubeconfig context points at, with no
740
+ project: chant's read-only lister runs API discovery and a
741
+ LIST per kind, and nothing is written (no index store, no
742
+ file). Cards are boxed by namespace; cluster-scoped objects
743
+ sit in a box named cluster. Not with a dir or --changed.
744
+ A Secret's data is masked by the
745
+ lister, and so is any field whose name matches /secret/i.
746
+ --kubeconfig <file>
747
+ The kubeconfig to read (default: the first path in
748
+ KUBECONFIG, then ~/.kube/config). Alone it reads that file's
749
+ current-context.
750
+ --namespace <ns,...>
751
+ With --context: list only these namespaces. Add cluster to
752
+ list cluster-scoped objects too. Default: all of them.
753
+ --types <t,...>
754
+ With --context: list only these types, as the lister names
755
+ them (apps/v1/Deployment, v1/Service).
756
+ --allow-exec-plugin
757
+ With --context: a kubeconfig user that authenticates through
758
+ an exec plugin (the GKE, EKS and AKS tools write these) is
759
+ refused by default, because behold would run the command the
760
+ file names. This runs it once and reads with the credential
761
+ it prints. An auth-provider user is always refused.
762
+ --depth <n> Hops for --changed and --around.
763
+ --budget <n> Cards a --changed cut may hold before it folds.
764
+ `;
765
+ }
766
+ function parse(argv) {
767
+ let dir;
768
+ let format;
769
+ let out;
770
+ let detail;
771
+ let forge;
772
+ let theme;
773
+ let source = false;
774
+ let alike = true;
775
+ let changed;
776
+ let around;
777
+ let depth;
778
+ let budget;
779
+ let direction;
780
+ let context;
781
+ let kubeconfig;
782
+ let namespaces;
783
+ let types;
784
+ let allowExec = false;
785
+ const formats = /* @__PURE__ */ new Set([...GRAPH_FORMATS.map((f) => f.name), ...Object.keys(PENDING_FORMATS)]);
786
+ for (let i = 0; i < argv.length; i++) {
787
+ const a = argv[i];
788
+ if (a === "-h" || a === "--help") return { help: true };
789
+ if (a.startsWith("--") && formats.has(a.slice(2))) {
790
+ if (format && format !== a.slice(2)) return { error: `--${format} and ${a} name two formats; give one` };
791
+ format = a.slice(2);
792
+ } else if (a === "-o" || a === "--out") {
793
+ out = argv[++i];
794
+ if (!out) return { error: `${a} needs a file` };
795
+ } else if (a === "--detail") {
796
+ const v = argv[++i];
797
+ if (v === void 0 || !/^[0-3]$/.test(v)) return { error: "--detail takes 0, 1, 2 or 3" };
798
+ detail = Number(v);
799
+ } else if (a === "--forge") {
800
+ const v = argv[++i];
801
+ if (v === void 0 || !isForge(v)) return { error: `--forge takes ${FORGES.join(", ")}` };
802
+ forge = v;
803
+ } else if (a === "--theme") {
804
+ const v = argv[++i];
805
+ if (v === void 0 || !isSvgTheme(v)) return { error: `--theme takes ${SVG_THEMES.join(" or ")}` };
806
+ theme = v;
807
+ } else if (a === "--context" || a === "--kubeconfig") {
808
+ const v = argv[++i];
809
+ if (!v) return { error: `${a} needs a ${a === "--context" ? "context name" : "file"}` };
810
+ if (a === "--context") context = v;
811
+ else kubeconfig = v;
812
+ } else if (a === "--namespace" || a === "--namespaces" || a === "--types") {
813
+ const v = argv[++i]?.split(",").map((x) => x.trim()).filter(Boolean);
814
+ if (!v?.length) return { error: `${a} needs one or more names, comma separated` };
815
+ if (a === "--types") types = v;
816
+ else namespaces = v;
817
+ } else if (a === "--allow-exec-plugin") {
818
+ allowExec = true;
819
+ } else if (a === "--source") {
820
+ source = true;
821
+ } else if (a === "--every-card") {
822
+ alike = false;
823
+ } else if (a === "--changed") {
824
+ changed = argv[++i];
825
+ if (!changed) return { error: "--changed needs a range: <base>..<head>" };
826
+ } else if (a === "--around") {
827
+ const v = argv[++i];
828
+ around = v?.split(",").map((x) => x.trim()).filter(Boolean);
829
+ if (!around?.length) return { error: "--around needs one or more ids, comma separated" };
830
+ } else if (a === "--depth" || a === "--budget") {
831
+ const v = argv[++i];
832
+ if (v === void 0 || !/^\d+$/.test(v) || a === "--budget" && Number(v) < 1) return { error: `${a} takes a whole number${a === "--budget" ? " of 1 or more" : ""}` };
833
+ if (a === "--depth") depth = Number(v);
834
+ else budget = Number(v);
835
+ } else if (a === "--up" || a === "--down") {
836
+ const d = a.slice(2);
837
+ if (direction && direction !== d) return { error: "--up and --down name two directions; give one, or neither for both" };
838
+ direction = d;
839
+ } else if (a.startsWith("-")) {
840
+ return { error: `unknown option ${a}` };
841
+ } else if (dir === void 0) {
842
+ dir = a;
843
+ } else {
844
+ return { error: `one directory only (got ${dir} and ${a})` };
845
+ }
846
+ }
847
+ const cluster = context !== void 0 || kubeconfig !== void 0;
848
+ if (cluster && dir !== void 0) return { error: `a directory and a cluster are two reads; give ${dir} or --context, not both` };
849
+ if (cluster && changed) return { error: "--changed reads two commits of a directory; it does not go with --context" };
850
+ if (!cluster && (namespaces || types || allowExec)) return { error: "--namespace, --types and --allow-exec-plugin go with --context" };
851
+ if (forge && format !== "mermaid") return { error: "--forge goes with --mermaid" };
852
+ if (changed && around) return { error: "--changed and --around are two cuts; give one" };
853
+ if ((depth !== void 0 || budget !== void 0 || direction) && !changed && !around) return { error: "--depth, --budget, --up and --down go with --changed or --around" };
854
+ if (changed && direction) return { error: "--up and --down go with --around: a changed cut keeps neighbours both ways" };
855
+ if (around && budget !== void 0) return { error: "--budget goes with --changed" };
856
+ if ((changed || around) && format === "ir") return { error: "--ir is always the whole view; a cut is over the --json document" };
857
+ if (theme && format !== "svg") return { error: "--theme goes with --svg" };
858
+ return {
859
+ dir: dir ?? ".",
860
+ format: format ?? "json",
861
+ ...out ? { out } : {},
862
+ ...detail !== void 0 ? { detail } : {},
863
+ ...forge ? { forge } : {},
864
+ ...theme ? { theme } : {},
865
+ source,
866
+ alike,
867
+ allowExec,
868
+ ...context ? { context } : {},
869
+ ...kubeconfig ? { kubeconfig } : {},
870
+ ...namespaces ? { namespaces } : {},
871
+ ...types ? { types } : {},
872
+ ...changed ? { changed } : {},
873
+ ...around ? { around } : {},
874
+ ...depth !== void 0 ? { depth } : {},
875
+ ...budget !== void 0 ? { budget } : {},
876
+ ...direction ? { direction } : {}
877
+ };
878
+ }
879
+ async function runGraph(argv, io) {
880
+ const stdout = io.stdout ?? ((t) => void process.stdout.write(t));
881
+ const stderr = io.stderr ?? ((t) => void process.stderr.write(t));
882
+ const usage = graphUsage(io.prog);
883
+ const parsed = parse(argv);
884
+ if ("help" in parsed) {
885
+ stdout(usage);
886
+ return 0;
887
+ }
888
+ if ("error" in parsed) {
889
+ stderr(`${io.prog ?? "behold graph"}: ${parsed.error}
890
+
891
+ ${usage}`);
892
+ return 2;
893
+ }
894
+ const pending = PENDING_FORMATS[parsed.format];
895
+ if (pending) {
896
+ stderr(`${io.prog ?? "behold graph"}: ${pending}
897
+ `);
898
+ return 2;
899
+ }
900
+ const format = graphFormat(parsed.format);
901
+ const cluster = parsed.context !== void 0 || parsed.kubeconfig !== void 0;
902
+ const dir = resolve3(parsed.dir);
903
+ if (!cluster && (!existsSync2(dir) || !statSync(dir).isDirectory())) {
904
+ stderr(`${io.prog ?? "behold graph"}: ${parsed.dir} is not a directory
905
+ `);
906
+ return 2;
907
+ }
908
+ const prog = io.prog ?? "behold graph";
909
+ let view;
910
+ let document;
911
+ let cut;
912
+ let keptCards;
913
+ try {
914
+ if (parsed.changed) {
915
+ const range = parseRange(parsed.changed);
916
+ if ("error" in range) {
917
+ stderr(`${prog}: ${range.error}
918
+ `);
919
+ return 2;
920
+ }
921
+ const root = gitRoot(dir);
922
+ const { base, head } = resolveRange(root, range);
923
+ const detail = parsed.detail ?? 3;
924
+ const opts = { alike: false, detail, behold: io.version, source: parsed.source };
925
+ const headRead = await readAtRevision(root, dir, head, opts);
926
+ if (!headRead) {
927
+ stderr(`${prog}: ${parsed.dir} does not exist at ${range.head} (${head.slice(0, 10)})
928
+ `);
929
+ return 1;
930
+ }
931
+ const baseRead = await readAtRevision(root, dir, base, opts);
932
+ const before = baseRead?.document ?? emptyDocument(headRead.document, base);
933
+ view = headRead.view;
934
+ document = headRead.options;
935
+ const names = { base: range.mergeBase ? `${range.base}...` : range.base, head: range.head };
936
+ cut = (after) => {
937
+ const doc = cutChanged(before, after, {
938
+ base: names.base,
939
+ head: names.head,
940
+ ...parsed.depth !== void 0 ? { depth: parsed.depth } : {},
941
+ ...parsed.budget !== void 0 ? { budget: parsed.budget } : {}
942
+ });
943
+ keptCards = doc.nodes.length;
944
+ if (detail < 3) doc.notes.push({ kind: "changed-detail", text: `read at --detail ${detail}: a card holds no attributes there, so only added and removed cards show; use --detail 3 to see an edited attribute` });
945
+ return doc;
946
+ };
947
+ } else if (cluster) {
948
+ const read = await readCluster({
949
+ ...parsed.context ? { context: parsed.context } : {},
950
+ ...parsed.kubeconfig ? { kubeconfig: parsed.kubeconfig } : {},
951
+ ...parsed.namespaces ? { namespaces: parsed.namespaces } : {},
952
+ ...parsed.types ? { types: parsed.types } : {},
953
+ allowExecPlugin: parsed.allowExec,
954
+ version: io.version
955
+ });
956
+ view = await clusterView(read, { alike: parsed.alike, ...parsed.detail !== void 0 ? { detail: parsed.detail } : {} });
957
+ document = { generator: { behold: io.version }, origin: { dir: "." }, members: {}, scrub: documentScrubber(resolve3("."), []) };
958
+ } else {
959
+ view = await graphView(dir, { alike: parsed.alike, ...parsed.detail !== void 0 ? { detail: parsed.detail } : {} });
960
+ document = documentOptions({ projectDir: dir, ...view.read.workspace ? { workspace: view.read.workspace } : {}, behold: io.version });
961
+ }
962
+ if (parsed.around) {
963
+ const ids = parsed.around;
964
+ cut = (doc) => {
965
+ const r = cutDocument(doc, ids, { ...parsed.depth !== void 0 ? { depth: parsed.depth } : {}, ...parsed.direction ? { direction: parsed.direction } : {} });
966
+ if (!r.ok) throw new CutRefused(r.error);
967
+ keptCards = r.document.nodes.length;
968
+ return r.document;
969
+ };
970
+ }
971
+ } catch (err) {
972
+ if (err instanceof ReadGraphError) {
973
+ stderr(`${err.refusal.error}
974
+ ${err.refusal.remedy}
975
+ `);
976
+ return 1;
977
+ }
978
+ if (err instanceof ClusterReadRefusal) {
979
+ stderr(`${prog}: ${err.message}
980
+ ${err.remedy}
981
+ `);
982
+ return err.code === "exec-plugin" || err.code === "auth-provider" ? 2 : 1;
983
+ }
984
+ if (err instanceof RevisionError) {
985
+ stderr(`${prog}: ${err.message}
986
+ ${err.remedy ? `${err.remedy}
987
+ ` : ""}`);
988
+ return 1;
989
+ }
990
+ throw err;
991
+ }
992
+ let text;
993
+ try {
994
+ text = format.emit({ view, document, source: parsed.source, ...parsed.forge ? { forge: parsed.forge } : {}, ...parsed.theme ? { theme: parsed.theme } : {}, ...cut ? { cut } : {} });
995
+ } catch (err) {
996
+ if (err instanceof CutRefused || err instanceof FlatLayoutTooLarge) {
997
+ stderr(`${prog}: ${err.message}
998
+ `);
999
+ return 1;
1000
+ }
1001
+ throw err;
1002
+ }
1003
+ const cards = keptCards ?? view.ir.nodes.length;
1004
+ if (parsed.out) {
1005
+ writeFileSync(resolve3(parsed.out), text);
1006
+ stderr(`wrote ${parsed.out} (${cards} ${cards === 1 ? "card" : "cards"})
1007
+ `);
1008
+ } else {
1009
+ stdout(text);
1010
+ }
1011
+ return 0;
1012
+ }
1013
+ var CutRefused = class extends Error {
1014
+ };
1015
+
1016
+ export {
1017
+ graphUsage,
1018
+ runGraph
1019
+ };