@hunt-labs/bytekit-cli 0.5.0 → 0.7.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 CHANGED
@@ -18,6 +18,24 @@ export const MIN_RETRY_AFTER_MS = 1_000;
18
18
  export const MAX_RETRY_AFTER_MS = 60_000;
19
19
  /** Exactly one retry. A second 429 is terminal — no loop. */
20
20
  export const MAX_RETRIES = 1;
21
+ /**
22
+ * Cap on a best-effort, discard-only body drain (#2587 cr2-1). Independent of the per-attempt
23
+ * abort budget: the 429 drain below (`response.text().catch(() => {})`) exists ONLY so undici can
24
+ * return the socket to the connection pool — nothing downstream reads the drained bytes — but
25
+ * binding that read to the FULL per-attempt budget (120 s default, or, under `timeoutMs <= 0`,
26
+ * to no bound at all) let a stalled 429 body burn the whole budget, or hang forever, before a
27
+ * retry that needs nothing from that body. Short enough that a legitimately stalled 429 body costs
28
+ * the retry very little wall-clock time.
29
+ *
30
+ * #2587 cr3-2: past this cap, the read is not merely abandoned — {@link drainBestEffort} actively
31
+ * ABORTS its underlying request. Resolving the race without aborting anything (the earlier
32
+ * cr2-1 shape) let the retry proceed on schedule while the abandoned `response.text()` kept
33
+ * reading against a live socket forever, which — because the CLI exits via a soft
34
+ * `process.exitCode` (#2544) rather than `process.exit()` — kept the whole process alive
35
+ * indefinitely. `.catch`-guarding the read only made it safe to abandon the RESULT; it never made
36
+ * abandoning the underlying READ safe.
37
+ */
38
+ export const DRAIN_TIMEOUT_MS = 2_000;
21
39
  /**
22
40
  * Default CLIENT-SIDE abort budget for a single fetch attempt, in ms.
23
41
  *
@@ -36,25 +54,44 @@ function timeoutReason(ms) {
36
54
  return reason;
37
55
  }
38
56
  /**
39
- * A per-attempt abort budget: an `AbortController` fired by a `setTimeout`.
57
+ * A per-attempt abort budget: an `AbortController`, optionally fired by a `setTimeout`.
40
58
  *
41
59
  * The budget spans the WHOLE attempt — time-to-headers **and** the response body read (#2546).
42
60
  * Arming it only until headers arrive left `response.text()` / `response.arrayBuffer()` unbounded,
43
61
  * so a server that answered with headers and then stalled its body hung the CLI forever.
44
62
  *
63
+ * The controller ALWAYS exists, even when `ms <= 0` — only its own timeout timer is conditional
64
+ * on `ms > 0`. `sendWithRetry`'s 429-drain cap ({@link DRAIN_TIMEOUT_MS}, via the returned
65
+ * `abort()`) needs a live controller to tear down an abandoned body read regardless of whether the
66
+ * OVERALL per-attempt budget is enabled — `ms <= 0` must still mean "no full-attempt timeout", not
67
+ * "no controller to abort a stalled drain with" (#2587 cr3-2: the earlier drain fix abandoned the
68
+ * read entirely rather than aborting it, so the socket — and the event loop — stayed alive
69
+ * indefinitely, worse than the pre-fix baseline it replaced).
70
+ *
45
71
  * Deliberately NOT `AbortSignal.timeout` (which the SDK prefers): that schedules on a timer the
46
72
  * test runner's fake timers cannot advance, so the transport's timeout would be untestable under
47
73
  * `vi.useFakeTimers()`. CLI requests are short-lived and single-shot, so the GC advantage
48
74
  * `AbortSignal.timeout` buys the long-running SDK does not apply here. The timer is `unref`'d so a
49
75
  * pending budget never keeps the process alive, and `cleanup()` clears it on every exit path.
76
+ *
77
+ * Exported so `lib/download-artifact.ts` can reuse the same budget for the artifact-download path
78
+ * (#2587) rather than growing a second timeout implementation — that path sits entirely outside
79
+ * `sendWithRetry` (it is not a JSON/raw API call), so it would otherwise never inherit this bound.
50
80
  */
