chesly 0.0.1 → 0.2.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/LICENSE +21 -0
- package/README.md +412 -3
- package/dist/errors.js +171 -0
- package/dist/index.js +2896 -0
- package/package.json +43 -6
- package/cli.js +0 -2
package/dist/index.js
ADDED
|
@@ -0,0 +1,2896 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { Command } from "commander";
|
|
5
|
+
|
|
6
|
+
// src/api.ts
|
|
7
|
+
import { STATUS_CODES } from "http";
|
|
8
|
+
|
|
9
|
+
// package.json
|
|
10
|
+
var package_default = {
|
|
11
|
+
name: "chesly",
|
|
12
|
+
version: "0.2.0",
|
|
13
|
+
description: "Chesly CLI: your chats from the terminal and your agents",
|
|
14
|
+
license: "MIT",
|
|
15
|
+
type: "module",
|
|
16
|
+
bin: {
|
|
17
|
+
chesly: "dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
files: [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
engines: {
|
|
23
|
+
node: ">=20"
|
|
24
|
+
},
|
|
25
|
+
scripts: {
|
|
26
|
+
build: "tsup src/index.ts src/errors.ts --format esm --target node20 --clean --no-splitting",
|
|
27
|
+
"export-errors": "npm run build --silent && node scripts/export-errors.mjs",
|
|
28
|
+
prepare: "npm run build",
|
|
29
|
+
test: "vitest run",
|
|
30
|
+
typecheck: "tsc"
|
|
31
|
+
},
|
|
32
|
+
repository: {
|
|
33
|
+
type: "git",
|
|
34
|
+
url: "git+https://github.com/chesly-app/cli.git"
|
|
35
|
+
},
|
|
36
|
+
homepage: "https://github.com/chesly-app/cli#readme",
|
|
37
|
+
keywords: [
|
|
38
|
+
"chesly",
|
|
39
|
+
"cli",
|
|
40
|
+
"messages",
|
|
41
|
+
"chat",
|
|
42
|
+
"agents",
|
|
43
|
+
"mcp"
|
|
44
|
+
],
|
|
45
|
+
dependencies: {
|
|
46
|
+
"@napi-rs/keyring": "2.1.1",
|
|
47
|
+
commander: "14.0.3"
|
|
48
|
+
},
|
|
49
|
+
devDependencies: {
|
|
50
|
+
"@types/node": "22.20.5",
|
|
51
|
+
tsup: "8.5.1",
|
|
52
|
+
typescript: "7.0.2",
|
|
53
|
+
vitest: "5.0.4"
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// src/errors.ts
|
|
58
|
+
var EXIT = {
|
|
59
|
+
OK: 0,
|
|
60
|
+
ERROR: 1,
|
|
61
|
+
USAGE: 2,
|
|
62
|
+
NOT_SIGNED_IN: 3,
|
|
63
|
+
NOT_FOUND: 4,
|
|
64
|
+
/**
|
|
65
|
+
* Temporary: a 429 (a limit), a 408 (a request, such as an upload, too slow to arrive), a 502-504
|
|
66
|
+
* (briefly unavailable) or a first attempt still running (409). Retry later.
|
|
67
|
+
*/
|
|
68
|
+
RETRY_LATER: 5,
|
|
69
|
+
/** A 402: the account needs an API plan, or the plan's transcription minutes for the period are used up. */
|
|
70
|
+
PAYMENT_REQUIRED: 6
|
|
71
|
+
};
|
|
72
|
+
var HTTP_ERROR_TITLES = {
|
|
73
|
+
400: "Bad Request, without details.",
|
|
74
|
+
404: "Not Found, without details.",
|
|
75
|
+
413: "Payload Too Large, without details.",
|
|
76
|
+
429: "Too Many Requests, without details.",
|
|
77
|
+
500: "Internal Server Error, without details.",
|
|
78
|
+
502: "Bad Gateway, without details.",
|
|
79
|
+
503: "Service Unavailable, without details.",
|
|
80
|
+
504: "Gateway Timeout, without details."
|
|
81
|
+
};
|
|
82
|
+
function httpErrorCode(status) {
|
|
83
|
+
return status in HTTP_ERROR_TITLES ? `http_${status}` : "http_error";
|
|
84
|
+
}
|
|
85
|
+
var LOCAL_ERROR_CODES = [
|
|
86
|
+
{ code: "access_denied", title: "The sign-in was denied." },
|
|
87
|
+
{ code: "ambiguous_chat", title: "The chat name matches more than one chat." },
|
|
88
|
+
{ code: "chat_not_found", title: "Chat not found." },
|
|
89
|
+
{ code: "credentials_file_error", title: "The credentials file couldn't be read or written." },
|
|
90
|
+
{ code: "delivery_failed", title: "The network did not take the message." },
|
|
91
|
+
{ code: "delivery_unconfirmed", title: "The network didn't confirm the message, so it may have been delivered." },
|
|
92
|
+
{ code: "expired_token", title: "The sign-in code expired." },
|
|
93
|
+
{ code: "file_unreadable", title: "The file can't be read." },
|
|
94
|
+
{ code: "internal_error", title: "Something went wrong on our side." },
|
|
95
|
+
{ code: "invalid_api_url", title: "CHESLY_API_URL is not a usable API URL." },
|
|
96
|
+
{ code: "invalid_key_format", title: "The API key is not well formed." },
|
|
97
|
+
{ code: "invalid_response", title: "The API's answer is not what the CLI expects." },
|
|
98
|
+
{ code: "keychain_error", title: "The OS keychain refused." },
|
|
99
|
+
{ code: "keychain_timeout", title: "The OS keychain didn't answer in time." },
|
|
100
|
+
{ code: "login_not_started", title: "No sign-in is waiting to finish." },
|
|
101
|
+
{ code: "media_too_large", title: "The media is too large." },
|
|
102
|
+
{ code: "network_error", title: "The CLI couldn't reach the API." },
|
|
103
|
+
{ code: "not_signed_in", title: "Not signed in." },
|
|
104
|
+
{ code: "usage_error", title: "The command is not valid." },
|
|
105
|
+
...Object.entries(HTTP_ERROR_TITLES).map(([status, title]) => ({ code: `http_${status}`, title })),
|
|
106
|
+
{ code: "http_error", title: "An HTTP error without details." }
|
|
107
|
+
];
|
|
108
|
+
var RETRY_LATER_STATUSES = /* @__PURE__ */ new Set([408, 429, 502, 503, 504]);
|
|
109
|
+
function apiExitCode(status, code) {
|
|
110
|
+
if (status === 400 && code === "invalid_request") return EXIT.USAGE;
|
|
111
|
+
if (status === 401) return EXIT.NOT_SIGNED_IN;
|
|
112
|
+
if (status === 402) return EXIT.PAYMENT_REQUIRED;
|
|
113
|
+
if (status === 404) return EXIT.NOT_FOUND;
|
|
114
|
+
if (RETRY_LATER_STATUSES.has(status)) return EXIT.RETRY_LATER;
|
|
115
|
+
if (status === 409 && code === "idempotency_in_progress") return EXIT.RETRY_LATER;
|
|
116
|
+
return EXIT.ERROR;
|
|
117
|
+
}
|
|
118
|
+
var KeychainTimeoutError = class extends Error {
|
|
119
|
+
constructor(seconds) {
|
|
120
|
+
super(`The keychain didn't answer within ${seconds} s.`);
|
|
121
|
+
this.seconds = seconds;
|
|
122
|
+
this.name = "KeychainTimeoutError";
|
|
123
|
+
}
|
|
124
|
+
seconds;
|
|
125
|
+
};
|
|
126
|
+
function errorType(code) {
|
|
127
|
+
return `https://agents.chesly.app/docs/errors#${code}`;
|
|
128
|
+
}
|
|
129
|
+
var AnnotatedError = class extends Error {
|
|
130
|
+
constructor(error, extras, hint) {
|
|
131
|
+
super(error.message);
|
|
132
|
+
this.error = error;
|
|
133
|
+
this.extras = extras;
|
|
134
|
+
this.hint = hint;
|
|
135
|
+
this.name = "AnnotatedError";
|
|
136
|
+
}
|
|
137
|
+
error;
|
|
138
|
+
extras;
|
|
139
|
+
hint;
|
|
140
|
+
};
|
|
141
|
+
var CliError = class extends Error {
|
|
142
|
+
constructor(code, message, exitCode = EXIT.ERROR, details = {}) {
|
|
143
|
+
super(message);
|
|
144
|
+
this.code = code;
|
|
145
|
+
this.exitCode = exitCode;
|
|
146
|
+
this.name = "CliError";
|
|
147
|
+
this.extras = details.extras ?? {};
|
|
148
|
+
this.hint = details.hint;
|
|
149
|
+
}
|
|
150
|
+
code;
|
|
151
|
+
exitCode;
|
|
152
|
+
extras;
|
|
153
|
+
hint;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// src/api.ts
|
|
157
|
+
var VERSION = package_default.version;
|
|
158
|
+
var DEFAULT_API_URL = "https://api.chesly.app";
|
|
159
|
+
var USER_AGENT = `chesly-cli/${VERSION} (node ${process.version}; ${process.platform} ${process.arch})`;
|
|
160
|
+
var TIMEOUT_MS = 3e4;
|
|
161
|
+
var KEY_FORMAT = /^ck_live_[A-Za-z0-9_-]{48}$/;
|
|
162
|
+
function isApiKey(value) {
|
|
163
|
+
return typeof value === "string" && KEY_FORMAT.test(value);
|
|
164
|
+
}
|
|
165
|
+
function apiBaseUrl() {
|
|
166
|
+
const configured = process.env.CHESLY_API_URL?.trim();
|
|
167
|
+
const base = (configured || DEFAULT_API_URL).replace(/\/+$/, "");
|
|
168
|
+
if (!URL.canParse(base)) throw new CliError("invalid_api_url", "CHESLY_API_URL is not a valid URL.");
|
|
169
|
+
const { protocol, hostname: hostname2 } = new URL(base);
|
|
170
|
+
if (protocol !== "https:" && protocol !== "http:") {
|
|
171
|
+
throw new CliError("invalid_api_url", "CHESLY_API_URL must start with https://, like https://api.chesly.app.");
|
|
172
|
+
}
|
|
173
|
+
if (protocol === "http:" && !isLoopbackHost(hostname2)) {
|
|
174
|
+
throw new CliError(
|
|
175
|
+
"invalid_api_url",
|
|
176
|
+
"CHESLY_API_URL may use http:// only for this computer (localhost, 127.0.0.1 or [::1]); use https://."
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
return base;
|
|
180
|
+
}
|
|
181
|
+
function isLoopbackHost(hostname2) {
|
|
182
|
+
return hostname2 === "localhost" || hostname2 === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname2);
|
|
183
|
+
}
|
|
184
|
+
var CheslyApiError = class extends Error {
|
|
185
|
+
status;
|
|
186
|
+
code;
|
|
187
|
+
title;
|
|
188
|
+
detail;
|
|
189
|
+
requestId;
|
|
190
|
+
/** Seconds: the problem's `retry_after`, else the Retry-After header. */
|
|
191
|
+
retryAfter;
|
|
192
|
+
/** What JSON mode prints: the API's problem details as received, or ones built from the answer. */
|
|
193
|
+
problem;
|
|
194
|
+
constructor(fields) {
|
|
195
|
+
super(fields.detail ?? fields.title);
|
|
196
|
+
this.name = "CheslyApiError";
|
|
197
|
+
this.status = fields.status;
|
|
198
|
+
this.code = fields.code;
|
|
199
|
+
this.title = fields.title;
|
|
200
|
+
this.detail = fields.detail;
|
|
201
|
+
this.requestId = fields.requestId;
|
|
202
|
+
this.retryAfter = fields.retryAfter;
|
|
203
|
+
this.problem = fields.problem ?? {
|
|
204
|
+
type: errorType(fields.code),
|
|
205
|
+
title: fields.title,
|
|
206
|
+
status: fields.status,
|
|
207
|
+
...fields.detail === void 0 ? {} : { detail: fields.detail },
|
|
208
|
+
code: fields.code,
|
|
209
|
+
...fields.requestId === void 0 ? {} : { request_id: fields.requestId },
|
|
210
|
+
...fields.retryAfter === void 0 ? {} : { retry_after: fields.retryAfter }
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
var CheslyNetworkError = class extends Error {
|
|
215
|
+
/** No answer came within the request's time limit. */
|
|
216
|
+
timedOut;
|
|
217
|
+
constructor(url, cause, timeoutMs = TIMEOUT_MS) {
|
|
218
|
+
super(`Couldn't reach ${new URL(url).origin}: ${networkReason(cause, timeoutMs)}`);
|
|
219
|
+
this.name = "CheslyNetworkError";
|
|
220
|
+
this.timedOut = isTimeout(rootCause(cause));
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
async function apiRequest(path, init = {}) {
|
|
224
|
+
const headers = requestHeaders(init.key, "application/json", init.headers);
|
|
225
|
+
const url = `${apiBaseUrl()}${path}${queryString(init.query)}`;
|
|
226
|
+
let body;
|
|
227
|
+
if (init.form !== void 0) {
|
|
228
|
+
body = init.form;
|
|
229
|
+
} else if (init.body !== void 0) {
|
|
230
|
+
headers["content-type"] = "application/json";
|
|
231
|
+
body = JSON.stringify(init.body);
|
|
232
|
+
}
|
|
233
|
+
const timeoutMs = init.timeoutMs ?? TIMEOUT_MS;
|
|
234
|
+
let response;
|
|
235
|
+
let text;
|
|
236
|
+
try {
|
|
237
|
+
response = await fetch(url, {
|
|
238
|
+
method: init.method ?? (body === void 0 ? "GET" : "POST"),
|
|
239
|
+
headers,
|
|
240
|
+
body,
|
|
241
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
242
|
+
});
|
|
243
|
+
text = await response.text();
|
|
244
|
+
} catch (cause) {
|
|
245
|
+
throw new CheslyNetworkError(url, cause, timeoutMs);
|
|
246
|
+
}
|
|
247
|
+
const parsed = parseJson(text);
|
|
248
|
+
if (!response.ok) throw errorFromResponse(response, parsed);
|
|
249
|
+
if (text === "") return void 0;
|
|
250
|
+
if (parsed === void 0) {
|
|
251
|
+
throw new CheslyApiError({
|
|
252
|
+
status: response.status,
|
|
253
|
+
code: "invalid_response",
|
|
254
|
+
title: "The API answered with something that is not JSON.",
|
|
255
|
+
requestId: response.headers.get("x-request-id") ?? void 0
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
return parsed;
|
|
259
|
+
}
|
|
260
|
+
var RETRY_DELAYS_MS = [1e3, 2e3];
|
|
261
|
+
var MAX_RETRY_WAIT_S = 10;
|
|
262
|
+
var MAX_IN_PROGRESS = 3;
|
|
263
|
+
async function idempotentPost(path, init) {
|
|
264
|
+
const flags = init.again?.flags ?? `--idempotency-key ${init.idempotencyKey}`;
|
|
265
|
+
const extras = { idempotency_key: init.idempotencyKey, ...init.again?.extras };
|
|
266
|
+
let failures = 0;
|
|
267
|
+
let inProgress = 0;
|
|
268
|
+
for (; ; ) {
|
|
269
|
+
try {
|
|
270
|
+
return await apiRequest(path, {
|
|
271
|
+
method: "POST",
|
|
272
|
+
key: init.key,
|
|
273
|
+
body: init.body,
|
|
274
|
+
headers: { "idempotency-key": init.idempotencyKey }
|
|
275
|
+
});
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (error instanceof CheslyApiError && error.status === 409 && error.code === "idempotency_in_progress") {
|
|
278
|
+
if (++inProgress >= MAX_IN_PROGRESS) {
|
|
279
|
+
throw new AnnotatedError(
|
|
280
|
+
error,
|
|
281
|
+
extras,
|
|
282
|
+
`The first attempt is still running. Run the command again with ${flags} to see its result.`
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
await sleep(retryWaitMs(error, inProgress - 1));
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (!isShortLimit(error) && !isTransient(error)) throw error;
|
|
289
|
+
if (failures >= RETRY_DELAYS_MS.length) {
|
|
290
|
+
if (isShortLimit(error)) throw error;
|
|
291
|
+
throw new AnnotatedError(
|
|
292
|
+
error,
|
|
293
|
+
extras,
|
|
294
|
+
`It may have gone through. To retry without repeating it, run the command again with ${flags}.`
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
await sleep(retryWaitMs(error, failures++));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function retryWaitMs(error, retried) {
|
|
302
|
+
const retryAfter = error instanceof CheslyApiError ? error.retryAfter : void 0;
|
|
303
|
+
if (retryAfter !== void 0) return Math.min(retryAfter, MAX_RETRY_WAIT_S) * 1e3;
|
|
304
|
+
return RETRY_DELAYS_MS[Math.min(retried, RETRY_DELAYS_MS.length - 1)] ?? 0;
|
|
305
|
+
}
|
|
306
|
+
function isShortLimit(error) {
|
|
307
|
+
return error instanceof CheslyApiError && error.status === 429 && (error.retryAfter === void 0 || error.retryAfter <= MAX_RETRY_WAIT_S);
|
|
308
|
+
}
|
|
309
|
+
function isTransient(error) {
|
|
310
|
+
if (error instanceof CheslyNetworkError) return true;
|
|
311
|
+
return error instanceof CheslyApiError && (error.status === 502 || error.status === 503 || error.status === 504);
|
|
312
|
+
}
|
|
313
|
+
function sleep(ms, signal) {
|
|
314
|
+
return new Promise((resolve) => {
|
|
315
|
+
if (signal?.aborted) {
|
|
316
|
+
resolve();
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
const done = () => {
|
|
320
|
+
clearTimeout(timer);
|
|
321
|
+
signal?.removeEventListener("abort", done);
|
|
322
|
+
resolve();
|
|
323
|
+
};
|
|
324
|
+
const timer = setTimeout(done, ms);
|
|
325
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
async function openEventStream(path, init) {
|
|
329
|
+
const headers = requestHeaders(
|
|
330
|
+
init.key,
|
|
331
|
+
"text/event-stream",
|
|
332
|
+
init.lastEventId === void 0 ? {} : { "last-event-id": init.lastEventId }
|
|
333
|
+
);
|
|
334
|
+
const url = `${apiBaseUrl()}${path}${queryString(init.query)}`;
|
|
335
|
+
const connection = new AbortController();
|
|
336
|
+
const close = () => connection.abort(init.signal.reason);
|
|
337
|
+
init.signal.addEventListener("abort", close, { once: true });
|
|
338
|
+
if (init.signal.aborted) close();
|
|
339
|
+
const timer = setTimeout(
|
|
340
|
+
() => connection.abort(new DOMException("No answer in time.", "TimeoutError")),
|
|
341
|
+
TIMEOUT_MS
|
|
342
|
+
);
|
|
343
|
+
try {
|
|
344
|
+
let response;
|
|
345
|
+
try {
|
|
346
|
+
response = await fetch(url, { headers, signal: connection.signal });
|
|
347
|
+
} catch (cause) {
|
|
348
|
+
if (init.signal.aborted) throw cause;
|
|
349
|
+
throw new CheslyNetworkError(url, cause);
|
|
350
|
+
}
|
|
351
|
+
const requestId = response.headers.get("x-request-id") ?? void 0;
|
|
352
|
+
if (!response.ok) {
|
|
353
|
+
const text = await response.text().catch(() => "");
|
|
354
|
+
throw errorFromResponse(response, parseJson(text));
|
|
355
|
+
}
|
|
356
|
+
if (mediaTypeOf(response) !== "text/event-stream") {
|
|
357
|
+
await response.body?.cancel().catch(() => {
|
|
358
|
+
});
|
|
359
|
+
throw new CheslyApiError({
|
|
360
|
+
status: response.status,
|
|
361
|
+
code: "invalid_response",
|
|
362
|
+
title: "The API answered with something that is not an event stream.",
|
|
363
|
+
requestId
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
return response;
|
|
367
|
+
} catch (error) {
|
|
368
|
+
init.signal.removeEventListener("abort", close);
|
|
369
|
+
throw error;
|
|
370
|
+
} finally {
|
|
371
|
+
clearTimeout(timer);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
function requestHeaders(key, accept, extra = {}) {
|
|
375
|
+
if (key !== void 0 && !isApiKey(key)) {
|
|
376
|
+
throw new CliError("invalid_key_format", "Refused to send an API key that is not well formed.", EXIT.NOT_SIGNED_IN);
|
|
377
|
+
}
|
|
378
|
+
const headers = { accept, "user-agent": USER_AGENT };
|
|
379
|
+
for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value;
|
|
380
|
+
if (key !== void 0) headers.authorization = `Bearer ${key}`;
|
|
381
|
+
return headers;
|
|
382
|
+
}
|
|
383
|
+
function queryString(query = {}) {
|
|
384
|
+
const pairs = Object.entries(query).flatMap(
|
|
385
|
+
([name, value]) => value === void 0 ? [] : [`${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`]
|
|
386
|
+
);
|
|
387
|
+
return pairs.length === 0 ? "" : `?${pairs.join("&")}`;
|
|
388
|
+
}
|
|
389
|
+
function errorFromResponse(response, body) {
|
|
390
|
+
const fields = isRecord(body) ? body : {};
|
|
391
|
+
const code = token(fields.code) ?? token(fields.error) ?? httpErrorCode(response.status);
|
|
392
|
+
const sentence = token(fields.error) === void 0 ? nonEmpty(fields.error) : void 0;
|
|
393
|
+
return new CheslyApiError({
|
|
394
|
+
status: response.status,
|
|
395
|
+
code,
|
|
396
|
+
// HTTP/2 answers carry no reason phrase, so the standard one stands in.
|
|
397
|
+
title: nonEmpty(fields.title) ?? nonEmpty(fields.error_description) ?? STATUS_CODES[response.status] ?? (response.statusText || `HTTP ${response.status}`),
|
|
398
|
+
detail: nonEmpty(fields.detail) ?? sentence ?? nonEmpty(fields.message),
|
|
399
|
+
requestId: nonEmpty(fields.request_id) ?? response.headers.get("x-request-id") ?? void 0,
|
|
400
|
+
retryAfter: retryAfterSeconds(fields.retry_after) ?? retryAfterSeconds(response.headers.get("retry-after")),
|
|
401
|
+
// Problem details are printed exactly as received; anything else gets problem details built for it.
|
|
402
|
+
problem: isProblem(response, fields) ? fields : void 0
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
function isProblem(response, fields) {
|
|
406
|
+
if (Object.keys(fields).length === 0) return false;
|
|
407
|
+
return mediaTypeOf(response) === "application/problem+json" || typeof fields.type === "string" || token(fields.code) !== void 0;
|
|
408
|
+
}
|
|
409
|
+
function token(value) {
|
|
410
|
+
return typeof value === "string" && /^[a-z][a-z0-9_]*$/.test(value) ? value : void 0;
|
|
411
|
+
}
|
|
412
|
+
function mediaTypeOf(response) {
|
|
413
|
+
return response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
414
|
+
}
|
|
415
|
+
function retryAfterSeconds(value) {
|
|
416
|
+
if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? Math.ceil(value) : void 0;
|
|
417
|
+
if (typeof value !== "string" || value.trim() === "") return void 0;
|
|
418
|
+
const seconds = Number(value);
|
|
419
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
420
|
+
const date = Date.parse(value);
|
|
421
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - Date.now()) / 1e3));
|
|
422
|
+
}
|
|
423
|
+
function parseJson(text) {
|
|
424
|
+
try {
|
|
425
|
+
return JSON.parse(text);
|
|
426
|
+
} catch {
|
|
427
|
+
return void 0;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
function isRecord(value) {
|
|
431
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
432
|
+
}
|
|
433
|
+
function nonEmpty(value) {
|
|
434
|
+
return typeof value === "string" && value.trim() !== "" ? value : void 0;
|
|
435
|
+
}
|
|
436
|
+
function networkReason(error, timeoutMs) {
|
|
437
|
+
const current = rootCause(error);
|
|
438
|
+
if (isTimeout(current)) return `no answer within ${timeoutMs / 1e3} s`;
|
|
439
|
+
if (current instanceof AggregateError) {
|
|
440
|
+
const tried = current.errors.filter(isSystemError).map((attempt) => attempt.message);
|
|
441
|
+
if (tried.length > 0) return tried.join("; ");
|
|
442
|
+
}
|
|
443
|
+
if (isSystemError(current)) return current.message;
|
|
444
|
+
return "the request failed before it reached the API";
|
|
445
|
+
}
|
|
446
|
+
function rootCause(error) {
|
|
447
|
+
let current = error;
|
|
448
|
+
for (let depth = 0; depth < 5 && current instanceof Error && current.cause !== void 0; depth++) {
|
|
449
|
+
current = current.cause;
|
|
450
|
+
}
|
|
451
|
+
return current;
|
|
452
|
+
}
|
|
453
|
+
function isTimeout(error) {
|
|
454
|
+
return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
455
|
+
}
|
|
456
|
+
function isSystemError(error) {
|
|
457
|
+
return error instanceof Error && typeof error.code === "string" && error.message !== "";
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// src/auth.ts
|
|
461
|
+
import { mkdir, readFile, rename, rm, writeFile } from "fs/promises";
|
|
462
|
+
import { homedir } from "os";
|
|
463
|
+
import { dirname, join } from "path";
|
|
464
|
+
|
|
465
|
+
// src/keychain.ts
|
|
466
|
+
import { spawn } from "child_process";
|
|
467
|
+
var SERVICE = "chesly";
|
|
468
|
+
var ACCOUNT = "default";
|
|
469
|
+
var TIMEOUT_MS2 = 1e4;
|
|
470
|
+
var unfinished = 0;
|
|
471
|
+
function unfinishedKeychainCalls() {
|
|
472
|
+
return unfinished;
|
|
473
|
+
}
|
|
474
|
+
async function openKeychain() {
|
|
475
|
+
return process.platform === "darwin" ? macosKeychain() : napiKeychain();
|
|
476
|
+
}
|
|
477
|
+
var SECURITY = "/usr/bin/security";
|
|
478
|
+
var ITEM_NOT_FOUND = 44;
|
|
479
|
+
function macosKeychain() {
|
|
480
|
+
const item = ["-s", SERVICE, "-a", ACCOUNT];
|
|
481
|
+
return {
|
|
482
|
+
async get() {
|
|
483
|
+
const result = await security(["find-generic-password", ...item, "-w"]);
|
|
484
|
+
if (result.code === ITEM_NOT_FOUND) return null;
|
|
485
|
+
if (result.code !== 0) throw securityError(result);
|
|
486
|
+
return result.stdout.trim() || null;
|
|
487
|
+
},
|
|
488
|
+
async set(key) {
|
|
489
|
+
if (!/^[A-Za-z0-9_-]+$/.test(key)) throw new Error("A key with unexpected characters was not stored.");
|
|
490
|
+
const result = await security(["-i"], `add-generic-password -U ${item.join(" ")} -w ${key}
|
|
491
|
+
`);
|
|
492
|
+
if (result.code !== 0) throw securityError(result);
|
|
493
|
+
},
|
|
494
|
+
async delete() {
|
|
495
|
+
const result = await security(["delete-generic-password", ...item]);
|
|
496
|
+
if (result.code === ITEM_NOT_FOUND) return false;
|
|
497
|
+
if (result.code !== 0) throw securityError(result);
|
|
498
|
+
return true;
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
async function napiKeychain() {
|
|
503
|
+
try {
|
|
504
|
+
const { AsyncEntry } = await import("@napi-rs/keyring");
|
|
505
|
+
const entry = new AsyncEntry(SERVICE, ACCOUNT, { linux: { store: "secret-service" } });
|
|
506
|
+
return {
|
|
507
|
+
get: () => withTimeout((signal) => entry.getPassword(signal)),
|
|
508
|
+
set: (key) => withTimeout((signal) => entry.setPassword(key, signal)),
|
|
509
|
+
delete: () => withTimeout((signal) => entry.deletePassword(signal))
|
|
510
|
+
};
|
|
511
|
+
} catch {
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
function withTimeout(call) {
|
|
516
|
+
const controller = new AbortController();
|
|
517
|
+
return new Promise((resolve, reject) => {
|
|
518
|
+
const running = call(controller.signal);
|
|
519
|
+
const timer = setTimeout(() => {
|
|
520
|
+
controller.abort();
|
|
521
|
+
unfinished++;
|
|
522
|
+
running.then(
|
|
523
|
+
() => unfinished--,
|
|
524
|
+
() => unfinished--
|
|
525
|
+
);
|
|
526
|
+
reject(new KeychainTimeoutError(TIMEOUT_MS2 / 1e3));
|
|
527
|
+
}, TIMEOUT_MS2);
|
|
528
|
+
running.then(
|
|
529
|
+
(value) => {
|
|
530
|
+
clearTimeout(timer);
|
|
531
|
+
resolve(value);
|
|
532
|
+
},
|
|
533
|
+
(error) => {
|
|
534
|
+
clearTimeout(timer);
|
|
535
|
+
reject(error);
|
|
536
|
+
}
|
|
537
|
+
);
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
function security(args, input = "") {
|
|
541
|
+
return new Promise((resolve, reject) => {
|
|
542
|
+
const child = spawn(SECURITY, args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
543
|
+
const timer = setTimeout(() => {
|
|
544
|
+
child.kill("SIGKILL");
|
|
545
|
+
reject(new KeychainTimeoutError(TIMEOUT_MS2 / 1e3));
|
|
546
|
+
}, TIMEOUT_MS2);
|
|
547
|
+
let stdout = "";
|
|
548
|
+
let stderr = "";
|
|
549
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
550
|
+
stdout += chunk;
|
|
551
|
+
});
|
|
552
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
553
|
+
stderr += chunk;
|
|
554
|
+
});
|
|
555
|
+
child.on("error", (error) => {
|
|
556
|
+
clearTimeout(timer);
|
|
557
|
+
reject(error);
|
|
558
|
+
});
|
|
559
|
+
child.on("close", (code) => {
|
|
560
|
+
clearTimeout(timer);
|
|
561
|
+
resolve({ code: code ?? 1, stdout, stderr });
|
|
562
|
+
});
|
|
563
|
+
child.stdin.on("error", () => {
|
|
564
|
+
});
|
|
565
|
+
child.stdin.end(input);
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
function securityError(result) {
|
|
569
|
+
return new Error(result.stderr.trim() || `security exited with code ${result.code}`);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// src/auth.ts
|
|
573
|
+
function configDir() {
|
|
574
|
+
return join(homedir(), ".config", "chesly");
|
|
575
|
+
}
|
|
576
|
+
function credentialsPath() {
|
|
577
|
+
return join(configDir(), "credentials.json");
|
|
578
|
+
}
|
|
579
|
+
function pendingLoginPath() {
|
|
580
|
+
return join(configDir(), "pending-login.json");
|
|
581
|
+
}
|
|
582
|
+
async function savePendingLogin(login) {
|
|
583
|
+
try {
|
|
584
|
+
await writePrivateFile(pendingLoginPath(), `${JSON.stringify(login)}
|
|
585
|
+
`);
|
|
586
|
+
} catch (error) {
|
|
587
|
+
throw new CliError("credentials_file_error", `Couldn't save the sign-in to ${pendingLoginPath()}: ${reasonOf(error)}`);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
async function readPendingLogin() {
|
|
591
|
+
try {
|
|
592
|
+
const value = JSON.parse(await readFile(pendingLoginPath(), "utf8"));
|
|
593
|
+
const { deviceCode, userCode, link, interval, expiresAt } = value;
|
|
594
|
+
if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof link !== "string") return null;
|
|
595
|
+
if (typeof interval !== "number" || typeof expiresAt !== "number") return null;
|
|
596
|
+
const replaces = (Array.isArray(value.replaces) ? value.replaces : []).flatMap((hint) => {
|
|
597
|
+
const { prefix, last4 } = hint ?? {};
|
|
598
|
+
return typeof prefix === "string" && typeof last4 === "string" ? [{ prefix, last4 }] : [];
|
|
599
|
+
});
|
|
600
|
+
return { deviceCode, userCode, link, interval, expiresAt, replaces, force: value.force === true };
|
|
601
|
+
} catch {
|
|
602
|
+
return null;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
async function deletePendingLogin() {
|
|
606
|
+
await rm(pendingLoginPath(), { force: true }).catch(() => {
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
async function findKey() {
|
|
610
|
+
const fromEnv = process.env.CHESLY_API_KEY?.trim();
|
|
611
|
+
if (fromEnv) return { key: wellFormed(fromEnv, "env"), source: "env" };
|
|
612
|
+
const fromKeychain = await readKeychain();
|
|
613
|
+
if (fromKeychain.key) return { key: wellFormed(fromKeychain.key, "keychain"), source: "keychain" };
|
|
614
|
+
const fromFile = await readCredentialsFile();
|
|
615
|
+
if (fromFile) return { key: wellFormed(fromFile, "file"), source: "file" };
|
|
616
|
+
if (fromKeychain.failure !== void 0) {
|
|
617
|
+
const hint = "Unlock it (or answer its dialog), then try again, or set CHESLY_API_KEY.";
|
|
618
|
+
throw keychainFailure("read the key from", fromKeychain.failure, hint);
|
|
619
|
+
}
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
function wellFormed(key, source) {
|
|
623
|
+
if (isApiKey(key)) return key;
|
|
624
|
+
throw new CliError(
|
|
625
|
+
"invalid_key_format",
|
|
626
|
+
source === "env" ? "CHESLY_API_KEY is not a Chesly API key (ck_live_ and 48 letters, digits, _ or -). Fix or unset it." : `The key stored in ${describeSource(source)} is not a Chesly API key. Run \`chesly login\` again.`,
|
|
627
|
+
EXIT.NOT_SIGNED_IN
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
async function requireKey() {
|
|
631
|
+
const found = await findKey();
|
|
632
|
+
if (!found) {
|
|
633
|
+
throw new CliError("not_signed_in", "Not signed in. Run `chesly login`, or set CHESLY_API_KEY.", EXIT.NOT_SIGNED_IN);
|
|
634
|
+
}
|
|
635
|
+
return found;
|
|
636
|
+
}
|
|
637
|
+
async function storedKeys() {
|
|
638
|
+
const keys = [];
|
|
639
|
+
const fromKeychain = await readKeychain();
|
|
640
|
+
if (isApiKey(fromKeychain.key)) keys.push({ key: fromKeychain.key, source: "keychain" });
|
|
641
|
+
const fromFile = await readCredentialsFile();
|
|
642
|
+
if (isApiKey(fromFile) && fromFile !== fromKeychain.key) keys.push({ key: fromFile, source: "file" });
|
|
643
|
+
const failure = fromKeychain.failure === void 0 ? void 0 : keychainFailure("read the key from", fromKeychain.failure, "Unlock it (or answer its dialog), then try again.");
|
|
644
|
+
return { keys, keychainFailure: failure };
|
|
645
|
+
}
|
|
646
|
+
function keyOnce() {
|
|
647
|
+
let found;
|
|
648
|
+
return () => found ??= requireKey().then(({ key }) => key);
|
|
649
|
+
}
|
|
650
|
+
async function storeKey(key) {
|
|
651
|
+
if (!isApiKey(key)) throw new CliError("invalid_key_format", "Refused to store an API key that is not well formed.");
|
|
652
|
+
const keychain = await openKeychain();
|
|
653
|
+
if (keychain) {
|
|
654
|
+
const stored = await keychain.set(key).then(
|
|
655
|
+
() => true,
|
|
656
|
+
() => false
|
|
657
|
+
);
|
|
658
|
+
if (stored) {
|
|
659
|
+
await removeCredentialsFile().catch(() => false);
|
|
660
|
+
return "keychain";
|
|
661
|
+
}
|
|
662
|
+
await keychain.delete().catch(() => false);
|
|
663
|
+
}
|
|
664
|
+
await writeCredentialsFile(key);
|
|
665
|
+
return "file";
|
|
666
|
+
}
|
|
667
|
+
async function deleteStoredKey() {
|
|
668
|
+
let fromFile = false;
|
|
669
|
+
let fromKeychain = false;
|
|
670
|
+
let failure;
|
|
671
|
+
try {
|
|
672
|
+
fromFile = await removeCredentialsFile();
|
|
673
|
+
} catch (error) {
|
|
674
|
+
const message = `Couldn't remove the key from ${credentialsPath()}: ${reasonOf(error)}`;
|
|
675
|
+
failure = new CliError("credentials_file_error", message);
|
|
676
|
+
}
|
|
677
|
+
const keychain = await openKeychain();
|
|
678
|
+
if (keychain) {
|
|
679
|
+
try {
|
|
680
|
+
fromKeychain = await keychain.delete();
|
|
681
|
+
} catch (error) {
|
|
682
|
+
const hint = "Unlock it (or answer its dialog), then run `chesly logout` again.";
|
|
683
|
+
failure ??= keychainFailure("remove the key from", error, hint);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
const removed = [];
|
|
687
|
+
if (fromKeychain) removed.push("keychain");
|
|
688
|
+
if (fromFile) removed.push("file");
|
|
689
|
+
if (failure) {
|
|
690
|
+
const went = removed.length === 0 ? "Nothing was removed." : `Removed it from ${removed.map(describeSource).join(" and ")}.`;
|
|
691
|
+
throw new CliError(failure.code, failure.message, failure.exitCode, {
|
|
692
|
+
extras: { ...failure.extras, removed },
|
|
693
|
+
hint: failure.hint === void 0 ? went : `${went}
|
|
694
|
+
${failure.hint}`
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
return removed;
|
|
698
|
+
}
|
|
699
|
+
function keychainFailure(action, error, hint) {
|
|
700
|
+
const where = describeSource("keychain");
|
|
701
|
+
if (error instanceof KeychainTimeoutError) {
|
|
702
|
+
const why = "It may be locked, or waiting for someone to answer a dialog.";
|
|
703
|
+
const message = `Couldn't ${action} ${where}: it didn't answer within ${error.seconds} s. ${why}`;
|
|
704
|
+
return new CliError("keychain_timeout", message, EXIT.ERROR, { hint });
|
|
705
|
+
}
|
|
706
|
+
return new CliError("keychain_error", `Couldn't ${action} ${where}: ${reasonOf(error)}`, EXIT.ERROR, { hint });
|
|
707
|
+
}
|
|
708
|
+
function reasonOf(error) {
|
|
709
|
+
return (error instanceof Error ? error.message : String(error)).replace(/ck_live_[A-Za-z0-9_-]*/g, "ck_live_\u2026");
|
|
710
|
+
}
|
|
711
|
+
function describeSource(source) {
|
|
712
|
+
if (source === "env") return "the CHESLY_API_KEY environment variable";
|
|
713
|
+
if (source === "file") return credentialsPath();
|
|
714
|
+
if (process.platform === "darwin") return "the macOS Keychain";
|
|
715
|
+
if (process.platform === "win32") return "Windows Credential Manager";
|
|
716
|
+
return "the system keyring";
|
|
717
|
+
}
|
|
718
|
+
function keyHint(key) {
|
|
719
|
+
if (key.length < 40) return { prefix: key.slice(0, 4), last4: "" };
|
|
720
|
+
return { prefix: key.slice(0, 12), last4: key.slice(-4) };
|
|
721
|
+
}
|
|
722
|
+
function maskKey(key) {
|
|
723
|
+
const { prefix, last4 } = keyHint(key);
|
|
724
|
+
return `${prefix}\u2026${last4}`;
|
|
725
|
+
}
|
|
726
|
+
async function readKeychain() {
|
|
727
|
+
const keychain = await openKeychain();
|
|
728
|
+
if (!keychain) return { key: null };
|
|
729
|
+
try {
|
|
730
|
+
return { key: (await keychain.get())?.trim() || null };
|
|
731
|
+
} catch (error) {
|
|
732
|
+
return { key: null, failure: error ?? new Error("The keychain failed without saying why.") };
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
async function readCredentialsFile() {
|
|
736
|
+
try {
|
|
737
|
+
const parsed = JSON.parse(await readFile(credentialsPath(), "utf8"));
|
|
738
|
+
return typeof parsed.api_key === "string" && parsed.api_key.trim() ? parsed.api_key.trim() : null;
|
|
739
|
+
} catch {
|
|
740
|
+
return null;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
async function writeCredentialsFile(key) {
|
|
744
|
+
await writePrivateFile(credentialsPath(), `${JSON.stringify({ api_key: key }, null, 2)}
|
|
745
|
+
`);
|
|
746
|
+
}
|
|
747
|
+
async function writePrivateFile(file, content) {
|
|
748
|
+
await mkdir(dirname(file), { recursive: true, mode: 448 });
|
|
749
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
750
|
+
await rm(temp, { force: true });
|
|
751
|
+
await writeFile(temp, content, { mode: 384, flag: "wx" });
|
|
752
|
+
await rename(temp, file);
|
|
753
|
+
}
|
|
754
|
+
async function removeCredentialsFile() {
|
|
755
|
+
try {
|
|
756
|
+
await rm(credentialsPath());
|
|
757
|
+
return true;
|
|
758
|
+
} catch (error) {
|
|
759
|
+
if (error.code === "ENOENT") return false;
|
|
760
|
+
throw error;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// src/output.ts
|
|
765
|
+
import { CommanderError } from "commander";
|
|
766
|
+
function processIo() {
|
|
767
|
+
return {
|
|
768
|
+
out: (text) => void process.stdout.write(text),
|
|
769
|
+
err: (text) => void process.stderr.write(text),
|
|
770
|
+
isTTY: process.stdout.isTTY === true,
|
|
771
|
+
stdin: {
|
|
772
|
+
// A getter: only a command that asks touches process.stdin.
|
|
773
|
+
get isTTY() {
|
|
774
|
+
return process.stdin.isTTY === true;
|
|
775
|
+
},
|
|
776
|
+
read: async () => {
|
|
777
|
+
const chunks = [];
|
|
778
|
+
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
779
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
780
|
+
}
|
|
781
|
+
},
|
|
782
|
+
onInterrupt: (handler) => {
|
|
783
|
+
let interrupted = false;
|
|
784
|
+
const listener = () => {
|
|
785
|
+
if (interrupted) process.exit(130);
|
|
786
|
+
interrupted = true;
|
|
787
|
+
handler();
|
|
788
|
+
};
|
|
789
|
+
process.on("SIGINT", listener);
|
|
790
|
+
return () => void process.off("SIGINT", listener);
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
var Output = class {
|
|
795
|
+
constructor(io, options = {}) {
|
|
796
|
+
this.io = io;
|
|
797
|
+
this.json = options.json === true || !io.isTTY;
|
|
798
|
+
}
|
|
799
|
+
io;
|
|
800
|
+
json;
|
|
801
|
+
/**
|
|
802
|
+
* The command's result: `data` exactly as JSON, or `human()` in a terminal. Everything printed for
|
|
803
|
+
* people goes through terminalSafe, whatever the renderer did: much of it comes from the API.
|
|
804
|
+
*/
|
|
805
|
+
result(data, human) {
|
|
806
|
+
this.io.out(this.json ? `${toJson(data, 2)}
|
|
807
|
+
` : withNewline(terminalSafe(human())));
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* A note for people in a terminal (a paging hint, progress). JSON mode leaves it out: what it says is
|
|
811
|
+
* in the result, or the command sends a JSON notice instead (`notice`, `warn`).
|
|
812
|
+
*/
|
|
813
|
+
note(text) {
|
|
814
|
+
if (!this.json) this.io.err(withNewline(terminalSafe(text)));
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Something the person must see while the command runs, on stderr: `data` as one JSON line in JSON
|
|
818
|
+
* mode, `human()` in a terminal.
|
|
819
|
+
*/
|
|
820
|
+
notice(data, human) {
|
|
821
|
+
this.io.err(this.json ? `${toJson(data)}
|
|
822
|
+
` : withNewline(terminalSafe(human())));
|
|
823
|
+
}
|
|
824
|
+
/** A warning on stderr: `{ "warning": <code>, "message", ...extras }` as one JSON line, or the message. */
|
|
825
|
+
warn(code, message, extras = {}) {
|
|
826
|
+
this.notice({ warning: code, message, ...extras }, () => message);
|
|
827
|
+
}
|
|
828
|
+
/** One result of a stream, written at once: `data` as one JSON line, or `human()` in a terminal. */
|
|
829
|
+
line(data, human) {
|
|
830
|
+
this.io.out(this.json ? `${toJson(data)}
|
|
831
|
+
` : withNewline(terminalSafe(human())));
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
function formatTable(rows) {
|
|
835
|
+
const widths = [];
|
|
836
|
+
for (const row of rows) {
|
|
837
|
+
row.forEach((cell, i) => {
|
|
838
|
+
widths[i] = Math.max(widths[i] ?? 0, cell.length);
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
return rows.map(
|
|
842
|
+
(row) => row.map((cell, i) => i === row.length - 1 ? cell : cell.padEnd(widths[i] ?? 0)).join(" ").trimEnd()
|
|
843
|
+
).join("\n");
|
|
844
|
+
}
|
|
845
|
+
function toJson(value, space) {
|
|
846
|
+
return (JSON.stringify(value, null, space) ?? "null").replace(
|
|
847
|
+
/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,
|
|
848
|
+
(char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`
|
|
849
|
+
);
|
|
850
|
+
}
|
|
851
|
+
function shellQuote(value) {
|
|
852
|
+
return /^[A-Za-z0-9_./:@,+-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
|
|
853
|
+
}
|
|
854
|
+
function indent(text, prefix) {
|
|
855
|
+
return text.split("\n").map((line) => `${prefix}${line}`).join("\n");
|
|
856
|
+
}
|
|
857
|
+
function terminalSafe(text) {
|
|
858
|
+
return text.replace(/\r\n?/g, "\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "");
|
|
859
|
+
}
|
|
860
|
+
function oneLine(text, max = Number.POSITIVE_INFINITY) {
|
|
861
|
+
const flat = terminalSafe(text).replace(/\s+/g, " ").trim();
|
|
862
|
+
const chars = Array.from(flat);
|
|
863
|
+
return chars.length > max ? `${chars.slice(0, max - 1).join("")}\u2026` : flat;
|
|
864
|
+
}
|
|
865
|
+
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
866
|
+
function formatWhen(iso, options = {}) {
|
|
867
|
+
const date = new Date(iso ?? "");
|
|
868
|
+
if (Number.isNaN(date.getTime())) return "";
|
|
869
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
870
|
+
const clock = `${twoDigits(date.getHours())}:${twoDigits(date.getMinutes())}`;
|
|
871
|
+
if (date.toDateString() === now.toDateString()) return clock;
|
|
872
|
+
const day = date.getFullYear() === now.getFullYear() ? `${MONTHS[date.getMonth()]} ${date.getDate()}` : `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;
|
|
873
|
+
return options.time ? `${day} ${clock}` : day;
|
|
874
|
+
}
|
|
875
|
+
function twoDigits(value) {
|
|
876
|
+
return String(value).padStart(2, "0");
|
|
877
|
+
}
|
|
878
|
+
function reportError(error, io, json) {
|
|
879
|
+
if (error instanceof CommanderError) {
|
|
880
|
+
return error.exitCode === 0 ? EXIT.OK : EXIT.USAGE;
|
|
881
|
+
}
|
|
882
|
+
const failure = describeFailure(error);
|
|
883
|
+
if (json) {
|
|
884
|
+
io.err(`${toJson(failure.problem)}
|
|
885
|
+
`);
|
|
886
|
+
} else {
|
|
887
|
+
const requestId = failure.requestId === void 0 ? "" : ` (request ${oneLine(failure.requestId, 64)})`;
|
|
888
|
+
const hint = failure.hint ? `${terminalSafe(failure.hint)}
|
|
889
|
+
` : "";
|
|
890
|
+
io.err(`Error: ${terminalSafe(failure.message)}${requestId}
|
|
891
|
+
${hint}`);
|
|
892
|
+
}
|
|
893
|
+
return failure.exitCode;
|
|
894
|
+
}
|
|
895
|
+
function formatUsageError(message, json) {
|
|
896
|
+
if (!json) return message;
|
|
897
|
+
return `${toJson(cliProblem("usage_error", message.replace(/^error:\s*/, "").trim()))}
|
|
898
|
+
`;
|
|
899
|
+
}
|
|
900
|
+
function cliProblem(code, title) {
|
|
901
|
+
return { type: errorType(code), title, code };
|
|
902
|
+
}
|
|
903
|
+
var CLI_WORDING = {
|
|
904
|
+
chat_not_found: { hint: "chesly chats lists your chats (email threads with --network email)." },
|
|
905
|
+
account_not_found: { hint: "chesly accounts lists your accounts." },
|
|
906
|
+
message_not_found: { hint: "chesly read <chat> shows a chat's messages with their IDs." },
|
|
907
|
+
account_reconnect_required: {
|
|
908
|
+
hint: "Chesly can't sign in to that email account. Reconnect it in the Chesly app; chesly accounts shows its status."
|
|
909
|
+
},
|
|
910
|
+
invalid_reply_to: {
|
|
911
|
+
message: "--reply-to must be a message in this chat.",
|
|
912
|
+
hint: "chesly read <chat> shows its messages with their IDs."
|
|
913
|
+
},
|
|
914
|
+
webhook_not_found: { hint: "chesly webhooks list lists your webhooks." },
|
|
915
|
+
upload_timeout: {
|
|
916
|
+
message: "The upload was too slow, or didn't finish within 60 s.",
|
|
917
|
+
hint: "Send it again in 60 s: this account's uploads are held that long after a slow one. On a slow connection, send a smaller file."
|
|
918
|
+
},
|
|
919
|
+
key_not_found: { hint: "chesly keys list lists your API keys." }
|
|
920
|
+
};
|
|
921
|
+
function describeFailure(error) {
|
|
922
|
+
if (error instanceof AnnotatedError) {
|
|
923
|
+
const failure = describeFailure(error.error);
|
|
924
|
+
return {
|
|
925
|
+
...failure,
|
|
926
|
+
problem: { ...failure.problem, ...error.extras },
|
|
927
|
+
hint: failure.hint === void 0 ? error.hint : `${failure.hint}
|
|
928
|
+
${error.hint}`
|
|
929
|
+
};
|
|
930
|
+
}
|
|
931
|
+
if (error instanceof CheslyApiError) {
|
|
932
|
+
const wording = CLI_WORDING[error.code];
|
|
933
|
+
const message2 = wording === void 0 ? error.message : wording.message ?? error.title;
|
|
934
|
+
return {
|
|
935
|
+
message: message2,
|
|
936
|
+
exitCode: apiExitCode(error.status, error.code),
|
|
937
|
+
problem: error.problem,
|
|
938
|
+
requestId: error.requestId,
|
|
939
|
+
hint: [wording?.hint, hintFor(error, message2)].filter(Boolean).join("\n") || void 0
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
if (error instanceof CliError) {
|
|
943
|
+
return {
|
|
944
|
+
message: error.message,
|
|
945
|
+
exitCode: error.exitCode,
|
|
946
|
+
problem: { ...cliProblem(error.code, error.message), ...error.extras },
|
|
947
|
+
hint: error.hint
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
if (error instanceof CheslyNetworkError) {
|
|
951
|
+
return { message: error.message, exitCode: EXIT.ERROR, problem: cliProblem("network_error", error.message) };
|
|
952
|
+
}
|
|
953
|
+
const message = `Unexpected error: ${error instanceof Error ? error.message : String(error)}`;
|
|
954
|
+
return { message, exitCode: EXIT.ERROR, problem: cliProblem("internal_error", message) };
|
|
955
|
+
}
|
|
956
|
+
function hintFor(error, message) {
|
|
957
|
+
if (error.status === 401) return "Run `chesly login` to sign in again, or check CHESLY_API_KEY.";
|
|
958
|
+
const retryable = RETRY_LATER_STATUSES.has(error.status);
|
|
959
|
+
if (retryable && error.retryAfter !== void 0 && !/\bretry in\b/i.test(message)) return `Retry in ${error.retryAfter} s.`;
|
|
960
|
+
return void 0;
|
|
961
|
+
}
|
|
962
|
+
function withNewline(text) {
|
|
963
|
+
return text.endsWith("\n") ? text : `${text}
|
|
964
|
+
`;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// src/shapes.ts
|
|
968
|
+
function expectAnswer(answer, valid, what) {
|
|
969
|
+
if (!valid(answer)) throw new CliError("invalid_response", `The API's answer is not ${what}.`);
|
|
970
|
+
return answer;
|
|
971
|
+
}
|
|
972
|
+
function isSendLimit(value) {
|
|
973
|
+
return isRecord2(value) && typeof value.network === "string" && ["per_hour", "per_day", "used_last_hour", "used_last_day"].every((field) => typeof value[field] === "number");
|
|
974
|
+
}
|
|
975
|
+
function isKeyList(value) {
|
|
976
|
+
return isRecord2(value) && Array.isArray(value.keys) && value.keys.every((key) => isRecord2(key) && typeof key.id === "string");
|
|
977
|
+
}
|
|
978
|
+
function isMe(value) {
|
|
979
|
+
if (typeof value !== "object" || value === null) return false;
|
|
980
|
+
const { key } = value;
|
|
981
|
+
if (typeof key !== "object" || key === null) return false;
|
|
982
|
+
const { name, scope } = key;
|
|
983
|
+
return typeof name === "string" && typeof scope === "string";
|
|
984
|
+
}
|
|
985
|
+
function isAccountList(value) {
|
|
986
|
+
return isRecord2(value) && Array.isArray(value.accounts) && value.accounts.every(hasId);
|
|
987
|
+
}
|
|
988
|
+
function isChatPage(value) {
|
|
989
|
+
return isRecord2(value) && Array.isArray(value.chats) && value.chats.every(hasId);
|
|
990
|
+
}
|
|
991
|
+
function deliveryState(delivery) {
|
|
992
|
+
if (delivery === null || delivery === void 0) return void 0;
|
|
993
|
+
if (delivery.status === "failed") return delivery.error?.certain === true ? "failed" : "unconfirmed";
|
|
994
|
+
return delivery.status;
|
|
995
|
+
}
|
|
996
|
+
function isMessage(value) {
|
|
997
|
+
return isRecord2(value) && typeof value.id === "string" && value.id !== "" && typeof value.chat_id === "string";
|
|
998
|
+
}
|
|
999
|
+
function isMessageList(value) {
|
|
1000
|
+
return isRecord2(value) && Array.isArray(value.messages) && value.messages.every(isMessage);
|
|
1001
|
+
}
|
|
1002
|
+
function isCatchUp(value) {
|
|
1003
|
+
return isRecord2(value) && Array.isArray(value.chats) && value.chats.every((entry) => isRecord2(entry) && hasId(entry.chat) && Array.isArray(entry.messages));
|
|
1004
|
+
}
|
|
1005
|
+
function isApiEvent(value) {
|
|
1006
|
+
return isRecord2(value) && typeof value.id === "string" && typeof value.type === "string" && isRecord2(value.data);
|
|
1007
|
+
}
|
|
1008
|
+
function isWebhook(value) {
|
|
1009
|
+
return isRecord2(value) && typeof value.id === "string" && typeof value.url === "string";
|
|
1010
|
+
}
|
|
1011
|
+
function isCreatedWebhook(value) {
|
|
1012
|
+
return isWebhook(value) && typeof value.secret === "string";
|
|
1013
|
+
}
|
|
1014
|
+
function isWebhookList(value) {
|
|
1015
|
+
return isRecord2(value) && Array.isArray(value.webhooks) && value.webhooks.every(isWebhook);
|
|
1016
|
+
}
|
|
1017
|
+
function isRotatedSecret(value) {
|
|
1018
|
+
return isRecord2(value) && typeof value.secret === "string";
|
|
1019
|
+
}
|
|
1020
|
+
function isTestDelivery(value) {
|
|
1021
|
+
return isRecord2(value) && typeof value.delivery_id === "string";
|
|
1022
|
+
}
|
|
1023
|
+
function isDeliveryPage(value) {
|
|
1024
|
+
return isRecord2(value) && Array.isArray(value.deliveries) && value.deliveries.every((d) => isRecord2(d) && typeof d.id === "string");
|
|
1025
|
+
}
|
|
1026
|
+
function isMediaUpload(value) {
|
|
1027
|
+
return isRecord2(value) && typeof value.id === "string" && value.id !== "";
|
|
1028
|
+
}
|
|
1029
|
+
function hasId(value) {
|
|
1030
|
+
return isRecord2(value) && typeof value.id === "string";
|
|
1031
|
+
}
|
|
1032
|
+
function isRecord2(value) {
|
|
1033
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
// src/render.ts
|
|
1037
|
+
function scopeLabel(scope) {
|
|
1038
|
+
if (scope === "full") return "full access";
|
|
1039
|
+
if (scope === "read") return "read only";
|
|
1040
|
+
return String(scope);
|
|
1041
|
+
}
|
|
1042
|
+
function accountTable(accounts) {
|
|
1043
|
+
return formatTable([
|
|
1044
|
+
["ID", "NETWORK", "STATUS", "CONNECTED", "NAME"],
|
|
1045
|
+
...accounts.map((account) => [
|
|
1046
|
+
account.id,
|
|
1047
|
+
account.network,
|
|
1048
|
+
statusLabel(account.status),
|
|
1049
|
+
formatWhen(account.connected_at),
|
|
1050
|
+
oneLine(account.display_name ?? "", 60)
|
|
1051
|
+
])
|
|
1052
|
+
]);
|
|
1053
|
+
}
|
|
1054
|
+
function statusLabel(status) {
|
|
1055
|
+
return typeof status === "string" && status !== "" ? status.replaceAll("_", " ") : "unknown";
|
|
1056
|
+
}
|
|
1057
|
+
function chatTable(chats) {
|
|
1058
|
+
return formatTable([
|
|
1059
|
+
["ID", "NETWORK", "TYPE", "UNREAD", "LAST", "NAME"],
|
|
1060
|
+
...chats.map((chat) => [
|
|
1061
|
+
chat.id,
|
|
1062
|
+
chat.network,
|
|
1063
|
+
chat.type,
|
|
1064
|
+
chat.unread_count > 0 ? String(chat.unread_count) : "",
|
|
1065
|
+
formatWhen(chat.last_message_at),
|
|
1066
|
+
chatLabel(chat)
|
|
1067
|
+
])
|
|
1068
|
+
]);
|
|
1069
|
+
}
|
|
1070
|
+
function chatLabel(chat) {
|
|
1071
|
+
const name = oneLine(chat.name ?? "", 60) || "(no name)";
|
|
1072
|
+
const flags = [
|
|
1073
|
+
chat.is_pinned ? "pinned" : "",
|
|
1074
|
+
chat.is_muted ? "muted" : "",
|
|
1075
|
+
chat.is_archived ? "archived" : "",
|
|
1076
|
+
chat.is_message_request ? "message request" : ""
|
|
1077
|
+
].filter(Boolean);
|
|
1078
|
+
return flags.length === 0 ? name : `${name} [${flags.join(", ")}]`;
|
|
1079
|
+
}
|
|
1080
|
+
function searchTable(hits) {
|
|
1081
|
+
return formatTable([
|
|
1082
|
+
["WHEN", "CHAT", "FROM", "MESSAGE"],
|
|
1083
|
+
...hits.map((hit) => [
|
|
1084
|
+
formatWhen(hit.sent_at, { time: true }),
|
|
1085
|
+
oneLine(hit.chat_name ?? "", 30) || hit.chat_id,
|
|
1086
|
+
senderLabel(hit),
|
|
1087
|
+
oneLine(messageText(hit), 100)
|
|
1088
|
+
])
|
|
1089
|
+
]);
|
|
1090
|
+
}
|
|
1091
|
+
function transcript(messages) {
|
|
1092
|
+
const rows = chronological(messages).map((message) => ({
|
|
1093
|
+
when: formatWhen(message.sent_at, { time: true }),
|
|
1094
|
+
who: senderLabel(message),
|
|
1095
|
+
lines: messageText(message).split("\n")
|
|
1096
|
+
}));
|
|
1097
|
+
const whenWidth = Math.max(0, ...rows.map((row) => row.when.length));
|
|
1098
|
+
const whoWidth = Math.max(0, ...rows.map((row) => row.who.length));
|
|
1099
|
+
const gutter = " ".repeat(whenWidth + whoWidth + 4);
|
|
1100
|
+
return rows.flatMap(
|
|
1101
|
+
({ when, who, lines }) => lines.map((line, i) => i === 0 ? `${when.padEnd(whenWidth)} ${who.padEnd(whoWidth)} ${line}` : `${gutter}${line}`)
|
|
1102
|
+
).map((line) => line.trimEnd()).join("\n");
|
|
1103
|
+
}
|
|
1104
|
+
function senderLabel(message) {
|
|
1105
|
+
if (message.sender?.is_me) return "You";
|
|
1106
|
+
return oneLine(message.sender?.name ?? "", 24) || "Unknown";
|
|
1107
|
+
}
|
|
1108
|
+
function messageText(message) {
|
|
1109
|
+
if (message.deleted) return "[deleted]";
|
|
1110
|
+
const text = terminalSafe(message.text ?? "").trim();
|
|
1111
|
+
const body = message.type === "text" ? text : [`[${message.type}]`, text || oneLine(message.media?.file_name ?? "")].filter(Boolean).join(" ");
|
|
1112
|
+
return `${body}${message.truncated ? " \u2026" : ""}${message.edited ? " (edited)" : ""}`;
|
|
1113
|
+
}
|
|
1114
|
+
function sentLine(chat, message) {
|
|
1115
|
+
const where = oneLine(chat.name ?? "", 60) || chat.id;
|
|
1116
|
+
const state = deliveryState(message.delivery);
|
|
1117
|
+
return state === void 0 ? `Sent to ${where}` : `Sent to ${where} \xB7 ${state}`;
|
|
1118
|
+
}
|
|
1119
|
+
function eventLine(event) {
|
|
1120
|
+
const when = formatWhen(event.timestamp, { time: true });
|
|
1121
|
+
const { data } = event;
|
|
1122
|
+
const chat = isRecord2(data.chat) ? data.chat : {};
|
|
1123
|
+
if (isMessage(data.message)) {
|
|
1124
|
+
const { message } = data;
|
|
1125
|
+
const network = oneLine(textOf(chat.network), 20);
|
|
1126
|
+
const name = oneLine(textOf(chat.name), 40) || message.chat_id;
|
|
1127
|
+
return `${when} [${network}] ${name} \u2014 ${senderLabel(message)}: ${oneLine(messageText(message), 200)}`;
|
|
1128
|
+
}
|
|
1129
|
+
return [when, oneLine(event.type, 40), subjectOf(data, chat)].filter(Boolean).join(" ");
|
|
1130
|
+
}
|
|
1131
|
+
function subjectOf(data, chat) {
|
|
1132
|
+
if (isRecord2(data.account)) {
|
|
1133
|
+
const { network, display_name: name, id } = data.account;
|
|
1134
|
+
return [oneLine(textOf(network), 20), oneLine(textOf(name), 60) || textOf(id)].filter(Boolean).join(" ");
|
|
1135
|
+
}
|
|
1136
|
+
const where = oneLine(textOf(chat.name), 40) || oneLine(textOf(data.chat_id), 40) || oneLine(textOf(chat.id), 40);
|
|
1137
|
+
if (isRecord2(data.reaction)) {
|
|
1138
|
+
const sender = isRecord2(data.reaction.sender) ? data.reaction.sender : {};
|
|
1139
|
+
const who = sender.is_me === true ? "You" : oneLine(textOf(sender.name), 24) || "Unknown";
|
|
1140
|
+
return `${where} \u2014 ${who}: ${oneLine(textOf(data.reaction.key), 20)}`;
|
|
1141
|
+
}
|
|
1142
|
+
if (isRecord2(data.error) && typeof data.error.message === "string") {
|
|
1143
|
+
const state = data.error.certain === true ? "failed" : "unconfirmed, it may have been delivered";
|
|
1144
|
+
return `${where}: ${state}: ${oneLine(data.error.message, 120)}`;
|
|
1145
|
+
}
|
|
1146
|
+
if (Array.isArray(data.changes) && data.changes.length > 0) {
|
|
1147
|
+
return `${where} (${oneLine(data.changes.map(String).join(", "), 60)})`;
|
|
1148
|
+
}
|
|
1149
|
+
return where;
|
|
1150
|
+
}
|
|
1151
|
+
function textOf(value) {
|
|
1152
|
+
return typeof value === "string" ? value : "";
|
|
1153
|
+
}
|
|
1154
|
+
function webhookTable(webhooks) {
|
|
1155
|
+
return formatTable([
|
|
1156
|
+
["ID", "STATUS", "EVENTS", "NETWORKS", "URL", "DESCRIPTION"],
|
|
1157
|
+
...webhooks.map((webhook) => [
|
|
1158
|
+
webhook.id,
|
|
1159
|
+
webhookStatus(webhook),
|
|
1160
|
+
listLabel(webhook.event_types, "all", 60),
|
|
1161
|
+
listLabel(webhook.networks, "all but email", 40),
|
|
1162
|
+
oneLine(webhook.url, 80),
|
|
1163
|
+
oneLine(webhook.description ?? "", 40)
|
|
1164
|
+
])
|
|
1165
|
+
]);
|
|
1166
|
+
}
|
|
1167
|
+
function createdWebhook(webhook) {
|
|
1168
|
+
return [
|
|
1169
|
+
`Created ${webhook.id} for ${oneLine(webhook.url, 200)}`,
|
|
1170
|
+
[
|
|
1171
|
+
`Events: ${listLabel(webhook.event_types, "all", 200)}`,
|
|
1172
|
+
`Networks: ${listLabel(webhook.networks, "all but email", 200)}`,
|
|
1173
|
+
`Payload: ${oneLine(String(webhook.payload), 10)}`
|
|
1174
|
+
].join(" \xB7 "),
|
|
1175
|
+
`Secret (shown once): ${oneLine(webhook.secret)}`
|
|
1176
|
+
].join("\n");
|
|
1177
|
+
}
|
|
1178
|
+
var DISABLED_BECAUSE = /* @__PURE__ */ new Map([
|
|
1179
|
+
["user", "you turned it off"],
|
|
1180
|
+
["failing", "it failed for 3 days"],
|
|
1181
|
+
["gone", "your endpoint answered 410 Gone"],
|
|
1182
|
+
["key_revoked", "the key that set it up was revoked"]
|
|
1183
|
+
]);
|
|
1184
|
+
function webhookStatus(webhook) {
|
|
1185
|
+
const reason = webhook.disabled_reason;
|
|
1186
|
+
if (webhook.status !== "disabled" || !reason) return oneLine(String(webhook.status), 20);
|
|
1187
|
+
return `disabled: ${DISABLED_BECAUSE.get(String(reason)) ?? oneLine(String(reason), 40)}`;
|
|
1188
|
+
}
|
|
1189
|
+
function listLabel(items, none, max) {
|
|
1190
|
+
return Array.isArray(items) && items.length > 0 ? oneLine(items.map(String).join(","), max) : none;
|
|
1191
|
+
}
|
|
1192
|
+
function deliveryTable(deliveries) {
|
|
1193
|
+
return formatTable([
|
|
1194
|
+
["ID", "STATUS", "EVENT", "ATTEMPTS", "RESULT", "WHEN"],
|
|
1195
|
+
...deliveries.map((delivery) => [
|
|
1196
|
+
delivery.id,
|
|
1197
|
+
oneLine(String(delivery.status), 12),
|
|
1198
|
+
oneLine(String(delivery.event_type), 40),
|
|
1199
|
+
String(delivery.attempts),
|
|
1200
|
+
delivery.last_status_code === null ? oneLine(delivery.last_error ?? "", 30) : String(delivery.last_status_code),
|
|
1201
|
+
formatWhen(delivery.last_attempt_at ?? delivery.created_at, { time: true })
|
|
1202
|
+
])
|
|
1203
|
+
]);
|
|
1204
|
+
}
|
|
1205
|
+
function keyTable(keys, inUse) {
|
|
1206
|
+
return formatTable([
|
|
1207
|
+
["ID", "SCOPE", "KEY", "MADE BY", "CREATED", "LAST USED", "NAME"],
|
|
1208
|
+
...keys.map((key) => {
|
|
1209
|
+
const mine = key.prefix === inUse.prefix && key.last4 === inUse.last4;
|
|
1210
|
+
return [
|
|
1211
|
+
key.id,
|
|
1212
|
+
scopeLabel(key.scope),
|
|
1213
|
+
`${oneLine(String(key.prefix), 12)}\u2026${oneLine(String(key.last4), 4)}`,
|
|
1214
|
+
oneLine(String(key.created_via), 20),
|
|
1215
|
+
formatWhen(key.created_at),
|
|
1216
|
+
formatWhen(key.last_used_at) || "never",
|
|
1217
|
+
`${oneLine(String(key.name), 60)}${mine ? " (this CLI)" : ""}`
|
|
1218
|
+
];
|
|
1219
|
+
})
|
|
1220
|
+
]);
|
|
1221
|
+
}
|
|
1222
|
+
var BILLING_URL = "https://web.chesly.app/api/billing";
|
|
1223
|
+
var PLAN_NAMES = /* @__PURE__ */ new Map([
|
|
1224
|
+
["personal", "Personal"],
|
|
1225
|
+
["pro", "Pro"]
|
|
1226
|
+
]);
|
|
1227
|
+
var NO_PERIOD = /* @__PURE__ */ new Set(["none", "canceled", "unpaid"]);
|
|
1228
|
+
function usageSummary(me) {
|
|
1229
|
+
const lines = [];
|
|
1230
|
+
const plan = isRecord2(me.plan) ? me.plan : void 0;
|
|
1231
|
+
if (plan !== void 0) lines.push(planLine(plan));
|
|
1232
|
+
if (plan !== void 0 && !NO_PERIOD.has(String(plan.status))) {
|
|
1233
|
+
lines.push(`Calls this period: ${count(plan.calls_this_period)} (counted, not billed)`);
|
|
1234
|
+
lines.push(`Transcription this period: ${transcriptionMinutes(plan)}`);
|
|
1235
|
+
} else if (isRecord2(me.usage) && typeof me.usage.calls === "number") {
|
|
1236
|
+
lines.push(`Calls this month: ${count(me.usage.calls)} (counted, not billed)`);
|
|
1237
|
+
}
|
|
1238
|
+
const limits = limitsLine(me.limits);
|
|
1239
|
+
if (limits !== "") lines.push(`Limits: ${limits}`);
|
|
1240
|
+
const sends = Array.isArray(me.limits?.sends) ? me.limits.sends.filter(isSendLimit) : [];
|
|
1241
|
+
if (sends.length > 0) lines.push("Sends:", ...sends.map((limit) => ` ${sendLimitLine(limit, sends)}`));
|
|
1242
|
+
return lines.join("\n");
|
|
1243
|
+
}
|
|
1244
|
+
function limitsLine(limits) {
|
|
1245
|
+
if (!isRecord2(limits)) return "";
|
|
1246
|
+
const perSecond = limitOf(limits.requests_per_second);
|
|
1247
|
+
const perMinute = limitOf(limits.requests_per_minute);
|
|
1248
|
+
const keys = limitOf(limits.api_keys);
|
|
1249
|
+
const webhooks = limitOf(limits.webhooks);
|
|
1250
|
+
const streams = limitOf(limits.event_streams);
|
|
1251
|
+
const history = limitOf(limits.event_retention_days);
|
|
1252
|
+
const parts = [];
|
|
1253
|
+
if (perSecond !== void 0) {
|
|
1254
|
+
parts.push(`${amount(perSecond, "request", "requests")} a second${perMinute === void 0 ? "" : `, ${count(perMinute)} a minute`}`);
|
|
1255
|
+
} else if (perMinute !== void 0) {
|
|
1256
|
+
parts.push(`${amount(perMinute, "request", "requests")} a minute`);
|
|
1257
|
+
}
|
|
1258
|
+
if (keys !== void 0) parts.push(amount(keys, "API key", "API keys"));
|
|
1259
|
+
if (webhooks !== void 0) parts.push(amount(webhooks, "webhook", "webhooks"));
|
|
1260
|
+
if (streams !== void 0) parts.push(amount(streams, "event stream", "event streams"));
|
|
1261
|
+
if (history !== void 0) parts.push(`${amount(history, "day", "days")} of event history`);
|
|
1262
|
+
return parts.join(" \xB7 ");
|
|
1263
|
+
}
|
|
1264
|
+
function planLine(plan) {
|
|
1265
|
+
const status = oneLine(String(plan.status), 20).replaceAll("_", " ");
|
|
1266
|
+
if (plan.status === "none" || plan.status === "canceled") return `Plan: ${status}. Start one at ${BILLING_URL}`;
|
|
1267
|
+
const name = planName(plan.plan);
|
|
1268
|
+
const named = name === void 0 ? `Plan: ${status}` : `Plan: ${name}, ${status}`;
|
|
1269
|
+
if (plan.status === "unpaid") return `${named}, so calls are refused. Pay it or update the card at ${BILLING_URL}`;
|
|
1270
|
+
const ends = formatWhen(plan.cancel_at);
|
|
1271
|
+
if (ends !== "") return `${named}, canceled: it ends ${ends}`;
|
|
1272
|
+
if (plan.status === "past_due") return `${named}: the last payment failed. Update the card at ${BILLING_URL}`;
|
|
1273
|
+
const change = scheduledChange(plan.scheduled_change);
|
|
1274
|
+
const trialEnds = plan.status === "trialing" ? formatWhen(plan.trial_ends_at) : "";
|
|
1275
|
+
if (trialEnds !== "") return `${named}: the trial ends ${trialEnds}${change === "" ? "" : `; ${change}`}`;
|
|
1276
|
+
if (change !== "") return `${named}: ${change}`;
|
|
1277
|
+
const renews = plan.status === "active" ? formatWhen(plan.period_end) : "";
|
|
1278
|
+
return renews === "" ? named : `${named}: it renews ${renews}`;
|
|
1279
|
+
}
|
|
1280
|
+
function planName(plan) {
|
|
1281
|
+
return typeof plan === "string" ? PLAN_NAMES.get(plan) ?? oneLine(plan, 20) : void 0;
|
|
1282
|
+
}
|
|
1283
|
+
function scheduledChange(change) {
|
|
1284
|
+
if (!isRecord2(change)) return "";
|
|
1285
|
+
const name = planName(change.plan);
|
|
1286
|
+
const when = typeof change.at === "string" ? formatWhen(change.at) : "";
|
|
1287
|
+
if (name === void 0 || when === "") return "";
|
|
1288
|
+
return `changes to ${name} ${when.includes(":") ? "at" : "on"} ${when}`;
|
|
1289
|
+
}
|
|
1290
|
+
function transcriptionMinutes(plan) {
|
|
1291
|
+
const usedSeconds = Number(plan.transcription_seconds_this_period) || 0;
|
|
1292
|
+
const used = count(Math.floor(usedSeconds / 60));
|
|
1293
|
+
const included = Number(plan.transcription_seconds_included);
|
|
1294
|
+
if (!(included > 0)) return `${used} min`;
|
|
1295
|
+
const minutes = `${used} of ${count(Math.floor(included / 60))} min`;
|
|
1296
|
+
if (usedSeconds < included) return minutes;
|
|
1297
|
+
const back = formatWhen(plan.period_end);
|
|
1298
|
+
return back === "" ? `${minutes}, used up` : `${minutes}, used up until ${back}`;
|
|
1299
|
+
}
|
|
1300
|
+
function sendLimitLine(limit, all) {
|
|
1301
|
+
const shared = all.filter((other) => other.network === limit.network).length > 1;
|
|
1302
|
+
const network = oneLine(limit.network, 20);
|
|
1303
|
+
const label = shared && limit.account_id ? `${network} (${oneLine(limit.account_id, 40)})` : network;
|
|
1304
|
+
return `${label} \xB7 ${limit.used_last_hour}/${limit.per_hour} this hour \xB7 ${limit.used_last_day}/${limit.per_day} today`;
|
|
1305
|
+
}
|
|
1306
|
+
function count(value) {
|
|
1307
|
+
return Number(value ?? 0).toLocaleString("en-US");
|
|
1308
|
+
}
|
|
1309
|
+
function limitOf(value) {
|
|
1310
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
|
|
1311
|
+
}
|
|
1312
|
+
function amount(value, one, many) {
|
|
1313
|
+
return `${count(value)} ${value === 1 ? one : many}`;
|
|
1314
|
+
}
|
|
1315
|
+
function chronological(messages) {
|
|
1316
|
+
return messages.toReversed().sort((a, b) => sentAt(a) - sentAt(b));
|
|
1317
|
+
}
|
|
1318
|
+
function sentAt(message) {
|
|
1319
|
+
return Date.parse(message.sent_at) || 0;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// src/commands/accounts.ts
|
|
1323
|
+
function registerAccounts(program, io) {
|
|
1324
|
+
program.command("accounts").description("List your connected chat accounts and their status").addHelpText(
|
|
1325
|
+
"after",
|
|
1326
|
+
`
|
|
1327
|
+
Prints the API's { "accounts": [...] }, or a table in a terminal: each
|
|
1328
|
+
account's ID (acct_\u2026, what --account takes), network, status (connected,
|
|
1329
|
+
disconnected or needs attention), when it connected, and its name.
|
|
1330
|
+
|
|
1331
|
+
Example:
|
|
1332
|
+
chesly accounts --json`
|
|
1333
|
+
).action(async (_options, command) => {
|
|
1334
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
1335
|
+
const { key } = await requireKey();
|
|
1336
|
+
const result = expectAnswer(await apiRequest("/v1/accounts", { key }), isAccountList, "a list of accounts");
|
|
1337
|
+
out.result(
|
|
1338
|
+
result,
|
|
1339
|
+
() => result.accounts.length === 0 ? "No accounts connected. Connect one in the Chesly app." : accountTable(result.accounts)
|
|
1340
|
+
);
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
// src/options.ts
|
|
1345
|
+
import { InvalidArgumentError } from "commander";
|
|
1346
|
+
var MAX_LIMIT = 100;
|
|
1347
|
+
function parseLimit(value) {
|
|
1348
|
+
const limit = wholeNumber(value);
|
|
1349
|
+
if (limit === void 0 || limit > MAX_LIMIT) {
|
|
1350
|
+
throw new InvalidArgumentError(`Use a whole number from 1 to ${MAX_LIMIT}.`);
|
|
1351
|
+
}
|
|
1352
|
+
return limit;
|
|
1353
|
+
}
|
|
1354
|
+
function upTo(max) {
|
|
1355
|
+
return (value) => {
|
|
1356
|
+
const count2 = wholeNumber(value);
|
|
1357
|
+
if (count2 === void 0 || count2 > max) throw new InvalidArgumentError(`Use a whole number from 1 to ${max}.`);
|
|
1358
|
+
return count2;
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
function parseNetwork(value) {
|
|
1362
|
+
const network = value.trim().toLowerCase();
|
|
1363
|
+
if (!/^[a-z][a-z0-9_-]{0,31}$/.test(network)) {
|
|
1364
|
+
throw new InvalidArgumentError("Use a network name such as email, whatsapp or telegram.");
|
|
1365
|
+
}
|
|
1366
|
+
return network;
|
|
1367
|
+
}
|
|
1368
|
+
function parseList(value) {
|
|
1369
|
+
const items = [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))];
|
|
1370
|
+
if (items.length === 0) throw new InvalidArgumentError("Give one or more names, separated by commas.");
|
|
1371
|
+
return items;
|
|
1372
|
+
}
|
|
1373
|
+
var IDEMPOTENCY_KEY = /^[A-Za-z0-9._:-]{1,255}$/;
|
|
1374
|
+
function parseIdempotencyKey(value) {
|
|
1375
|
+
if (!IDEMPOTENCY_KEY.test(value)) {
|
|
1376
|
+
throw new InvalidArgumentError('Use 1 to 255 letters, digits, ".", "_", ":" or "-".');
|
|
1377
|
+
}
|
|
1378
|
+
return value;
|
|
1379
|
+
}
|
|
1380
|
+
function wholeNumber(value) {
|
|
1381
|
+
if (!/^[1-9]\d*$/.test(value)) return void 0;
|
|
1382
|
+
const number = Number(value);
|
|
1383
|
+
return Number.isSafeInteger(number) ? number : void 0;
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
// src/commands/catchup.ts
|
|
1387
|
+
function registerCatchup(program, io) {
|
|
1388
|
+
program.command("catchup").description("Unread chats with their latest messages, in one call").option("--chats <n>", "how many chats, 1 to 50 (default 20)", upTo(50)).option("--per-chat <n>", "how many messages from each chat, 1 to 20 (default 5)", upTo(20)).option("--network <name>", "only this network: email, whatsapp, telegram\u2026 (email only when named)", parseNetwork).addHelpText(
|
|
1389
|
+
"after",
|
|
1390
|
+
`
|
|
1391
|
+
Muted and archived chats are left out. When the answer would be too long,
|
|
1392
|
+
messages are left out and "truncated" is true; chesly read shows a whole chat.
|
|
1393
|
+
|
|
1394
|
+
Prints the API's { "chats": [{ "chat", "messages" }], "truncated" }, or a
|
|
1395
|
+
digest in a terminal: each chat's name, network, unread count and ID, then
|
|
1396
|
+
its latest messages, oldest first.
|
|
1397
|
+
|
|
1398
|
+
Examples:
|
|
1399
|
+
chesly catchup --json
|
|
1400
|
+
chesly catchup --network email --chats 10 --per-chat 3`
|
|
1401
|
+
).action(async (options, command) => {
|
|
1402
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
1403
|
+
const { key } = await requireKey();
|
|
1404
|
+
const answer = await apiRequest("/v1/catch_up", {
|
|
1405
|
+
key,
|
|
1406
|
+
query: { chats: options.chats, per_chat: options.perChat, network: options.network }
|
|
1407
|
+
});
|
|
1408
|
+
const result = expectAnswer(answer, isCatchUp, "a catch-up");
|
|
1409
|
+
out.result(result, () => digest(result));
|
|
1410
|
+
if (!out.json && result.truncated) {
|
|
1411
|
+
out.note("Some messages were left out to keep this short. `chesly read <chat>` shows a whole chat.");
|
|
1412
|
+
}
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
function digest(result) {
|
|
1416
|
+
if (result.chats.length === 0) return "You're all caught up.";
|
|
1417
|
+
return result.chats.map(({ chat, messages }) => {
|
|
1418
|
+
const heading = [oneLine(chat.name ?? "", 60) || "(no name)", chat.network, `${chat.unread_count} unread`, chat.id].join(" \xB7 ");
|
|
1419
|
+
return messages.length === 0 ? heading : `${heading}
|
|
1420
|
+
${indent(transcript(messages), " ")}`;
|
|
1421
|
+
}).join("\n\n");
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
// src/commands/chats.ts
|
|
1425
|
+
function registerChats(program, io) {
|
|
1426
|
+
program.command("chats").description("List your chats: pinned chats first, then the most recent").option("--unread", "only chats with unread messages").option("--account <id>", "only chats on this account: an acct_ ID from `chesly accounts`").option("--network <name>", "only this network: email, whatsapp, telegram\u2026 (email only when named)", parseNetwork).option("--limit <n>", "how many chats, 1 to 100 (default 50)", parseLimit).option("--cursor <cursor>", "the next page: next_cursor from the page before").addHelpText(
|
|
1427
|
+
"after",
|
|
1428
|
+
`
|
|
1429
|
+
Archived chats are left out, as is email unless --network email asks for it.
|
|
1430
|
+
A name lookup (chesly read, chesly send) still finds an archived chat.
|
|
1431
|
+
|
|
1432
|
+
Prints the API's page, { "chats": [...], "next_cursor" }, or a table in a
|
|
1433
|
+
terminal, with the command for the next page while there is one.
|
|
1434
|
+
|
|
1435
|
+
Examples:
|
|
1436
|
+
chesly chats --unread
|
|
1437
|
+
chesly chats --network email --limit 20`
|
|
1438
|
+
).action(async (options, command) => {
|
|
1439
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
1440
|
+
const { key } = await requireKey();
|
|
1441
|
+
const answer = await apiRequest("/v1/chats", {
|
|
1442
|
+
key,
|
|
1443
|
+
query: {
|
|
1444
|
+
account_id: options.account,
|
|
1445
|
+
network: options.network,
|
|
1446
|
+
unread: options.unread ? true : void 0,
|
|
1447
|
+
limit: options.limit,
|
|
1448
|
+
cursor: options.cursor
|
|
1449
|
+
}
|
|
1450
|
+
});
|
|
1451
|
+
const page = expectAnswer(answer, isChatPage, "a page of chats");
|
|
1452
|
+
out.result(page, () => {
|
|
1453
|
+
if (page.chats.length > 0) return chatTable(page.chats);
|
|
1454
|
+
return options.unread ? "No unread chats." : "No chats.";
|
|
1455
|
+
});
|
|
1456
|
+
if (!out.json && page.next_cursor) {
|
|
1457
|
+
const flags = [
|
|
1458
|
+
options.unread ? "--unread" : "",
|
|
1459
|
+
options.account ? `--account ${shellQuote(options.account)}` : "",
|
|
1460
|
+
options.network ? `--network ${options.network}` : "",
|
|
1461
|
+
options.limit ? `--limit ${options.limit}` : "",
|
|
1462
|
+
`--cursor ${shellQuote(oneLine(page.next_cursor))}`
|
|
1463
|
+
];
|
|
1464
|
+
out.note(`More chats: chesly chats ${flags.filter(Boolean).join(" ")}`);
|
|
1465
|
+
}
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
// src/commands/key.ts
|
|
1470
|
+
function registerKey(program, io) {
|
|
1471
|
+
program.command("key").description("Show the API key in use, masked; --reveal prints the whole key, for MCP clients").option("--reveal", "print the whole key and nothing else (as JSON only with an explicit --json)").addHelpText(
|
|
1472
|
+
"after",
|
|
1473
|
+
`
|
|
1474
|
+
Example: add the Chesly MCP server to Claude Code
|
|
1475
|
+
claude mcp add --transport http chesly https://api.chesly.app/mcp \\
|
|
1476
|
+
--header "Authorization: Bearer $(chesly key --reveal)"`
|
|
1477
|
+
).action(async (options, command) => {
|
|
1478
|
+
const globals = command.optsWithGlobals();
|
|
1479
|
+
const { key, source } = await requireKey();
|
|
1480
|
+
if (options.reveal && globals.json !== true) {
|
|
1481
|
+
io.out(`${key}
|
|
1482
|
+
`);
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
const out = new Output(io, globals);
|
|
1486
|
+
const data = options.reveal ? { key, source } : { ...keyHint(key), source };
|
|
1487
|
+
out.result(data, () => `${maskKey(key)} (from ${describeSource(source)})`);
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
// src/commands/keys.ts
|
|
1492
|
+
var REVOKE_TIMEOUT_MS = 1e4;
|
|
1493
|
+
async function revokeKey(key, fallback) {
|
|
1494
|
+
const { prefix, last4 } = keyHint(key);
|
|
1495
|
+
let id;
|
|
1496
|
+
try {
|
|
1497
|
+
const me = await apiRequest("/v1/me", { key, timeoutMs: REVOKE_TIMEOUT_MS });
|
|
1498
|
+
if (!isMe(me)) return { id: null, prefix, last4, outcome: "active" };
|
|
1499
|
+
id = me.key.id;
|
|
1500
|
+
} catch (error) {
|
|
1501
|
+
const refused = error instanceof CheslyApiError && error.status === 401;
|
|
1502
|
+
return { id: null, prefix, last4, outcome: refused ? "gone" : "active" };
|
|
1503
|
+
}
|
|
1504
|
+
let outcome = await deleteKey(id, key, true);
|
|
1505
|
+
if (outcome === "forbidden" && fallback !== void 0) outcome = await deleteKey(id, fallback, false);
|
|
1506
|
+
return { id, prefix, last4, outcome: outcome === "forbidden" ? "active" : outcome };
|
|
1507
|
+
}
|
|
1508
|
+
async function deleteKey(id, using, self) {
|
|
1509
|
+
try {
|
|
1510
|
+
await apiRequest(`/v1/keys/${encodeURIComponent(id)}`, { method: "DELETE", key: using, timeoutMs: REVOKE_TIMEOUT_MS });
|
|
1511
|
+
return "revoked";
|
|
1512
|
+
} catch (error) {
|
|
1513
|
+
if (!(error instanceof CheslyApiError)) return "active";
|
|
1514
|
+
if (error.status === 403) return "forbidden";
|
|
1515
|
+
if (self && (error.status === 401 || error.status === 404 && error.code === "key_not_found")) return "gone";
|
|
1516
|
+
return "active";
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
async function checkKey(key) {
|
|
1520
|
+
const { prefix, last4 } = keyHint(key);
|
|
1521
|
+
try {
|
|
1522
|
+
const me = await apiRequest("/v1/me", { key, timeoutMs: REVOKE_TIMEOUT_MS });
|
|
1523
|
+
return { id: isMe(me) ? me.key.id : null, prefix, last4, outcome: "active" };
|
|
1524
|
+
} catch (error) {
|
|
1525
|
+
const refused = error instanceof CheslyApiError && error.status === 401;
|
|
1526
|
+
return { id: null, prefix, last4, outcome: refused ? "gone" : "active" };
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
function stillActiveMessage(revocation, which = "This key") {
|
|
1530
|
+
const id = revocation.id === null ? "" : `, id ${revocation.id}`;
|
|
1531
|
+
return `${which} (${revocation.prefix}\u2026${revocation.last4}${id}) is still active; revoke it in the dashboard at web.chesly.app/api/keys.`;
|
|
1532
|
+
}
|
|
1533
|
+
function registerKeys(program, io) {
|
|
1534
|
+
const keys = program.command("keys").description("List your API keys, or revoke one").addHelpText(
|
|
1535
|
+
"after",
|
|
1536
|
+
`
|
|
1537
|
+
There is no keys create. New keys come from chesly login, or from the dashboard at
|
|
1538
|
+
https://web.chesly.app/api/keys. chesly key shows the key this CLI uses.
|
|
1539
|
+
|
|
1540
|
+
Examples:
|
|
1541
|
+
chesly keys list
|
|
1542
|
+
chesly keys revoke 0b5c9a52-6f1e-4c41-9a43-2b7f0d0e1a07`
|
|
1543
|
+
);
|
|
1544
|
+
keys.command("list").description("List your active API keys, marking the one this CLI uses").addHelpText(
|
|
1545
|
+
"after",
|
|
1546
|
+
`
|
|
1547
|
+
Prints the API's { "keys": [...] }, or a table in a terminal. A key shows only
|
|
1548
|
+
its first 12 and last 4 characters, never the whole key.
|
|
1549
|
+
|
|
1550
|
+
Example:
|
|
1551
|
+
chesly keys list --json`
|
|
1552
|
+
).action(async (_options, command) => {
|
|
1553
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
1554
|
+
const { key } = await requireKey();
|
|
1555
|
+
const answer = expectAnswer(await apiRequest("/v1/keys", { key }), isKeyList, "a list of API keys");
|
|
1556
|
+
out.result(answer, () => answer.keys.length === 0 ? "No API keys." : keyTable(answer.keys, keyHint(key)));
|
|
1557
|
+
});
|
|
1558
|
+
keys.command("revoke").description("Revoke an API key; its next request is refused").argument("<key_id>", "the key: an ID from chesly keys list").addHelpText(
|
|
1559
|
+
"after",
|
|
1560
|
+
`
|
|
1561
|
+
Prints { "id", "revoked": true, "in_use" }, or a sentence in a terminal.
|
|
1562
|
+
"in_use" says it was the key this CLI uses, which then needs chesly login.
|
|
1563
|
+
An unknown ID exits 4; a read-only key can't revoke.
|
|
1564
|
+
|
|
1565
|
+
Example:
|
|
1566
|
+
chesly keys revoke 0b5c9a52-6f1e-4c41-9a43-2b7f0d0e1a07`
|
|
1567
|
+
).action(async (keyId, _options, command) => {
|
|
1568
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
1569
|
+
const { key, source } = await requireKey();
|
|
1570
|
+
const id = keyId.trim();
|
|
1571
|
+
const me = expectAnswer(await apiRequest("/v1/me", { key }), isMe, "the details of this key");
|
|
1572
|
+
await apiRequest(`/v1/keys/${encodeURIComponent(id)}`, { method: "DELETE", key });
|
|
1573
|
+
const inUse = me.key.id === id;
|
|
1574
|
+
out.result({ id, revoked: true, in_use: inUse }, () => {
|
|
1575
|
+
if (!inUse) return `Revoked ${id}.`;
|
|
1576
|
+
if (source === "env") {
|
|
1577
|
+
return `Revoked ${id}. This was the key this CLI uses, from CHESLY_API_KEY: put another key there, or unset it and run chesly login.`;
|
|
1578
|
+
}
|
|
1579
|
+
return `Revoked ${id}. This was the key this CLI uses; run chesly login.`;
|
|
1580
|
+
});
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
// src/commands/login.ts
|
|
1585
|
+
import { spawn as spawn2 } from "child_process";
|
|
1586
|
+
import { hostname } from "os";
|
|
1587
|
+
function registerLogin(program, io) {
|
|
1588
|
+
program.command("login").description("Sign in: approve this computer on web.chesly.app, or store a key with --key").option("--key <key>", "check an API key with the API, then store it (no browser); - reads it from stdin").option("--no-browser", "print the link only, without opening a browser").option("--force", "sign in with a new key even when the stored one works (which is then revoked)").option("--wait", "finish the sign-in --no-wait started: wait for the approval, then store the key").option("--no-wait", "start a sign-in, print its link and code, and exit at once").addHelpText(
|
|
1589
|
+
"after",
|
|
1590
|
+
`
|
|
1591
|
+
When the key it stored still works, chesly login says "Already signed in"
|
|
1592
|
+
and stops: each sign-in makes a key, and an account has 25 at most. --force
|
|
1593
|
+
signs in anyway, and revokes the stored keys the new one replaces (any other
|
|
1594
|
+
replaced key that still works is named in a key_still_active warning);
|
|
1595
|
+
chesly logout revokes the stored key.
|
|
1596
|
+
|
|
1597
|
+
Without --key, chesly login prints a link and a code, opens your browser
|
|
1598
|
+
(wherever there is one to show: not over SSH, not in CI, not with
|
|
1599
|
+
--no-browser), and waits until you approve the code on web.chesly.app.
|
|
1600
|
+
It never reads input. In JSON mode the link and the code are one line on
|
|
1601
|
+
stderr, and the result is one object on stdout:
|
|
1602
|
+
{"verification_uri_complete":"\u2026","user_code":"ABCD-EFGH","expires_in":600}
|
|
1603
|
+
{"status":"signed_in","stored_in":"keychain","key":{\u2026}}
|
|
1604
|
+
|
|
1605
|
+
Agents: a tool that shows a command's output only once it ends can sign in in
|
|
1606
|
+
two steps. chesly login --no-wait prints the link and the code and exits:
|
|
1607
|
+
{"status":"pending","verification_uri_complete":"\u2026","user_code":"\u2026","expires_in":600}
|
|
1608
|
+
Show them to your person, then run chesly login --wait, which waits for the
|
|
1609
|
+
approval and stores the key. A --wait cut short can run again until the code
|
|
1610
|
+
expires. A tool that streams output can instead run chesly login in the
|
|
1611
|
+
background and relay the first line of stderr.
|
|
1612
|
+
|
|
1613
|
+
The key goes to the OS keychain, or to ~/.config/chesly/credentials.json
|
|
1614
|
+
(mode 0600) where there is no keychain. CHESLY_API_KEY, when set, wins over it.
|
|
1615
|
+
A keychain that refuses or doesn't answer stops plain login and --no-wait
|
|
1616
|
+
with keychain_error or keychain_timeout (it may hold a working key), unless a
|
|
1617
|
+
key in the credentials file works; --key and --force store the key in the
|
|
1618
|
+
credentials file instead, as --wait does.
|
|
1619
|
+
|
|
1620
|
+
Pass a key through stdin (--key -), never as an argument: an argument shows
|
|
1621
|
+
in the process list and the shell history. In CI, set CHESLY_API_KEY instead.
|
|
1622
|
+
|
|
1623
|
+
Examples:
|
|
1624
|
+
chesly login
|
|
1625
|
+
chesly login --no-wait then, once you have shown the link: chesly login --wait
|
|
1626
|
+
chesly login --key - < chesly-key.txt`
|
|
1627
|
+
).action(async (options, command) => {
|
|
1628
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
1629
|
+
if (options.key !== void 0) {
|
|
1630
|
+
if (options.wait !== void 0) {
|
|
1631
|
+
throw new CliError("usage_error", "--key stores a key at once: leave out --wait and --no-wait.", EXIT.USAGE);
|
|
1632
|
+
}
|
|
1633
|
+
await loginWithKey(out, (await keyArgument(options.key, io)).trim());
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
if (options.wait === true) {
|
|
1637
|
+
await finishPendingSignIn(out);
|
|
1638
|
+
return;
|
|
1639
|
+
}
|
|
1640
|
+
const stored = await storedKeys();
|
|
1641
|
+
const force = options.force === true;
|
|
1642
|
+
if (!force && await alreadySignedIn(out, stored)) return;
|
|
1643
|
+
const signIn = await startSignIn();
|
|
1644
|
+
const seen = stored.keys.map(({ key: key2 }) => keyHint(key2));
|
|
1645
|
+
if (options.wait === false) {
|
|
1646
|
+
await savePendingLogin({ ...signIn, replaces: seen, force });
|
|
1647
|
+
const opened2 = options.browser !== false && openBrowser(signIn.link);
|
|
1648
|
+
showPending(out, signIn, opened2);
|
|
1649
|
+
return;
|
|
1650
|
+
}
|
|
1651
|
+
showLink(out, signIn);
|
|
1652
|
+
const opened = options.browser !== false && openBrowser(signIn.link);
|
|
1653
|
+
out.note(`${opened ? "Opened your browser. " : ""}Waiting for approval\u2026 (Ctrl+C to cancel)`);
|
|
1654
|
+
const key = await pollForKey(signIn);
|
|
1655
|
+
await keepKey(out, key);
|
|
1656
|
+
await retireReplacedKeys(out, stored.keys, key, mayReplace(seen, force));
|
|
1657
|
+
});
|
|
1658
|
+
}
|
|
1659
|
+
async function keyArgument(value, io) {
|
|
1660
|
+
if (value !== "-") return value;
|
|
1661
|
+
if (io.stdin.isTTY) {
|
|
1662
|
+
throw new CliError(
|
|
1663
|
+
"usage_error",
|
|
1664
|
+
"--key - reads the key from stdin, and stdin is a terminal. Pipe the key in, or set CHESLY_API_KEY.",
|
|
1665
|
+
EXIT.USAGE
|
|
1666
|
+
);
|
|
1667
|
+
}
|
|
1668
|
+
return io.stdin.read();
|
|
1669
|
+
}
|
|
1670
|
+
async function loginWithKey(out, key) {
|
|
1671
|
+
if (!isApiKey(key)) {
|
|
1672
|
+
throw new CliError(
|
|
1673
|
+
"invalid_key_format",
|
|
1674
|
+
"That is not a Chesly API key: ck_live_ and 48 letters, digits, _ or -.",
|
|
1675
|
+
EXIT.USAGE
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1678
|
+
const me = await apiRequest("/v1/me", { key });
|
|
1679
|
+
if (!isMe(me)) throw badAnswer("The API sent no details for this key. Nothing was stored.");
|
|
1680
|
+
signedIn(out, await storeKey(key), me);
|
|
1681
|
+
}
|
|
1682
|
+
async function alreadySignedIn(out, { keys, keychainFailure: keychainFailure2 }) {
|
|
1683
|
+
const [stored] = keys;
|
|
1684
|
+
const me = stored === void 0 ? void 0 : await detailsOf(stored.key);
|
|
1685
|
+
if (stored === void 0 || me === void 0) {
|
|
1686
|
+
if (keychainFailure2 !== void 0) throw keychainFailure2;
|
|
1687
|
+
return false;
|
|
1688
|
+
}
|
|
1689
|
+
out.result(
|
|
1690
|
+
{ status: "already_signed_in", stored_in: stored.source, key: me.key },
|
|
1691
|
+
() => [
|
|
1692
|
+
`Already signed in as "${oneLine(me.key.name ?? "", 100)}" (${scopeLabel(me.key.scope)}), with the key in ${describeSource(stored.source)}.`,
|
|
1693
|
+
"chesly login --force signs in with a new key; chesly logout revokes this one."
|
|
1694
|
+
].join("\n")
|
|
1695
|
+
);
|
|
1696
|
+
return true;
|
|
1697
|
+
}
|
|
1698
|
+
async function detailsOf(key) {
|
|
1699
|
+
try {
|
|
1700
|
+
const me = await apiRequest("/v1/me", { key });
|
|
1701
|
+
return isMe(me) ? me : void 0;
|
|
1702
|
+
} catch (error) {
|
|
1703
|
+
if (error instanceof CheslyApiError && error.status === 401) return void 0;
|
|
1704
|
+
throw error;
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
async function finishPendingSignIn(out) {
|
|
1708
|
+
const pending = await readPendingLogin();
|
|
1709
|
+
if (pending === null) {
|
|
1710
|
+
throw new CliError("login_not_started", "No sign-in is waiting to finish. Start one with `chesly login --no-wait`.");
|
|
1711
|
+
}
|
|
1712
|
+
out.note(`Waiting for approval of the code ${terminalSafe(pending.userCode)}\u2026 (Ctrl+C to stop; --wait picks it up again)`);
|
|
1713
|
+
let key;
|
|
1714
|
+
try {
|
|
1715
|
+
key = await pollForKey(pending);
|
|
1716
|
+
} finally {
|
|
1717
|
+
await deletePendingLogin();
|
|
1718
|
+
}
|
|
1719
|
+
const before = (await storedKeys()).keys;
|
|
1720
|
+
await keepKey(out, key);
|
|
1721
|
+
await retireReplacedKeys(out, before, key, mayReplace(pending.replaces, pending.force));
|
|
1722
|
+
}
|
|
1723
|
+
function mayReplace(seen, force) {
|
|
1724
|
+
return force ? seen : seen.slice(0, 1);
|
|
1725
|
+
}
|
|
1726
|
+
async function retireReplacedKeys(out, before, key, allowed) {
|
|
1727
|
+
const after = await storedKeys();
|
|
1728
|
+
const kept = new Set(after.keys.map((stored) => stored.key));
|
|
1729
|
+
for (const old of before) {
|
|
1730
|
+
if (old.key === key) continue;
|
|
1731
|
+
const letGo = !kept.has(old.key) && !(old.source === "keychain" && after.keychainFailure !== void 0);
|
|
1732
|
+
const hint = keyHint(old.key);
|
|
1733
|
+
const mayRevoke = letGo && allowed.some((pair) => pair.prefix === hint.prefix && pair.last4 === hint.last4);
|
|
1734
|
+
const result = mayRevoke ? await revokeKey(old.key, key) : await checkKey(old.key);
|
|
1735
|
+
if (result.outcome === "revoked") {
|
|
1736
|
+
out.note(`Revoked the key this one replaced${result.id === null ? "" : ` (id ${result.id})`}.`);
|
|
1737
|
+
} else if (result.outcome === "active") {
|
|
1738
|
+
const { id, prefix, last4 } = result;
|
|
1739
|
+
out.warn("key_still_active", stillActiveMessage(result, "The key this replaced"), { id, prefix, last4 });
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
async function keepKey(out, key) {
|
|
1744
|
+
let me;
|
|
1745
|
+
try {
|
|
1746
|
+
me = await apiRequest("/v1/me", { key });
|
|
1747
|
+
} catch (error) {
|
|
1748
|
+
if (!checkCouldNotRun(error)) throw error;
|
|
1749
|
+
signedIn(out, await storeKey(key), null);
|
|
1750
|
+
out.warn("key_details_unavailable", `The key's details didn't load (${error.message}). chesly whoami shows them.`);
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
const store = await storeKey(key);
|
|
1754
|
+
if (!isMe(me)) {
|
|
1755
|
+
const saved = `It is saved in ${describeSource(store)}: run \`chesly whoami\` to check it.`;
|
|
1756
|
+
throw badAnswer(`The API sent no details for the new key. ${saved}`);
|
|
1757
|
+
}
|
|
1758
|
+
signedIn(out, store, me);
|
|
1759
|
+
}
|
|
1760
|
+
function checkCouldNotRun(error) {
|
|
1761
|
+
if (error instanceof CheslyNetworkError) return true;
|
|
1762
|
+
return error instanceof CheslyApiError && (error.status >= 500 || error.status === 429);
|
|
1763
|
+
}
|
|
1764
|
+
var MAX_BACKOFF_SECONDS = 30;
|
|
1765
|
+
async function startSignIn() {
|
|
1766
|
+
const answer = await apiRequest("/v1/cli/sessions", { method: "POST", body: { client_name: hostname() } });
|
|
1767
|
+
return checkSession(answer);
|
|
1768
|
+
}
|
|
1769
|
+
function expiresIn(signIn) {
|
|
1770
|
+
return Math.max(0, Math.round((signIn.expiresAt - Date.now()) / 1e3));
|
|
1771
|
+
}
|
|
1772
|
+
function showLink(out, signIn) {
|
|
1773
|
+
out.notice(
|
|
1774
|
+
{ verification_uri_complete: signIn.link, user_code: signIn.userCode, expires_in: expiresIn(signIn) },
|
|
1775
|
+
() => `To sign in, open this link:
|
|
1776
|
+
|
|
1777
|
+
${terminalSafe(signIn.link)}
|
|
1778
|
+
|
|
1779
|
+
Approve it if the page shows the code ${terminalSafe(signIn.userCode)}.`
|
|
1780
|
+
);
|
|
1781
|
+
}
|
|
1782
|
+
function showPending(out, signIn, opened) {
|
|
1783
|
+
out.result(
|
|
1784
|
+
{
|
|
1785
|
+
status: "pending",
|
|
1786
|
+
verification_uri_complete: signIn.link,
|
|
1787
|
+
user_code: signIn.userCode,
|
|
1788
|
+
expires_in: expiresIn(signIn)
|
|
1789
|
+
},
|
|
1790
|
+
() => `To sign in, open this link:
|
|
1791
|
+
|
|
1792
|
+
${terminalSafe(signIn.link)}
|
|
1793
|
+
|
|
1794
|
+
Approve it if the page shows the code ${terminalSafe(signIn.userCode)}, then run chesly login --wait.`
|
|
1795
|
+
);
|
|
1796
|
+
if (opened) out.note("Opened your browser.");
|
|
1797
|
+
}
|
|
1798
|
+
async function pollForKey(signIn) {
|
|
1799
|
+
let interval = signIn.interval;
|
|
1800
|
+
const { expiresAt } = signIn;
|
|
1801
|
+
for (; ; ) {
|
|
1802
|
+
const left = expiresAt - Date.now();
|
|
1803
|
+
if (left <= 0) throw expired();
|
|
1804
|
+
await sleep(Math.min(interval * 1e3, left));
|
|
1805
|
+
if (Date.now() >= expiresAt) throw expired();
|
|
1806
|
+
let token2;
|
|
1807
|
+
try {
|
|
1808
|
+
token2 = await apiRequest("/v1/cli/sessions/token", {
|
|
1809
|
+
method: "POST",
|
|
1810
|
+
body: { device_code: signIn.deviceCode }
|
|
1811
|
+
});
|
|
1812
|
+
} catch (error) {
|
|
1813
|
+
if (error instanceof CheslyApiError) {
|
|
1814
|
+
if (error.code === "authorization_pending") continue;
|
|
1815
|
+
if (error.code === "slow_down") {
|
|
1816
|
+
interval += 5;
|
|
1817
|
+
continue;
|
|
1818
|
+
}
|
|
1819
|
+
if (error.code === "access_denied") {
|
|
1820
|
+
throw new CliError("access_denied", "The sign-in was denied on web.chesly.app. Nothing was stored.");
|
|
1821
|
+
}
|
|
1822
|
+
if (error.code === "expired_token") throw expired();
|
|
1823
|
+
if (error.status === 429) {
|
|
1824
|
+
interval = Math.max(interval + 5, error.retryAfter ?? 0);
|
|
1825
|
+
continue;
|
|
1826
|
+
}
|
|
1827
|
+
if (error.status >= 500) {
|
|
1828
|
+
interval = slowerAfterFailure(interval);
|
|
1829
|
+
continue;
|
|
1830
|
+
}
|
|
1831
|
+
} else if (error instanceof CheslyNetworkError) {
|
|
1832
|
+
interval = slowerAfterFailure(interval);
|
|
1833
|
+
continue;
|
|
1834
|
+
}
|
|
1835
|
+
throw error;
|
|
1836
|
+
}
|
|
1837
|
+
const apiKey = token2?.api_key;
|
|
1838
|
+
if (!isApiKey(apiKey)) {
|
|
1839
|
+
throw badAnswer("The sign-in was approved, but the API sent no valid key. Nothing was stored; run `chesly login` again.");
|
|
1840
|
+
}
|
|
1841
|
+
return apiKey;
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
function slowerAfterFailure(interval) {
|
|
1845
|
+
return Math.max(interval, Math.min(interval * 2, MAX_BACKOFF_SECONDS));
|
|
1846
|
+
}
|
|
1847
|
+
function checkSession(answer) {
|
|
1848
|
+
const fields = typeof answer === "object" && answer !== null ? answer : {};
|
|
1849
|
+
const { device_code: deviceCode, user_code: userCode } = fields;
|
|
1850
|
+
if (typeof deviceCode !== "string" || deviceCode === "" || typeof userCode !== "string" || userCode === "") {
|
|
1851
|
+
throw badAnswer("The API did not start a sign-in. Run `chesly login` again.");
|
|
1852
|
+
}
|
|
1853
|
+
return {
|
|
1854
|
+
deviceCode,
|
|
1855
|
+
userCode,
|
|
1856
|
+
link: approvalLink(fields.verification_uri_complete, fields.verification_uri, userCode),
|
|
1857
|
+
expiresAt: Date.now() + positiveOr(fields.expires_in, 600) * 1e3,
|
|
1858
|
+
interval: positiveOr(fields.interval, 5)
|
|
1859
|
+
};
|
|
1860
|
+
}
|
|
1861
|
+
function approvalLink(complete, page, userCode) {
|
|
1862
|
+
if (typeof complete === "string" && URL.canParse(complete)) return complete;
|
|
1863
|
+
if (typeof page === "string" && URL.canParse(page)) {
|
|
1864
|
+
const url = new URL(page);
|
|
1865
|
+
url.searchParams.set("code", userCode);
|
|
1866
|
+
return url.toString();
|
|
1867
|
+
}
|
|
1868
|
+
throw badAnswer("The API sent no sign-in link. Run `chesly login` again.");
|
|
1869
|
+
}
|
|
1870
|
+
function signedIn(out, store, me) {
|
|
1871
|
+
out.result(
|
|
1872
|
+
{ status: "signed_in", stored_in: store, key: me?.key ?? null },
|
|
1873
|
+
() => me === null ? `Signed in, and saved the key in ${describeSource(store)}.` : `Signed in with the key "${oneLine(me.key?.name ?? "", 100)}" (${scopeLabel(me.key?.scope)}).
|
|
1874
|
+
Saved it in ${describeSource(store)}.`
|
|
1875
|
+
);
|
|
1876
|
+
if (process.env.CHESLY_API_KEY?.trim()) {
|
|
1877
|
+
const message = "CHESLY_API_KEY is set in your environment and wins over the stored key until you unset it.";
|
|
1878
|
+
out.notice({ warning: "env_key_set", message }, () => `Note: ${message}`);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
function badAnswer(message) {
|
|
1882
|
+
return new CliError("invalid_response", message);
|
|
1883
|
+
}
|
|
1884
|
+
function expired() {
|
|
1885
|
+
return new CliError("expired_token", "The sign-in code expired. Run `chesly login` again.");
|
|
1886
|
+
}
|
|
1887
|
+
function openBrowser(url) {
|
|
1888
|
+
if (!isWebUrl(url) || process.env.SSH_CONNECTION || process.env.SSH_TTY || inCi()) return false;
|
|
1889
|
+
let command;
|
|
1890
|
+
let args;
|
|
1891
|
+
if (process.platform === "darwin") {
|
|
1892
|
+
[command, args] = ["open", [url]];
|
|
1893
|
+
} else if (process.platform === "win32") {
|
|
1894
|
+
[command, args] = ["rundll32", ["url.dll,FileProtocolHandler", url]];
|
|
1895
|
+
} else {
|
|
1896
|
+
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return false;
|
|
1897
|
+
[command, args] = ["xdg-open", [url]];
|
|
1898
|
+
}
|
|
1899
|
+
try {
|
|
1900
|
+
const child = spawn2(command, args, { stdio: "ignore", detached: true });
|
|
1901
|
+
child.on("error", () => {
|
|
1902
|
+
});
|
|
1903
|
+
child.unref();
|
|
1904
|
+
return true;
|
|
1905
|
+
} catch {
|
|
1906
|
+
return false;
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
function inCi() {
|
|
1910
|
+
const ci = process.env.CI?.trim().toLowerCase();
|
|
1911
|
+
return ci !== void 0 && ci !== "" && ci !== "false" && ci !== "0";
|
|
1912
|
+
}
|
|
1913
|
+
function isWebUrl(value) {
|
|
1914
|
+
try {
|
|
1915
|
+
const url = new URL(value);
|
|
1916
|
+
if (url.protocol === "https:") return true;
|
|
1917
|
+
return url.protocol === "http:" && isLoopbackHost(url.hostname);
|
|
1918
|
+
} catch {
|
|
1919
|
+
return false;
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
function positiveOr(value, fallback) {
|
|
1923
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
// src/commands/logout.ts
|
|
1927
|
+
function registerLogout(program, io) {
|
|
1928
|
+
program.command("logout").description("Sign out: revoke the key chesly login stored, and remove it from this computer").addHelpText(
|
|
1929
|
+
"after",
|
|
1930
|
+
`
|
|
1931
|
+
The key is revoked first, so it stops working everywhere, then removed from
|
|
1932
|
+
the keychain and the credentials file. When it can't be revoked from here
|
|
1933
|
+
(offline, or a read-only key), it is removed all the same, and chesly logout
|
|
1934
|
+
names it as still active. CHESLY_API_KEY is never touched.
|
|
1935
|
+
|
|
1936
|
+
Prints { "removed": [...], "revoked": true|false, "env_key_set": \u2026, "keys":
|
|
1937
|
+
[{ "id", "prefix", "last4", "revoked" }] }, or sentences in a terminal.
|
|
1938
|
+
|
|
1939
|
+
Example:
|
|
1940
|
+
chesly logout`
|
|
1941
|
+
).action(async (_options, command) => {
|
|
1942
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
1943
|
+
const revocations = [];
|
|
1944
|
+
for (const { key } of (await storedKeys()).keys) revocations.push(await revokeKey(key));
|
|
1945
|
+
const removed = await deleteStoredKey();
|
|
1946
|
+
const stillActive = revocations.filter((revocation) => revocation.outcome === "active");
|
|
1947
|
+
const revoked = revocations.length > 0 && stillActive.length === 0;
|
|
1948
|
+
const envKeySet = Boolean(process.env.CHESLY_API_KEY?.trim());
|
|
1949
|
+
const keys = revocations.map(({ id, prefix, last4, outcome }) => ({ id, prefix, last4, revoked: outcome !== "active" }));
|
|
1950
|
+
out.result({ removed, revoked, env_key_set: envKeySet, keys }, () => {
|
|
1951
|
+
const where = removed.map(describeSource).join(" and ");
|
|
1952
|
+
const revokedNow = revocations.some((revocation) => revocation.outcome === "revoked");
|
|
1953
|
+
const lines = [];
|
|
1954
|
+
if (removed.length === 0) lines.push("No key was stored on this computer.");
|
|
1955
|
+
else if (revokedNow && stillActive.length === 0) lines.push(`Signed out: revoked the key and removed it from ${where}.`);
|
|
1956
|
+
else lines.push(`Signed out: removed the key from ${where}.`);
|
|
1957
|
+
for (const revocation of stillActive) lines.push(stillActiveMessage(revocation));
|
|
1958
|
+
if (removed.length > 0 && revocations.length > 0 && !revokedNow && stillActive.length === 0) {
|
|
1959
|
+
lines.push("It had already stopped working.");
|
|
1960
|
+
}
|
|
1961
|
+
if (envKeySet) lines.push("CHESLY_API_KEY is still set in your environment. Unset it to stop using that key.");
|
|
1962
|
+
return lines.join("\n");
|
|
1963
|
+
});
|
|
1964
|
+
if (out.json) {
|
|
1965
|
+
for (const revocation of stillActive) {
|
|
1966
|
+
const { id, prefix, last4 } = revocation;
|
|
1967
|
+
out.warn("key_still_active", stillActiveMessage(revocation), { id, prefix, last4 });
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
// src/resolve-chat.ts
|
|
1974
|
+
var LOOKUP_LIMIT = 10;
|
|
1975
|
+
var CHAT_ARGUMENT_HELP = `A <chat> is a chat ID (chat_\u2026) or a name. An exact name wins, in any case;
|
|
1976
|
+
so does the only partial match. No match, or several, exits 4, and JSON
|
|
1977
|
+
mode lists the chats a name could mean as "candidates". Names are looked up
|
|
1978
|
+
on every network but email; --network names the one to look in (an email
|
|
1979
|
+
thread's name is its subject: --network email).`;
|
|
1980
|
+
async function resolveChat(arg, key, options = {}) {
|
|
1981
|
+
const name = arg.trim();
|
|
1982
|
+
if (name.startsWith("chat_")) return { id: name, name: null };
|
|
1983
|
+
if (name === "") throw new CliError("usage_error", "Give a chat ID (chat_\u2026) or a chat name.", EXIT.USAGE);
|
|
1984
|
+
const answer = await apiRequest("/v1/chats", {
|
|
1985
|
+
key: await key(),
|
|
1986
|
+
query: { q: name, archived: "all", limit: LOOKUP_LIMIT, network: options.network, account_id: options.accountId }
|
|
1987
|
+
});
|
|
1988
|
+
const page = expectAnswer(answer, isChatPage, "a page of chats");
|
|
1989
|
+
const exact = page.chats.filter((chat) => sameName(chat.name, name));
|
|
1990
|
+
const candidates = exact.length > 0 ? exact : page.chats;
|
|
1991
|
+
const [first, ...others] = candidates;
|
|
1992
|
+
if (first === void 0) {
|
|
1993
|
+
throw new CliError("chat_not_found", `No chat matches "${name}".`, EXIT.NOT_FOUND, {
|
|
1994
|
+
hint: "Run `chesly chats` to list your chats, or pass a chat ID."
|
|
1995
|
+
});
|
|
1996
|
+
}
|
|
1997
|
+
if (others.length === 0) return { id: first.id, name: first.name ?? null };
|
|
1998
|
+
const count2 = `${page.next_cursor ? "at least " : ""}${candidates.length}`;
|
|
1999
|
+
throw new CliError("ambiguous_chat", `"${name}" matches ${count2} chats. Use one of their chat IDs instead.`, EXIT.NOT_FOUND, {
|
|
2000
|
+
extras: { candidates },
|
|
2001
|
+
hint: indent(chatTable(candidates), " ")
|
|
2002
|
+
});
|
|
2003
|
+
}
|
|
2004
|
+
function sameName(chatName, name) {
|
|
2005
|
+
return (chatName ?? "").trim().localeCompare(name, void 0, { sensitivity: "accent" }) === 0;
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
// src/commands/read.ts
|
|
2009
|
+
function registerRead(program, io) {
|
|
2010
|
+
program.command("read").description("Read a chat's latest messages, by chat ID or name").argument("<chat>", "a chat ID (chat_\u2026) or a chat name").option("--limit <n>", "how many messages, 1 to 100 (default 50)", parseLimit).option("--cursor <cursor>", "older messages: next_cursor from the page before").option("--network <name>", "look the chat name up on this network: email for an email thread", parseNetwork).addHelpText(
|
|
2011
|
+
"after",
|
|
2012
|
+
`
|
|
2013
|
+
${CHAT_ARGUMENT_HELP}
|
|
2014
|
+
|
|
2015
|
+
Prints the API's page as JSON (newest first, with next_cursor while there
|
|
2016
|
+
are older messages), or the messages oldest first in a terminal.
|
|
2017
|
+
|
|
2018
|
+
Examples:
|
|
2019
|
+
chesly read "Mom"
|
|
2020
|
+
chesly read "Invoice 42" --network email
|
|
2021
|
+
chesly read chat_7Hq2mR9xLp4vT1sK8nWz --limit 20`
|
|
2022
|
+
).action(async (chat, options, command) => {
|
|
2023
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2024
|
+
const key = keyOnce();
|
|
2025
|
+
const { id: chatId } = await resolveChat(chat, key, { network: options.network });
|
|
2026
|
+
const answer = await apiRequest(`/v1/chats/${encodeURIComponent(chatId)}/messages`, {
|
|
2027
|
+
key: await key(),
|
|
2028
|
+
query: { limit: options.limit, cursor: options.cursor }
|
|
2029
|
+
});
|
|
2030
|
+
const page = expectAnswer(answer, isMessageList, "a page of messages");
|
|
2031
|
+
out.result(page, () => page.messages.length === 0 ? "No messages." : transcript(page.messages));
|
|
2032
|
+
if (!out.json && page.next_cursor) {
|
|
2033
|
+
const limit = options.limit === void 0 ? "" : ` --limit ${options.limit}`;
|
|
2034
|
+
out.note(`Older messages: chesly read ${shellQuote(chatId)}${limit} --cursor ${shellQuote(oneLine(page.next_cursor))}`);
|
|
2035
|
+
}
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
// src/commands/search.ts
|
|
2040
|
+
function registerSearch(program, io) {
|
|
2041
|
+
program.command("search").description("Search your messages, across every chat or in one").argument("<query>", "the words to look for, at most 200 characters").option("--chat <chat>", "only this chat: a chat ID (chat_\u2026) or a chat name").option("--limit <n>", "how many messages, 1 to 100", parseLimit).option("--network <name>", "only this network: email, whatsapp, telegram\u2026 (email only when named)", parseNetwork).addHelpText(
|
|
2042
|
+
"after",
|
|
2043
|
+
`
|
|
2044
|
+
${CHAT_ARGUMENT_HELP}
|
|
2045
|
+
|
|
2046
|
+
Prints the API's { "messages": [...] }, each with its chat's name and
|
|
2047
|
+
network, or a table in a terminal.
|
|
2048
|
+
|
|
2049
|
+
Examples:
|
|
2050
|
+
chesly search "flight number"
|
|
2051
|
+
chesly search invoice --chat "Accounting" --limit 10`
|
|
2052
|
+
).action(async (query, options, command) => {
|
|
2053
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2054
|
+
const q = query.trim();
|
|
2055
|
+
if (q === "") throw new CliError("usage_error", "Give the words to search for.", EXIT.USAGE);
|
|
2056
|
+
const key = keyOnce();
|
|
2057
|
+
const chatId = options.chat === void 0 ? void 0 : (await resolveChat(options.chat, key, { network: options.network })).id;
|
|
2058
|
+
const answer = await apiRequest("/v1/messages/search", {
|
|
2059
|
+
key: await key(),
|
|
2060
|
+
query: { q, chat_id: chatId, limit: options.limit, network: options.network }
|
|
2061
|
+
});
|
|
2062
|
+
const result = expectAnswer(answer, isMessageList, "a list of messages");
|
|
2063
|
+
out.result(
|
|
2064
|
+
result,
|
|
2065
|
+
() => result.messages.length === 0 ? `No messages match "${q}".` : searchTable(result.messages)
|
|
2066
|
+
);
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
// src/commands/send.ts
|
|
2071
|
+
import { randomUUID } from "crypto";
|
|
2072
|
+
|
|
2073
|
+
// src/upload.ts
|
|
2074
|
+
import { openAsBlob } from "fs";
|
|
2075
|
+
import { stat } from "fs/promises";
|
|
2076
|
+
import { basename, extname } from "path";
|
|
2077
|
+
var MAX_UPLOAD_BYTES = 5e7;
|
|
2078
|
+
var MIME_TYPES = {
|
|
2079
|
+
jpg: "image/jpeg",
|
|
2080
|
+
jpeg: "image/jpeg",
|
|
2081
|
+
png: "image/png",
|
|
2082
|
+
gif: "image/gif",
|
|
2083
|
+
webp: "image/webp",
|
|
2084
|
+
heic: "image/heic",
|
|
2085
|
+
heif: "image/heif",
|
|
2086
|
+
avif: "image/avif",
|
|
2087
|
+
bmp: "image/bmp",
|
|
2088
|
+
tif: "image/tiff",
|
|
2089
|
+
tiff: "image/tiff",
|
|
2090
|
+
svg: "image/svg+xml",
|
|
2091
|
+
mp4: "video/mp4",
|
|
2092
|
+
m4v: "video/x-m4v",
|
|
2093
|
+
mov: "video/quicktime",
|
|
2094
|
+
webm: "video/webm",
|
|
2095
|
+
mkv: "video/x-matroska",
|
|
2096
|
+
"3gp": "video/3gpp",
|
|
2097
|
+
mp3: "audio/mpeg",
|
|
2098
|
+
m4a: "audio/mp4",
|
|
2099
|
+
aac: "audio/aac",
|
|
2100
|
+
wav: "audio/wav",
|
|
2101
|
+
flac: "audio/flac",
|
|
2102
|
+
ogg: "audio/ogg",
|
|
2103
|
+
oga: "audio/ogg",
|
|
2104
|
+
opus: "audio/ogg",
|
|
2105
|
+
amr: "audio/amr",
|
|
2106
|
+
pdf: "application/pdf",
|
|
2107
|
+
txt: "text/plain",
|
|
2108
|
+
md: "text/markdown",
|
|
2109
|
+
csv: "text/csv",
|
|
2110
|
+
json: "application/json",
|
|
2111
|
+
vcf: "text/vcard",
|
|
2112
|
+
ics: "text/calendar",
|
|
2113
|
+
zip: "application/zip",
|
|
2114
|
+
doc: "application/msword",
|
|
2115
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
2116
|
+
xls: "application/vnd.ms-excel",
|
|
2117
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
2118
|
+
ppt: "application/vnd.ms-powerpoint",
|
|
2119
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
|
2120
|
+
};
|
|
2121
|
+
var SLOWEST_UPLOAD_BYTES_PER_SECOND = 131072;
|
|
2122
|
+
async function readUpload(path) {
|
|
2123
|
+
try {
|
|
2124
|
+
const info = await stat(path);
|
|
2125
|
+
if (!info.isFile()) throw new CliError("file_unreadable", `${path} is not a file.`, EXIT.USAGE);
|
|
2126
|
+
if (info.size > MAX_UPLOAD_BYTES) {
|
|
2127
|
+
throw new CliError("media_too_large", `${path} is over 50 MB, the most a message can carry.`);
|
|
2128
|
+
}
|
|
2129
|
+
return { blob: await openAsBlob(path, { type: mimeTypeOf(path) }), name: basename(path), size: info.size };
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
if (error instanceof CliError) throw error;
|
|
2132
|
+
throw new CliError("file_unreadable", `Can't read ${path}: ${reasonOf2(error)}`, EXIT.USAGE);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
async function uploadFile(file, key) {
|
|
2136
|
+
const form = new FormData();
|
|
2137
|
+
form.append("file", file.blob, file.name);
|
|
2138
|
+
const upload = await apiRequest("/v1/media", {
|
|
2139
|
+
key,
|
|
2140
|
+
form,
|
|
2141
|
+
timeoutMs: 3e4 + Math.ceil(file.size / SLOWEST_UPLOAD_BYTES_PER_SECOND) * 1e3
|
|
2142
|
+
});
|
|
2143
|
+
if (!isMediaUpload(upload)) throw new CliError("invalid_response", "The API sent no media ID for the upload.");
|
|
2144
|
+
return upload;
|
|
2145
|
+
}
|
|
2146
|
+
function mimeTypeOf(path) {
|
|
2147
|
+
return MIME_TYPES[extname(path).slice(1).toLowerCase()] ?? "application/octet-stream";
|
|
2148
|
+
}
|
|
2149
|
+
function reasonOf2(error) {
|
|
2150
|
+
const { code, message } = error ?? {};
|
|
2151
|
+
if (code === "ENOENT") return "no such file";
|
|
2152
|
+
if (code === "EACCES" || code === "EPERM") return "permission denied";
|
|
2153
|
+
return typeof message === "string" && message !== "" ? message : "it failed";
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
// src/commands/send.ts
|
|
2157
|
+
var WAIT_MS = 3e4;
|
|
2158
|
+
var POLL_MS = 1e3;
|
|
2159
|
+
var MIN_POLL_MS = 1e3;
|
|
2160
|
+
function registerSend(program, io) {
|
|
2161
|
+
program.command("send").description("Send a message to one of your chats: text, a reply, or a file with a caption").argument("<chat>", "a chat ID (chat_\u2026) or a chat name").argument("[text]", "the text to send; - reads it from stdin").option("--reply-to <msg_id>", "reply to this message: a msg_ ID from chesly read").option("--file <path>", "attach this file (at most 50 MB); the text becomes its caption").option("--media-id <id>", "attach a file uploaded before (a media_ ID), as a retry of a file send does").option("--wait", "wait up to 30 s until the network has it: sent, delivered or failed").option(
|
|
2162
|
+
"--idempotency-key <key>",
|
|
2163
|
+
"send at most once per key, however often the command runs (default: a new key)",
|
|
2164
|
+
parseIdempotencyKey
|
|
2165
|
+
).option("--network <name>", "look the chat name up on this network: email for an email thread", parseNetwork).addHelpText(
|
|
2166
|
+
"after",
|
|
2167
|
+
`
|
|
2168
|
+
${CHAT_ARGUMENT_HELP}
|
|
2169
|
+
|
|
2170
|
+
Prints the message the API answered: its JSON, or "Sent to <chat> \xB7 <status>"
|
|
2171
|
+
in a terminal. The status is queued until the network takes the message;
|
|
2172
|
+
with --wait the command waits up to 30 s in all for sent, delivered or failed
|
|
2173
|
+
(it asks once a second, or later when a refused ask's Retry-After says so,
|
|
2174
|
+
and each ask counts as an API call). A failure the network confirms exits 1
|
|
2175
|
+
(delivery_failed) with the reason. One it didn't confirm reads "unconfirmed":
|
|
2176
|
+
the message may have been delivered, so check the chat before you send it
|
|
2177
|
+
again; --wait goes on asking, and if it stays unconfirmed the command exits 5
|
|
2178
|
+
(delivery_unconfirmed). Once the message went out it is always printed, and
|
|
2179
|
+
following it failing is only a warning on stderr (delivery_wait_failed).
|
|
2180
|
+
|
|
2181
|
+
Every send carries an Idempotency-Key, and the CLI's own retries (after a
|
|
2182
|
+
network error, a 502, 503 or 504, a 429, or while a first attempt is still
|
|
2183
|
+
running) reuse it, so the message goes out at most once. Each waits for the
|
|
2184
|
+
answer's Retry-After, at most 10 s, or 1 s and then 2 s without one; a 429
|
|
2185
|
+
that lifts later (a send cap) exits 5 at once. To retry later without
|
|
2186
|
+
sending twice, pass the same --idempotency-key again. A file send that gives
|
|
2187
|
+
up also names its upload: retry it with --media-id <id> instead of --file, as
|
|
2188
|
+
a new upload would make another media ID, which the same key refuses (422).
|
|
2189
|
+
|
|
2190
|
+
Pass the text on stdin with a quoted heredoc (- <<'EOF'), not as a
|
|
2191
|
+
double-quoted argument: inside double quotes the shell still expands $ and
|
|
2192
|
+
backticks, while the quoted EOF keeps the text exactly as written.
|
|
2193
|
+
|
|
2194
|
+
Examples:
|
|
2195
|
+
chesly send "Mom" - --wait <<'EOF'
|
|
2196
|
+
On my way
|
|
2197
|
+
EOF
|
|
2198
|
+
chesly send "Invoice 42" - --network email <<'EOF'
|
|
2199
|
+
Paid, thank you.
|
|
2200
|
+
EOF
|
|
2201
|
+
chesly send chat_7Hq2mR9xLp4vT1sK8nWz - --file report.pdf <<'EOF'
|
|
2202
|
+
The report is attached.
|
|
2203
|
+
EOF`
|
|
2204
|
+
).action(async (chat, text, options, command) => {
|
|
2205
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2206
|
+
const body = await messageText2(text, io);
|
|
2207
|
+
if (options.file !== void 0 && options.mediaId !== void 0) {
|
|
2208
|
+
throw new CliError("usage_error", "A message carries one attachment: give --file or --media-id, not both.", EXIT.USAGE);
|
|
2209
|
+
}
|
|
2210
|
+
if (body === void 0 && options.file === void 0 && options.mediaId === void 0) {
|
|
2211
|
+
throw new CliError("usage_error", "Give the text to send, - to read it from stdin, or --file.", EXIT.USAGE);
|
|
2212
|
+
}
|
|
2213
|
+
const file = options.file === void 0 ? void 0 : await readUpload(options.file);
|
|
2214
|
+
const key = keyOnce();
|
|
2215
|
+
const target = await resolveChat(chat, key, { network: options.network });
|
|
2216
|
+
const idempotencyKey = options.idempotencyKey ?? randomUUID();
|
|
2217
|
+
const uploaded = file === void 0 ? void 0 : await uploadFile(file, await key());
|
|
2218
|
+
const mediaId = uploaded?.id ?? options.mediaId;
|
|
2219
|
+
const again = {
|
|
2220
|
+
flags: uploaded === void 0 ? `--idempotency-key ${idempotencyKey}` : `--media-id ${shellQuote(uploaded.id)} --idempotency-key ${idempotencyKey} (instead of --file)`,
|
|
2221
|
+
extras: { idempotency_key: idempotencyKey, ...mediaId === void 0 ? {} : { media_id: mediaId } }
|
|
2222
|
+
};
|
|
2223
|
+
const answer = await idempotentPost(`/v1/chats/${encodeURIComponent(target.id)}/messages`, {
|
|
2224
|
+
key: await key(),
|
|
2225
|
+
idempotencyKey,
|
|
2226
|
+
body: {
|
|
2227
|
+
...body === void 0 ? {} : { text: body },
|
|
2228
|
+
...options.replyTo === void 0 ? {} : { reply_to: options.replyTo },
|
|
2229
|
+
...mediaId === void 0 ? {} : { media_id: mediaId }
|
|
2230
|
+
},
|
|
2231
|
+
again
|
|
2232
|
+
});
|
|
2233
|
+
if (!isMessage(answer)) {
|
|
2234
|
+
throw new AnnotatedError(
|
|
2235
|
+
new CliError("invalid_response", "The API sent no message for the send."),
|
|
2236
|
+
again.extras,
|
|
2237
|
+
`It may have gone out. Run the command again with ${again.flags} to see the API's answer.`
|
|
2238
|
+
);
|
|
2239
|
+
}
|
|
2240
|
+
const waited = options.wait ? await waitForDelivery(answer, await key()) : { message: answer, ranOut: false, failure: void 0 };
|
|
2241
|
+
const { message } = waited;
|
|
2242
|
+
const state = deliveryState(message.delivery);
|
|
2243
|
+
out.result(message, () => sentLine(target, message));
|
|
2244
|
+
if (waited.failure !== void 0) {
|
|
2245
|
+
out.warn(
|
|
2246
|
+
"delivery_wait_failed",
|
|
2247
|
+
`The message was sent, but following its delivery failed (${waited.failure}). chesly read shows it, and the command run again with ${again.flags} shows the API's answer.`,
|
|
2248
|
+
again.extras
|
|
2249
|
+
);
|
|
2250
|
+
} else if (waited.ranOut && state === "queued") {
|
|
2251
|
+
out.note(`Still queued after ${WAIT_MS / 1e3} s.`);
|
|
2252
|
+
}
|
|
2253
|
+
const delivery = message.delivery;
|
|
2254
|
+
if (state === "failed") {
|
|
2255
|
+
throw new CliError("delivery_failed", delivery?.error?.message ?? "The network did not take the message.", EXIT.ERROR, {
|
|
2256
|
+
extras: { message_id: message.id, delivery }
|
|
2257
|
+
});
|
|
2258
|
+
}
|
|
2259
|
+
if (state === "unconfirmed") {
|
|
2260
|
+
throw new CliError(
|
|
2261
|
+
"delivery_unconfirmed",
|
|
2262
|
+
"The network didn't confirm the message, so it may have been delivered. Check the chat before you send it again.",
|
|
2263
|
+
EXIT.RETRY_LATER,
|
|
2264
|
+
{ extras: { message_id: message.id, delivery } }
|
|
2265
|
+
);
|
|
2266
|
+
}
|
|
2267
|
+
});
|
|
2268
|
+
}
|
|
2269
|
+
async function messageText2(text, io) {
|
|
2270
|
+
if (text !== "-") return text === "" ? void 0 : text;
|
|
2271
|
+
if (io.stdin.isTTY) {
|
|
2272
|
+
throw new CliError(
|
|
2273
|
+
"usage_error",
|
|
2274
|
+
"The text - reads stdin, and stdin is a terminal. Pipe the text in, or give it as an argument.",
|
|
2275
|
+
EXIT.USAGE
|
|
2276
|
+
);
|
|
2277
|
+
}
|
|
2278
|
+
const piped = (await io.stdin.read()).replace(/(?:\r?\n)+$/, "");
|
|
2279
|
+
return piped === "" ? void 0 : piped;
|
|
2280
|
+
}
|
|
2281
|
+
async function waitForDelivery(sent, key) {
|
|
2282
|
+
let message = sent;
|
|
2283
|
+
let failure;
|
|
2284
|
+
let pauseMs = POLL_MS;
|
|
2285
|
+
const deadline = Date.now() + WAIT_MS;
|
|
2286
|
+
while (!settled(message)) {
|
|
2287
|
+
if (deadline - Date.now() < pauseMs + MIN_POLL_MS) return { message, ranOut: failure === void 0, failure };
|
|
2288
|
+
await sleep(pauseMs);
|
|
2289
|
+
pauseMs = POLL_MS;
|
|
2290
|
+
try {
|
|
2291
|
+
const timeoutMs = deadline - Date.now();
|
|
2292
|
+
const polled = await apiRequest(`/v1/messages/${encodeURIComponent(message.id)}`, { key, timeoutMs });
|
|
2293
|
+
if (!isMessage(polled)) return { message, ranOut: false, failure: "the API sent an answer that is not a message" };
|
|
2294
|
+
message = polled;
|
|
2295
|
+
failure = void 0;
|
|
2296
|
+
} catch (error) {
|
|
2297
|
+
if (error instanceof CheslyNetworkError && error.timedOut) return { message, ranOut: true, failure: void 0 };
|
|
2298
|
+
failure = pollFailure(error);
|
|
2299
|
+
const passing = isTransient(error) || error instanceof CheslyApiError && error.status === 429;
|
|
2300
|
+
if (!passing) return { message, ranOut: false, failure };
|
|
2301
|
+
if (error instanceof CheslyApiError && error.retryAfter !== void 0) {
|
|
2302
|
+
pauseMs = Math.max(POLL_MS, error.retryAfter * 1e3);
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
return { message, ranOut: false, failure: void 0 };
|
|
2307
|
+
}
|
|
2308
|
+
function pollFailure(error) {
|
|
2309
|
+
if (error instanceof CheslyApiError) return `${error.status} ${error.code}`;
|
|
2310
|
+
if (error instanceof CheslyNetworkError) return "no answer from the API";
|
|
2311
|
+
return "an unexpected error";
|
|
2312
|
+
}
|
|
2313
|
+
function settled(message) {
|
|
2314
|
+
const state = deliveryState(message.delivery);
|
|
2315
|
+
return state === void 0 || state === "sent" || state === "delivered" || state === "failed";
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
// src/commands/usage.ts
|
|
2319
|
+
function registerUsage(program, io) {
|
|
2320
|
+
program.command("usage").description("Your API plan: this period's calls and minutes, its limits, and send caps").addHelpText(
|
|
2321
|
+
"after",
|
|
2322
|
+
`
|
|
2323
|
+
Prints the API's GET /v1/me answer as JSON, or in a terminal: the plan and
|
|
2324
|
+
its status (when a trial ends, when it renews, changes plan or ends), this
|
|
2325
|
+
period's calls (counted, not billed), the transcription minutes used of
|
|
2326
|
+
those included (and, once they're used up, when they come back), the plan's
|
|
2327
|
+
limits, and each connected account's sends this hour and today against its
|
|
2328
|
+
caps. Plans: https://web.chesly.app/api/billing
|
|
2329
|
+
|
|
2330
|
+
Example:
|
|
2331
|
+
chesly usage --json`
|
|
2332
|
+
).action(async (_options, command) => {
|
|
2333
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2334
|
+
const { key } = await requireKey();
|
|
2335
|
+
const me = expectAnswer(await apiRequest("/v1/me", { key }), isMe, "the details of this key");
|
|
2336
|
+
out.result(me, () => usageSummary(me));
|
|
2337
|
+
});
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
// src/sse.ts
|
|
2341
|
+
var MAX_LINE_CHARS = 1048576;
|
|
2342
|
+
var MAX_FRAME_CHARS = 4194304;
|
|
2343
|
+
var EventStreamLimitError = class extends Error {
|
|
2344
|
+
constructor(part, eventId) {
|
|
2345
|
+
super(part === "line" ? "The event stream sent a line over 1 MiB." : "The event stream sent an event over 4 MiB.");
|
|
2346
|
+
this.part = part;
|
|
2347
|
+
this.eventId = eventId;
|
|
2348
|
+
this.name = "EventStreamLimitError";
|
|
2349
|
+
}
|
|
2350
|
+
part;
|
|
2351
|
+
eventId;
|
|
2352
|
+
};
|
|
2353
|
+
var IdleTimeoutError = class extends Error {
|
|
2354
|
+
constructor(ms) {
|
|
2355
|
+
super(`The event stream sent nothing for ${ms / 1e3} s.`);
|
|
2356
|
+
this.ms = ms;
|
|
2357
|
+
this.name = "IdleTimeoutError";
|
|
2358
|
+
}
|
|
2359
|
+
ms;
|
|
2360
|
+
};
|
|
2361
|
+
async function* readEventStream(response, options = {}) {
|
|
2362
|
+
if (response.body === null) return;
|
|
2363
|
+
const reader = response.body.getReader();
|
|
2364
|
+
const lines = new LineSplitter();
|
|
2365
|
+
const decoder = new TextDecoder();
|
|
2366
|
+
let data = "";
|
|
2367
|
+
let type = "";
|
|
2368
|
+
let lastId = "";
|
|
2369
|
+
let frameHasId = false;
|
|
2370
|
+
let retry;
|
|
2371
|
+
try {
|
|
2372
|
+
for (; ; ) {
|
|
2373
|
+
const { done, value } = await within(reader.read(), options.idleTimeoutMs);
|
|
2374
|
+
if (done) return;
|
|
2375
|
+
const { complete, overflow } = lines.push(decoder.decode(value, { stream: true }));
|
|
2376
|
+
for (const line of complete) {
|
|
2377
|
+
if (line === "") {
|
|
2378
|
+
const frame = data;
|
|
2379
|
+
const frameType = type;
|
|
2380
|
+
const movedId = frameHasId;
|
|
2381
|
+
data = "";
|
|
2382
|
+
type = "";
|
|
2383
|
+
frameHasId = false;
|
|
2384
|
+
const id = lastId === "" ? null : lastId;
|
|
2385
|
+
const retryField = retry === void 0 ? {} : { retry };
|
|
2386
|
+
if (frame !== "") {
|
|
2387
|
+
yield { id, event: frameType === "" ? null : frameType, data: frame.slice(0, -1), ...retryField };
|
|
2388
|
+
} else if (movedId) {
|
|
2389
|
+
yield { id, event: null, data: null, ...retryField };
|
|
2390
|
+
}
|
|
2391
|
+
continue;
|
|
2392
|
+
}
|
|
2393
|
+
if (line.startsWith(":")) continue;
|
|
2394
|
+
const colon = line.indexOf(":");
|
|
2395
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
2396
|
+
let value2 = colon === -1 ? "" : line.slice(colon + 1);
|
|
2397
|
+
if (value2.startsWith(" ")) value2 = value2.slice(1);
|
|
2398
|
+
if (field === "data") {
|
|
2399
|
+
data += `${value2}
|
|
2400
|
+
`;
|
|
2401
|
+
if (data.length > MAX_FRAME_CHARS) throw new EventStreamLimitError("frame", frameHasId ? lastId : null);
|
|
2402
|
+
} else if (field === "event") type = value2;
|
|
2403
|
+
else if (field === "id" && !value2.includes("\0")) {
|
|
2404
|
+
lastId = value2;
|
|
2405
|
+
frameHasId = true;
|
|
2406
|
+
} else if (field === "retry" && /^[0-9]+$/.test(value2)) retry = Number(value2);
|
|
2407
|
+
}
|
|
2408
|
+
if (overflow) throw new EventStreamLimitError("line", frameHasId ? lastId : null);
|
|
2409
|
+
}
|
|
2410
|
+
} finally {
|
|
2411
|
+
await reader.cancel().catch(() => {
|
|
2412
|
+
});
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
var LineSplitter = class {
|
|
2416
|
+
pending = "";
|
|
2417
|
+
afterCr = false;
|
|
2418
|
+
push(text) {
|
|
2419
|
+
if (text === "") return { complete: [], overflow: false };
|
|
2420
|
+
let rest = text;
|
|
2421
|
+
if (this.afterCr && rest.startsWith("\n")) rest = rest.slice(1);
|
|
2422
|
+
this.afterCr = false;
|
|
2423
|
+
const buffer = this.pending + rest;
|
|
2424
|
+
const complete = [];
|
|
2425
|
+
let start = 0;
|
|
2426
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
2427
|
+
const char = buffer[i];
|
|
2428
|
+
if (char !== "\n" && char !== "\r") continue;
|
|
2429
|
+
if (i - start > MAX_LINE_CHARS) return { complete, overflow: true };
|
|
2430
|
+
complete.push(buffer.slice(start, i));
|
|
2431
|
+
if (char === "\r") {
|
|
2432
|
+
if (i + 1 === buffer.length) this.afterCr = true;
|
|
2433
|
+
else if (buffer[i + 1] === "\n") i++;
|
|
2434
|
+
}
|
|
2435
|
+
start = i + 1;
|
|
2436
|
+
}
|
|
2437
|
+
this.pending = buffer.slice(start);
|
|
2438
|
+
return { complete, overflow: this.pending.length > MAX_LINE_CHARS };
|
|
2439
|
+
}
|
|
2440
|
+
};
|
|
2441
|
+
async function within(read, ms) {
|
|
2442
|
+
if (ms === void 0) return read;
|
|
2443
|
+
let timer;
|
|
2444
|
+
const idle = new Promise((_, reject) => {
|
|
2445
|
+
timer = setTimeout(() => reject(new IdleTimeoutError(ms)), ms);
|
|
2446
|
+
});
|
|
2447
|
+
try {
|
|
2448
|
+
return await Promise.race([read, idle]);
|
|
2449
|
+
} finally {
|
|
2450
|
+
clearTimeout(timer);
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
// src/commands/watch.ts
|
|
2455
|
+
var STREAM_PATH = "/v1/events/stream";
|
|
2456
|
+
var FIRST_RETRY_MS = 3e3;
|
|
2457
|
+
var MIN_RETRY_MS = 1e3;
|
|
2458
|
+
var MAX_RETRY_MS = 3e4;
|
|
2459
|
+
var IDLE_TIMEOUT_MS = 45e3;
|
|
2460
|
+
function registerWatch(program, io) {
|
|
2461
|
+
program.command("watch").description("Stream your events live, one line each, until Ctrl+C").option("--chat <chat>", "only this chat: a chat ID (chat_\u2026) or a chat name").option("--account <acct_id>", "only this account: an acct_ ID from chesly accounts").option("--types <a,b>", "only these event types, such as message.received,message.sent", parseList).option("--networks <a,b>", "only these networks, such as whatsapp,telegram (email only when named)", parseList).option("--after <evt_id>", "start after this event instead of now (as far back as your plan's event history)").addHelpText(
|
|
2462
|
+
"after",
|
|
2463
|
+
`
|
|
2464
|
+
${CHAT_ARGUMENT_HELP}
|
|
2465
|
+
|
|
2466
|
+
Prints one line per event. JSON mode (piped, or --json) prints each event's
|
|
2467
|
+
JSON as the API sends it, one per line: { "id", "type", "timestamp", "data" }.
|
|
2468
|
+
A terminal shows "HH:MM [network] <chat> \u2014 <sender>: <text>" for messages and
|
|
2469
|
+
"HH:MM <type> <chat or account>" for everything else.
|
|
2470
|
+
|
|
2471
|
+
The types: message.received, message.sent (yours, from any device),
|
|
2472
|
+
message.edited, message.deleted, message.delivery_failed, chat.created,
|
|
2473
|
+
chat.updated, chat.read, account.connected, account.disconnected,
|
|
2474
|
+
account.needs_attention, reaction.added and reaction.removed.
|
|
2475
|
+
|
|
2476
|
+
It runs until Ctrl+C, which exits 0. A dropped connection is retried on its
|
|
2477
|
+
own, after 3 s and then longer (up to 30 s; it keeps growing while connections
|
|
2478
|
+
drop before any event), resuming after the last event ID
|
|
2479
|
+
the stream gave: an event's, or the stream's starting point when the API names
|
|
2480
|
+
it. From then on nothing is missed; before it, events during a reconnect can
|
|
2481
|
+
be (--after <evt_id> pins the start). An event can come twice: skip ids you
|
|
2482
|
+
have seen. An event too large to read (over 4 MiB) that ends the connection
|
|
2483
|
+
twice in a row is skipped, with an event_too_large warning naming its id. A
|
|
2484
|
+
resume point older than your plan's event history starts over from new
|
|
2485
|
+
events, with a warning on stderr (a JSON line in JSON mode). How many days
|
|
2486
|
+
that is, and how many streams you can have open at once, are your plan's:
|
|
2487
|
+
chesly usage shows both. One stream more exits 5 (too_many_streams).
|
|
2488
|
+
|
|
2489
|
+
Email events come only when --networks names email, or --account is an
|
|
2490
|
+
email account. With --networks naming one network, --chat looks its name up
|
|
2491
|
+
there, so --chat "Invoice 42" --networks email finds an email thread.
|
|
2492
|
+
|
|
2493
|
+
Examples:
|
|
2494
|
+
chesly watch --json
|
|
2495
|
+
chesly watch --chat "Mom" --types message.received`
|
|
2496
|
+
).action(async (options, command) => {
|
|
2497
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2498
|
+
const key = keyOnce();
|
|
2499
|
+
const network = options.networks?.length === 1 ? options.networks[0] : void 0;
|
|
2500
|
+
const lookup = { network, accountId: options.account };
|
|
2501
|
+
const chatId = options.chat === void 0 ? void 0 : (await resolveChat(options.chat, key, lookup)).id;
|
|
2502
|
+
const filters = {
|
|
2503
|
+
chat_id: chatId,
|
|
2504
|
+
account_id: options.account,
|
|
2505
|
+
types: options.types?.join(","),
|
|
2506
|
+
networks: options.networks?.join(",")
|
|
2507
|
+
};
|
|
2508
|
+
await watchEvents(out, await key(), filters, options.after);
|
|
2509
|
+
});
|
|
2510
|
+
}
|
|
2511
|
+
async function watchEvents(out, key, filters, after) {
|
|
2512
|
+
const stopped = new AbortController();
|
|
2513
|
+
const stopListening = out.io.onInterrupt(() => stopped.abort());
|
|
2514
|
+
let lastId;
|
|
2515
|
+
let cursor = after;
|
|
2516
|
+
let retryMs = FIRST_RETRY_MS;
|
|
2517
|
+
let failures = 0;
|
|
2518
|
+
let connected = false;
|
|
2519
|
+
let tooLarge;
|
|
2520
|
+
try {
|
|
2521
|
+
while (!stopped.signal.aborted) {
|
|
2522
|
+
const connection = new AbortController();
|
|
2523
|
+
const hangUp = () => connection.abort();
|
|
2524
|
+
stopped.signal.addEventListener("abort", hangUp, { once: true });
|
|
2525
|
+
let dropped;
|
|
2526
|
+
try {
|
|
2527
|
+
const response = await openEventStream(STREAM_PATH, {
|
|
2528
|
+
key,
|
|
2529
|
+
signal: connection.signal,
|
|
2530
|
+
...lastId === void 0 ? {} : { lastEventId: lastId },
|
|
2531
|
+
query: { ...filters, after: lastId === void 0 ? cursor : void 0 }
|
|
2532
|
+
});
|
|
2533
|
+
connected = true;
|
|
2534
|
+
try {
|
|
2535
|
+
for await (const event of readEventStream(response, { idleTimeoutMs: IDLE_TIMEOUT_MS })) {
|
|
2536
|
+
if (stopped.signal.aborted) return;
|
|
2537
|
+
if (event.retry !== void 0) retryMs = Math.min(Math.max(event.retry, MIN_RETRY_MS), MAX_RETRY_MS);
|
|
2538
|
+
if (event.data === null) {
|
|
2539
|
+
lastId = event.id ?? void 0;
|
|
2540
|
+
cursor = void 0;
|
|
2541
|
+
continue;
|
|
2542
|
+
}
|
|
2543
|
+
const apiEvent = parseEvent(event.data);
|
|
2544
|
+
if (apiEvent === void 0) out.warn("invalid_event", "Skipped an event that is not an event object.");
|
|
2545
|
+
else out.line(apiEvent, () => eventLine(apiEvent));
|
|
2546
|
+
lastId = event.id ?? apiEvent?.id ?? lastId;
|
|
2547
|
+
failures = 0;
|
|
2548
|
+
tooLarge = void 0;
|
|
2549
|
+
}
|
|
2550
|
+
} catch (error) {
|
|
2551
|
+
dropped = error;
|
|
2552
|
+
}
|
|
2553
|
+
} catch (error) {
|
|
2554
|
+
if (stopped.signal.aborted) return;
|
|
2555
|
+
if (error instanceof CheslyApiError && error.code === "events_expired") {
|
|
2556
|
+
out.warn(
|
|
2557
|
+
"events_expired",
|
|
2558
|
+
`Events after ${lastId ?? cursor ?? "that point"} are no longer kept: they are older than your plan's event history. Watching new events from now.`
|
|
2559
|
+
);
|
|
2560
|
+
lastId = void 0;
|
|
2561
|
+
cursor = void 0;
|
|
2562
|
+
continue;
|
|
2563
|
+
}
|
|
2564
|
+
if (!connected || !mayReconnect(error)) throw error;
|
|
2565
|
+
dropped = error;
|
|
2566
|
+
} finally {
|
|
2567
|
+
stopped.signal.removeEventListener("abort", hangUp);
|
|
2568
|
+
connection.abort();
|
|
2569
|
+
}
|
|
2570
|
+
if (stopped.signal.aborted) return;
|
|
2571
|
+
if (dropped instanceof EventStreamLimitError && dropped.eventId !== null) {
|
|
2572
|
+
if (dropped.eventId === tooLarge) {
|
|
2573
|
+
out.warn(
|
|
2574
|
+
"event_too_large",
|
|
2575
|
+
`Skipped event ${dropped.eventId}: it is over the size watch reads (a line over 1 MiB or an event over 4 MiB).`,
|
|
2576
|
+
{ id: dropped.eventId }
|
|
2577
|
+
);
|
|
2578
|
+
lastId = dropped.eventId;
|
|
2579
|
+
cursor = void 0;
|
|
2580
|
+
tooLarge = void 0;
|
|
2581
|
+
} else {
|
|
2582
|
+
tooLarge = dropped.eventId;
|
|
2583
|
+
}
|
|
2584
|
+
} else {
|
|
2585
|
+
tooLarge = void 0;
|
|
2586
|
+
}
|
|
2587
|
+
const waitMs = Math.max(backoff(retryMs, failures++), retryAfterMs(dropped));
|
|
2588
|
+
out.warn("reconnecting", `The event stream ${dropReason(dropped)}. Reconnecting in ${Math.round(waitMs / 1e3)} s.`, {
|
|
2589
|
+
retry_in_ms: waitMs
|
|
2590
|
+
});
|
|
2591
|
+
await sleep(waitMs, stopped.signal);
|
|
2592
|
+
}
|
|
2593
|
+
} finally {
|
|
2594
|
+
stopListening();
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
function parseEvent(data) {
|
|
2598
|
+
try {
|
|
2599
|
+
const value = JSON.parse(data);
|
|
2600
|
+
return isApiEvent(value) ? value : void 0;
|
|
2601
|
+
} catch {
|
|
2602
|
+
return void 0;
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
function mayReconnect(error) {
|
|
2606
|
+
if (isTransient(error)) return true;
|
|
2607
|
+
return error instanceof CheslyApiError && error.status === 429 && error.code !== "too_many_streams";
|
|
2608
|
+
}
|
|
2609
|
+
function backoff(baseMs, failures) {
|
|
2610
|
+
const nominal = Math.min(MAX_RETRY_MS, baseMs * 2 ** failures);
|
|
2611
|
+
return Math.min(MAX_RETRY_MS, Math.round(nominal * (0.8 + Math.random() * 0.4)));
|
|
2612
|
+
}
|
|
2613
|
+
function retryAfterMs(error) {
|
|
2614
|
+
return error instanceof CheslyApiError && error.retryAfter !== void 0 ? error.retryAfter * 1e3 : 0;
|
|
2615
|
+
}
|
|
2616
|
+
function dropReason(error) {
|
|
2617
|
+
if (error === void 0) return "ended";
|
|
2618
|
+
if (error instanceof IdleTimeoutError) return `went quiet for ${error.ms / 1e3} s`;
|
|
2619
|
+
if (error instanceof EventStreamLimitError) return `sent a ${error.part} over the size limit`;
|
|
2620
|
+
if (error instanceof CheslyApiError) return `was refused (${error.status} ${error.code})`;
|
|
2621
|
+
if (error instanceof CheslyNetworkError) return `could not reconnect (${error.message})`;
|
|
2622
|
+
return "dropped";
|
|
2623
|
+
}
|
|
2624
|
+
|
|
2625
|
+
// src/commands/webhooks.ts
|
|
2626
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
2627
|
+
import { Option } from "commander";
|
|
2628
|
+
var KEY_HELP = "do it at most once per key, however often the command runs (default: a new key)";
|
|
2629
|
+
function registerWebhooks(program, io) {
|
|
2630
|
+
const webhooks = program.command("webhooks").description("Manage the URLs Chesly posts your events to, signed (Standard Webhooks)").addHelpText(
|
|
2631
|
+
"after",
|
|
2632
|
+
`
|
|
2633
|
+
Chesly POSTs each event to your URL as JSON ({ "id", "type", "timestamp",
|
|
2634
|
+
"data" }), signed with the webhook's secret: verify the webhook-id,
|
|
2635
|
+
webhook-timestamp and webhook-signature headers before you trust a body,
|
|
2636
|
+
for example with the standardwebhooks package:
|
|
2637
|
+
new Webhook(secret).verify(rawBody, headers)
|
|
2638
|
+
Failed deliveries are retried for about 28 hours. Email events go only to
|
|
2639
|
+
webhooks whose --networks names email.
|
|
2640
|
+
|
|
2641
|
+
Examples:
|
|
2642
|
+
chesly webhooks create https://example.com/chesly --types message.received
|
|
2643
|
+
chesly webhooks list`
|
|
2644
|
+
);
|
|
2645
|
+
webhooks.command("list").description("List your webhooks (never their secrets)").addHelpText("after", `
|
|
2646
|
+
Prints the API's { "webhooks": [...] }, or a table in a terminal.
|
|
2647
|
+
|
|
2648
|
+
Example:
|
|
2649
|
+
chesly webhooks list --json`).action(async (_options, command) => {
|
|
2650
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2651
|
+
const { key } = await requireKey();
|
|
2652
|
+
const answer = expectAnswer(await apiRequest("/v1/webhooks", { key }), isWebhookList, "a list of webhooks");
|
|
2653
|
+
out.result(
|
|
2654
|
+
answer,
|
|
2655
|
+
() => answer.webhooks.length === 0 ? "No webhooks. chesly webhooks create <url> adds one." : webhookTable(answer.webhooks)
|
|
2656
|
+
);
|
|
2657
|
+
});
|
|
2658
|
+
webhooks.command("create").description("Add a webhook; its signing secret is printed once").argument("<url>", "an https:// URL that answers 2xx; Chesly POSTs your events to it").option("--types <a,b>", "only these event types (default: all of them)", parseList).option("--networks <a,b>", "only these networks (default: all but email; name email to get it)", parseList).addOption(
|
|
2659
|
+
new Option("--payload <payload>", "full: the event with its data; ids: only the IDs (default full)").choices([
|
|
2660
|
+
"full",
|
|
2661
|
+
"ids"
|
|
2662
|
+
])
|
|
2663
|
+
).option("--description <text>", "a note to tell your webhooks apart").option("--idempotency-key <key>", KEY_HELP, parseIdempotencyKey).addHelpText(
|
|
2664
|
+
"after",
|
|
2665
|
+
`
|
|
2666
|
+
Prints the new webhook with its secret (whsec_\u2026): the API's JSON, or
|
|
2667
|
+
"Secret (shown once): whsec_\u2026" in a terminal. Keep the secret: no later
|
|
2668
|
+
answer shows it, and chesly webhooks rotate replaces it.
|
|
2669
|
+
|
|
2670
|
+
Example:
|
|
2671
|
+
chesly webhooks create https://example.com/chesly --types message.received,message.sent`
|
|
2672
|
+
).action(async (url, options, command) => {
|
|
2673
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2674
|
+
const { key } = await requireKey();
|
|
2675
|
+
const answer = await idempotentPost("/v1/webhooks", {
|
|
2676
|
+
key,
|
|
2677
|
+
idempotencyKey: options.idempotencyKey ?? randomUUID2(),
|
|
2678
|
+
body: {
|
|
2679
|
+
url,
|
|
2680
|
+
...options.types === void 0 ? {} : { event_types: options.types },
|
|
2681
|
+
...options.networks === void 0 ? {} : { networks: options.networks },
|
|
2682
|
+
...options.payload === void 0 ? {} : { payload: options.payload },
|
|
2683
|
+
...options.description === void 0 ? {} : { description: options.description }
|
|
2684
|
+
}
|
|
2685
|
+
});
|
|
2686
|
+
const webhook = expectAnswer(answer, isCreatedWebhook, "a new webhook with its secret");
|
|
2687
|
+
out.result(webhook, () => createdWebhook(webhook));
|
|
2688
|
+
});
|
|
2689
|
+
webhooks.command("delete").description("Delete a webhook; its pending deliveries are dropped").argument("<id>", "the webhook: a wh_ ID from chesly webhooks list").addHelpText("after", '\nPrints { "id", "deleted": true }, or "Deleted <id>." in a terminal. An unknown ID exits 4.\n\nExample:\n chesly webhooks delete wh_3kTq9ZxLmP2vR8sN4bYc').action(async (id, _options, command) => {
|
|
2690
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2691
|
+
const { key } = await requireKey();
|
|
2692
|
+
await apiRequest(webhookPath(id), { method: "DELETE", key });
|
|
2693
|
+
out.result({ id, deleted: true }, () => `Deleted ${id}.`);
|
|
2694
|
+
});
|
|
2695
|
+
webhooks.command("rotate").description("Replace a webhook's secret; the old one keeps signing for 24 hours").argument("<id>", "the webhook: a wh_ ID from chesly webhooks list").option("--idempotency-key <key>", KEY_HELP, parseIdempotencyKey).addHelpText(
|
|
2696
|
+
"after",
|
|
2697
|
+
`
|
|
2698
|
+
Prints { "secret", "previous_secret_expires_at" }, or the new secret in a
|
|
2699
|
+
terminal. Deliveries carry both signatures until the old secret expires, so
|
|
2700
|
+
switch your receiver over within 24 hours. A retried rotate (the same
|
|
2701
|
+
--idempotency-key) shows the same new secret again instead of rotating twice.
|
|
2702
|
+
|
|
2703
|
+
Example:
|
|
2704
|
+
chesly webhooks rotate wh_3kTq9ZxLmP2vR8sN4bYc`
|
|
2705
|
+
).action(async (id, options, command) => {
|
|
2706
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2707
|
+
const { key } = await requireKey();
|
|
2708
|
+
const answer = await idempotentPost(`${webhookPath(id)}/rotate_secret`, {
|
|
2709
|
+
key,
|
|
2710
|
+
idempotencyKey: options.idempotencyKey ?? randomUUID2()
|
|
2711
|
+
});
|
|
2712
|
+
const rotated = expectAnswer(answer, isRotatedSecret, "a new secret");
|
|
2713
|
+
out.result(rotated, () => {
|
|
2714
|
+
const until = formatWhen(rotated.previous_secret_expires_at, { time: true });
|
|
2715
|
+
const old = until === "" ? "The old secret no longer signs." : `The old secret keeps working until ${until}.`;
|
|
2716
|
+
return `Secret (shown once): ${oneLine(rotated.secret)}
|
|
2717
|
+
${old}`;
|
|
2718
|
+
});
|
|
2719
|
+
});
|
|
2720
|
+
webhooks.command("test").description("Send a webhook a test event (type webhook.test)").argument("<id>", "the webhook: a wh_ ID from chesly webhooks list").option("--idempotency-key <key>", KEY_HELP, parseIdempotencyKey).addHelpText(
|
|
2721
|
+
"after",
|
|
2722
|
+
'\nPrints { "delivery_id" }; chesly webhooks deliveries <id> then shows how it went.\n\nExample:\n chesly webhooks test wh_3kTq9ZxLmP2vR8sN4bYc'
|
|
2723
|
+
).action(async (id, options, command) => {
|
|
2724
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2725
|
+
const { key } = await requireKey();
|
|
2726
|
+
const answer = await idempotentPost(`${webhookPath(id)}/test`, {
|
|
2727
|
+
key,
|
|
2728
|
+
idempotencyKey: options.idempotencyKey ?? randomUUID2()
|
|
2729
|
+
});
|
|
2730
|
+
const queued = expectAnswer(answer, isTestDelivery, "a test delivery");
|
|
2731
|
+
out.result(queued, () => `Queued a test event: delivery ${oneLine(queued.delivery_id, 64)}`);
|
|
2732
|
+
if (!out.json) out.note(`See how it went: chesly webhooks deliveries ${shellQuote(id)}`);
|
|
2733
|
+
});
|
|
2734
|
+
webhooks.command("deliveries").description("A webhook's deliveries, newest first: status, attempts and the endpoint's answer").argument("<id>", "the webhook: a wh_ ID from chesly webhooks list").addOption(new Option("--status <status>", "only deliveries in this state").choices(["pending", "succeeded", "failed", "discarded"])).option("--limit <n>", "how many, 1 to 100 (default 50)", parseLimit).option("--cursor <cursor>", "older deliveries: next_cursor from the page before").addHelpText(
|
|
2735
|
+
"after",
|
|
2736
|
+
`
|
|
2737
|
+
Prints the API's { "deliveries": [...], "next_cursor" }, or a table in a terminal.
|
|
2738
|
+
|
|
2739
|
+
Example:
|
|
2740
|
+
chesly webhooks deliveries wh_3kTq9ZxLmP2vR8sN4bYc --status failed`
|
|
2741
|
+
).action(async (id, options, command) => {
|
|
2742
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2743
|
+
const { key } = await requireKey();
|
|
2744
|
+
const answer = await apiRequest(`${webhookPath(id)}/deliveries`, {
|
|
2745
|
+
key,
|
|
2746
|
+
query: { status: options.status, limit: options.limit, cursor: options.cursor }
|
|
2747
|
+
});
|
|
2748
|
+
const page = expectAnswer(answer, isDeliveryPage, "a page of deliveries");
|
|
2749
|
+
out.result(page, () => page.deliveries.length === 0 ? "No deliveries." : deliveryTable(page.deliveries));
|
|
2750
|
+
if (!out.json && page.next_cursor) {
|
|
2751
|
+
const flags = [
|
|
2752
|
+
options.status ? `--status ${options.status}` : "",
|
|
2753
|
+
options.limit ? `--limit ${options.limit}` : "",
|
|
2754
|
+
`--cursor ${shellQuote(oneLine(page.next_cursor))}`
|
|
2755
|
+
];
|
|
2756
|
+
out.note(`Older deliveries: chesly webhooks deliveries ${shellQuote(id)} ${flags.filter(Boolean).join(" ")}`);
|
|
2757
|
+
}
|
|
2758
|
+
});
|
|
2759
|
+
}
|
|
2760
|
+
function webhookPath(id) {
|
|
2761
|
+
return `/v1/webhooks/${encodeURIComponent(id.trim())}`;
|
|
2762
|
+
}
|
|
2763
|
+
|
|
2764
|
+
// src/commands/whoami.ts
|
|
2765
|
+
function registerWhoami(program, io) {
|
|
2766
|
+
program.command("whoami").description("Show the API key in use: its name, scope, API version and the plan's limits").addHelpText(
|
|
2767
|
+
"after",
|
|
2768
|
+
`
|
|
2769
|
+
Prints the API's GET /v1/me answer as JSON, or a table in a terminal: the
|
|
2770
|
+
key's name, ID and scope, the API version, the plan's limits, and where the
|
|
2771
|
+
key in use comes from (masked). chesly usage shows the plan, and this
|
|
2772
|
+
period's calls and transcription minutes.
|
|
2773
|
+
|
|
2774
|
+
Example:
|
|
2775
|
+
chesly whoami --json`
|
|
2776
|
+
).action(async (_options, command) => {
|
|
2777
|
+
const out = new Output(io, command.optsWithGlobals());
|
|
2778
|
+
const { key, source } = await requireKey();
|
|
2779
|
+
const me = await apiRequest("/v1/me", { key });
|
|
2780
|
+
if (!isMe(me)) throw new CliError("invalid_response", "The API sent no details for this key.");
|
|
2781
|
+
out.result(me, () => describeMe(me, key, source));
|
|
2782
|
+
});
|
|
2783
|
+
}
|
|
2784
|
+
function describeMe(me, key, source) {
|
|
2785
|
+
const limits = limitsLine(me.limits);
|
|
2786
|
+
return formatTable([
|
|
2787
|
+
["Key", `${oneLine(me.key?.name ?? "", 100)} (${oneLine(String(me.key?.id ?? ""), 40)})`],
|
|
2788
|
+
["Scope", scopeLabel(me.key?.scope)],
|
|
2789
|
+
["API version", oneLine(String(me.key?.api_version ?? ""), 20)],
|
|
2790
|
+
...limits === "" ? [] : [["Limits", limits]],
|
|
2791
|
+
["Using", `${maskKey(key)} from ${describeSource(source)}`]
|
|
2792
|
+
]);
|
|
2793
|
+
}
|
|
2794
|
+
|
|
2795
|
+
// src/cli.ts
|
|
2796
|
+
var HELP_FOOTER = `
|
|
2797
|
+
Signing in:
|
|
2798
|
+
chesly login keeps the key in your OS keychain, or in
|
|
2799
|
+
~/.config/chesly/credentials.json (mode 0600) where there is no keychain.
|
|
2800
|
+
CHESLY_API_KEY, when set, wins over the stored key.
|
|
2801
|
+
|
|
2802
|
+
Output:
|
|
2803
|
+
Tables in a terminal. JSON when stdout is piped, or with --json: the API's
|
|
2804
|
+
JSON as is. Errors go to stderr, as one JSON line in JSON mode.
|
|
2805
|
+
Nothing ever prompts.
|
|
2806
|
+
|
|
2807
|
+
Chats:
|
|
2808
|
+
${indent(CHAT_ARGUMENT_HELP, " ")}
|
|
2809
|
+
|
|
2810
|
+
Networks:
|
|
2811
|
+
chats, catchup and search take --network <name> to list or search one
|
|
2812
|
+
network; read and send take it to look a chat name up there. Email is left
|
|
2813
|
+
out unless you name it, as in chesly chats --network email.
|
|
2814
|
+
|
|
2815
|
+
Exit codes:
|
|
2816
|
+
0 ok
|
|
2817
|
+
1 error
|
|
2818
|
+
2 usage
|
|
2819
|
+
3 not signed in
|
|
2820
|
+
4 not found or ambiguous
|
|
2821
|
+
5 not final, come back to it: rate limited (429), an upload that took too
|
|
2822
|
+
long (408), briefly unavailable (502, 503, 504), a first attempt still
|
|
2823
|
+
running (409), or a send the network didn't confirm (check the chat
|
|
2824
|
+
before sending again); retry_after, when there is one, says when
|
|
2825
|
+
6 payment required: an API plan is needed, or this period's transcription
|
|
2826
|
+
minutes are used up
|
|
2827
|
+
|
|
2828
|
+
Examples:
|
|
2829
|
+
chesly catchup your unread chats and their latest messages
|
|
2830
|
+
chesly send "Mom" - --wait <<'EOF' the text on stdin, exactly as written
|
|
2831
|
+
On my way
|
|
2832
|
+
EOF
|
|
2833
|
+
chesly watch --json live events, one JSON object a line
|
|
2834
|
+
chesly chats --network email your email threads
|
|
2835
|
+
|
|
2836
|
+
Environment:
|
|
2837
|
+
CHESLY_API_KEY the API key to use instead of the stored one
|
|
2838
|
+
CHESLY_API_URL the API base URL (default https://api.chesly.app)`;
|
|
2839
|
+
function buildProgram(io, json) {
|
|
2840
|
+
const program = new Command("chesly").description("Chesly from the terminal: your chats, for you and your agents.").version(VERSION).option("--json", "print the API's JSON (the default when stdout isn't a terminal)").configureOutput({
|
|
2841
|
+
writeOut: io.out,
|
|
2842
|
+
writeErr: io.err,
|
|
2843
|
+
outputError: (message, write) => write(formatUsageError(message, json))
|
|
2844
|
+
}).configureHelp({ showGlobalOptions: true }).exitOverride().addHelpText("after", HELP_FOOTER);
|
|
2845
|
+
if (!json) program.showHelpAfterError("(run chesly --help for usage)");
|
|
2846
|
+
if (json) {
|
|
2847
|
+
program.on("afterAllHelp", (context) => {
|
|
2848
|
+
if (context.error) context.write(formatUsageError(`Give a command; ${commandPath(context.command)} --help lists them.`, true));
|
|
2849
|
+
});
|
|
2850
|
+
}
|
|
2851
|
+
registerLogin(program, io);
|
|
2852
|
+
registerLogout(program, io);
|
|
2853
|
+
registerWhoami(program, io);
|
|
2854
|
+
registerKey(program, io);
|
|
2855
|
+
registerAccounts(program, io);
|
|
2856
|
+
registerChats(program, io);
|
|
2857
|
+
registerRead(program, io);
|
|
2858
|
+
registerSearch(program, io);
|
|
2859
|
+
registerCatchup(program, io);
|
|
2860
|
+
registerSend(program, io);
|
|
2861
|
+
registerWatch(program, io);
|
|
2862
|
+
registerWebhooks(program, io);
|
|
2863
|
+
registerKeys(program, io);
|
|
2864
|
+
registerUsage(program, io);
|
|
2865
|
+
return program;
|
|
2866
|
+
}
|
|
2867
|
+
function commandPath(command) {
|
|
2868
|
+
const names = [];
|
|
2869
|
+
for (let current = command; current !== null; current = current.parent) names.unshift(current.name());
|
|
2870
|
+
return names.join(" ");
|
|
2871
|
+
}
|
|
2872
|
+
async function run(argv, io = processIo()) {
|
|
2873
|
+
const json = argv.includes("--json") || !io.isTTY;
|
|
2874
|
+
const program = buildProgram(io, json);
|
|
2875
|
+
try {
|
|
2876
|
+
await program.parseAsync([...argv], { from: "user" });
|
|
2877
|
+
return EXIT.OK;
|
|
2878
|
+
} catch (error) {
|
|
2879
|
+
return reportError(error, io, json);
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
|
|
2883
|
+
// src/index.ts
|
|
2884
|
+
process.stdout.on("error", (error) => {
|
|
2885
|
+
if (error.code === "EPIPE") process.exit(0);
|
|
2886
|
+
throw error;
|
|
2887
|
+
});
|
|
2888
|
+
process.exitCode = await run(process.argv.slice(2));
|
|
2889
|
+
if (unfinishedKeychainCalls() > 0) {
|
|
2890
|
+
let streams = 2;
|
|
2891
|
+
const flushed = () => {
|
|
2892
|
+
if (--streams === 0) process.exit();
|
|
2893
|
+
};
|
|
2894
|
+
process.stdout.write("", flushed);
|
|
2895
|
+
process.stderr.write("", flushed);
|
|
2896
|
+
}
|