@cavelon/cli 0.0.0 → 0.1.1
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/README.md +697 -3
- package/dist/LICENSE +201 -0
- package/dist/agents.js +91 -0
- package/dist/branches.js +61 -0
- package/dist/capacity.js +162 -0
- package/dist/cli.js +4 -0
- package/dist/command.js +62 -0
- package/dist/commands/api.js +243 -0
- package/dist/commands/async.js +207 -0
- package/dist/commands/docs.js +158 -0
- package/dist/commands/index.js +112 -0
- package/dist/commands/init.js +452 -0
- package/dist/commands/inventory.js +56 -0
- package/dist/commands/limits-set.js +624 -0
- package/dist/commands/limits.js +156 -0
- package/dist/commands/loops.js +792 -0
- package/dist/commands/models.js +197 -0
- package/dist/commands/sandboxes.js +667 -0
- package/dist/commands/session.js +476 -0
- package/dist/commands/solution.js +760 -0
- package/dist/commands/tenants.js +266 -0
- package/dist/commands/values.js +383 -0
- package/dist/commands/work.js +744 -0
- package/dist/context.js +56 -0
- package/dist/contracts.js +189 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.js +64 -0
- package/dist/features.js +37 -0
- package/dist/format.js +36 -0
- package/dist/fsutil.js +40 -0
- package/dist/git.js +41 -0
- package/dist/http.js +286 -0
- package/dist/invoke.js +161 -0
- package/dist/io.js +49 -0
- package/dist/limits.js +299 -0
- package/dist/local-state.js +60 -0
- package/dist/main.js +227 -0
- package/dist/markers.js +113 -0
- package/dist/mcp.js +130 -0
- package/dist/openapi.js +223 -0
- package/dist/operations.js +107 -0
- package/dist/package-check.js +342 -0
- package/dist/package-files.js +329 -0
- package/dist/pair-order.js +39 -0
- package/dist/paths.js +28 -0
- package/dist/principal.js +33 -0
- package/dist/project.js +138 -0
- package/dist/prompt.js +34 -0
- package/dist/results.js +66 -0
- package/dist/session.js +166 -0
- package/dist/shell.js +41 -0
- package/dist/skills/cavelon-authoring/SKILL.md +214 -0
- package/dist/skills/cavelon-long-running/SKILL.md +181 -0
- package/dist/skills/cavelon-loop/SKILL.md +158 -0
- package/dist/skills/cavelon-testing/SKILL.md +90 -0
- package/dist/sse.js +44 -0
- package/dist/tar.js +172 -0
- package/dist/user-config.js +36 -0
- package/dist/version.js +17 -0
- package/dist/zip.js +132 -0
- package/package.json +40 -4
package/dist/http.js
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { capacityCodeIn, capacityHint } from "./capacity.js";
|
|
2
|
+
import { ceilingRefusal, LIMIT_ABOVE_CEILING } from "./limits.js";
|
|
3
|
+
import { CavelonError, ExitCode } from "./errors.js";
|
|
4
|
+
import { KIT_VERSION } from "./version.js";
|
|
5
|
+
export const DEFAULT_TIMEOUT_MS = 30_000;
|
|
6
|
+
export const NOT_HERE = [301, 302, 303, 307, 308, 401, 403, 404, 405, 406];
|
|
7
|
+
export const PERSONAL_ACCESS_TOKENS_DISABLED = "personal_access_tokens_disabled";
|
|
8
|
+
const TOKEN_ROUTE = "/api/v1/personal-access-tokens/options";
|
|
9
|
+
export function tokensDisabledError(url) {
|
|
10
|
+
return new CavelonError(ExitCode.unauthorized, {
|
|
11
|
+
code: PERSONAL_ACCESS_TOKENS_DISABLED,
|
|
12
|
+
status: 401,
|
|
13
|
+
message: `${url} has personal access tokens turned off, so it refuses every cvpat_ token, this one included.`,
|
|
14
|
+
hint: "The instance's operator turns them on with PERSONAL_ACCESS_TOKENS_ENABLED. Until then, a tenant API key (cbp_…) " +
|
|
15
|
+
"works for the commands that accept one: a person runs `cavelon login` with it.",
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
export class ApiClient {
|
|
19
|
+
target;
|
|
20
|
+
env;
|
|
21
|
+
tokensOff;
|
|
22
|
+
constructor(target, env = {}) {
|
|
23
|
+
this.target = target;
|
|
24
|
+
this.env = env;
|
|
25
|
+
}
|
|
26
|
+
get url() {
|
|
27
|
+
return this.target.url;
|
|
28
|
+
}
|
|
29
|
+
resolve(pathOrUrl, query) {
|
|
30
|
+
const base = new URL(this.target.url.endsWith("/") ? this.target.url : `${this.target.url}/`);
|
|
31
|
+
let url;
|
|
32
|
+
if (/^https?:\/\//i.test(pathOrUrl)) {
|
|
33
|
+
url = new URL(pathOrUrl);
|
|
34
|
+
if (url.origin !== base.origin) {
|
|
35
|
+
throw new CavelonError(ExitCode.usage, {
|
|
36
|
+
code: "foreign_url",
|
|
37
|
+
message: `Refusing to send the token to ${url.origin}; the instance is ${base.origin}.`,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
url = new URL(pathOrUrl.replace(/^\/+/, ""), base);
|
|
43
|
+
}
|
|
44
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
45
|
+
if (value === undefined || value === null)
|
|
46
|
+
continue;
|
|
47
|
+
if (Array.isArray(value))
|
|
48
|
+
for (const item of value)
|
|
49
|
+
url.searchParams.append(key, String(item));
|
|
50
|
+
else
|
|
51
|
+
url.searchParams.set(key, String(value));
|
|
52
|
+
}
|
|
53
|
+
return url;
|
|
54
|
+
}
|
|
55
|
+
headers(options = {}) {
|
|
56
|
+
const headers = {
|
|
57
|
+
"User-Agent": `cavelon/${KIT_VERSION} node/${process.versions.node}`,
|
|
58
|
+
Accept: options.accept ?? "application/json",
|
|
59
|
+
...options.headers,
|
|
60
|
+
};
|
|
61
|
+
if (options.sendAuth !== false && this.target.token)
|
|
62
|
+
headers.Authorization = `Bearer ${this.target.token}`;
|
|
63
|
+
if (options.sendTenant !== false && this.target.tenantId && !this.target.token?.startsWith("cbp_")) {
|
|
64
|
+
headers["X-Tenant-Id"] = this.target.tenantId;
|
|
65
|
+
}
|
|
66
|
+
return headers;
|
|
67
|
+
}
|
|
68
|
+
async fetchRaw(method, path, options = {}) {
|
|
69
|
+
const url = this.resolve(path, options.query);
|
|
70
|
+
const headers = this.headers(options);
|
|
71
|
+
let body;
|
|
72
|
+
if (options.form)
|
|
73
|
+
body = options.form;
|
|
74
|
+
else if (options.bytes)
|
|
75
|
+
body = options.bytes;
|
|
76
|
+
else if (options.json !== undefined) {
|
|
77
|
+
headers["Content-Type"] = "application/json";
|
|
78
|
+
body = JSON.stringify(options.json);
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
return await fetch(url, { method, headers, body, signal: options.signal, redirect: "manual" });
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
throw networkError(error, url, options.signal);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async request(method, path, options = {}) {
|
|
88
|
+
const timeoutMs = options.timeoutMs ?? (Number(this.env.CAVELON_HTTP_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS);
|
|
89
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
90
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
91
|
+
const response = await this.fetchRaw(method, path, { ...options, signal });
|
|
92
|
+
let text;
|
|
93
|
+
try {
|
|
94
|
+
text = await response.text();
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
throw networkError(error, this.resolve(path), signal);
|
|
98
|
+
}
|
|
99
|
+
const data = parseBody(text, response.headers.get("content-type"));
|
|
100
|
+
if (response.status >= 300 && response.status < 400 && !options.allow?.includes(response.status)) {
|
|
101
|
+
throw new CavelonError(ExitCode.server, {
|
|
102
|
+
code: "unexpected_redirect",
|
|
103
|
+
status: response.status,
|
|
104
|
+
message: `${method} ${path} redirected to ${response.headers.get("location") ?? "?"}; check the instance URL.`,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
if (!response.ok && !options.allow?.includes(response.status)) {
|
|
108
|
+
throw await this.refusal(response.status, data, `${method} ${new URL(response.url || this.resolve(path)).pathname}`, response.headers);
|
|
109
|
+
}
|
|
110
|
+
return { status: response.status, headers: response.headers, data: data, text };
|
|
111
|
+
}
|
|
112
|
+
async refusal(status, body, what, headers) {
|
|
113
|
+
if (status === 401 && this.target.token?.startsWith("cvpat_") && (await this.personalAccessTokensOff())) {
|
|
114
|
+
return tokensDisabledError(this.url);
|
|
115
|
+
}
|
|
116
|
+
return errorFromResponse(status, body, what, headers);
|
|
117
|
+
}
|
|
118
|
+
personalAccessTokensOff() {
|
|
119
|
+
this.tokensOff ??= (async () => {
|
|
120
|
+
try {
|
|
121
|
+
const response = await this.fetchRaw("GET", TOKEN_ROUTE, {
|
|
122
|
+
sendAuth: false,
|
|
123
|
+
sendTenant: false,
|
|
124
|
+
signal: AbortSignal.timeout(Math.min(Number(this.env.CAVELON_HTTP_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS, 10_000)),
|
|
125
|
+
});
|
|
126
|
+
await response.body?.cancel();
|
|
127
|
+
return response.status === 404;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
})();
|
|
133
|
+
return this.tokensOff;
|
|
134
|
+
}
|
|
135
|
+
get(path, options) {
|
|
136
|
+
return this.request("GET", path, options);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function parseBody(text, contentType) {
|
|
140
|
+
if (!text)
|
|
141
|
+
return null;
|
|
142
|
+
if (contentType?.includes("json") || /^\s*[[{]/.test(text)) {
|
|
143
|
+
try {
|
|
144
|
+
return JSON.parse(text);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return text;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return text;
|
|
151
|
+
}
|
|
152
|
+
function networkError(error, url, signal) {
|
|
153
|
+
const reason = signal?.reason;
|
|
154
|
+
if (reason?.name === "TimeoutError" || error?.name === "TimeoutError") {
|
|
155
|
+
return new CavelonError(ExitCode.server, {
|
|
156
|
+
code: "request_timeout",
|
|
157
|
+
message: `${url.origin} did not answer in time.`,
|
|
158
|
+
hint: "Retry; CAVELON_HTTP_TIMEOUT_MS raises the limit per request.",
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
const cause = error?.cause;
|
|
162
|
+
const detail = cause?.code ?? cause?.message ?? (error instanceof Error ? error.message : String(error));
|
|
163
|
+
return new CavelonError(ExitCode.server, {
|
|
164
|
+
code: "network_error",
|
|
165
|
+
message: `Cannot reach ${url.origin}: ${detail}`,
|
|
166
|
+
hint: "Check the instance URL and the network (VPN, proxy, allowlist).",
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
const BARE_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/;
|
|
170
|
+
export function errorFromResponse(status, body, what, headers) {
|
|
171
|
+
let code;
|
|
172
|
+
let message;
|
|
173
|
+
let hint;
|
|
174
|
+
let docs;
|
|
175
|
+
let details;
|
|
176
|
+
let blockers;
|
|
177
|
+
const pick = (source) => {
|
|
178
|
+
if (typeof source.code === "string")
|
|
179
|
+
code = source.code;
|
|
180
|
+
if (typeof source.error === "string" && !code)
|
|
181
|
+
code = source.error;
|
|
182
|
+
if (typeof source.message === "string")
|
|
183
|
+
message = source.message;
|
|
184
|
+
if (typeof source.hint === "string")
|
|
185
|
+
hint = source.hint;
|
|
186
|
+
if (typeof source.docs === "string")
|
|
187
|
+
docs = source.docs;
|
|
188
|
+
const said = Array.isArray(source.blockers) ? source.blockers.filter((b) => typeof b === "string" && b !== "") : [];
|
|
189
|
+
if (said.length)
|
|
190
|
+
blockers = said;
|
|
191
|
+
};
|
|
192
|
+
if (body && typeof body === "object" && !Array.isArray(body)) {
|
|
193
|
+
const map = body;
|
|
194
|
+
pick(map);
|
|
195
|
+
const detail = map.detail;
|
|
196
|
+
if (typeof detail === "string") {
|
|
197
|
+
message = detail;
|
|
198
|
+
if (!code && BARE_CODE.test(detail))
|
|
199
|
+
code = detail;
|
|
200
|
+
}
|
|
201
|
+
else if (Array.isArray(detail)) {
|
|
202
|
+
details = detail;
|
|
203
|
+
message = detail
|
|
204
|
+
.slice(0, 5)
|
|
205
|
+
.map((item) => {
|
|
206
|
+
const entry = item;
|
|
207
|
+
return `${(entry.loc ?? []).join(".")}: ${entry.msg ?? "invalid"}`;
|
|
208
|
+
})
|
|
209
|
+
.join("; ");
|
|
210
|
+
}
|
|
211
|
+
else if (detail && typeof detail === "object") {
|
|
212
|
+
pick(detail);
|
|
213
|
+
if (!message && typeof detail.detail === "string") {
|
|
214
|
+
message = detail.detail;
|
|
215
|
+
}
|
|
216
|
+
if (message === undefined)
|
|
217
|
+
details = detail;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
else if (typeof body === "string" && body.trim() && !/^\s*</.test(body)) {
|
|
221
|
+
message = body.trim().slice(0, 300);
|
|
222
|
+
}
|
|
223
|
+
const exitCode = exitCodeForStatus(status);
|
|
224
|
+
const retryAfter = headers?.get("retry-after");
|
|
225
|
+
if (status === 429 && !hint)
|
|
226
|
+
hint = retryAfter ? `Retry after ${retryAfter} seconds.` : "Retry later.";
|
|
227
|
+
const capacity = capacityCodeIn(code) ?? (status === 429 || status === 503 ? capacityCodeIn(message) : undefined);
|
|
228
|
+
if (capacity)
|
|
229
|
+
hint = [hint, capacityHint(capacity), `\`cavelon explain ${capacity}\` says more.`].filter(Boolean).join(" ");
|
|
230
|
+
const ceiling = code === LIMIT_ABOVE_CEILING ? ceilingRefusal(body) : undefined;
|
|
231
|
+
if (ceiling) {
|
|
232
|
+
hint = ceiling.hint;
|
|
233
|
+
details = details && typeof details === "object" ? { ...details, ...ceiling.details } : ceiling.details;
|
|
234
|
+
}
|
|
235
|
+
if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
|
|
236
|
+
hint = "Choose a tenant with `cavelon use <tenant>`, --tenant or CAVELON_TENANT.";
|
|
237
|
+
}
|
|
238
|
+
if ((status === 401 || status === 403) && !hint) {
|
|
239
|
+
hint =
|
|
240
|
+
status === 401
|
|
241
|
+
? "The token is missing, expired or revoked. A person runs `cavelon login` with a new one."
|
|
242
|
+
: "The token does not reach this. Check the tenant (`cavelon whoami`) and the token's permission ceiling.";
|
|
243
|
+
}
|
|
244
|
+
return new CavelonError(exitCode, {
|
|
245
|
+
code: code ?? defaultCode(status),
|
|
246
|
+
message: message ? `${what}: ${message}` : `${what} answered ${status}.`,
|
|
247
|
+
hint,
|
|
248
|
+
docs,
|
|
249
|
+
status,
|
|
250
|
+
details,
|
|
251
|
+
blockers,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
export function exitCodeForStatus(status) {
|
|
255
|
+
if (status === 401 || status === 403)
|
|
256
|
+
return ExitCode.unauthorized;
|
|
257
|
+
if (status === 400 || status === 422)
|
|
258
|
+
return ExitCode.validation;
|
|
259
|
+
if (status === 409 || status === 412)
|
|
260
|
+
return ExitCode.conflict;
|
|
261
|
+
if (status === 408 || status === 429 || status >= 500)
|
|
262
|
+
return ExitCode.server;
|
|
263
|
+
return ExitCode.failure;
|
|
264
|
+
}
|
|
265
|
+
function defaultCode(status) {
|
|
266
|
+
switch (status) {
|
|
267
|
+
case 400:
|
|
268
|
+
return "bad_request";
|
|
269
|
+
case 401:
|
|
270
|
+
return "unauthorized";
|
|
271
|
+
case 403:
|
|
272
|
+
return "forbidden";
|
|
273
|
+
case 404:
|
|
274
|
+
return "not_found";
|
|
275
|
+
case 409:
|
|
276
|
+
return "conflict";
|
|
277
|
+
case 412:
|
|
278
|
+
return "precondition_failed";
|
|
279
|
+
case 422:
|
|
280
|
+
return "validation_failed";
|
|
281
|
+
case 429:
|
|
282
|
+
return "rate_limited";
|
|
283
|
+
default:
|
|
284
|
+
return status >= 500 ? "server_error" : `http_${status}`;
|
|
285
|
+
}
|
|
286
|
+
}
|
package/dist/invoke.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { CavelonError, ExitCode, validationError } from "./errors.js";
|
|
4
|
+
import { coerceParameter, isArrayParameter, operationAt, validateBody } from "./openapi.js";
|
|
5
|
+
export async function openapiOrWarn(ctx) {
|
|
6
|
+
try {
|
|
7
|
+
return await (await ctx.contracts()).openapi();
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
if (error instanceof CavelonError && error.code === "openapi_unavailable") {
|
|
11
|
+
ctx.warn(`${error.message} Arguments are not checked before sending.`);
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function buildRequest(op, args) {
|
|
18
|
+
const given = { ...(args.params ?? {}) };
|
|
19
|
+
const query = {};
|
|
20
|
+
const headers = { ...(args.headers ?? {}) };
|
|
21
|
+
let filled = op.path;
|
|
22
|
+
const missing = [];
|
|
23
|
+
for (const param of op.parameters) {
|
|
24
|
+
const values = given[param.name];
|
|
25
|
+
delete given[param.name];
|
|
26
|
+
if (!values || values.length === 0) {
|
|
27
|
+
if (param.required)
|
|
28
|
+
missing.push(`${param.name} (${param.in})`);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (param.in === "path") {
|
|
32
|
+
filled = filled.replace(`{${param.name}}`, encodeURIComponent(values[values.length - 1]));
|
|
33
|
+
}
|
|
34
|
+
else if (param.in === "query") {
|
|
35
|
+
query[param.name] = isArrayParameter(param)
|
|
36
|
+
? values.map((v) => coerceParameter(param, v))
|
|
37
|
+
: coerceParameter(param, values[values.length - 1]);
|
|
38
|
+
}
|
|
39
|
+
else if (param.in === "header") {
|
|
40
|
+
const name = param.name.toLowerCase();
|
|
41
|
+
if (name === "authorization" || name === "x-tenant-id" || name === "cookie")
|
|
42
|
+
continue;
|
|
43
|
+
headers[param.name] = values[values.length - 1];
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const unknown = Object.keys(given);
|
|
47
|
+
if (unknown.length) {
|
|
48
|
+
const known = op.parameters.map((p) => p.name);
|
|
49
|
+
throw validationError(`${op.alias} has no parameter ${unknown.map((u) => `"${u}"`).join(", ")}.`, { unknown, known }, known.length ? `Its parameters: ${known.join(", ")}.` : `${op.alias} takes no parameters.`);
|
|
50
|
+
}
|
|
51
|
+
if (missing.length) {
|
|
52
|
+
throw validationError(`${op.alias} needs ${missing.join(", ")}.`, { missing }, "Pass each as -p name=value.");
|
|
53
|
+
}
|
|
54
|
+
if (op.requestBody?.required && args.body === undefined && !args.files?.length && !args.bytes) {
|
|
55
|
+
throw validationError(`${op.alias} needs a request body.`, undefined, "Pass it with --json '<body>' (or @file, or - for stdin).");
|
|
56
|
+
}
|
|
57
|
+
return { path: filled, query, headers };
|
|
58
|
+
}
|
|
59
|
+
export async function callOperation(ctx, client, doc, op, args) {
|
|
60
|
+
const { path: target, query, headers } = buildRequest(op, args);
|
|
61
|
+
const contentTypes = Object.keys(op.requestBody?.content ?? {});
|
|
62
|
+
const multipart = contentTypes.includes("multipart/form-data") && !contentTypes.includes("application/json");
|
|
63
|
+
let form;
|
|
64
|
+
let json;
|
|
65
|
+
if (multipart || args.files?.length) {
|
|
66
|
+
form = new FormData();
|
|
67
|
+
if (args.body && typeof args.body === "object") {
|
|
68
|
+
for (const [key, value] of Object.entries(args.body)) {
|
|
69
|
+
if (value === undefined || value === null)
|
|
70
|
+
continue;
|
|
71
|
+
form.append(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
for (const file of args.files ?? []) {
|
|
75
|
+
const content = await fs.readFile(file.path);
|
|
76
|
+
form.append(file.field, new Blob([content]), path.basename(file.path));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
else if (args.body !== undefined) {
|
|
80
|
+
if (doc)
|
|
81
|
+
validateBody(doc, op, args.body);
|
|
82
|
+
json = args.body;
|
|
83
|
+
}
|
|
84
|
+
const response = await client.fetchRaw(op.method, target, {
|
|
85
|
+
query,
|
|
86
|
+
headers,
|
|
87
|
+
json,
|
|
88
|
+
form,
|
|
89
|
+
sendTenant: args.sendTenant,
|
|
90
|
+
signal: AbortSignal.timeout(args.timeoutMs ?? (Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 30_000)),
|
|
91
|
+
});
|
|
92
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
93
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
94
|
+
const isText = /json|text|xml|yaml|markdown|event-stream/.test(contentType) || bytes.length === 0;
|
|
95
|
+
const text = isText ? new TextDecoder().decode(bytes) : "";
|
|
96
|
+
let data = text;
|
|
97
|
+
if (contentType.includes("json") && text) {
|
|
98
|
+
try {
|
|
99
|
+
data = JSON.parse(text);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
data = text;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (!response.ok)
|
|
106
|
+
throw await client.refusal(response.status, data, `${op.method} ${new URL(client.resolve(target)).pathname}`, response.headers);
|
|
107
|
+
return { status: response.status, contentType, data: isText ? (text ? data : null) : undefined, bytes: isText ? undefined : bytes };
|
|
108
|
+
}
|
|
109
|
+
export async function workflowOperation(ctx, method, pathTemplate, what) {
|
|
110
|
+
const doc = await openapiOrWarn(ctx);
|
|
111
|
+
if (doc) {
|
|
112
|
+
const op = operationAt(doc, method, pathTemplate);
|
|
113
|
+
if (!op) {
|
|
114
|
+
throw new CavelonError(ExitCode.failure, {
|
|
115
|
+
code: "operation_unavailable",
|
|
116
|
+
message: `This instance does not offer ${what} (${method} ${pathTemplate} is not in its OpenAPI).`,
|
|
117
|
+
hint: "The instance may be older than this feature; `cavelon status` shows its version.",
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
return { doc, op };
|
|
121
|
+
}
|
|
122
|
+
const names = [...pathTemplate.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
|
|
123
|
+
return {
|
|
124
|
+
op: {
|
|
125
|
+
operationId: `${method} ${pathTemplate}`,
|
|
126
|
+
alias: `${method} ${pathTemplate}`,
|
|
127
|
+
method,
|
|
128
|
+
path: pathTemplate,
|
|
129
|
+
tags: [],
|
|
130
|
+
parameters: names.map((name) => ({ name, in: "path", required: true })),
|
|
131
|
+
responses: {},
|
|
132
|
+
readOnly: method === "GET",
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
export async function callStable(ctx, method, pathTemplate, what, args = {}) {
|
|
137
|
+
const client = await ctx.client({ tenant: args.sendTenant !== false });
|
|
138
|
+
const { doc, op } = await workflowOperation(ctx, method, pathTemplate, what);
|
|
139
|
+
const params = { ...(args.params ?? {}) };
|
|
140
|
+
for (const [key, value] of Object.entries(args.query ?? {})) {
|
|
141
|
+
if (value === undefined || value === null)
|
|
142
|
+
continue;
|
|
143
|
+
params[key] = Array.isArray(value) ? value.map(String) : [String(value)];
|
|
144
|
+
}
|
|
145
|
+
if (doc) {
|
|
146
|
+
const unknown = Object.keys(params).filter((key) => !op.parameters.some((p) => p.name === key));
|
|
147
|
+
if (unknown.length) {
|
|
148
|
+
throw new CavelonError(ExitCode.failure, {
|
|
149
|
+
code: "operation_unavailable",
|
|
150
|
+
message: `This instance's ${method} ${pathTemplate} does not take ${unknown.join(", ")}, so it cannot do this (${what}).`,
|
|
151
|
+
hint: "The instance may be older than this feature; `cavelon status` shows its version.",
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
for (const key of Object.keys(args.query ?? {}))
|
|
157
|
+
op.parameters.push({ name: key, in: "query" });
|
|
158
|
+
}
|
|
159
|
+
const result = await callOperation(ctx, client, doc, op, { ...args, params });
|
|
160
|
+
return result.data;
|
|
161
|
+
}
|
package/dist/io.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export function processIo() {
|
|
2
|
+
return {
|
|
3
|
+
stdout: process.stdout,
|
|
4
|
+
stderr: process.stderr,
|
|
5
|
+
stdin: process.stdin,
|
|
6
|
+
env: process.env,
|
|
7
|
+
cwd: process.cwd(),
|
|
8
|
+
now: () => new Date(),
|
|
9
|
+
sleep: defaultSleep,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export function defaultSleep(ms, signal) {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
if (signal?.aborted)
|
|
15
|
+
return resolve();
|
|
16
|
+
const timer = setTimeout(done, ms);
|
|
17
|
+
function done() {
|
|
18
|
+
clearTimeout(timer);
|
|
19
|
+
signal?.removeEventListener("abort", done);
|
|
20
|
+
resolve();
|
|
21
|
+
}
|
|
22
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export async function readAll(stream) {
|
|
26
|
+
const chunks = [];
|
|
27
|
+
for await (const chunk of stream)
|
|
28
|
+
chunks.push(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
|
|
29
|
+
return chunks.join("");
|
|
30
|
+
}
|
|
31
|
+
export function colorEnabled(io, json) {
|
|
32
|
+
if (json || !io.stdout.isTTY)
|
|
33
|
+
return false;
|
|
34
|
+
if (io.env.NO_COLOR !== undefined && io.env.NO_COLOR !== "")
|
|
35
|
+
return false;
|
|
36
|
+
return io.env.TERM !== "dumb";
|
|
37
|
+
}
|
|
38
|
+
const plain = { bold: (s) => s, dim: (s) => s, red: (s) => s, green: (s) => s, yellow: (s) => s };
|
|
39
|
+
const ansi = (open, close) => (s) => `\u001b[${open}m${s}\u001b[${close}m`;
|
|
40
|
+
const colored = {
|
|
41
|
+
bold: ansi(1, 22),
|
|
42
|
+
dim: ansi(2, 22),
|
|
43
|
+
red: ansi(31, 39),
|
|
44
|
+
green: ansi(32, 39),
|
|
45
|
+
yellow: ansi(33, 39),
|
|
46
|
+
};
|
|
47
|
+
export function styleFor(enabled) {
|
|
48
|
+
return enabled ? colored : plain;
|
|
49
|
+
}
|