@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.
- package/AGENTS.md +64 -3133
- package/README.md +17 -6
- package/dist/chant-KLLNQOCK.js +117 -0
- package/dist/choudoufu-chant-read-MJ6DK23L.js +36 -0
- package/dist/chunk-26K6QLVB.js +157 -0
- package/dist/chunk-4IETG5U7.js +267 -0
- package/dist/chunk-7DQDWJI5.js +46 -0
- package/dist/chunk-ANJ33KX4.js +78 -0
- package/dist/chunk-C7OMVDI5.js +124 -0
- package/dist/chunk-GG3SLEYM.js +30297 -0
- package/dist/chunk-GMCRBXPQ.js +15578 -0
- package/dist/chunk-IMX6PXXA.js +1019 -0
- package/dist/chunk-JHLNY324.js +232 -0
- package/dist/chunk-JJPU2DXX.js +54 -0
- package/dist/chunk-KUHU6T4P.js +2820 -0
- package/dist/chunk-OY4EF7ZO.js +5651 -0
- package/dist/chunk-XKWCGNT2.js +8139 -0
- package/dist/chunk-YO233FHU.js +136 -0
- package/dist/cli.js +859 -77499
- package/dist/config-XKQQ4ORG.js +69 -0
- package/dist/config-run-4IMSAYPX.js +418 -0
- package/dist/declaration-5NE7H5UD.js +6867 -0
- package/dist/index.js +99 -0
- package/dist/main-4PGA5RJS.js +2509 -0
- package/dist/mcp-W2CHVEPI.js +753 -0
- package/dist/object-store-H77QSRIZ.js +1033 -0
- package/dist/src-54PT4UC5.js +1189 -0
- package/dist/tree-W23HE2EZ.js +17 -0
- package/example-choudoufu-estate/chant.workspace.json +1 -1
- package/example-terraform-estate/README.md +2 -2
- package/example-terraform-estate/chant.workspace.json +1 -1
- package/example-three-cloud/chant.workspace.json +2 -2
- package/example-three-cloud/package-lock.json +32 -515
- package/example-three-cloud/package.json +5 -5
- package/package.json +18 -16
|
@@ -0,0 +1,1189 @@
|
|
|
1
|
+
import "./chunk-7DQDWJI5.js";
|
|
2
|
+
|
|
3
|
+
// node_modules/@intentius/chant-k8s-client/src/errors.ts
|
|
4
|
+
var K8sApiError = class _K8sApiError extends Error {
|
|
5
|
+
constructor(statusCode, reason, apiMessage, target, status) {
|
|
6
|
+
super(
|
|
7
|
+
`${target ? `${target}: ` : ""}${apiMessage || "request failed"} (HTTP ${statusCode}${reason ? `, ${reason}` : ""})`
|
|
8
|
+
);
|
|
9
|
+
this.statusCode = statusCode;
|
|
10
|
+
this.reason = reason;
|
|
11
|
+
this.apiMessage = apiMessage;
|
|
12
|
+
this.target = target;
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.name = "K8sApiError";
|
|
15
|
+
}
|
|
16
|
+
statusCode;
|
|
17
|
+
reason;
|
|
18
|
+
apiMessage;
|
|
19
|
+
target;
|
|
20
|
+
status;
|
|
21
|
+
/**
|
|
22
|
+
* Which cluster the failing read actually talked to, e.g.
|
|
23
|
+
* `context "k3d-fountain-local" (bound by k8s.profiles.local.context)`.
|
|
24
|
+
* Stamped by the client that issued the request (chant #1488) — a
|
|
25
|
+
* `read-failed` that does not name the cluster it read cost an afternoon on
|
|
26
|
+
* a laptop with two k3d clusters, so the failure carries it from birth.
|
|
27
|
+
*/
|
|
28
|
+
contextNote;
|
|
29
|
+
/** The object is not there. The only failure that establishes absence. */
|
|
30
|
+
get notFound() {
|
|
31
|
+
return this.statusCode === 404 || this.reason === "NotFound";
|
|
32
|
+
}
|
|
33
|
+
/** RBAC denied the read. Proves nothing about whether the object exists. */
|
|
34
|
+
get forbidden() {
|
|
35
|
+
return this.statusCode === 403 || this.reason === "Forbidden";
|
|
36
|
+
}
|
|
37
|
+
/** No usable credentials for this cluster. */
|
|
38
|
+
get unauthorized() {
|
|
39
|
+
return this.statusCode === 401 || this.reason === "Unauthorized";
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Server-side-apply field-ownership conflict. `./conflict.ts`'s
|
|
43
|
+
* {@link import("./conflict").FieldManagerConflictError} is the presented
|
|
44
|
+
* form (chant #1075); this predicate still answers for both.
|
|
45
|
+
*/
|
|
46
|
+
get conflict() {
|
|
47
|
+
return this.statusCode === 409 || this.reason === "Conflict";
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Build from a raw response body, which is a `Status` on every well-behaved
|
|
51
|
+
* Kubernetes error and occasionally plain text from a proxy in front of one.
|
|
52
|
+
*/
|
|
53
|
+
static fromResponse(statusCode, body, target) {
|
|
54
|
+
let status;
|
|
55
|
+
try {
|
|
56
|
+
const parsed = JSON.parse(body);
|
|
57
|
+
if (parsed && typeof parsed === "object" && parsed.kind === "Status") {
|
|
58
|
+
status = parsed;
|
|
59
|
+
}
|
|
60
|
+
} catch {
|
|
61
|
+
}
|
|
62
|
+
const message = status?.message ?? firstLine(body) ?? "";
|
|
63
|
+
return new _K8sApiError(statusCode, status?.reason, message, target, status);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
var K8sTransportError = class extends Error {
|
|
67
|
+
constructor(message, target, options) {
|
|
68
|
+
super(target ? `${target}: ${message}` : message);
|
|
69
|
+
this.target = target;
|
|
70
|
+
this.name = "K8sTransportError";
|
|
71
|
+
if (options && "cause" in options) this.cause = options.cause;
|
|
72
|
+
}
|
|
73
|
+
target;
|
|
74
|
+
/** Which cluster context the failed request was aimed at — see {@link K8sApiError.contextNote}. */
|
|
75
|
+
contextNote;
|
|
76
|
+
};
|
|
77
|
+
var K8sClientUnavailableError = class extends Error {
|
|
78
|
+
constructor(cause) {
|
|
79
|
+
super(
|
|
80
|
+
"the Kubernetes API client is unavailable \u2014 @kubernetes/client-node could not be loaded. Install it with `npm i @intentius/chant-k8s-client` (it is an optional dependency of @intentius/chant-lexicon-k8s, so `--omit=optional` installs skip it)."
|
|
81
|
+
);
|
|
82
|
+
this.name = "K8sClientUnavailableError";
|
|
83
|
+
if (cause !== void 0) this.cause = cause;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
var ExecCredentialNotAllowedError = class extends Error {
|
|
87
|
+
constructor(command, allowed) {
|
|
88
|
+
super(
|
|
89
|
+
`k8s: the kubeconfig for this context authenticates with the exec credential plugin "${command}", which is not on chant's allowlist (${allowed.join(", ")}). An exec plugin is an arbitrary binary named in a file chant did not write. If "${command}" is expected, add it to k8s.execCredentialPlugins in chant.config.ts.`
|
|
90
|
+
);
|
|
91
|
+
this.command = command;
|
|
92
|
+
this.allowed = allowed;
|
|
93
|
+
this.name = "ExecCredentialNotAllowedError";
|
|
94
|
+
}
|
|
95
|
+
command;
|
|
96
|
+
allowed;
|
|
97
|
+
};
|
|
98
|
+
var FieldManagerError = class extends Error {
|
|
99
|
+
constructor(message) {
|
|
100
|
+
super(`k8s: ${message}`);
|
|
101
|
+
this.name = "FieldManagerError";
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
var KubeConfigError = class extends Error {
|
|
105
|
+
constructor(message) {
|
|
106
|
+
super(`k8s: ${message}`);
|
|
107
|
+
this.name = "KubeConfigError";
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var UnknownResourceError = class extends Error {
|
|
111
|
+
constructor(selectorText2, message) {
|
|
112
|
+
super(message ?? `k8s: the cluster's API discovery reports no resource matching "${selectorText2}"`);
|
|
113
|
+
this.selectorText = selectorText2;
|
|
114
|
+
this.name = "UnknownResourceError";
|
|
115
|
+
}
|
|
116
|
+
selectorText;
|
|
117
|
+
};
|
|
118
|
+
function firstLine(text, max = 300) {
|
|
119
|
+
const line = text.split("\n").find((l) => l.trim().length > 0)?.trim();
|
|
120
|
+
if (!line) return void 0;
|
|
121
|
+
return line.length > max ? `${line.slice(0, max - 3)}...` : line;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// node_modules/@intentius/chant-k8s-client/src/credentials.ts
|
|
125
|
+
var DEFAULT_EXEC_ALLOWLIST = [
|
|
126
|
+
"aws",
|
|
127
|
+
// EKS — `aws eks get-token`
|
|
128
|
+
"aws-iam-authenticator",
|
|
129
|
+
// EKS, pre-`aws eks get-token`
|
|
130
|
+
"gke-gcloud-auth-plugin",
|
|
131
|
+
// GKE
|
|
132
|
+
"kubelogin",
|
|
133
|
+
// AKS
|
|
134
|
+
"kubectl"
|
|
135
|
+
// OIDC via `kubectl oidc-login`, and k3d/kind setups
|
|
136
|
+
];
|
|
137
|
+
function execConfigOf(user) {
|
|
138
|
+
if (!user) return void 0;
|
|
139
|
+
if (user.exec) return user.exec;
|
|
140
|
+
const providerExec = user.authProvider?.config?.exec;
|
|
141
|
+
if (providerExec) return providerExec;
|
|
142
|
+
return void 0;
|
|
143
|
+
}
|
|
144
|
+
function execCommandName(command) {
|
|
145
|
+
const base = command.split(/[\\/]/).pop() ?? command;
|
|
146
|
+
return base.replace(/\.(exe|cmd|bat)$/i, "");
|
|
147
|
+
}
|
|
148
|
+
function assertExecCredentialAllowed(user, allowlist = DEFAULT_EXEC_ALLOWLIST) {
|
|
149
|
+
const exec = execConfigOf(user);
|
|
150
|
+
if (!exec?.command) return;
|
|
151
|
+
const name = execCommandName(exec.command);
|
|
152
|
+
if (allowlist.some((entry) => execCommandName(entry) === name)) return;
|
|
153
|
+
throw new ExecCredentialNotAllowedError(exec.command, allowlist);
|
|
154
|
+
}
|
|
155
|
+
function credentialPathOf(user) {
|
|
156
|
+
const exec = execConfigOf(user);
|
|
157
|
+
if (exec?.command) return { credential: "exec-plugin", execCommand: exec.command };
|
|
158
|
+
if (user?.authProvider?.name) return { credential: "auth-provider" };
|
|
159
|
+
if (user?.token) return { credential: "token" };
|
|
160
|
+
if (user?.certData || user?.certFile) return { credential: "client-certificate" };
|
|
161
|
+
if (user?.username) return { credential: "basic-auth" };
|
|
162
|
+
return { credential: "none" };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// node_modules/@intentius/chant-k8s-client/src/conflict.ts
|
|
166
|
+
var FieldManagerConflictError = class extends K8sApiError {
|
|
167
|
+
/** Every contested field, in the order the server reported them. */
|
|
168
|
+
conflicts;
|
|
169
|
+
/** The field manager chant applied as, and which was refused. */
|
|
170
|
+
fieldManager;
|
|
171
|
+
constructor(statusCode, apiMessage, conflicts, fieldManager, target, status) {
|
|
172
|
+
super(statusCode, status?.reason ?? "Conflict", apiMessage, target, status);
|
|
173
|
+
this.name = "FieldManagerConflictError";
|
|
174
|
+
this.conflicts = conflicts;
|
|
175
|
+
this.fieldManager = fieldManager;
|
|
176
|
+
this.message = renderConflictReport({ conflicts, fieldManager, target, apiMessage });
|
|
177
|
+
}
|
|
178
|
+
/** Contested paths grouped by the manager that owns them, managers sorted. */
|
|
179
|
+
get byManager() {
|
|
180
|
+
const grouped = {};
|
|
181
|
+
for (const conflict of this.conflicts) {
|
|
182
|
+
(grouped[conflict.manager] ??= []).push(conflict.field);
|
|
183
|
+
}
|
|
184
|
+
return Object.fromEntries(
|
|
185
|
+
Object.entries(grouped).sort(([a], [b]) => a.localeCompare(b)).map(([manager, fields]) => [manager, [...fields].sort()])
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
/** The competing managers, sorted. */
|
|
189
|
+
get managers() {
|
|
190
|
+
return Object.keys(this.byManager);
|
|
191
|
+
}
|
|
192
|
+
/** The contested paths, sorted and deduplicated. */
|
|
193
|
+
get fields() {
|
|
194
|
+
return [...new Set(this.conflicts.map((c) => c.field))].sort();
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
function renderConflictReport(report) {
|
|
198
|
+
const { conflicts, fieldManager, target } = report;
|
|
199
|
+
const subject = target ? `${target}` : "this object";
|
|
200
|
+
if (conflicts.length === 0) {
|
|
201
|
+
return `k8s: server-side apply of ${subject} was refused with a field-ownership conflict, but the API server reported no field causes${report.apiMessage ? ` \u2014 it said: ${report.apiMessage}` : ""}. chant applied as field manager "${fieldManager}".`;
|
|
202
|
+
}
|
|
203
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
204
|
+
for (const conflict of conflicts) {
|
|
205
|
+
const list = grouped.get(conflict.manager) ?? [];
|
|
206
|
+
if (!list.includes(conflict.field)) list.push(conflict.field);
|
|
207
|
+
grouped.set(conflict.manager, list);
|
|
208
|
+
}
|
|
209
|
+
const count = new Set(conflicts.map((c) => c.field)).size;
|
|
210
|
+
const lines = [
|
|
211
|
+
`k8s: server-side apply of ${subject} was refused \u2014 ${count} ${count === 1 ? "field is" : "fields are"} owned by another field manager.`,
|
|
212
|
+
""
|
|
213
|
+
];
|
|
214
|
+
for (const [manager, fields] of [...grouped].sort(([a], [b]) => a.localeCompare(b))) {
|
|
215
|
+
lines.push(` "${manager}" owns:`);
|
|
216
|
+
for (const field of [...fields].sort()) lines.push(` ${field}`);
|
|
217
|
+
}
|
|
218
|
+
lines.push(
|
|
219
|
+
"",
|
|
220
|
+
`chant applied as field manager "${fieldManager}". Taking these fields means the managers above`,
|
|
221
|
+
`stop owning them, and will contest them again on their next apply.`,
|
|
222
|
+
"",
|
|
223
|
+
"chant does not force this for you. Either:",
|
|
224
|
+
" - remove the contested fields from your chant source, leaving them to their current owner; or",
|
|
225
|
+
" - re-run this apply with force-conflicts on, deliberately (the `force: true` activity argument,",
|
|
226
|
+
" or `forceConflicts: true` on ApplyOp), which transfers ownership to chant."
|
|
227
|
+
);
|
|
228
|
+
return lines.join("\n");
|
|
229
|
+
}
|
|
230
|
+
function parseFieldConflicts(status, message) {
|
|
231
|
+
const fromCauses = causesOf(status);
|
|
232
|
+
if (fromCauses.length > 0) return fromCauses;
|
|
233
|
+
return parseConflictMessage(message ?? status?.message ?? "");
|
|
234
|
+
}
|
|
235
|
+
function causesOf(status) {
|
|
236
|
+
const details = status?.details;
|
|
237
|
+
if (!details || typeof details !== "object") return [];
|
|
238
|
+
const causes = details.causes;
|
|
239
|
+
if (!Array.isArray(causes)) return [];
|
|
240
|
+
const out = [];
|
|
241
|
+
for (const raw of causes) {
|
|
242
|
+
if (!raw || typeof raw !== "object") continue;
|
|
243
|
+
if (raw.type !== void 0 && raw.type !== "FieldManagerConflict") continue;
|
|
244
|
+
const field = typeof raw.field === "string" ? raw.field : void 0;
|
|
245
|
+
if (!field) continue;
|
|
246
|
+
const { manager, apiVersion } = parseCauseMessage(raw.message ?? "");
|
|
247
|
+
out.push({
|
|
248
|
+
manager: manager ?? "an unnamed manager",
|
|
249
|
+
field,
|
|
250
|
+
...apiVersion ? { apiVersion } : {}
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
function parseCauseMessage(message) {
|
|
256
|
+
const manager = /conflicts? with "([^"]+)"/.exec(message)?.[1];
|
|
257
|
+
const apiVersion = /\busing ([^\s:]+)\b/.exec(message)?.[1];
|
|
258
|
+
return { ...manager ? { manager } : {}, ...apiVersion ? { apiVersion } : {} };
|
|
259
|
+
}
|
|
260
|
+
function parseConflictMessage(message) {
|
|
261
|
+
if (!message) return [];
|
|
262
|
+
const out = [];
|
|
263
|
+
let manager;
|
|
264
|
+
let apiVersion;
|
|
265
|
+
for (const rawLine of message.split("\n")) {
|
|
266
|
+
const line = rawLine.trim();
|
|
267
|
+
if (line.length === 0) continue;
|
|
268
|
+
const header = /conflicts? with "([^"]+)"(?: using ([^\s:]+))?/.exec(line);
|
|
269
|
+
if (header) {
|
|
270
|
+
manager = header[1];
|
|
271
|
+
apiVersion = header[2];
|
|
272
|
+
const inline = /:\s*(\.[^\s]+)$/.exec(line);
|
|
273
|
+
if (inline) out.push({ manager, field: inline[1], ...apiVersion ? { apiVersion } : {} });
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
const bullet = /^-\s*(\S.*)$/.exec(line);
|
|
277
|
+
if (bullet && manager) {
|
|
278
|
+
out.push({ manager, field: bullet[1].trim(), ...apiVersion ? { apiVersion } : {} });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
function asFieldManagerConflict(error, fieldManager) {
|
|
284
|
+
if (!(error instanceof K8sApiError) || !error.conflict) return error;
|
|
285
|
+
if (error instanceof FieldManagerConflictError) return error;
|
|
286
|
+
return new FieldManagerConflictError(
|
|
287
|
+
error.statusCode,
|
|
288
|
+
error.apiMessage,
|
|
289
|
+
parseFieldConflicts(error.status, error.apiMessage),
|
|
290
|
+
fieldManager,
|
|
291
|
+
error.target,
|
|
292
|
+
error.status
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// node_modules/@intentius/chant-k8s-client/src/field-manager.ts
|
|
297
|
+
var CHANT_FIELD_MANAGER = "chant";
|
|
298
|
+
var FIELD_MANAGER_SEPARATOR = ":";
|
|
299
|
+
var FIELD_MANAGER_MAX_LENGTH = 128;
|
|
300
|
+
function fieldManagerFor(identity) {
|
|
301
|
+
const stack = identity?.stack?.trim();
|
|
302
|
+
if (!stack) return CHANT_FIELD_MANAGER;
|
|
303
|
+
const manager = `${CHANT_FIELD_MANAGER}${FIELD_MANAGER_SEPARATOR}${stack}`;
|
|
304
|
+
assertValidFieldManager(manager, stack);
|
|
305
|
+
return manager;
|
|
306
|
+
}
|
|
307
|
+
function assertValidFieldManager(manager, stack) {
|
|
308
|
+
const source = stack === void 0 ? `field manager "${manager}"` : `ownership.stack "${stack}"`;
|
|
309
|
+
if (manager.length === 0) {
|
|
310
|
+
throw new FieldManagerError(`${source} produces an empty field manager, which the API server rejects`);
|
|
311
|
+
}
|
|
312
|
+
if (manager.length > FIELD_MANAGER_MAX_LENGTH) {
|
|
313
|
+
throw new FieldManagerError(
|
|
314
|
+
`${source} produces the field manager "${manager}" (${manager.length} characters), over the API server's ${FIELD_MANAGER_MAX_LENGTH}-character limit`
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
const badIndex = [...manager].findIndex((ch) => {
|
|
318
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
319
|
+
return code <= 32 || code === 127;
|
|
320
|
+
});
|
|
321
|
+
if (badIndex !== -1) {
|
|
322
|
+
throw new FieldManagerError(
|
|
323
|
+
`${source} produces the field manager "${manager}", which contains whitespace or a control character at position ${badIndex}. A field manager is an identity recorded on every object chant applies; keep it to printable, space-free text.`
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function isChantFieldManager(manager) {
|
|
328
|
+
if (!manager) return false;
|
|
329
|
+
return manager === CHANT_FIELD_MANAGER || manager.startsWith(`${CHANT_FIELD_MANAGER}${FIELD_MANAGER_SEPARATOR}`);
|
|
330
|
+
}
|
|
331
|
+
function chantStackOf(manager) {
|
|
332
|
+
if (!manager || !isChantFieldManager(manager)) return void 0;
|
|
333
|
+
const stack = manager.slice(CHANT_FIELD_MANAGER.length + FIELD_MANAGER_SEPARATOR.length);
|
|
334
|
+
return stack.length > 0 ? stack : void 0;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// node_modules/@intentius/chant-k8s-client/src/concurrency.ts
|
|
338
|
+
var DEFAULT_CONCURRENCY = 8;
|
|
339
|
+
async function mapConcurrent(items, fn, limit = DEFAULT_CONCURRENCY) {
|
|
340
|
+
const width = Math.max(1, Math.min(limit, items.length));
|
|
341
|
+
const results = new Array(items.length);
|
|
342
|
+
let next = 0;
|
|
343
|
+
async function worker() {
|
|
344
|
+
while (true) {
|
|
345
|
+
const index = next++;
|
|
346
|
+
if (index >= items.length) return;
|
|
347
|
+
results[index] = await fn(items[index], index);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
await Promise.all(Array.from({ length: width }, () => worker()));
|
|
351
|
+
return results;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// node_modules/@intentius/chant-k8s-client/src/kubeconfig.ts
|
|
355
|
+
import { delimiter } from "node:path";
|
|
356
|
+
function kubeconfigPathList() {
|
|
357
|
+
const raw = process.env.KUBECONFIG;
|
|
358
|
+
if (!raw) return [];
|
|
359
|
+
return raw.split(delimiter).filter((f) => f.length > 0);
|
|
360
|
+
}
|
|
361
|
+
function mergeKubeconfigFiles(mod, files) {
|
|
362
|
+
const clusters = [];
|
|
363
|
+
const users = [];
|
|
364
|
+
const contexts = [];
|
|
365
|
+
const seenClusters = /* @__PURE__ */ new Set();
|
|
366
|
+
const seenUsers = /* @__PURE__ */ new Set();
|
|
367
|
+
const seenContexts = /* @__PURE__ */ new Set();
|
|
368
|
+
let currentContext;
|
|
369
|
+
for (const file of files) {
|
|
370
|
+
const part = new mod.KubeConfig();
|
|
371
|
+
try {
|
|
372
|
+
part.loadFromFile(file);
|
|
373
|
+
} catch {
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
for (const cluster of part.getClusters()) {
|
|
377
|
+
if (seenClusters.has(cluster.name)) continue;
|
|
378
|
+
seenClusters.add(cluster.name);
|
|
379
|
+
clusters.push(cluster);
|
|
380
|
+
}
|
|
381
|
+
for (const user of part.getUsers()) {
|
|
382
|
+
if (seenUsers.has(user.name)) continue;
|
|
383
|
+
seenUsers.add(user.name);
|
|
384
|
+
users.push(user);
|
|
385
|
+
}
|
|
386
|
+
for (const context of part.getContexts()) {
|
|
387
|
+
if (seenContexts.has(context.name)) continue;
|
|
388
|
+
seenContexts.add(context.name);
|
|
389
|
+
contexts.push(context);
|
|
390
|
+
}
|
|
391
|
+
if (currentContext === void 0) {
|
|
392
|
+
const current = part.getCurrentContext();
|
|
393
|
+
if (current) currentContext = current;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
const kc = new mod.KubeConfig();
|
|
397
|
+
kc.loadFromOptions({ clusters, users, contexts, currentContext });
|
|
398
|
+
return kc;
|
|
399
|
+
}
|
|
400
|
+
function loadKubeConfig(mod, options = {}) {
|
|
401
|
+
if (options.kubeconfig !== void 0) {
|
|
402
|
+
const kc2 = new mod.KubeConfig();
|
|
403
|
+
kc2.loadFromString(options.kubeconfig);
|
|
404
|
+
return { kc: kc2, source: "explicit-string" };
|
|
405
|
+
}
|
|
406
|
+
if (options.kubeconfigPath !== void 0) {
|
|
407
|
+
const kc2 = new mod.KubeConfig();
|
|
408
|
+
kc2.loadFromFile(options.kubeconfigPath);
|
|
409
|
+
return { kc: kc2, source: "explicit-path" };
|
|
410
|
+
}
|
|
411
|
+
const files = kubeconfigPathList();
|
|
412
|
+
if (files.length > 1) return { kc: mergeKubeconfigFiles(mod, files), source: "default" };
|
|
413
|
+
const kc = new mod.KubeConfig();
|
|
414
|
+
kc.loadFromDefault(void 0, true);
|
|
415
|
+
return { kc, source: kc.getCurrentContext() === "inCluster" ? "in-cluster" : "default" };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// node_modules/@intentius/chant-k8s-client/src/watch.ts
|
|
419
|
+
var EVENT_TYPES = /* @__PURE__ */ new Set(["ADDED", "MODIFIED", "DELETED", "BOOKMARK", "ERROR"]);
|
|
420
|
+
function parseWatchFrames(chunk, carry = "") {
|
|
421
|
+
const combined = carry + chunk;
|
|
422
|
+
const lines = combined.split("\n");
|
|
423
|
+
const rest = lines.pop() ?? "";
|
|
424
|
+
const frames = [];
|
|
425
|
+
for (const line of lines) {
|
|
426
|
+
const trimmed = line.trim();
|
|
427
|
+
if (!trimmed) continue;
|
|
428
|
+
let parsed;
|
|
429
|
+
try {
|
|
430
|
+
parsed = JSON.parse(trimmed);
|
|
431
|
+
} catch {
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
if (!parsed || typeof parsed !== "object") continue;
|
|
435
|
+
const { type, object } = parsed;
|
|
436
|
+
if (typeof type !== "string" || !EVENT_TYPES.has(type)) continue;
|
|
437
|
+
frames.push({
|
|
438
|
+
type,
|
|
439
|
+
object: object && typeof object === "object" ? object : {}
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
return { frames, carry: rest };
|
|
443
|
+
}
|
|
444
|
+
function isExpiredFrame(frame) {
|
|
445
|
+
if (frame.type !== "ERROR") return false;
|
|
446
|
+
const status = frame.object;
|
|
447
|
+
if (status.code === 410) return true;
|
|
448
|
+
return status.reason === "Expired" || status.reason === "Gone";
|
|
449
|
+
}
|
|
450
|
+
function resourceVersionOf(frame) {
|
|
451
|
+
const rv = frame.object?.metadata?.resourceVersion;
|
|
452
|
+
return typeof rv === "string" && rv.length > 0 ? rv : void 0;
|
|
453
|
+
}
|
|
454
|
+
async function* streamLines(source) {
|
|
455
|
+
const decoder = new TextDecoder();
|
|
456
|
+
let carry = "";
|
|
457
|
+
const emit = function* (chunk) {
|
|
458
|
+
const lines = (carry + chunk).split("\n");
|
|
459
|
+
carry = lines.pop() ?? "";
|
|
460
|
+
for (const line of lines) yield line;
|
|
461
|
+
};
|
|
462
|
+
const decode = (value) => typeof value === "string" ? value : decoder.decode(value, { stream: true });
|
|
463
|
+
if (source && typeof source.getReader === "function") {
|
|
464
|
+
const reader = source.getReader();
|
|
465
|
+
try {
|
|
466
|
+
for (; ; ) {
|
|
467
|
+
const { done, value } = await reader.read();
|
|
468
|
+
if (done) break;
|
|
469
|
+
yield* emit(decode(value));
|
|
470
|
+
}
|
|
471
|
+
} finally {
|
|
472
|
+
try {
|
|
473
|
+
reader.releaseLock();
|
|
474
|
+
} catch {
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
} else if (source && typeof source[Symbol.asyncIterator] === "function") {
|
|
478
|
+
for await (const value of source) {
|
|
479
|
+
yield* emit(decode(value));
|
|
480
|
+
}
|
|
481
|
+
} else {
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
if (carry.trim()) yield carry;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// node_modules/@intentius/chant-k8s-client/src/client.ts
|
|
488
|
+
var clientNodeModule;
|
|
489
|
+
async function loadClientNode() {
|
|
490
|
+
if (!clientNodeModule) {
|
|
491
|
+
clientNodeModule = import("@kubernetes/client-node").catch((err) => {
|
|
492
|
+
clientNodeModule = void 0;
|
|
493
|
+
throw new K8sClientUnavailableError(err);
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
return clientNodeModule;
|
|
497
|
+
}
|
|
498
|
+
async function isK8sClientAvailable() {
|
|
499
|
+
try {
|
|
500
|
+
await loadClientNode();
|
|
501
|
+
return true;
|
|
502
|
+
} catch {
|
|
503
|
+
return false;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async function readAmbientContext(options = {}) {
|
|
507
|
+
try {
|
|
508
|
+
const { kc } = loadKubeConfig(await loadClientNode(), options);
|
|
509
|
+
return kc.getCurrentContext() || void 0;
|
|
510
|
+
} catch {
|
|
511
|
+
return void 0;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
async function readKubeconfigView(options = {}) {
|
|
515
|
+
let kc;
|
|
516
|
+
try {
|
|
517
|
+
({ kc } = loadKubeConfig(await loadClientNode(), options));
|
|
518
|
+
} catch {
|
|
519
|
+
return { contexts: [] };
|
|
520
|
+
}
|
|
521
|
+
try {
|
|
522
|
+
const servers = /* @__PURE__ */ new Map();
|
|
523
|
+
for (const cluster of kc.getClusters()) servers.set(cluster.name, cluster.server || void 0);
|
|
524
|
+
const contexts = kc.getContexts().map((context) => {
|
|
525
|
+
const server = servers.get(context.cluster);
|
|
526
|
+
return {
|
|
527
|
+
name: context.name,
|
|
528
|
+
cluster: context.cluster ?? "",
|
|
529
|
+
...context.user ? { user: context.user } : {},
|
|
530
|
+
...context.namespace ? { namespace: context.namespace } : {},
|
|
531
|
+
...server ? { server } : {}
|
|
532
|
+
};
|
|
533
|
+
});
|
|
534
|
+
return { contexts, ...kc.getCurrentContext() ? { currentContext: kc.getCurrentContext() } : {} };
|
|
535
|
+
} catch {
|
|
536
|
+
return { contexts: [] };
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
var SELF_SUBJECT_REVIEW_VERSIONS = ["v1", "v1beta1", "v1alpha1"];
|
|
540
|
+
async function createK8sClient(options = {}) {
|
|
541
|
+
const mod = await loadClientNode();
|
|
542
|
+
const { kc, source: kubeconfigSource } = loadKubeConfig(mod, options);
|
|
543
|
+
if (options.context !== void 0) {
|
|
544
|
+
if (!kc.getContextObject(options.context)) {
|
|
545
|
+
const known = kc.getContexts().map((c) => c.name);
|
|
546
|
+
throw new KubeConfigError(
|
|
547
|
+
`the kubeconfig has no context named "${options.context}" (it has ${known.length > 0 ? known.map((n) => `"${n}"`).join(", ") : "no contexts at all"}). This is the context the environment is bound to via k8s.profiles.<env>.context.`
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
kc.setCurrentContext(options.context);
|
|
551
|
+
}
|
|
552
|
+
const cluster = kc.getCurrentCluster();
|
|
553
|
+
if (!cluster) {
|
|
554
|
+
throw new KubeConfigError(
|
|
555
|
+
`the kubeconfig resolves to no cluster for context "${kc.getCurrentContext() || "(unset)"}"`
|
|
556
|
+
);
|
|
557
|
+
}
|
|
558
|
+
const user = kc.getCurrentUser();
|
|
559
|
+
assertExecCredentialAllowed(user, options.execAllowlist ?? DEFAULT_EXEC_ALLOWLIST);
|
|
560
|
+
const provenance = {
|
|
561
|
+
server: cluster.server,
|
|
562
|
+
context: kc.getCurrentContext() || void 0,
|
|
563
|
+
contextSource: options.contextSource ?? "ambient",
|
|
564
|
+
kubeconfigSource,
|
|
565
|
+
...credentialPathOf(user)
|
|
566
|
+
};
|
|
567
|
+
const configuration = mod.createConfiguration({
|
|
568
|
+
baseServer: new mod.ServerConfiguration(cluster.server, {}),
|
|
569
|
+
authMethods: { default: kc },
|
|
570
|
+
...options.requestLayer ? {
|
|
571
|
+
httpApi: mod.wrapHttpLibrary({
|
|
572
|
+
send: (request) => Promise.resolve(
|
|
573
|
+
options.requestLayer.send(request)
|
|
574
|
+
)
|
|
575
|
+
})
|
|
576
|
+
} : {}
|
|
577
|
+
});
|
|
578
|
+
const defaultNamespace = kc.getContextObject(kc.getCurrentContext())?.namespace || "default";
|
|
579
|
+
const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
|
|
580
|
+
const contextNote = `context "${provenance.context ?? "(unset)"}" (${options.contextLabel ?? provenance.contextSource})`;
|
|
581
|
+
function noted(err) {
|
|
582
|
+
err.contextNote = contextNote;
|
|
583
|
+
return err;
|
|
584
|
+
}
|
|
585
|
+
const discoveryCache = /* @__PURE__ */ new Map();
|
|
586
|
+
let rootDiscoveryCache;
|
|
587
|
+
async function send(path, method, opts = {}) {
|
|
588
|
+
const ctx = configuration.baseServer.makeRequestContext(path, method);
|
|
589
|
+
ctx.setHeaderParam("Accept", "application/json");
|
|
590
|
+
for (const [key, value] of Object.entries(opts.query ?? {})) ctx.setQueryParam(key, value);
|
|
591
|
+
if (opts.body !== void 0) {
|
|
592
|
+
ctx.setHeaderParam("Content-Type", opts.contentType ?? "application/json");
|
|
593
|
+
ctx.setBody(opts.body);
|
|
594
|
+
}
|
|
595
|
+
if (opts.signal) ctx.setSignal(opts.signal);
|
|
596
|
+
await kc.applySecurityAuthentication(ctx);
|
|
597
|
+
let response;
|
|
598
|
+
try {
|
|
599
|
+
response = await configuration.httpApi.send(ctx).toPromise();
|
|
600
|
+
} catch (err) {
|
|
601
|
+
throw noted(
|
|
602
|
+
new K8sTransportError(err instanceof Error ? err.message : String(err), opts.target ?? `${method} ${path}`, {
|
|
603
|
+
cause: err
|
|
604
|
+
})
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
let text;
|
|
608
|
+
try {
|
|
609
|
+
text = await response.body.text();
|
|
610
|
+
} catch (err) {
|
|
611
|
+
throw noted(
|
|
612
|
+
new K8sTransportError(
|
|
613
|
+
`response body could not be read: ${err instanceof Error ? err.message : String(err)}`,
|
|
614
|
+
opts.target ?? `${method} ${path}`,
|
|
615
|
+
{ cause: err }
|
|
616
|
+
)
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
return { status: response.httpStatusCode, body: text };
|
|
620
|
+
}
|
|
621
|
+
async function sendJson(path, method, opts = {}) {
|
|
622
|
+
const { status, body } = await send(path, method, opts);
|
|
623
|
+
if (status < 200 || status > 299) {
|
|
624
|
+
throw noted(K8sApiError.fromResponse(status, body, opts.target));
|
|
625
|
+
}
|
|
626
|
+
try {
|
|
627
|
+
return JSON.parse(body);
|
|
628
|
+
} catch (err) {
|
|
629
|
+
throw noted(
|
|
630
|
+
new K8sTransportError(
|
|
631
|
+
`the API server returned HTTP ${status} with a body that is not JSON`,
|
|
632
|
+
opts.target ?? `${method} ${path}`,
|
|
633
|
+
{ cause: err }
|
|
634
|
+
)
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
async function apiResourceList(apiVersion, signal) {
|
|
639
|
+
const cached = discoveryCache.get(apiVersion);
|
|
640
|
+
if (cached) return cached;
|
|
641
|
+
const pending = (async () => {
|
|
642
|
+
try {
|
|
643
|
+
return await sendJson(apiVersionPath(apiVersion), "GET", {
|
|
644
|
+
signal,
|
|
645
|
+
target: `discovery ${apiVersion}`
|
|
646
|
+
});
|
|
647
|
+
} catch (err) {
|
|
648
|
+
if (err instanceof K8sApiError && err.notFound) return null;
|
|
649
|
+
discoveryCache.delete(apiVersion);
|
|
650
|
+
throw err;
|
|
651
|
+
}
|
|
652
|
+
})();
|
|
653
|
+
discoveryCache.set(apiVersion, pending);
|
|
654
|
+
return pending;
|
|
655
|
+
}
|
|
656
|
+
async function rootDiscovery(signal) {
|
|
657
|
+
if (rootDiscoveryCache) return rootDiscoveryCache;
|
|
658
|
+
rootDiscoveryCache = (async () => {
|
|
659
|
+
const core = await sendJson("/api", "GET", {
|
|
660
|
+
signal,
|
|
661
|
+
target: "discovery /api"
|
|
662
|
+
});
|
|
663
|
+
const groups = await sendJson("/apis", "GET", { signal, target: "discovery /apis" });
|
|
664
|
+
return {
|
|
665
|
+
coreVersions: core.versions ?? ["v1"],
|
|
666
|
+
groups: (groups.groups ?? []).map((group) => ({
|
|
667
|
+
preferred: group.preferredVersion?.groupVersion,
|
|
668
|
+
versions: (group.versions ?? []).map((v) => v.groupVersion).filter((gv) => typeof gv === "string" && gv.length > 0)
|
|
669
|
+
}))
|
|
670
|
+
};
|
|
671
|
+
})().catch((err) => {
|
|
672
|
+
rootDiscoveryCache = void 0;
|
|
673
|
+
throw err;
|
|
674
|
+
});
|
|
675
|
+
return rootDiscoveryCache;
|
|
676
|
+
}
|
|
677
|
+
async function servedGroupVersions(signal) {
|
|
678
|
+
const root = await rootDiscovery(signal);
|
|
679
|
+
const out = [...root.coreVersions];
|
|
680
|
+
for (const group of root.groups) {
|
|
681
|
+
if (group.preferred) out.push(group.preferred);
|
|
682
|
+
for (const gv of group.versions) {
|
|
683
|
+
if (gv !== group.preferred) out.push(gv);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
return [...new Set(out)];
|
|
687
|
+
}
|
|
688
|
+
async function preferredGroupVersions(signal) {
|
|
689
|
+
const root = await rootDiscovery(signal);
|
|
690
|
+
const core = root.coreVersions.includes("v1") ? "v1" : root.coreVersions[0];
|
|
691
|
+
const out = core ? [core] : [];
|
|
692
|
+
for (const group of root.groups) {
|
|
693
|
+
const gv = group.preferred ?? group.versions[0];
|
|
694
|
+
if (gv) out.push(gv);
|
|
695
|
+
}
|
|
696
|
+
return [...new Set(out)];
|
|
697
|
+
}
|
|
698
|
+
function toInfo(apiVersion, entry) {
|
|
699
|
+
const [group, version] = splitApiVersion(apiVersion);
|
|
700
|
+
return {
|
|
701
|
+
name: entry.name ?? "",
|
|
702
|
+
singularName: entry.singularName || void 0,
|
|
703
|
+
kind: entry.kind ?? "",
|
|
704
|
+
namespaced: entry.namespaced === true,
|
|
705
|
+
verbs: entry.verbs ?? [],
|
|
706
|
+
shortNames: entry.shortNames,
|
|
707
|
+
group,
|
|
708
|
+
version,
|
|
709
|
+
apiVersion
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
async function resolveByGvk(apiVersion, kind, signal) {
|
|
713
|
+
const list2 = await apiResourceList(apiVersion, signal);
|
|
714
|
+
if (!list2) return void 0;
|
|
715
|
+
const entry = (list2.resources ?? []).find((r) => r.kind === kind && !(r.name ?? "").includes("/"));
|
|
716
|
+
return entry ? toInfo(apiVersion, entry) : void 0;
|
|
717
|
+
}
|
|
718
|
+
async function resolveByResourceString(resource, group, signal) {
|
|
719
|
+
const dot = resource.indexOf(".");
|
|
720
|
+
const bare = dot === -1 ? resource : resource.slice(0, dot);
|
|
721
|
+
const fromString = dot === -1 ? void 0 : resource.slice(dot + 1);
|
|
722
|
+
const wantedGroup = fromString ?? group;
|
|
723
|
+
const needle = bare.toLowerCase();
|
|
724
|
+
const all = await servedGroupVersions(signal);
|
|
725
|
+
const candidates = wantedGroup === void 0 ? all : all.filter((gv) => splitApiVersion(gv)[0] === (wantedGroup === "" ? "" : wantedGroup));
|
|
726
|
+
const lists = await mapConcurrent(
|
|
727
|
+
candidates,
|
|
728
|
+
async (gv) => ({ gv, list: await apiResourceList(gv, signal).catch(() => null) }),
|
|
729
|
+
concurrency
|
|
730
|
+
);
|
|
731
|
+
const matchers = [
|
|
732
|
+
(r) => (r.name ?? "").toLowerCase() === needle,
|
|
733
|
+
(r) => (r.singularName ?? "").toLowerCase() === needle,
|
|
734
|
+
(r) => (r.kind ?? "").toLowerCase() === needle,
|
|
735
|
+
(r) => (r.shortNames ?? []).some((s) => s.toLowerCase() === needle)
|
|
736
|
+
];
|
|
737
|
+
for (const matches of matchers) {
|
|
738
|
+
for (const { gv, list: list2 } of lists) {
|
|
739
|
+
const entry = (list2?.resources ?? []).find((r) => !(r.name ?? "").includes("/") && matches(r));
|
|
740
|
+
if (entry) return toInfo(gv, entry);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
return void 0;
|
|
744
|
+
}
|
|
745
|
+
async function resolve(selector, signal) {
|
|
746
|
+
return "apiVersion" in selector ? resolveByGvk(selector.apiVersion, selector.kind, signal) : resolveByResourceString(selector.resource, selector.group, signal);
|
|
747
|
+
}
|
|
748
|
+
async function resolveOrThrow(selector, signal) {
|
|
749
|
+
const info = await resolve(selector, signal);
|
|
750
|
+
if (!info) throw new UnknownResourceError(selectorText(selector));
|
|
751
|
+
return info;
|
|
752
|
+
}
|
|
753
|
+
function objectPath(info, name, namespace) {
|
|
754
|
+
const parts = [apiVersionPath(info.apiVersion)];
|
|
755
|
+
if (info.namespaced) parts.push("namespaces", encodeURIComponent(namespace || defaultNamespace));
|
|
756
|
+
parts.push(info.name);
|
|
757
|
+
if (name) parts.push(encodeURIComponent(name));
|
|
758
|
+
return parts.join("/");
|
|
759
|
+
}
|
|
760
|
+
async function pathFor(ref, signal) {
|
|
761
|
+
const info = await resolve({ apiVersion: ref.apiVersion, kind: ref.kind }, signal);
|
|
762
|
+
if (!info) return void 0;
|
|
763
|
+
return objectPath(info, ref.name, ref.namespace);
|
|
764
|
+
}
|
|
765
|
+
async function read(ref, opts = {}) {
|
|
766
|
+
const info = await resolveOrThrow({ apiVersion: ref.apiVersion, kind: ref.kind }, opts.signal);
|
|
767
|
+
return sendJson(objectPath(info, ref.name, ref.namespace), "GET", {
|
|
768
|
+
signal: opts.signal,
|
|
769
|
+
target: refText(ref)
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
async function readIfPresent(ref, opts = {}) {
|
|
773
|
+
try {
|
|
774
|
+
return await read(ref, opts);
|
|
775
|
+
} catch (err) {
|
|
776
|
+
if (err instanceof K8sApiError && err.notFound) return void 0;
|
|
777
|
+
throw err;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
async function list(selector, opts = {}) {
|
|
781
|
+
const info = await resolveOrThrow(selector, opts.signal);
|
|
782
|
+
const items = [];
|
|
783
|
+
let cont;
|
|
784
|
+
do {
|
|
785
|
+
const query = {};
|
|
786
|
+
if (cont) query.continue = cont;
|
|
787
|
+
if (opts.labelSelector) query.labelSelector = opts.labelSelector;
|
|
788
|
+
const page = await sendJson(
|
|
789
|
+
// Omitting the namespace segment lists across all namespaces, which is
|
|
790
|
+
// what `kubectl get <kind> -A` does and what the import path wants.
|
|
791
|
+
opts.namespace ? objectPath(info, void 0, opts.namespace) : `${apiVersionPath(info.apiVersion)}/${info.name}`,
|
|
792
|
+
"GET",
|
|
793
|
+
{
|
|
794
|
+
signal: opts.signal,
|
|
795
|
+
query: Object.keys(query).length > 0 ? query : void 0,
|
|
796
|
+
target: `list ${selectorText(selector)}`
|
|
797
|
+
}
|
|
798
|
+
);
|
|
799
|
+
items.push(...page.items ?? []);
|
|
800
|
+
cont = page.metadata?.continue || void 0;
|
|
801
|
+
} while (cont);
|
|
802
|
+
return items;
|
|
803
|
+
}
|
|
804
|
+
async function openStream(path, query, signal, target) {
|
|
805
|
+
const ctx = configuration.baseServer.makeRequestContext(path, "GET");
|
|
806
|
+
ctx.setHeaderParam("Accept", "application/json");
|
|
807
|
+
for (const [key, value] of Object.entries(query)) ctx.setQueryParam(key, value);
|
|
808
|
+
ctx.setSignal(signal);
|
|
809
|
+
await kc.applySecurityAuthentication(ctx);
|
|
810
|
+
let response;
|
|
811
|
+
try {
|
|
812
|
+
response = await configuration.httpApi.send(ctx).toPromise();
|
|
813
|
+
} catch (err) {
|
|
814
|
+
throw noted(
|
|
815
|
+
new K8sTransportError(err instanceof Error ? err.message : String(err), target, { cause: err })
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
if (response.httpStatusCode < 200 || response.httpStatusCode > 299) {
|
|
819
|
+
throw noted(K8sApiError.fromResponse(response.httpStatusCode, await response.body.text(), target));
|
|
820
|
+
}
|
|
821
|
+
const raw = response.body.stream?.();
|
|
822
|
+
if (raw === void 0 || raw === null) {
|
|
823
|
+
const text = await response.body.text();
|
|
824
|
+
return { status: response.httpStatusCode, lines: (async function* () {
|
|
825
|
+
yield* text.split("\n");
|
|
826
|
+
})() };
|
|
827
|
+
}
|
|
828
|
+
return { status: response.httpStatusCode, lines: streamLines(raw) };
|
|
829
|
+
}
|
|
830
|
+
async function watch(selector, opts = {}) {
|
|
831
|
+
const info = await resolveOrThrow(selector, opts.signal);
|
|
832
|
+
const target = `watch ${selectorText(selector)}`;
|
|
833
|
+
const reopenDelayMs = opts.reopenDelayMs ?? 1e3;
|
|
834
|
+
const controller = new AbortController();
|
|
835
|
+
const stopOnCallerAbort = () => controller.abort();
|
|
836
|
+
if (opts.signal) {
|
|
837
|
+
if (opts.signal.aborted) controller.abort();
|
|
838
|
+
else opts.signal.addEventListener("abort", stopOnCallerAbort, { once: true });
|
|
839
|
+
}
|
|
840
|
+
const listPath = opts.namespace ? objectPath(info, void 0, opts.namespace) : `${apiVersionPath(info.apiVersion)}/${info.name}`;
|
|
841
|
+
const listQuery = {};
|
|
842
|
+
if (opts.labelSelector) listQuery.labelSelector = opts.labelSelector;
|
|
843
|
+
async function listResourceVersion() {
|
|
844
|
+
const page = await sendJson(listPath, "GET", {
|
|
845
|
+
signal: controller.signal,
|
|
846
|
+
// `limit=1` because nothing here wants the objects: the list exists
|
|
847
|
+
// for the `resourceVersion` in its metadata, which every page carries.
|
|
848
|
+
query: { ...listQuery, limit: "1" },
|
|
849
|
+
target: `${target} (initial list)`
|
|
850
|
+
});
|
|
851
|
+
return page.metadata?.resourceVersion;
|
|
852
|
+
}
|
|
853
|
+
let ended = false;
|
|
854
|
+
const end = (message) => {
|
|
855
|
+
if (ended) return;
|
|
856
|
+
ended = true;
|
|
857
|
+
if (message !== void 0) opts.onError?.(message);
|
|
858
|
+
};
|
|
859
|
+
const done = (async () => {
|
|
860
|
+
try {
|
|
861
|
+
let resourceVersion = await listResourceVersion();
|
|
862
|
+
while (!controller.signal.aborted) {
|
|
863
|
+
const query = {
|
|
864
|
+
...listQuery,
|
|
865
|
+
watch: "1",
|
|
866
|
+
// Bookmarks are how a quiet watch keeps its resourceVersion fresh
|
|
867
|
+
// without any object changing, which is what keeps a reconnect
|
|
868
|
+
// from re-listing. A cluster that does not support them ignores it.
|
|
869
|
+
allowWatchBookmarks: "true"
|
|
870
|
+
};
|
|
871
|
+
if (resourceVersion) query.resourceVersion = resourceVersion;
|
|
872
|
+
const { lines } = await openStream(listPath, query, controller.signal, target);
|
|
873
|
+
let expired = false;
|
|
874
|
+
const iterator = lines[Symbol.asyncIterator]();
|
|
875
|
+
const stopped = new Promise((resolve2) => {
|
|
876
|
+
const finish = () => resolve2({ done: true, value: void 0 });
|
|
877
|
+
if (controller.signal.aborted) finish();
|
|
878
|
+
else controller.signal.addEventListener("abort", finish, { once: true });
|
|
879
|
+
});
|
|
880
|
+
for (; ; ) {
|
|
881
|
+
const next = await Promise.race([iterator.next(), stopped]);
|
|
882
|
+
if (next.done || controller.signal.aborted) break;
|
|
883
|
+
const { frames } = parseWatchFrames(`${next.value}
|
|
884
|
+
`);
|
|
885
|
+
for (const frame of frames) {
|
|
886
|
+
if (isExpiredFrame(frame)) {
|
|
887
|
+
expired = true;
|
|
888
|
+
break;
|
|
889
|
+
}
|
|
890
|
+
const rv = resourceVersionOf(frame);
|
|
891
|
+
if (rv) resourceVersion = rv;
|
|
892
|
+
if (frame.type !== "ERROR") opts.onEvent?.(frame);
|
|
893
|
+
}
|
|
894
|
+
if (expired) break;
|
|
895
|
+
}
|
|
896
|
+
void iterator.return?.(void 0)?.catch?.(() => {
|
|
897
|
+
});
|
|
898
|
+
if (controller.signal.aborted) break;
|
|
899
|
+
if (expired) {
|
|
900
|
+
resourceVersion = await listResourceVersion();
|
|
901
|
+
continue;
|
|
902
|
+
}
|
|
903
|
+
await new Promise((resolve2) => {
|
|
904
|
+
const timer = setTimeout(resolve2, reopenDelayMs);
|
|
905
|
+
controller.signal.addEventListener("abort", () => {
|
|
906
|
+
clearTimeout(timer);
|
|
907
|
+
resolve2(void 0);
|
|
908
|
+
}, { once: true });
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
end();
|
|
912
|
+
} catch (err) {
|
|
913
|
+
if (controller.signal.aborted) return end();
|
|
914
|
+
end(err instanceof Error ? err.message : String(err));
|
|
915
|
+
} finally {
|
|
916
|
+
opts.signal?.removeEventListener("abort", stopOnCallerAbort);
|
|
917
|
+
}
|
|
918
|
+
})();
|
|
919
|
+
return {
|
|
920
|
+
done,
|
|
921
|
+
async close() {
|
|
922
|
+
controller.abort();
|
|
923
|
+
ended = true;
|
|
924
|
+
await done;
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
async function apply(object, opts = {}) {
|
|
929
|
+
const apiVersion = object.apiVersion;
|
|
930
|
+
const kind = object.kind;
|
|
931
|
+
if (!apiVersion || !kind) {
|
|
932
|
+
throw new KubeConfigError(
|
|
933
|
+
`cannot apply an object without both apiVersion and kind (got apiVersion=${String(apiVersion)}, kind=${String(kind)})`
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
const name = object.metadata?.name;
|
|
937
|
+
if (!name) {
|
|
938
|
+
throw new KubeConfigError(`cannot apply a ${apiVersion} ${kind} without metadata.name`);
|
|
939
|
+
}
|
|
940
|
+
const fieldManager = opts.fieldManager ?? CHANT_FIELD_MANAGER;
|
|
941
|
+
assertValidFieldManager(fieldManager);
|
|
942
|
+
const info = await resolveOrThrow({ apiVersion, kind }, opts.signal);
|
|
943
|
+
const query = {
|
|
944
|
+
fieldManager,
|
|
945
|
+
force: String(opts.force ?? false)
|
|
946
|
+
};
|
|
947
|
+
if (opts.dryRun) query.dryRun = "All";
|
|
948
|
+
try {
|
|
949
|
+
return await sendJson(objectPath(info, name, object.metadata?.namespace), "PATCH", {
|
|
950
|
+
// Server-side apply. JSON is valid YAML, so the JSON body is accepted
|
|
951
|
+
// under the apply-patch content type without a YAML round trip.
|
|
952
|
+
contentType: "application/apply-patch+yaml",
|
|
953
|
+
body: JSON.stringify(object),
|
|
954
|
+
query,
|
|
955
|
+
signal: opts.signal,
|
|
956
|
+
target: refText({ apiVersion, kind, name, namespace: object.metadata?.namespace })
|
|
957
|
+
});
|
|
958
|
+
} catch (err) {
|
|
959
|
+
throw asFieldManagerConflict(err, fieldManager);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
async function readLog(ref, opts = {}) {
|
|
963
|
+
const info = await resolveOrThrow({ apiVersion: ref.apiVersion, kind: ref.kind }, opts.signal);
|
|
964
|
+
const query = {};
|
|
965
|
+
if (opts.container) query.container = opts.container;
|
|
966
|
+
if (opts.previous) query.previous = "true";
|
|
967
|
+
if (opts.tailLines !== void 0) query.tailLines = String(opts.tailLines);
|
|
968
|
+
if (opts.sinceSeconds !== void 0) query.sinceSeconds = String(opts.sinceSeconds);
|
|
969
|
+
if (opts.timestamps) query.timestamps = "true";
|
|
970
|
+
const target = `${refText(ref)} logs`;
|
|
971
|
+
const { status, body } = await send(`${objectPath(info, ref.name, ref.namespace)}/log`, "GET", {
|
|
972
|
+
query: Object.keys(query).length > 0 ? query : void 0,
|
|
973
|
+
signal: opts.signal,
|
|
974
|
+
target
|
|
975
|
+
});
|
|
976
|
+
if (status < 200 || status > 299) {
|
|
977
|
+
throw noted(K8sApiError.fromResponse(status, body, target));
|
|
978
|
+
}
|
|
979
|
+
return body;
|
|
980
|
+
}
|
|
981
|
+
async function remove(ref, opts = {}) {
|
|
982
|
+
const info = await resolveOrThrow({ apiVersion: ref.apiVersion, kind: ref.kind }, opts.signal);
|
|
983
|
+
const query = {};
|
|
984
|
+
if (opts.propagationPolicy) query.propagationPolicy = opts.propagationPolicy;
|
|
985
|
+
if (opts.dryRun) query.dryRun = "All";
|
|
986
|
+
await sendJson(objectPath(info, ref.name, ref.namespace), "DELETE", {
|
|
987
|
+
signal: opts.signal,
|
|
988
|
+
query: Object.keys(query).length > 0 ? query : void 0,
|
|
989
|
+
target: refText(ref)
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
async function selfSubjectReview(signal) {
|
|
993
|
+
for (const version of SELF_SUBJECT_REVIEW_VERSIONS) {
|
|
994
|
+
const path = `/apis/authentication.k8s.io/${version}/selfsubjectreviews`;
|
|
995
|
+
let response;
|
|
996
|
+
try {
|
|
997
|
+
response = await sendJson(path, "POST", {
|
|
998
|
+
body: JSON.stringify({ apiVersion: `authentication.k8s.io/${version}`, kind: "SelfSubjectReview" }),
|
|
999
|
+
signal,
|
|
1000
|
+
target: `self subject review (${version})`
|
|
1001
|
+
});
|
|
1002
|
+
} catch (err) {
|
|
1003
|
+
if (err instanceof K8sApiError && err.notFound) continue;
|
|
1004
|
+
throw err;
|
|
1005
|
+
}
|
|
1006
|
+
const user2 = response.status?.userInfo;
|
|
1007
|
+
if (user2?.username) {
|
|
1008
|
+
return {
|
|
1009
|
+
username: user2.username,
|
|
1010
|
+
...user2.uid ? { uid: user2.uid } : {},
|
|
1011
|
+
...user2.groups && user2.groups.length > 0 ? { groups: user2.groups } : {}
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
return void 0;
|
|
1016
|
+
}
|
|
1017
|
+
async function resourcesOf(apiVersion, signal) {
|
|
1018
|
+
const list2 = await apiResourceList(apiVersion, signal);
|
|
1019
|
+
if (!list2) return [];
|
|
1020
|
+
return (list2.resources ?? []).filter((r) => !(r.name ?? "").includes("/")).map((entry) => toInfo(apiVersion, entry));
|
|
1021
|
+
}
|
|
1022
|
+
return {
|
|
1023
|
+
provenance,
|
|
1024
|
+
defaultNamespace,
|
|
1025
|
+
resolve,
|
|
1026
|
+
read,
|
|
1027
|
+
pathFor,
|
|
1028
|
+
readIfPresent,
|
|
1029
|
+
list,
|
|
1030
|
+
readLog,
|
|
1031
|
+
watch,
|
|
1032
|
+
apply,
|
|
1033
|
+
delete: remove,
|
|
1034
|
+
concurrently: (items, fn) => mapConcurrent(items, fn, concurrency),
|
|
1035
|
+
resources: resourcesOf,
|
|
1036
|
+
preferredGroupVersions,
|
|
1037
|
+
selfSubjectReview,
|
|
1038
|
+
discoveryCacheKeys: () => [...discoveryCache.keys()].sort()
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
function apiVersionPath(apiVersion) {
|
|
1042
|
+
return apiVersion.includes("/") ? `/apis/${apiVersion}` : `/api/${apiVersion}`;
|
|
1043
|
+
}
|
|
1044
|
+
function splitApiVersion(apiVersion) {
|
|
1045
|
+
const slash = apiVersion.indexOf("/");
|
|
1046
|
+
return slash === -1 ? ["", apiVersion] : [apiVersion.slice(0, slash), apiVersion.slice(slash + 1)];
|
|
1047
|
+
}
|
|
1048
|
+
function selectorText(selector) {
|
|
1049
|
+
return "apiVersion" in selector ? `${selector.apiVersion} ${selector.kind}` : selector.group ? `${selector.resource}.${selector.group}` : selector.resource;
|
|
1050
|
+
}
|
|
1051
|
+
function refText(ref) {
|
|
1052
|
+
return `${ref.apiVersion} ${ref.kind} ${ref.namespace ? `${ref.namespace}/` : ""}${ref.name}`;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
// node_modules/@intentius/chant-k8s-client/src/managed-fields.ts
|
|
1056
|
+
function managedFieldsOf(object) {
|
|
1057
|
+
const entries = object?.metadata?.managedFields;
|
|
1058
|
+
if (!Array.isArray(entries)) return [];
|
|
1059
|
+
return entries.filter((e) => e !== null && typeof e === "object").map((e) => e);
|
|
1060
|
+
}
|
|
1061
|
+
function fieldSetsOf(object) {
|
|
1062
|
+
return managedFieldsOf(object).filter((entry) => typeof entry.manager === "string" && entry.manager.length > 0).map((entry) => ({
|
|
1063
|
+
manager: entry.manager,
|
|
1064
|
+
operation: entry.operation ?? "Update",
|
|
1065
|
+
...entry.apiVersion !== void 0 ? { apiVersion: entry.apiVersion } : {},
|
|
1066
|
+
...entry.subresource !== void 0 ? { subresource: entry.subresource } : {},
|
|
1067
|
+
...entry.time !== void 0 ? { time: entry.time } : {},
|
|
1068
|
+
fields: fieldPathsOf(entry.fieldsV1)
|
|
1069
|
+
}));
|
|
1070
|
+
}
|
|
1071
|
+
function managersOf(object) {
|
|
1072
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1073
|
+
for (const entry of managedFieldsOf(object)) {
|
|
1074
|
+
if (typeof entry.manager === "string" && entry.manager.length > 0) seen.add(entry.manager);
|
|
1075
|
+
}
|
|
1076
|
+
return [...seen];
|
|
1077
|
+
}
|
|
1078
|
+
function fieldsOwnedBy(object, manager, options = {}) {
|
|
1079
|
+
const matches = typeof manager === "function" ? manager : (m) => m === manager;
|
|
1080
|
+
const paths = /* @__PURE__ */ new Set();
|
|
1081
|
+
for (const set of fieldSetsOf(object)) {
|
|
1082
|
+
if (!matches(set.manager)) continue;
|
|
1083
|
+
if (set.subresource !== void 0 && options.includeSubresources !== true) continue;
|
|
1084
|
+
for (const path of set.fields) paths.add(path);
|
|
1085
|
+
}
|
|
1086
|
+
return [...paths].sort();
|
|
1087
|
+
}
|
|
1088
|
+
function chantOwnedFields(object, options = {}) {
|
|
1089
|
+
return fieldsOwnedBy(object, isChantFieldManager, options);
|
|
1090
|
+
}
|
|
1091
|
+
function fieldOwners(object, options = {}) {
|
|
1092
|
+
const owners = /* @__PURE__ */ new Map();
|
|
1093
|
+
for (const set of fieldSetsOf(object)) {
|
|
1094
|
+
if (set.subresource !== void 0 && options.includeSubresources !== true) continue;
|
|
1095
|
+
for (const path of set.fields) {
|
|
1096
|
+
const list = owners.get(path) ?? [];
|
|
1097
|
+
if (!list.includes(set.manager)) list.push(set.manager);
|
|
1098
|
+
owners.set(path, list);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
return owners;
|
|
1102
|
+
}
|
|
1103
|
+
function fieldPathsOf(fieldsV1, prefix = "") {
|
|
1104
|
+
return [...collect(fieldsV1, prefix, /* @__PURE__ */ new Set())].sort();
|
|
1105
|
+
}
|
|
1106
|
+
function collect(node, prefix, into) {
|
|
1107
|
+
if (node === null || typeof node !== "object" || Array.isArray(node)) return into;
|
|
1108
|
+
for (const [key, child] of Object.entries(node)) {
|
|
1109
|
+
if (key === ".") {
|
|
1110
|
+
if (prefix !== "") into.add(prefix);
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
const segment = renderSegment(key);
|
|
1114
|
+
if (segment === void 0) continue;
|
|
1115
|
+
const path = `${prefix}${segment}`;
|
|
1116
|
+
into.add(path);
|
|
1117
|
+
collect(child, path, into);
|
|
1118
|
+
}
|
|
1119
|
+
return into;
|
|
1120
|
+
}
|
|
1121
|
+
function renderSegment(key) {
|
|
1122
|
+
if (key.startsWith("f:")) return `.${key.slice(2)}`;
|
|
1123
|
+
if (key.startsWith("i:")) return `[${key.slice(2)}]`;
|
|
1124
|
+
if (key.startsWith("v:")) return `[=${key.slice(2)}]`;
|
|
1125
|
+
if (key.startsWith("k:")) return renderKeySegment(key.slice(2));
|
|
1126
|
+
return void 0;
|
|
1127
|
+
}
|
|
1128
|
+
function renderKeySegment(json) {
|
|
1129
|
+
let parsed;
|
|
1130
|
+
try {
|
|
1131
|
+
parsed = JSON.parse(json);
|
|
1132
|
+
} catch {
|
|
1133
|
+
return `[${json}]`;
|
|
1134
|
+
}
|
|
1135
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return `[${json}]`;
|
|
1136
|
+
const parts = Object.entries(parsed).map(
|
|
1137
|
+
([name, value]) => `${name}=${JSON.stringify(value)}`
|
|
1138
|
+
);
|
|
1139
|
+
return `[${parts.join(",")}]`;
|
|
1140
|
+
}
|
|
1141
|
+
export {
|
|
1142
|
+
CHANT_FIELD_MANAGER,
|
|
1143
|
+
DEFAULT_CONCURRENCY,
|
|
1144
|
+
DEFAULT_EXEC_ALLOWLIST,
|
|
1145
|
+
ExecCredentialNotAllowedError,
|
|
1146
|
+
FIELD_MANAGER_MAX_LENGTH,
|
|
1147
|
+
FIELD_MANAGER_SEPARATOR,
|
|
1148
|
+
FieldManagerConflictError,
|
|
1149
|
+
FieldManagerError,
|
|
1150
|
+
K8sApiError,
|
|
1151
|
+
K8sClientUnavailableError,
|
|
1152
|
+
K8sTransportError,
|
|
1153
|
+
KubeConfigError,
|
|
1154
|
+
UnknownResourceError,
|
|
1155
|
+
apiVersionPath,
|
|
1156
|
+
asFieldManagerConflict,
|
|
1157
|
+
assertExecCredentialAllowed,
|
|
1158
|
+
assertValidFieldManager,
|
|
1159
|
+
chantOwnedFields,
|
|
1160
|
+
chantStackOf,
|
|
1161
|
+
createK8sClient,
|
|
1162
|
+
credentialPathOf,
|
|
1163
|
+
execCommandName,
|
|
1164
|
+
execConfigOf,
|
|
1165
|
+
fieldManagerFor,
|
|
1166
|
+
fieldOwners,
|
|
1167
|
+
fieldPathsOf,
|
|
1168
|
+
fieldSetsOf,
|
|
1169
|
+
fieldsOwnedBy,
|
|
1170
|
+
isChantFieldManager,
|
|
1171
|
+
isExpiredFrame,
|
|
1172
|
+
isK8sClientAvailable,
|
|
1173
|
+
loadClientNode,
|
|
1174
|
+
managedFieldsOf,
|
|
1175
|
+
managersOf,
|
|
1176
|
+
mapConcurrent,
|
|
1177
|
+
parseConflictMessage,
|
|
1178
|
+
parseFieldConflicts,
|
|
1179
|
+
parseWatchFrames,
|
|
1180
|
+
readAmbientContext,
|
|
1181
|
+
readKubeconfigView,
|
|
1182
|
+
refText,
|
|
1183
|
+
renderConflictReport,
|
|
1184
|
+
renderSegment,
|
|
1185
|
+
resourceVersionOf,
|
|
1186
|
+
selectorText,
|
|
1187
|
+
splitApiVersion,
|
|
1188
|
+
streamLines
|
|
1189
|
+
};
|