soltask 0.0.0-stage → 0.1.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/dist/client.js ADDED
@@ -0,0 +1,879 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import { isNonLoopbackHttp } from "./config.js";
3
+ import { CliError, EXIT_AUTH, EXIT_RUNTIME, exitCodeForStatus } from "./errors.js";
4
+ import { errOut } from "./output.js";
5
+ import { cellText, errorCode, isObject, nonEmptyString, oneLine, truncate } from "./util.js";
6
+ import { PROGRAM, PROTOCOL_VERSION, VERSION } from "./version.js";
7
+ export const UNLOCK_HEADER = "X-Task-Board-Key";
8
+ export const REQUEST_TIMEOUT_MS = 30_000;
9
+ export const MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
10
+ export const MAX_RATE_LIMIT_RETRIES = 2;
11
+ export const MAX_RETRY_SLEEP_MS = 5_000;
12
+ export const DEFAULT_WAIT_LIVE_TIMEOUT_MS = 15_000;
13
+ export const WAIT_LIVE_POLL_MS = 250;
14
+ // Headers a browser sends to say which page a request came from. A CLI client is not a page, so callers never send them.
15
+ const FORBIDDEN_REQUEST_HEADERS = /^(?:origin|sec-fetch-.*)$/i;
16
+ const MIN_VERSION_HEADER = /^x-(?:[a-z0-9-]+-)?cli-min-version$/i;
17
+ const RETRYABLE_HTTP_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
18
+ const TLS_ERROR_PATTERN = /(?:CERT_|ERR_TLS_|UNABLE_TO_VERIFY|SELF_SIGNED|DEPTH_ZERO|HOSTNAME_MISMATCH|ERR_SSL_)/i;
19
+ function defaultSleep(ms, signal) {
20
+ return sleep(ms, undefined, { signal });
21
+ }
22
+ function parseRetryAfter(header) {
23
+ if (header === undefined || !/^\s*\d+(?:\.\d+)?\s*$/.test(header)) {
24
+ return null;
25
+ }
26
+ const seconds = Number(header);
27
+ return Number.isFinite(seconds) ? seconds : null;
28
+ }
29
+ /**
30
+ * Milliseconds to wait for a numeric `Retry-After` (seconds); null when absent, non-numeric, or > `MAX_RETRY_SLEEP_MS`.
31
+ */
32
+ export function retryDelayMs(header) {
33
+ const seconds = parseRetryAfter(header);
34
+ if (seconds === null) {
35
+ return null;
36
+ }
37
+ const ms = seconds * 1000;
38
+ return ms > MAX_RETRY_SLEEP_MS ? null : ms;
39
+ }
40
+ const IMF_FIXDATE = /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/;
41
+ function retryAfterSeconds(header) {
42
+ const parsed = parseRetryAfter(header);
43
+ if (parsed !== null) {
44
+ const seconds = Math.ceil(parsed);
45
+ return Number.isSafeInteger(seconds) ? seconds : null;
46
+ }
47
+ if (header === undefined) {
48
+ return null;
49
+ }
50
+ const trimmed = header.trim();
51
+ if (!IMF_FIXDATE.test(trimmed)) {
52
+ return null;
53
+ }
54
+ const timestamp = Date.parse(trimmed);
55
+ if (!Number.isFinite(timestamp)) {
56
+ return null;
57
+ }
58
+ const delta = Math.ceil((timestamp - Date.now()) / 1000);
59
+ return delta > 0 && Number.isSafeInteger(delta) ? delta : null;
60
+ }
61
+ function retryAfterFromBody(value) {
62
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
63
+ return null;
64
+ }
65
+ const seconds = Math.ceil(value);
66
+ return Number.isSafeInteger(seconds) ? seconds : null;
67
+ }
68
+ /** Splits a comma-joined `Set-Cookie` header value without breaking `Expires=Wed, 21 Oct ...` dates. */
69
+ function splitCombinedSetCookie(combined) {
70
+ const parts = [];
71
+ let start = 0;
72
+ let inExpires = false;
73
+ for (let i = 0; i < combined.length; i += 1) {
74
+ if (combined.slice(i, i + 8).toLowerCase() === "expires=") {
75
+ inExpires = true;
76
+ }
77
+ else if (combined[i] === ";") {
78
+ inExpires = false;
79
+ }
80
+ else if (combined[i] === "," && !inExpires) {
81
+ const rest = combined.slice(i + 1).trimStart();
82
+ if (/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+=/.test(rest)) {
83
+ parts.push(combined.slice(start, i).trim());
84
+ start = i + 1;
85
+ }
86
+ }
87
+ }
88
+ const tail = combined.slice(start).trim();
89
+ if (tail !== "") {
90
+ parts.push(tail);
91
+ }
92
+ return parts;
93
+ }
94
+ function parseSingleSetCookie(header) {
95
+ const segments = header.split(";");
96
+ const first = segments[0]?.trim() ?? "";
97
+ const eq = first.indexOf("=");
98
+ if (eq <= 0) {
99
+ return null;
100
+ }
101
+ const name = first.slice(0, eq).trim();
102
+ const value = first.slice(eq + 1).trim();
103
+ if (name === "") {
104
+ return null;
105
+ }
106
+ const maxAgeZero = segments.slice(1).some((attr) => /^max-age\s*=\s*0$/i.test(attr.trim()));
107
+ return { name, value, cleared: value === "" || maxAgeZero };
108
+ }
109
+ function isStringArray(value) {
110
+ return Array.isArray(value);
111
+ }
112
+ /**
113
+ * Extracts a `Set-Cookie` entry from `Headers` (via `getSetCookie()` when available) or raw header strings.
114
+ * Prefers `preferredName`, then any `task_board_session*` cookie, then the first valid cookie.
115
+ */
116
+ export function parseSetCookie(headers, preferredName) {
117
+ let rawHeaders;
118
+ if (isStringArray(headers)) {
119
+ rawHeaders = [...headers];
120
+ }
121
+ else {
122
+ if (typeof headers.getSetCookie === "function") {
123
+ rawHeaders = headers.getSetCookie();
124
+ }
125
+ else {
126
+ const combined = headers.get("set-cookie");
127
+ rawHeaders = combined === null ? [] : splitCombinedSetCookie(combined);
128
+ }
129
+ }
130
+ const parsed = [];
131
+ for (const raw of rawHeaders) {
132
+ for (const piece of splitCombinedSetCookie(raw)) {
133
+ const entry = parseSingleSetCookie(piece);
134
+ if (entry !== null) {
135
+ parsed.push(entry);
136
+ }
137
+ }
138
+ }
139
+ if (parsed.length === 0) {
140
+ return null;
141
+ }
142
+ if (preferredName !== undefined) {
143
+ const exact = parsed.find((cookie) => cookie.name === preferredName);
144
+ if (exact !== undefined) {
145
+ return exact;
146
+ }
147
+ }
148
+ const sessionCookie = parsed.find((cookie) => cookie.name.startsWith("task_board_session"));
149
+ return sessionCookie ?? parsed[0] ?? null;
150
+ }
151
+ /** Redacts userinfo, query parameters, and fragments from a redirect Location before showing it to the user. */
152
+ function redactLocation(location, baseUrl) {
153
+ const cleaned = oneLine(location).trim();
154
+ if (cleaned === "") {
155
+ return "";
156
+ }
157
+ try {
158
+ const resolved = new URL(cleaned, baseUrl);
159
+ if (resolved.protocol === "http:" || resolved.protocol === "https:") {
160
+ return `${resolved.protocol}//${resolved.host}${resolved.pathname}`;
161
+ }
162
+ return `${resolved.protocol}//...`;
163
+ }
164
+ catch {
165
+ return cleaned.replace(/[?#].*$/, "").replace(/^([a-z][a-z0-9+.-]*:\/\/+)[^\s/?#]*@/i, "$1***@");
166
+ }
167
+ }
168
+ /** A short, safe description of a body that is not JSON: never the raw page, at most one trimmed line. */
169
+ export function describeNonJson(text, contentType) {
170
+ const looksHtml = /html/i.test(contentType) || /^\s*<(?:!doctype|html|head|body)/i.test(text);
171
+ let snippet;
172
+ if (looksHtml) {
173
+ const heading = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(text) ?? /<h1[^>]*>([\s\S]*?)<\/h1>/i.exec(text);
174
+ snippet = heading?.[1] ?? text.replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ");
175
+ }
176
+ else {
177
+ snippet = text;
178
+ }
179
+ const plain = oneLine(snippet.replace(/<[^>]*>/g, " "))
180
+ .replace(/&nbsp;/g, " ")
181
+ .replace(/&lt;/g, "<")
182
+ .replace(/&gt;/g, ">")
183
+ .replace(/&quot;/g, '"')
184
+ .replace(/&#39;/g, "'")
185
+ .replace(/&amp;/g, "&")
186
+ .replace(/\s+/g, " ")
187
+ .trim();
188
+ let kind;
189
+ if (looksHtml) {
190
+ kind = "an HTML page";
191
+ }
192
+ else if (contentType !== "") {
193
+ const mime = contentType.split(";")[0]?.trim() ?? "non-JSON";
194
+ if (plain === "" && text.trim() === "") {
195
+ kind = `an empty ${mime} body`;
196
+ }
197
+ else {
198
+ const article = /^[aeiou]/i.test(mime) ? "an" : "a";
199
+ kind = `${article} ${mime} body`;
200
+ }
201
+ }
202
+ else {
203
+ kind = "a non-JSON body";
204
+ }
205
+ return plain === "" ? kind : `${kind}: "${truncate(plain, 160)}"`;
206
+ }
207
+ function causeOf(err) {
208
+ return err instanceof Error ? err.cause : undefined;
209
+ }
210
+ function causeCode(cause) {
211
+ const direct = errorCode(cause);
212
+ if (direct !== undefined) {
213
+ return direct;
214
+ }
215
+ if (typeof cause === "object" && cause !== null && "errors" in cause && Array.isArray(cause.errors)) {
216
+ for (const inner of cause.errors) {
217
+ const code = causeCode(inner);
218
+ if (code !== undefined) {
219
+ return code;
220
+ }
221
+ }
222
+ }
223
+ return undefined;
224
+ }
225
+ function parseStreamFrame(eventName, dataText) {
226
+ if (eventName !== "task" && eventName !== "typing" && eventName !== "status") {
227
+ return null;
228
+ }
229
+ let parsed;
230
+ try {
231
+ parsed = JSON.parse(dataText);
232
+ }
233
+ catch {
234
+ return null;
235
+ }
236
+ if (!isObject(parsed)) {
237
+ return null;
238
+ }
239
+ if (eventName === "task") {
240
+ const community = nonEmptyString(parsed["community"]);
241
+ const root = nonEmptyString(parsed["root"]);
242
+ const version = parsed["version"];
243
+ if (community === undefined || root === undefined || typeof version !== "number") {
244
+ return null;
245
+ }
246
+ return { event: "task", data: { community, root, version } };
247
+ }
248
+ if (eventName === "typing") {
249
+ const community = nonEmptyString(parsed["community"]);
250
+ const channel = nonEmptyString(parsed["channel"]);
251
+ const pubkey = nonEmptyString(parsed["pubkey"]);
252
+ const root = parsed["root"] === null || typeof parsed["root"] === "string" ? parsed["root"] : null;
253
+ if (community === undefined || channel === undefined || pubkey === undefined) {
254
+ return null;
255
+ }
256
+ return { event: "typing", data: { community, channel, root, pubkey } };
257
+ }
258
+ const community = nonEmptyString(parsed["community"]);
259
+ const state = parsed["state"];
260
+ const degradedSince = parsed["degradedSince"];
261
+ if (community === undefined ||
262
+ (state !== "connecting" && state !== "live" && state !== "degraded" && state !== "closed") ||
263
+ (degradedSince !== null && typeof degradedSince !== "number")) {
264
+ return null;
265
+ }
266
+ return { event: "status", data: { community, state, degradedSince } };
267
+ }
268
+ export class ApiClient {
269
+ serverUrl;
270
+ currentSession;
271
+ timeoutMs;
272
+ maxResponseBytes;
273
+ missingAuthHint;
274
+ onCookieRenewed;
275
+ fetchFn;
276
+ sleepFn;
277
+ warnedCleartext = false;
278
+ warnedProtocol = false;
279
+ minProtocolRequired = null;
280
+ constructor(serverUrl, session = null, options = {}) {
281
+ this.serverUrl = serverUrl.replace(/\/+$/, "");
282
+ this.currentSession = session === null ? null : { ...session };
283
+ this.timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
284
+ this.maxResponseBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES;
285
+ this.missingAuthHint = options.missingAuthHint;
286
+ this.onCookieRenewed = options.onCookieRenewed;
287
+ this.fetchFn = options.fetchFn ?? fetch;
288
+ this.sleepFn = options.sleepFn ?? defaultSleep;
289
+ }
290
+ get session() {
291
+ return this.currentSession;
292
+ }
293
+ /** Higher protocol version advertised by the server's CLI min-version header, or null when compatible/absent. */
294
+ get requiredProtocolVersion() {
295
+ return this.minProtocolRequired;
296
+ }
297
+ checkProtocolHeader(headers) {
298
+ for (const [name, value] of Object.entries(headers)) {
299
+ if (!MIN_VERSION_HEADER.test(name) || !/^\s*\d+\s*$/.test(value)) {
300
+ continue;
301
+ }
302
+ const required = Number(value.trim());
303
+ if (Number.isSafeInteger(required) && required > PROTOCOL_VERSION) {
304
+ this.minProtocolRequired = Math.max(this.minProtocolRequired ?? 0, required);
305
+ if (!this.warnedProtocol) {
306
+ this.warnedProtocol = true;
307
+ errOut(`Warning: server requires CLI protocol v${required} (this ${PROGRAM} implements v${PROTOCOL_VERSION}); upgrade ${PROGRAM}.`);
308
+ }
309
+ }
310
+ }
311
+ }
312
+ maybeRenewCookie(setCookie, requireAuth) {
313
+ if (!requireAuth || setCookie === null || setCookie.cleared || setCookie.value === "") {
314
+ return;
315
+ }
316
+ if (this.currentSession?.mode === "cookie") {
317
+ this.currentSession = {
318
+ ...this.currentSession,
319
+ cookieName: setCookie.name,
320
+ cookieValue: setCookie.value,
321
+ };
322
+ }
323
+ this.onCookieRenewed?.({ name: setCookie.name, value: setCookie.value });
324
+ }
325
+ buildUrl(path, query) {
326
+ let url = `${this.serverUrl}${path}`;
327
+ if (query !== undefined) {
328
+ const params = new URLSearchParams();
329
+ for (const [key, value] of Object.entries(query)) {
330
+ if (value !== undefined && value !== null && value !== "") {
331
+ params.append(key, cellText(value));
332
+ }
333
+ }
334
+ const text = params.toString();
335
+ if (text !== "") {
336
+ url = `${url}?${text}`;
337
+ }
338
+ }
339
+ return url;
340
+ }
341
+ attachAuthHeaders(headers) {
342
+ if (this.currentSession === null) {
343
+ return;
344
+ }
345
+ if (!this.warnedCleartext && isNonLoopbackHttp(this.serverUrl)) {
346
+ this.warnedCleartext = true;
347
+ errOut(`Warning: sending session credentials over unencrypted HTTP (${this.serverUrl}); credentials travel in cleartext. Prefer HTTPS.`);
348
+ }
349
+ if (this.currentSession.mode === "cookie") {
350
+ headers["Cookie"] = `${this.currentSession.cookieName}=${this.currentSession.cookieValue}`;
351
+ headers[UNLOCK_HEADER] = this.currentSession.unlock;
352
+ }
353
+ else {
354
+ headers["Authorization"] = `Bearer ${this.currentSession.token}`;
355
+ }
356
+ }
357
+ rejectRedirect(status, locationHeader, url) {
358
+ const location = redactLocation(locationHeader ?? "", url);
359
+ const target = location === "" ? "" : ` to ${location}`;
360
+ const message = `The server answered with a redirect (HTTP ${status}${target}). ${PROGRAM} never follows redirects, so credentials cannot be sent to another ` +
361
+ "location; check the --server URL (scheme, host, and base path).";
362
+ return new CliError(message, {
363
+ exitCode: EXIT_RUNTIME,
364
+ payload: { ok: false, error: "redirect_refused", message },
365
+ });
366
+ }
367
+ async attempt(method, url, headers, payload, signal) {
368
+ const timeout = AbortSignal.timeout(this.timeoutMs);
369
+ try {
370
+ const response = await this.fetchFn(url, {
371
+ method,
372
+ headers,
373
+ ...(payload === undefined ? {} : { body: payload }),
374
+ redirect: "manual",
375
+ signal: signal === undefined ? timeout : AbortSignal.any([signal, timeout]),
376
+ });
377
+ if (response.status >= 300 && response.status < 400 && response.status !== 304) {
378
+ try {
379
+ await response.body?.cancel();
380
+ }
381
+ catch {
382
+ // Ignore stream-cancel errors so the redirect refusal is always reported.
383
+ }
384
+ throw this.rejectRedirect(response.status, response.headers.get("location"), url);
385
+ }
386
+ const responseHeaders = {};
387
+ response.headers.forEach((value, key) => {
388
+ responseHeaders[key.toLowerCase()] = value;
389
+ });
390
+ const preferredName = this.currentSession?.mode === "cookie" ? this.currentSession.cookieName : undefined;
391
+ const setCookie = parseSetCookie(response.headers, preferredName);
392
+ let bytes;
393
+ if (response.status === 204 || response.status === 205 || response.status === 304) {
394
+ try {
395
+ await response.body?.cancel();
396
+ }
397
+ catch {
398
+ // Empty-body status; ignore cancel errors.
399
+ }
400
+ bytes = Buffer.alloc(0);
401
+ }
402
+ else if (response.status >= 200 && response.status < 300) {
403
+ bytes = await this.readBounded(response, url);
404
+ }
405
+ else {
406
+ try {
407
+ bytes = await this.readBounded(response, url);
408
+ }
409
+ catch (err) {
410
+ if (signal?.aborted === true || timeout.aborted) {
411
+ throw err;
412
+ }
413
+ try {
414
+ await response.body?.cancel();
415
+ }
416
+ catch {
417
+ // Preserve the HTTP error status even when cancelling the unread error body fails.
418
+ }
419
+ bytes = Buffer.alloc(0);
420
+ }
421
+ }
422
+ return { status: response.status, statusText: response.statusText, headers: responseHeaders, setCookie, bytes };
423
+ }
424
+ catch (err) {
425
+ throw this.mapTransportError(err, method, url, signal, timeout);
426
+ }
427
+ }
428
+ async readBounded(response, url) {
429
+ const cap = this.maxResponseBytes;
430
+ const tooLarge = () => new CliError(`Response from ${url} exceeded ${cap} bytes`, { exitCode: EXIT_RUNTIME });
431
+ const contentLength = response.headers.get("content-length");
432
+ if (contentLength !== null && contentLength.trim() !== "") {
433
+ const declared = Number(contentLength);
434
+ if (Number.isFinite(declared) && declared > cap) {
435
+ try {
436
+ await response.body?.cancel();
437
+ }
438
+ catch {
439
+ // Ignore cancel errors so size-limit error is reported.
440
+ }
441
+ throw tooLarge();
442
+ }
443
+ }
444
+ if (response.body === null) {
445
+ return Buffer.alloc(0);
446
+ }
447
+ const reader = response.body.getReader();
448
+ const chunks = [];
449
+ let total = 0;
450
+ try {
451
+ for (;;) {
452
+ const step = await reader.read();
453
+ if (step.done || !(step.value instanceof Uint8Array)) {
454
+ break;
455
+ }
456
+ total += step.value.byteLength;
457
+ if (total > cap) {
458
+ try {
459
+ await reader.cancel();
460
+ }
461
+ catch {
462
+ // Ignore cancel errors so size-limit error is reported.
463
+ }
464
+ throw tooLarge();
465
+ }
466
+ chunks.push(Buffer.from(step.value));
467
+ }
468
+ return Buffer.concat(chunks);
469
+ }
470
+ finally {
471
+ reader.releaseLock();
472
+ }
473
+ }
474
+ mapTransportError(err, method, url, signal, timeout) {
475
+ if (err instanceof CliError) {
476
+ return err;
477
+ }
478
+ if (signal?.aborted === true && timeout?.aborted !== true) {
479
+ return new CliError(`${method} ${url} was aborted`, { exitCode: EXIT_RUNTIME });
480
+ }
481
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
482
+ return new CliError(`${method} ${url} timed out after ${this.timeoutMs} ms`, { exitCode: EXIT_RUNTIME, retryable: true });
483
+ }
484
+ const cause = causeOf(err);
485
+ const causeMessage = cause instanceof Error ? cause.message : "";
486
+ if (/redirect/i.test(causeMessage)) {
487
+ const message = `The server answered with a redirect. ${PROGRAM} never follows redirects, so credentials cannot be sent to another ` +
488
+ "location; check the --server URL (scheme, host, and base path).";
489
+ return new CliError(message, {
490
+ exitCode: EXIT_RUNTIME,
491
+ payload: { ok: false, error: "redirect_refused", message },
492
+ });
493
+ }
494
+ const code = causeCode(cause);
495
+ const detail = code ?? (causeMessage !== "" ? causeMessage : err instanceof Error ? err.message : String(err));
496
+ const isTlsError = TLS_ERROR_PATTERN.test(code ?? "") || TLS_ERROR_PATTERN.test(causeMessage);
497
+ return new CliError(`Request to ${url} failed: ${oneLine(detail)}`, {
498
+ exitCode: EXIT_RUNTIME,
499
+ retryable: !isTlsError,
500
+ });
501
+ }
502
+ /** Throws `EXIT_AUTH` (`not_logged_in`) when no session credentials are configured. */
503
+ assertAuthenticated() {
504
+ if (this.currentSession === null) {
505
+ const hint = this.missingAuthHint === undefined ? "" : ` ${this.missingAuthHint}`;
506
+ throw new CliError(`Not logged in. Run '${PROGRAM} login' or set SOLTASK_COOKIE and SOLTASK_UNLOCK_KEY.${hint}`, {
507
+ exitCode: EXIT_AUTH,
508
+ payload: { ok: false, error: "not_logged_in", message: `Not logged in.${hint}` },
509
+ });
510
+ }
511
+ }
512
+ /** Sends one HTTP request and returns the parsed JSON response (object, array, or undefined for 204/304). */
513
+ async request(method, path, options = {}) {
514
+ const requireAuth = options.requireAuth ?? true;
515
+ if (requireAuth) {
516
+ this.assertAuthenticated();
517
+ }
518
+ const url = this.buildUrl(path, options.query);
519
+ const headers = {
520
+ Accept: "application/json",
521
+ "User-Agent": `${PROGRAM}/${VERSION} (node/${process.versions.node}; ${process.platform})`,
522
+ };
523
+ if (requireAuth) {
524
+ this.attachAuthHeaders(headers);
525
+ }
526
+ if (options.etag !== undefined && options.etag !== "") {
527
+ headers["If-None-Match"] = options.etag;
528
+ }
529
+ let payload;
530
+ if (options.jsonBody !== undefined) {
531
+ payload = Buffer.from(JSON.stringify(options.jsonBody), "utf8");
532
+ headers["Content-Type"] = "application/json";
533
+ headers["Content-Length"] = String(payload.byteLength);
534
+ }
535
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
536
+ if (FORBIDDEN_REQUEST_HEADERS.test(name)) {
537
+ throw new Error(`${PROGRAM} never sends the ${name} header`);
538
+ }
539
+ headers[name] = value;
540
+ }
541
+ const allowStatuses = options.etag !== undefined && !(options.allowStatuses ?? []).includes(304)
542
+ ? [...(options.allowStatuses ?? []), 304]
543
+ : (options.allowStatuses ?? []);
544
+ let raw;
545
+ for (let retry = 0;; retry += 1) {
546
+ raw = await this.attempt(method, url, headers, payload, options.signal);
547
+ const delay = (options.retryRateLimit ?? true) && raw.status === 429 ? retryDelayMs(raw.headers["retry-after"]) : null;
548
+ if (delay === null || retry >= MAX_RATE_LIMIT_RETRIES) {
549
+ break;
550
+ }
551
+ try {
552
+ await this.sleepFn(delay, options.signal);
553
+ }
554
+ catch (err) {
555
+ if (options.signal?.aborted === true) {
556
+ throw new CliError(`${method} ${url} was aborted`, { exitCode: EXIT_RUNTIME });
557
+ }
558
+ throw err;
559
+ }
560
+ }
561
+ this.maybeRenewCookie(raw.setCookie, requireAuth);
562
+ return this.finish(raw, method, path, allowStatuses);
563
+ }
564
+ finish(raw, method, path, allowStatuses) {
565
+ this.checkProtocolHeader(raw.headers);
566
+ const etag = raw.headers["etag"] ?? null;
567
+ const ok = raw.status >= 200 && raw.status < 300;
568
+ if (raw.status === 204 || raw.status === 205 || (raw.status === 304 && allowStatuses.includes(304))) {
569
+ return { status: raw.status, headers: raw.headers, setCookie: raw.setCookie, etag, body: undefined };
570
+ }
571
+ let text;
572
+ if (ok) {
573
+ try {
574
+ text = new TextDecoder("utf-8", { fatal: true }).decode(raw.bytes);
575
+ }
576
+ catch {
577
+ throw new CliError(`Expected valid UTF-8 JSON from ${method} ${path} but received invalid UTF-8 bytes`, {
578
+ exitCode: EXIT_RUNTIME,
579
+ });
580
+ }
581
+ }
582
+ else {
583
+ text = new TextDecoder("utf-8").decode(raw.bytes);
584
+ }
585
+ const contentType = raw.headers["content-type"] ?? "";
586
+ let parsed;
587
+ let isJson = false;
588
+ if (text.trim() !== "") {
589
+ try {
590
+ parsed = JSON.parse(text);
591
+ isJson = true;
592
+ }
593
+ catch {
594
+ parsed = undefined;
595
+ }
596
+ }
597
+ if (ok) {
598
+ if (!isJson || (!isObject(parsed) && !Array.isArray(parsed))) {
599
+ throw new CliError(`Expected a JSON object or array from ${method} ${path} but received ${describeNonJson(text, contentType)}`, { exitCode: EXIT_RUNTIME });
600
+ }
601
+ return { status: raw.status, headers: raw.headers, setCookie: raw.setCookie, etag, body: parsed };
602
+ }
603
+ let body;
604
+ if (isJson && isObject(parsed)) {
605
+ body = parsed;
606
+ }
607
+ else if (isJson) {
608
+ body = { error: `http_${raw.status}`, message: oneLine(cellText(parsed)) };
609
+ }
610
+ else {
611
+ body = { error: `http_${raw.status}`, message: describeNonJson(text, contentType) };
612
+ }
613
+ if (allowStatuses.includes(raw.status)) {
614
+ return { status: raw.status, headers: raw.headers, setCookie: raw.setCookie, etag, body: body };
615
+ }
616
+ throw this.buildHttpError(raw, body);
617
+ }
618
+ buildHttpError(raw, body) {
619
+ const rawError = nonEmptyString(body["error"]);
620
+ const rawMessage = nonEmptyString(body["message"]);
621
+ const rawReason = nonEmptyString(body["reason"]);
622
+ const errCode = rawError !== undefined ? oneLine(rawError) : `http_${raw.status}`;
623
+ const detail = rawMessage ?? rawReason ?? raw.statusText;
624
+ const prefix = raw.status === 409 || raw.status === 428 ? "Conflict HTTP" : "HTTP";
625
+ const retryable = RETRYABLE_HTTP_STATUSES.has(raw.status);
626
+ const parsedWait = retryable
627
+ ? (retryAfterSeconds(raw.headers["retry-after"]) ?? retryAfterFromBody(body["retry_after"]))
628
+ : null;
629
+ const wait = raw.status === 429 ? parsedWait : null;
630
+ const payload = raw.status === 429 && wait !== null && body["retry_after"] === undefined ? { ...body, retry_after: wait } : body;
631
+ const cleanDetail = oneLine(detail);
632
+ const advice = wait === null || /\b(?:retry|try again)\s+in\b/i.test(cleanDetail) ? "" : ` Try again in ${wait} s.`;
633
+ const bareHumanError = rawMessage === undefined &&
634
+ rawReason === undefined &&
635
+ rawError !== undefined &&
636
+ (errCode.toLowerCase() === cleanDetail.toLowerCase() || /\s/.test(errCode));
637
+ const headline = bareHumanError
638
+ ? `${prefix} ${raw.status}: ${errCode}${advice}`
639
+ : `${prefix} ${raw.status} (${errCode}): ${cleanDetail}${advice}`;
640
+ return new CliError(headline, {
641
+ exitCode: exitCodeForStatus(raw.status),
642
+ payload,
643
+ retryable,
644
+ retryAfter: parsedWait,
645
+ });
646
+ }
647
+ /** Signs in with an `nsec` secret key (never stored or echoed by this client). */
648
+ async signIn(nsec, signal) {
649
+ const res = await this.request("POST", "/api/session", {
650
+ jsonBody: { nsec },
651
+ requireAuth: false,
652
+ signal,
653
+ });
654
+ return { data: res.body, cookie: res.setCookie };
655
+ }
656
+ /** Signs out the current session on the server (`DELETE /api/session`), allowing `401` if already expired. */
657
+ async signOut(signal) {
658
+ const res = await this.request("DELETE", "/api/session", {
659
+ allowStatuses: [401],
660
+ signal,
661
+ });
662
+ return { revoked: res.status === 204 || res.status === 200, status: res.status };
663
+ }
664
+ /** Fetches the authenticated user's profile and communities (`GET /api/me`). */
665
+ async me(signal) {
666
+ const res = await this.request("GET", "/api/me", { signal });
667
+ return res.body;
668
+ }
669
+ /** Lists configured communities with sync status and joined channels (`GET /api/communities`). */
670
+ async communities(signal) {
671
+ const res = await this.request("GET", "/api/communities", { signal });
672
+ if (!Array.isArray(res.body)) {
673
+ throw new CliError("Expected an array from GET /api/communities.", { exitCode: EXIT_RUNTIME });
674
+ }
675
+ return res.body;
676
+ }
677
+ /**
678
+ * Polls `GET /api/communities` while any target community reports `connecting` or `closed` (cold-vault catch-up),
679
+ * until all targets leave those states or `timeoutMs` elapses. Returns the final status map without failing on degraded.
680
+ */
681
+ async waitUntilLive(communities, timeoutMs = DEFAULT_WAIT_LIVE_TIMEOUT_MS, signal) {
682
+ const startedAt = Date.now();
683
+ const deadline = startedAt + Math.max(0, timeoutMs);
684
+ const wanted = communities !== undefined && communities.length > 0 ? new Set(communities) : null;
685
+ const isAborted = () => signal?.aborted === true;
686
+ let latest = await this.communities(signal);
687
+ const select = (list) => wanted === null ? [...list] : list.filter((item) => wanted.has(item.id));
688
+ const stillCatchingUp = (list) => list.some((item) => item.status === "connecting" || item.status === "closed");
689
+ let targets = select(latest);
690
+ while (targets.length > 0 && stillCatchingUp(targets)) {
691
+ const remaining = deadline - Date.now();
692
+ if (remaining <= 0 || isAborted()) {
693
+ break;
694
+ }
695
+ try {
696
+ await this.sleepFn(Math.min(WAIT_LIVE_POLL_MS, remaining), signal);
697
+ }
698
+ catch (err) {
699
+ if (isAborted()) {
700
+ break;
701
+ }
702
+ throw err;
703
+ }
704
+ latest = await this.communities(signal);
705
+ targets = select(latest);
706
+ }
707
+ const statuses = {};
708
+ for (const item of targets) {
709
+ statuses[item.id] = item.status;
710
+ }
711
+ const allLive = targets.every((item) => item.status === "live");
712
+ const timedOut = stillCatchingUp(targets) && Date.now() >= deadline;
713
+ return {
714
+ communities: latest,
715
+ statuses,
716
+ allLive,
717
+ waitedMs: Math.max(0, Date.now() - startedAt),
718
+ timedOut,
719
+ };
720
+ }
721
+ /**
722
+ * Connects to `GET /api/stream` over native `fetch`, parses multi-chunk SSE frames (`task`, `typing`, `status`),
723
+ * skips `: keepalive` comments, and exits cleanly when `signal` aborts or when the server closes the stream.
724
+ */
725
+ async *streamEvents(options = {}) {
726
+ this.assertAuthenticated();
727
+ const url = this.buildUrl("/api/stream", undefined);
728
+ const headers = {
729
+ Accept: "text/event-stream",
730
+ "Cache-Control": "no-cache",
731
+ "User-Agent": `${PROGRAM}/${VERSION} (node/${process.versions.node}; ${process.platform})`,
732
+ };
733
+ this.attachAuthHeaders(headers);
734
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
735
+ if (FORBIDDEN_REQUEST_HEADERS.test(name)) {
736
+ throw new Error(`${PROGRAM} never sends the ${name} header`);
737
+ }
738
+ headers[name] = value;
739
+ }
740
+ let response;
741
+ try {
742
+ response = await this.fetchFn(url, {
743
+ method: "GET",
744
+ headers,
745
+ redirect: "manual",
746
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
747
+ });
748
+ }
749
+ catch (err) {
750
+ if (options.signal?.aborted === true) {
751
+ return;
752
+ }
753
+ throw this.mapTransportError(err, "GET", url, options.signal);
754
+ }
755
+ if (response.status >= 300 && response.status < 400) {
756
+ try {
757
+ await response.body?.cancel();
758
+ }
759
+ catch {
760
+ // Ignore stream-cancel errors so redirect refusal is reported.
761
+ }
762
+ throw this.rejectRedirect(response.status, response.headers.get("location"), url);
763
+ }
764
+ const responseHeaders = {};
765
+ response.headers.forEach((value, key) => {
766
+ responseHeaders[key.toLowerCase()] = value;
767
+ });
768
+ this.checkProtocolHeader(responseHeaders);
769
+ const preferredName = this.currentSession?.mode === "cookie" ? this.currentSession.cookieName : undefined;
770
+ const setCookie = parseSetCookie(response.headers, preferredName);
771
+ this.maybeRenewCookie(setCookie, true);
772
+ if (!response.ok) {
773
+ const bytes = await this.readBounded(response, url).catch(() => Buffer.alloc(0));
774
+ const text = new TextDecoder("utf-8").decode(bytes);
775
+ let body;
776
+ try {
777
+ const parsed = JSON.parse(text);
778
+ body = isObject(parsed) ? parsed : { error: `http_${response.status}`, message: oneLine(cellText(parsed)) };
779
+ }
780
+ catch {
781
+ body = { error: `http_${response.status}`, message: describeNonJson(text, responseHeaders["content-type"] ?? "") };
782
+ }
783
+ throw this.buildHttpError({ status: response.status, statusText: response.statusText, headers: responseHeaders }, body);
784
+ }
785
+ if (response.body === null) {
786
+ return;
787
+ }
788
+ const reader = response.body.getReader();
789
+ const decoder = new TextDecoder("utf-8");
790
+ let buffer = "";
791
+ let eventName = "";
792
+ let dataLines = [];
793
+ const flushEvent = () => {
794
+ if (eventName === "" || dataLines.length === 0) {
795
+ eventName = "";
796
+ dataLines = [];
797
+ return null;
798
+ }
799
+ const ev = parseStreamFrame(eventName, dataLines.join("\n"));
800
+ eventName = "";
801
+ dataLines = [];
802
+ return ev;
803
+ };
804
+ const processLine = (rawLine) => {
805
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
806
+ if (line === "") {
807
+ return flushEvent();
808
+ }
809
+ if (line.startsWith(":")) {
810
+ return null;
811
+ }
812
+ const colon = line.indexOf(":");
813
+ const field = colon === -1 ? line : line.slice(0, colon);
814
+ let value = colon === -1 ? "" : line.slice(colon + 1);
815
+ if (value.startsWith(" ")) {
816
+ value = value.slice(1);
817
+ }
818
+ if (field === "event") {
819
+ eventName = value;
820
+ }
821
+ else if (field === "data") {
822
+ dataLines.push(value);
823
+ }
824
+ return null;
825
+ };
826
+ try {
827
+ for (;;) {
828
+ let step;
829
+ try {
830
+ step = await reader.read();
831
+ }
832
+ catch (err) {
833
+ if (options.signal?.aborted === true) {
834
+ return;
835
+ }
836
+ throw this.mapTransportError(err, "GET", url, options.signal);
837
+ }
838
+ if (step.done) {
839
+ break;
840
+ }
841
+ buffer += decoder.decode(step.value, { stream: true });
842
+ for (;;) {
843
+ const nl = buffer.indexOf("\n");
844
+ if (nl === -1) {
845
+ break;
846
+ }
847
+ const line = buffer.slice(0, nl);
848
+ buffer = buffer.slice(nl + 1);
849
+ const ev = processLine(line);
850
+ if (ev !== null) {
851
+ yield ev;
852
+ }
853
+ }
854
+ }
855
+ const tail = buffer + decoder.decode();
856
+ if (tail !== "") {
857
+ for (const line of tail.split("\n")) {
858
+ const ev = processLine(line);
859
+ if (ev !== null) {
860
+ yield ev;
861
+ }
862
+ }
863
+ }
864
+ const finalEvent = flushEvent();
865
+ if (finalEvent !== null) {
866
+ yield finalEvent;
867
+ }
868
+ }
869
+ finally {
870
+ try {
871
+ await reader.cancel();
872
+ }
873
+ catch {
874
+ // Ignore stream-cancel errors during cleanup.
875
+ }
876
+ reader.releaseLock();
877
+ }
878
+ }
879
+ }