51
- function createAttemptBudget(ms) {
81
+ export function createAttemptBudget(ms) {
52
82
  const controller = new AbortController();
53
- const timer = setTimeout(() => controller.abort(timeoutReason(ms)), ms);
54
- timer.unref?.();
83
+ let timer;
84
+ if (ms > 0) {
85
+ timer = setTimeout(() => controller.abort(timeoutReason(ms)), ms);
86
+ timer.unref?.();
87
+ }
55
88
  return {
56
89
  signal: controller.signal,
57
- cleanup: () => clearTimeout(timer),
90
+ cleanup: () => {
91
+ if (timer !== undefined)
92
+ clearTimeout(timer);
93
+ },
94
+ abort: (reason) => controller.abort(reason),
58
95
  };
59
96
  }
60
97
  /** The `name` of an error-shaped value, or `undefined` when it carries none. */
@@ -84,8 +121,11 @@ function abortNameOf(err) {
84
121
  * `timedOut` is true when this attempt's own budget fired the abort, which is the reliable
85
122
  * discriminator (undici rejects with the signal's reason — or a wrapper carrying it, see
86
123
  * {@link abortNameOf} — whose `name` we also inspect as a fallback for a caller-style AbortError).
124
+ *
125
+ * Exported so `lib/download-artifact.ts` reuses the same taxonomy for the artifact-download path
126
+ * (#2587) instead of hand-rolling a second error mapping.
87
127
  */
88
- function toConnectionError(err, method, path, timedOut) {
128
+ export function toConnectionError(err, method, path, timedOut) {
89
129
  const name = abortNameOf(err) ?? '';
90
130
  let code;
91
131
  if (timedOut || name === 'TimeoutError') {
@@ -128,19 +168,84 @@ function sleep(ms) {
128
168
  });
129
169
  }
130
170
  /**
131
- * Shape a failed response into the SDK's OWN error class, using the SDK's own body parsing.
171
+ * Read (and discard) `body`, TEARING DOWN its underlying request after `DRAIN_TIMEOUT_MS` if it
172
+ * has not settled by then (#2587 cr3-2). `body` must already be guarded against rejection by its
173
+ * caller — this function only races it against a short local timer, it never itself decides what
174
+ * a rejection means.
175
+ *
176
+ * `abort` MUST be the abort function of the SAME `AbortController` the read's request was made
177
+ * with. Merely resolving this promise when the cap fires (the earlier, defective version of this
178
+ * function) let the retry proceed promptly while the abandoned `response.text()` kept running
179
+ * against a live socket forever — nothing else in the process held a reference to that read, but
180
+ * the open socket itself kept the event loop alive, so the CLI's soft `process.exitCode` exit
181
+ * (#2544) never actually fired. `response.body?.cancel()` cannot substitute for this: `text()` has
182
+ * already locked the stream by the time this function is called (property 4), so cancelling the
183
+ * body is not an option — aborting the ORIGINAL request's controller is the only way left to
184
+ * release a read already in flight. This is the same mechanism `sendWithRetry`'s headers+body
185
+ * budget already relies on to bound a normal successful read (#2546), so it is a proven pattern:
186
+ * undici rejects the pending read when its controller aborts, and tears down the socket rather
187
+ * than leaving it open.
132
188
  *
133
- * Reusing `ByteKitError` keeps `{status, code, message}` identical to what a direct SDK call
134
- * would throw, so `handleError()`'s `'status' in err` branch still renders
135
- * `Error: <message> (status: <n>)` and exits 1.
189
+ * Deliberately a plain `setTimeout` (not `AbortSignal.timeout`), same reasoning as
190
+ * {@link createAttemptBudget}: a timer scheduled that way cannot be advanced by the test runner's
191
+ * fake timers, which would make this cap untestable under `vi.useFakeTimers()`. The cap timer is
192
+ * cleared as soon as `body` itself settles, so a fast drain never leaves a stray timer pending;
193
+ * conversely, if `body` settles only AFTER the cap fires, that later settlement is simply ignored
194
+ * — abandoning the VALUE is always safe because the caller already discards it either way (only
195
+ * the underlying READ itself must not be left running, which `abort` above now guarantees).
196
+ */
197
+ function drainBestEffort(body, abort) {
198
+ return new Promise((resolve) => {
199
+ let settled = false;
200
+ const cap = setTimeout(() => {
201
+ if (!settled) {
202
+ settled = true;
203
+ abort(timeoutReason(DRAIN_TIMEOUT_MS));
204
+ resolve();
205
+ }
206
+ }, DRAIN_TIMEOUT_MS);
207
+ cap.unref?.();
208
+ void body.then(() => {
209
+ if (!settled) {
210
+ settled = true;
211
+ clearTimeout(cap);
212
+ resolve();
213
+ }
214
+ });
215
+ });
216
+ }
217
+ /**
218
+ * Shape a failed response into the SDK's OWN error class, mirroring the SDK's own `send()` body
219
+ * parsing (`packages/sdk-typescript/src/client.ts`) EXACTLY — precedence rule included — so
220
+ * `{status, code, message}` stays identical to what a direct SDK call would throw and
221
+ * `handleError()`'s `'status' in err` branch renders the same `Error: <message> (<code>, status:
222
+ * <n>)` either way.
223
+ *
224
+ * Two error-body shapes exist across the API:
225
+ * - the canonical unified envelope `{error: {code, message}}` — tested FIRST, so it always wins;
226
+ * - a flat vendor-masked shape `{error: "<code>"}` (e.g. `/v1/search` 502:
227
+ * `{"error":"search_provider_error"}`, docs/api/openapi.yaml §/v1/search 502) — the flat form
228
+ * is strictly a FALLBACK and can never override an envelope (#2541, mirrored here for #2586:
229
+ * the CLI's own copy of this parser had drifted from the SDK's and still only read the
230
+ * envelope shape, so a flat 502 rendered `internal_error` instead of `search_provider_error`).
231
+ *
232
+ * The explicit `!== null` guard on the envelope check matters — `typeof null` is `'object'`.
136
233
  */
137
234
  async function toApiError(response) {
138
235
  let code = 'internal_error';
139
236
  let message = response.statusText;
140
237
  try {
141
238
  const json = (await response.json());
142
- code = json.error?.code ?? code;
143
- message = json.error?.message ?? message;
239
+ if (typeof json.error === 'object' && json.error !== null) {
240
+ code = json.error.code ?? code;
241
+ message = json.error.message ?? message;
242
+ }
243
+ else if (typeof json.error === 'string' && json.error.length > 0) {
244
+ // The string IS the error code. `message` falls back to it only when the response carried
245
+ // no statusText, so the thrown error is never message-empty.
246
+ code = json.error;
247
+ message = message || json.error;
248
+ }
144
249
  }
145
250
  catch {
146
251
  // leave defaults
@@ -189,11 +294,12 @@ async function sendWithRetry(apiKey, baseUrl, timeoutMs, method, path, body, rea
189
294
  if (body !== undefined) {
190
295
  init.body = JSON.stringify(body);
191
296
  }
192
- // Per-attempt abort budget: a fresh timer for THIS attempt. A budget of 0 disables it.
193
- const budget = timeoutMs > 0 ? createAttemptBudget(timeoutMs) : undefined;
194
- if (budget !== undefined) {
195
- init.signal = budget.signal;
196
- }
297
+ // Per-attempt abort budget: a fresh controller for THIS attempt. `timeoutMs <= 0` disables
298
+ // the OVERALL attempt timer (unchanged), but the controller itself always exists — the 429
299
+ // drain below needs something to abort even when the full-attempt timeout is off (#2587
300
+ // cr3-2).
301
+ const budget = createAttemptBudget(timeoutMs);
302
+ init.signal = budget.signal;
197
303
  // Set only by the 429-retry branch below — the one path that falls out of the `try` rather
198
304
  // than returning or throwing. Left `undefined` on every other path, which never reaches the
199
305
  // `sleep` after the `finally`.
@@ -207,7 +313,7 @@ async function sendWithRetry(apiKey, baseUrl, timeoutMs, method, path, body, rea
207
313
  // No HTTP response was produced (timeout, abort, socket/DNS/TLS). Re-throw as the SDK's
208
314
  // own ByteKitConnectionError so a hung server can never hang the CLI and a network failure
209
315
  // no longer surfaces as a bare `Error: fetch failed`.
210
- throw toConnectionError(err, method, path, budget?.signal.aborted === true);
316
+ throw toConnectionError(err, method, path, budget.signal.aborted === true);
211
317
  }
212
318
  if (response.ok) {
213
319
  try {
@@ -216,11 +322,44 @@ async function sendWithRetry(apiKey, baseUrl, timeoutMs, method, path, body, rea
216
322
  catch (err) {
217
323
  // A body read that never completes is aborted by the same budget; undici then rejects
218
324
  // the stream (#2546). Map it into the same taxonomy the headers phase uses.
219
- throw toConnectionError(err, method, path, budget?.signal.aborted === true);
325
+ throw toConnectionError(err, method, path, budget.signal.aborted === true);
220
326
  }
221
327
  }
222
328
  if (response.status === 429 && attempt < MAX_RETRIES) {
223
329
  retryAfterMs = parseRetryAfterMs(response.headers.get('Retry-After'));
330
+ // This 429 body is never read on the retry path (only the headers/Retry-After matter), so
331
+ // it must be fully CONSUMED before the retry — not merely cancelled — for undici to
332
+ // reclaim the underlying socket for connection-pool reuse (#2587 dod-4).
333
+ //
334
+ // #2587 cr-3 correction: an earlier version of this fix used `response.body?.cancel()`,
335
+ // reasoning that cancelling let undici reclaim the socket. That is backwards —
336
+ // `cancel()` ABORTS the fetch and DESTROYS the socket rather than returning it to the
337
+ // pool. Measured against a real `node:http` server and real undici (5x 429->200
338
+ // sequences, counting `connection` events): `cancel()` was inert for the gateway's actual
339
+ // tiny-JSON 429 body (2 conns, identical to no drain at all) and strictly WORSE than no
340
+ // drain for a large body (7 conns vs 6). A full read via `response.text()` is what
341
+ // actually lets undici return the connection to the pool (2 conns at either size). The
342
+ // `.catch(() => {})` guard stays: a real body read can still reject on an already-errored
343
+ // or locked stream, and that must never turn a recoverable 429 into a hard failure.
344
+ //
345
+ // #2587 cr2-1 correction: the read above was previously awaited directly, bounded only by
346
+ // the FULL per-attempt abort budget (120 s default) or, under `timeoutMs <= 0`, by nothing
347
+ // at all — a stalled 429 body could burn the whole budget (or hang forever) before a retry
348
+ // that needs nothing from that body (`Retry-After` is already parsed above).
349
+ // {@link drainBestEffort} bounds the read by its own short, independent cap
350
+ // ({@link DRAIN_TIMEOUT_MS}) instead, so a stalled drain can never delay the retry by more
351
+ // than that cap regardless of the attempt budget's size or absence.
352
+ //
353
+ // #2587 cr3-2 correction: cr2-1's `drainBestEffort` bounded only how long the RETRY
354
+ // waited — the cap resolved the returned promise but never touched the abandoned
355
+ // `response.text()` call itself, which kept reading against a live (never-aborted) socket
356
+ // indefinitely. Because every CLI success path exits via a soft `process.exitCode`
357
+ // (#2544) rather than `process.exit()`, that orphaned read then kept the event loop open
358
+ // forever: strictly WORSE than the pre-#2587 baseline (which at least exited once its own
359
+ // unbounded read finally settled or errored). `drainBestEffort` now takes this attempt's
360
+ // own `budget.abort` and calls it when the cap fires, so the abandoned read is actually
361
+ // torn down — not merely ignored — and the socket (and the event loop) is released.
362
+ await drainBestEffort(response.text().catch(() => { }), budget.abort);
224
363
  }
225
364
  else {
226
365
  // `toApiError` reads the error body, so it too runs inside the budget.
@@ -230,7 +369,7 @@ async function sendWithRetry(apiKey, baseUrl, timeoutMs, method, path, body, rea
230
369
  finally {
231
370
  // Clear the timer on every exit path — success (body read included), HTTP error, or
232
371
  // abort — so a healthy request leaves no dangling 120s timer.
233
- budget?.cleanup();
372
+ budget.cleanup();
234
373
  }
235
374
  // OUTSIDE the budget's `finally`: the backoff is not spent against any attempt's budget, and
236
375
  // the next attempt arms a fresh one. The `??` is unreachable in practice (only the branch
@@ -246,9 +385,21 @@ async function sendWithRetry(apiKey, baseUrl, timeoutMs, method, path, body, rea
246
385
  * property of the client (see {@link buildClient}) routes all JSON commands through it from one
247
386
  * seam. `/v1/fetch` does NOT ride this transport — it rides `requestRaw` (see
248
387
  * {@link createRetryingRequestRaw}); `/v1/fetch/bulk` is a JSON job envelope and does.
388
+ *
389
+ * DECISION (#2586 dod-4): the 4th `RequestOptions` parameter of the SDK's contract is accepted
390
+ * here — so the signature matches `ByteKit['request']` exactly, closing the gap where a caller-typo
391
+ * of a 5th positional argument would silently no-op instead of a compile error — but deliberately
392
+ * NOT forwarded into `sendWithRetry`. Two reasons: (1) no CLI command constructs a `RequestOptions`
393
+ * today (no `--timeout` flag exists yet, and `signal` has no CLI-level source), so the parameter is
394
+ * always `undefined` in practice; (2) the CLI already owns a per-attempt abort budget with its own
395
+ * semantics (`createAttemptBudget`, `timeoutMs` above) that would need explicit composition with a
396
+ * caller `signal` to honor `RequestOptions` correctly (the SDK's `composeSignals`) — inventing that
397
+ * unexercised composition here, with no caller able to reach it, would be undertested surface for no
398
+ * present behavior change. If a future CLI flag needs per-call overrides, wire it through
399
+ * `sendWithRetry`'s `timeoutMs` (already per-attempt) at that point, with its own tests.
249
400
  */
250
401
  export function createRetryingRequest(apiKey, baseUrl, timeoutMs = DEFAULT_TIMEOUT_MS) {
251
- return async function request(method, path, body) {
402
+ return async function request(method, path, body, _options) {
252
403
  // The reader consumes the stream and nothing else, so the abort budget covers the read
253
404
  // (#2546) while the 204/empty guard and `JSON.parse` stay OUTSIDE the guarded region —
254
405
  // a malformed 200 body must still surface its own SyntaxError, never a connection error.
@@ -273,9 +424,14 @@ export function createRetryingRequest(apiKey, baseUrl, timeoutMs = DEFAULT_TIMEO
273
424
  * so `FetchResource` builds an ordinary `FetchResult` from it and the CLI never forks fetch
274
425
  * handling away from the SDK. `bytes` is byte-exact (binary-safe); `body` is the best-effort UTF-8
275
426
  * decode, matching the SDK's own semantics.
427
+ *
428
+ * The 4th `RequestOptions` parameter is accepted but not forwarded — see the DECISION note on
429
+ * {@link createRetryingRequest}, which applies here verbatim. `FetchResource.create`/`get` DO thread
430
+ * a `requestOptions` argument through to this seam (unlike every other resource), but no CLI `fetch`
431
+ * command constructs one today (no `--timeout` flag), so it is still always `undefined` in practice.
276
432
  */
277
433
  export function createRetryingRequestRaw(apiKey, baseUrl, timeoutMs = DEFAULT_TIMEOUT_MS) {
278
- return async function requestRaw(method, path, body) {
434
+ return async function requestRaw(method, path, body, _options) {
279
435
  // As in `createRetryingRequest`: the reader only drains the stream (so the abort budget
280
436
  // covers it, #2546); the UTF-8 decode happens outside the guarded region.
281
437
  const { bytes, headers, status } = await sendWithRetry(apiKey, baseUrl, timeoutMs, method, path, body, async (response) => ({
@@ -291,28 +447,90 @@ export function createRetryingRequestRaw(apiKey, baseUrl, timeoutMs = DEFAULT_TI
291
447
  };
292
448
  };
293
449
  }
450
+ /**
451
+ * Build the CLI's header-carrying JSON transport: the SDK's `requestWithResponse` contract
452
+ * (`{data, headers, status}`, #2547), plus the same bounded 429 retry every other CLI transport
453
+ * gets.
454
+ *
455
+ * Unused by any CLI command today — `screenshots.createWithResponse` / `getWithResponse` and
456
+ * `sitemap.getWithResponse` all exist on the SDK surface but no command builds on them yet. It is
457
+ * still installed (see {@link buildClient}) rather than left un-overridden: the transport-coverage
458
+ * contract test (#2586 dod-3) derives its method list from the real SDK prototype, and leaving a
459
+ * transport method un-overridden is exactly how #2535 shipped broken — the first command that DOES
460
+ * call a `*WithResponse` resource method must not silently ride the bare SDK transport and skip the
461
+ * CLI's retry/timeout/error taxonomy.
462
+ *
463
+ * Same body-read shape as {@link createRetryingRequest} (204/empty → `undefined`, `JSON.parse`
464
+ * otherwise), with `headers` and `status` threaded through from the successful response alongside
465
+ * the parsed `data`. The 4th `RequestOptions` parameter is accepted but not forwarded — see the
466
+ * DECISION note on {@link createRetryingRequest}.
467
+ */
468
+ export function createRetryingRequestWithResponse(apiKey, baseUrl, timeoutMs = DEFAULT_TIMEOUT_MS) {
469
+ return async function requestWithResponse(method, path, body, _options) {
470
+ const { status, text, headers } = await sendWithRetry(apiKey, baseUrl, timeoutMs, method, path, body, async (response) => ({
471
+ status: response.status,
472
+ text: await response.text(),
473
+ headers: response.headers,
474
+ }));
475
+ const data = status === 204 || text.trim().length === 0 ? undefined : JSON.parse(text);
476
+ return { data, headers, status };
477
+ };
478
+ }
479
+ /**
480
+ * Strip a trailing slash (or run of them) from a base URL, mirroring the SDK's own constructor
481
+ * normalization verbatim (`packages/sdk-typescript/src/client.ts`, `/\/+$/`, #2481) — so
482
+ * `baseUrl + path` (every CLI-owned path already starts with `/`) never yields a double-slash URL.
483
+ * Only the trailing slash is removed; a path-carrying baseUrl (e.g. a reverse-proxy prefix
484
+ * `…/bytekit`) is preserved.
485
+ */
486
+ function normalizeBaseUrl(url) {
487
+ return url.replace(/\/+$/, '');
488
+ }
294
489
  /**
295
490
  * Build an authenticated SDK client from global CLI options.
296
491
  *
297
492
  * Resolution order (explicit input beats environment):
298
493
  * apiKey: --key flag → BYTEKIT_API_KEY.
299
494
  * baseUrl: --base-url flag → BYTEKIT_BASE_URL → DEFAULT_BASE_URL.
300
- * Exits with a descriptive error when no key is available.
301
495
  *
302
- * The returned client's `request` AND `requestRaw` are both replaced by the retrying transports, so
303
- * every command inherits the 429 retry — JSON commands via `request`, the `/v1/fetch` content
304
- * commands via `requestRaw`. Overriding only `request` is the #2535 defect: the SDK's fetch
305
- * resource rides `requestRaw`, so fetch bypassed the retry and the CLI's error taxonomy entirely.
496
+ * THROWS a plain `Error` when no key is available (#2686 item 4). It used to `console.error` and
497
+ * then hard-exit — an async stderr write followed immediately by the one call that discards
498
+ * the userspace stdio queue, which is exactly the defect the package's #2544 flush policy exists to
499
+ * prevent. Throwing stops just as hard (there is no client to return, E4) while routing the message
500
+ * through `handleError`, whose soft `process.exitCode` lets stderr drain first. The rendered stderr
501
+ * line is byte-identical: `handleError` supplies the `Error: ` prefix, and a plain Error carries
502
+ * neither a status nor a ByteKit code, so no parenthesised suffix is added.
503
+ *
504
+ * Because it throws, EVERY caller invokes it from inside its action's `try` block. `index.ts` drives
505
+ * commander with `.parse()`, not `.parseAsync()`, so nothing awaits an action's promise: a throw
506
+ * raised above the try would escape as an unhandled rejection and print a raw stack trace instead of
507
+ * the clean one-liner — the same constraint `commands/scrape.ts` already documents for
508
+ * `resolveOutputMode`. `error-exit-contract.test.ts` pins that placement structurally, across every
509
+ * call site at once.
510
+ *
511
+ * The returned client's `request`, `requestRaw`, AND `requestWithResponse` are all replaced by the
512
+ * retrying transports, so every command inherits the 429 retry — JSON commands via `request`, the
513
+ * `/v1/fetch` content commands via `requestRaw`, and the header-carrying `*WithResponse` surface via
514
+ * `requestWithResponse`. Overriding only `request` is the #2535 defect: the SDK's fetch resource
515
+ * rides `requestRaw`, so fetch bypassed the retry and the CLI's error taxonomy entirely; leaving
516
+ * `requestWithResponse` un-overridden is the same class of defect (#2586) — it is unused by any CLI
517
+ * command TODAY, but a future command built on `screenshots.createWithResponse` /
518
+ * `sitemap.getWithResponse` would otherwise silently ride the bare SDK transport.
519
+ *
520
+ * `baseUrl` is normalized ONCE, here, before it reaches either the SDK constructor or the CLI's own
521
+ * transport builders below — the CLI's transports build their request URL from this local variable
522
+ * directly (they do not call the SDK's own normalized `send()`), so a trailing-slash flag would
523
+ * otherwise double-slash every request the CLI makes (#2586).
306
524
  */
307
525
  export function buildClient(opts) {
308
526
  const apiKey = opts.key ?? process.env['BYTEKIT_API_KEY'];
309
527
  if (!apiKey) {
310
- console.error('Error: API key required. Pass --key or set BYTEKIT_API_KEY.');
311
- process.exit(1);
528
+ throw new Error('API key required. Pass --key or set BYTEKIT_API_KEY.');
312
529
  }
313
- const baseUrl = opts.baseUrl ?? process.env['BYTEKIT_BASE_URL'] ?? DEFAULT_BASE_URL;
530
+ const baseUrl = normalizeBaseUrl(opts.baseUrl ?? process.env['BYTEKIT_BASE_URL'] ?? DEFAULT_BASE_URL);
314
531
  const client = new ByteKit({ apiKey, baseUrl });
315
532
  client.request = createRetryingRequest(apiKey, baseUrl);
316
533
  client.requestRaw = createRetryingRequestRaw(apiKey, baseUrl);
534
+ client.requestWithResponse = createRetryingRequestWithResponse(apiKey, baseUrl);
317
535
  return client;
318
536
  }
@@ -19,8 +19,9 @@ export function makeAccountCommand(getGlobal) {
19
19
  .description('Get the authenticated account')
20
20
  .action(async () => {
21
21
  const g = getGlobal();
22
- const client = buildClient(g);
23
22
  try {
23
+ // Inside the try: buildClient() throws on a missing key (#2686 item 4) and the throw must reach handleError(). See its doc comment in client.ts.
24
+ const client = buildClient(g);
24
25
  const result = await client.account.get();
25
26
  printResult(result, g.json);
26
27
  }
@@ -1,7 +1,8 @@
1
1
  import { Command } from 'commander';
2
2
  import { buildClient } from '../client.js';
3
3
  import { printResult, handleError } from '../output.js';
4
- import { parseUrlLines } from '../lib/url-lines.js';
4
+ import { parseBulkLines, toBulkItems } from '../lib/url-lines.js';
5
+ import { parseJsonFlag } from '../lib/parse-flags.js';
5
6
  export function makeBulkCommand(getGlobal) {
6
7
  const cmd = new Command('bulk').description('Bulk screenshot operations');
7
8
  const screenshotsCmd = new Command('screenshots').description('Bulk screenshot sub-resources');
@@ -10,8 +11,9 @@ export function makeBulkCommand(getGlobal) {
10
11
  .description('List screenshots in a bulk job')
11
12
  .action(async (id) => {
12
13
  const g = getGlobal();
13
- const client = buildClient(g);
14
14
  try {
15
+ // Inside the try: buildClient() throws on a missing key (#2686 item 4) and the throw must reach handleError(). See its doc comment in client.ts.
16
+ const client = buildClient(g);
15
17
  const result = await client.bulk.screenshots.list(id);
16
18
  printResult(result, g.json);
17
19
  }
@@ -23,14 +25,32 @@ export function makeBulkCommand(getGlobal) {
23
25
  cmd
24
26
  .command('create')
25
27
  .description('Create a bulk screenshots job')
26
- .requiredOption('--file <path>', 'Path to newline-delimited file of URLs (plain URL or {"url":"..."} per line)')
28
+ .requiredOption('--file <path>', 'Path to a newline-delimited file. Each line is a plain URL, or a JSON object carrying "url" plus per-item config. A line whose only key is "url" behaves exactly as before (sent as a bare URL string); any line with additional keys switches the payload to the per-item shape.')
27
29
  .requiredOption('--webhook-url <url>', 'HTTPS webhook URL notified when the job completes')
30
+ .option('--webhook-secret <secret>', 'HMAC secret used to sign the completion webhook (omitted → unsigned)')
31
+ .option('--defaults <json>', 'Defaults applied to every entry, as a JSON object (omitted → none). Unknown keys are rejected by /v1/bulk (422) and ignored by scrape bulk / fetch bulk; fetch bulk additionally rejects browser-only keys (cookies, wait_until, wait_for_selector, delay_ms) with a 400.', (v) => parseJsonFlag('--defaults', v, 'object'))
32
+ .option('--metadata <json>', `Arbitrary metadata echoed on the job envelope, as a JSON object, e.g. '{"run":"7"}' (omitted → none)`, (v) => parseJsonFlag('--metadata', v, 'object'))
33
+ // Deliberately NO --custom: /v1/bulk is `.strict()` at the top level with no `custom`
34
+ // property (validators/bulk.ts:135), so the flag would 422 every call (#2596 drift D2).
28
35
  .action(async (opts) => {
29
36
  const g = getGlobal();
30
- const client = buildClient(g);
31
37
  try {
32
- const urls = parseUrlLines(opts.file);
33
- const result = await client.bulk.create({ urls, webhook_url: opts.webhookUrl });
38
+ // Inside the try: buildClient() throws on a missing key (#2686 item 4) and the throw must reach handleError(). See its doc comment in client.ts.
39
+ const client = buildClient(g);
40
+ const lines = parseBulkLines(opts.file);
41
+ // `urls` XOR `items` (validators/bulk.ts:136-155) — send exactly one. A file of only
42
+ // url-only lines keeps the pre-#2596 `{ urls, webhook_url }` body, key order included,
43
+ // so existing callers are byte-identical on the wire (E2).
44
+ const body = lines.every((l) => typeof l === 'string')
45
+ ? { urls: lines, webhook_url: opts.webhookUrl }
46
+ : { items: toBulkItems(lines), webhook_url: opts.webhookUrl };
47
+ if (opts.webhookSecret !== undefined)
48
+ body['webhook_secret'] = opts.webhookSecret;
49
+ if (opts.defaults !== undefined)
50
+ body['defaults'] = opts.defaults;
51
+ if (opts.metadata !== undefined)
52
+ body['metadata'] = opts.metadata;
53
+ const result = await client.bulk.create(body);
34
54
  printResult(result, g.json);
35
55
  }
36
56
  catch (err) {
@@ -42,8 +62,9 @@ export function makeBulkCommand(getGlobal) {
42
62
  .description('Get a bulk job status')
43
63
  .action(async (id) => {
44
64
  const g = getGlobal();
45
- const client = buildClient(g);
46
65
  try {
66
+ // Inside the try: buildClient() throws on a missing key (#2686 item 4) and the throw must reach handleError(). See its doc comment in client.ts.
67
+ const client = buildClient(g);
47
68
  const result = await client.bulk.get(id);
48
69
  printResult(result, g.json);
49
70
  }
@@ -56,8 +77,9 @@ export function makeBulkCommand(getGlobal) {
56
77
  .description('Cancel an in-flight bulk job')
57
78
  .action(async (id) => {
58
79
  const g = getGlobal();
59
- const client = buildClient(g);
60
80
  try {
81
+ // Inside the try: buildClient() throws on a missing key (#2686 item 4) and the throw must reach handleError(). See its doc comment in client.ts.
82
+ const client = buildClient(g);
61
83
  const result = await client.bulk.cancel(id);
62
84
  printResult(result, g.json);
63
85
  }