@usesocial/cli 0.2.3 → 0.2.5

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/index.d.mts CHANGED
@@ -1,3 +1,1256 @@
1
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/common.d.ts
2
+ type Primitive = null | undefined | string | number | boolean | symbol | bigint;
3
+ type LiteralUnion<LiteralType extends BaseType, BaseType extends Primitive> = LiteralType | (BaseType & {
4
+ _?: never;
5
+ });
6
+ //#endregion
7
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/hooks.d.ts
8
+ /**
9
+ This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here.
10
+
11
+ Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.
12
+
13
+ @example
14
+ ```
15
+ import ky from 'ky';
16
+
17
+ const api = ky.extend({
18
+ hooks: {
19
+ init: [
20
+ options => {
21
+ options.searchParams = {apiKey: getApiKey()};
22
+ },
23
+ ],
24
+ },
25
+ });
26
+
27
+ const response = await api.get('https://example.com/api/users');
28
+ // URL: https://example.com/api/users?apiKey=123
29
+ ```
30
+ */
31
+ type InitHook = (options: Options) => void;
32
+ type BeforeRequestState = {
33
+ request: KyRequest;
34
+ options: NormalizedOptions;
35
+ /**
36
+ The number of retries attempted. Always `0`, since `beforeRequest` hooks run once before retry handling begins.
37
+ */
38
+ retryCount: 0;
39
+ };
40
+ type BeforeRequestHook = (state: BeforeRequestState) => Request | Response | void | Promise<Request | Response | void>;
41
+ type BeforeRetryState = {
42
+ request: KyRequest;
43
+ options: NormalizedOptions;
44
+ error: Error;
45
+ /**
46
+ The number of retries attempted. Always `>= 1`, since this hook is only called during retries, not on the initial request.
47
+ */
48
+ retryCount: number;
49
+ };
50
+ type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;
51
+ type BeforeErrorState = {
52
+ request: KyRequest;
53
+ options: NormalizedOptions;
54
+ error: Error;
55
+ /**
56
+ The number of retries attempted. `0` for the initial request, increments with each retry.
57
+ This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).
58
+ */
59
+ retryCount: number;
60
+ };
61
+ type BeforeErrorHook = (state: BeforeErrorState) => Error | Promise<Error>;
62
+ type AfterResponseState = {
63
+ request: KyRequest;
64
+ options: NormalizedOptions;
65
+ response: KyResponse;
66
+ /**
67
+ The number of retries attempted. `0` for the initial request, increments with each retry.
68
+ This allows you to distinguish between the initial request and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).
69
+ */
70
+ retryCount: number;
71
+ };
72
+ type AfterResponseHook = (state: AfterResponseState) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;
73
+ type Hooks = {
74
+ /**
75
+ This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here.
76
+ Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.
77
+ A common use case is to add a search parameter to every request:
78
+ @example
79
+ ```
80
+ import ky from 'ky';
81
+ const api = ky.extend({
82
+ hooks: {
83
+ init: [
84
+ options => {
85
+ options.searchParams = {apiKey: getApiKey()};
86
+ },
87
+ ],
88
+ },
89
+ });
90
+ const response = await api.get('https://example.com/api/users');
91
+ // URL: https://example.com/api/users?apiKey=123
92
+ ```
93
+ @default []
94
+ */
95
+ init?: InitHook[];
96
+ /**
97
+ This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, and retry count. You could, for example, modify `request.headers` here.
98
+ The `retryCount` is always `0`, since `beforeRequest` hooks run once before retry handling begins.
99
+ The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request (remaining hooks will still run with the updated request). It can also return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request, in which case remaining `beforeRequest` hooks are skipped. This can be used to mock a request, check an internal cache, etc.
100
+ Any error thrown by `beforeRequest` hooks is treated as fatal and will not trigger Ky's retry logic.
101
+ @example
102
+ ```
103
+ import ky from 'ky';
104
+ const api = ky.extend({
105
+ hooks: {
106
+ beforeRequest: [
107
+ ({request}) => {
108
+ request.headers.set('Authorization', 'token initial-token');
109
+ }
110
+ ]
111
+ }
112
+ });
113
+ const response = await api.get('https://example.com/api/users');
114
+ ```
115
+ **Modifying the request URL:**
116
+ @example
117
+ ```
118
+ import ky from 'ky';
119
+ const api = ky.extend({
120
+ hooks: {
121
+ beforeRequest: [
122
+ ({request}) => {
123
+ const url = new URL(request.url);
124
+ url.searchParams.set('token', 'secret-token');
125
+ return new Request(url, request);
126
+ }
127
+ ]
128
+ }
129
+ });
130
+ const response = await api.get('https://example.com/api/users');
131
+ ```
132
+ @default []
133
+ */
134
+ beforeRequest?: BeforeRequestHook[];
135
+ /**
136
+ This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, an error instance, and retry count. You could, for example, modify `request.headers` here.
137
+ The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.
138
+ **Warning:** Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.
139
+ The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.
140
+ If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body will be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.
141
+ You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).
142
+ **Modifying headers:**
143
+ @example
144
+ ```
145
+ import ky from 'ky';
146
+ const response = await ky('https://example.com', {
147
+ hooks: {
148
+ beforeRetry: [
149
+ async ({request, options, error, retryCount}) => {
150
+ const token = await ky('https://example.com/refresh-token');
151
+ request.headers.set('Authorization', `token ${token}`);
152
+ }
153
+ ]
154
+ }
155
+ });
156
+ ```
157
+ **Modifying the request URL:**
158
+ @example
159
+ ```
160
+ import ky, {isHTTPError} from 'ky';
161
+ const response = await ky('https://example.com/api', {
162
+ hooks: {
163
+ beforeRetry: [
164
+ ({request, error}) => {
165
+ // Add query parameters based on error response
166
+ if (
167
+ isHTTPError(error)
168
+ && typeof error.data === 'object'
169
+ && error.data !== null
170
+ && 'processId' in error.data
171
+ ) {
172
+ const url = new URL(request.url);
173
+ url.searchParams.set('processId', String(error.data.processId));
174
+ return new Request(url, request);
175
+ }
176
+ }
177
+ ]
178
+ }
179
+ });
180
+ ```
181
+ **Returning a cached response:**
182
+ @example
183
+ ```
184
+ import ky from 'ky';
185
+ const response = await ky('https://example.com/api', {
186
+ hooks: {
187
+ beforeRetry: [
188
+ ({error, retryCount}) => {
189
+ // Use cached response instead of retrying
190
+ if (retryCount > 1 && cachedResponse) {
191
+ return cachedResponse;
192
+ }
193
+ }
194
+ ]
195
+ }
196
+ });
197
+ ```
198
+ @default []
199
+ */
200
+ beforeRetry?: BeforeRetryHook[];
201
+ /**
202
+ This hook enables you to modify any error right before it is thrown. The hook function receives a state object with the current request, the normalized Ky options, the error, and retry count, and should return an `Error` instance.
203
+ This hook is called for all error types, including `HTTPError`, `NetworkError`, `TimeoutError`, and `ForceRetryError` (when retry limit is exceeded via `ky.retry()`). Use type guards like `isHTTPError()`, `isNetworkError()`, or `isTimeoutError()` to handle specific error types.
204
+ The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).
205
+ If a `beforeRequest` or `beforeRetry` hook returns a new `Request`, inspect `request` for the final request state. `options` remains Ky's normalized options and may not mirror every property of a replacement `Request`.
206
+ @default []
207
+ @example
208
+ ```
209
+ import ky, {isHTTPError} from 'ky';
210
+ await ky('https://example.com', {
211
+ hooks: {
212
+ beforeError: [
213
+ ({request, options, error}) => {
214
+ if (isHTTPError(error)) {
215
+ if (
216
+ typeof error.data === 'object'
217
+ && error.data !== null
218
+ && 'message' in error.data
219
+ ) {
220
+ error.name = 'GitHubError';
221
+ error.message = `${String(error.data.message)} (${error.response.status})`;
222
+ }
223
+ }
224
+ // `request` and `options` are always available
225
+ console.log(`Request to ${request.url} failed`, options.context);
226
+ return error;
227
+ }
228
+ ]
229
+ }
230
+ });
231
+ ```
232
+ */
233
+ beforeError?: BeforeErrorHook[];
234
+ /**
235
+ This hook enables you to read and optionally modify the response. The hook function receives a state object with the normalized request, options, a clone of the response, and retry count. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
236
+ You can also force a retry by returning [`ky.retry(options)`](#kyretryoptions). This is useful when you need to retry based on the response body content, even if the response has a successful status code. The retry will respect the `retry.limit` option and be observable in `beforeRetry` hooks.
237
+ **Warning:** `ky.retry({request})` uses the replacement request as-is. If it targets another origin, remove any credentials you do not want forwarded.
238
+ Any non-`ky.retry()` error thrown by `afterResponse` hooks is treated as fatal and will not trigger Ky's retry logic.
239
+ The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).
240
+ @default []
241
+ @example
242
+ ```
243
+ import ky from 'ky';
244
+ const response = await ky('https://example.com', {
245
+ hooks: {
246
+ afterResponse: [
247
+ ({response}) => {
248
+ // You could do something with the response, for example, logging.
249
+ log(response);
250
+ // Or return a `Response` instance to overwrite the response.
251
+ return new Response('A different response', {status: 200});
252
+ },
253
+ // Or retry with a fresh token on a 401 error
254
+ async ({request, response, retryCount}) => {
255
+ if (response.status === 401 && retryCount === 0) {
256
+ // Only refresh on first 401, not on subsequent retries
257
+ const {token} = await ky.post('https://example.com/auth/refresh').json();
258
+ const headers = new Headers(request.headers);
259
+ headers.set('Authorization', `Bearer ${token}`);
260
+ return ky.retry({
261
+ request: new Request(request, {headers}),
262
+ code: 'TOKEN_REFRESHED'
263
+ });
264
+ }
265
+ },
266
+ // Or force retry based on response body content
267
+ async ({response}) => {
268
+ if (response.status === 200) {
269
+ const data = await response.json();
270
+ if (data.error?.code === 'RATE_LIMIT') {
271
+ // Retry with custom delay from API response
272
+ return ky.retry({
273
+ delay: data.error.retryAfter * 1000,
274
+ code: 'RATE_LIMIT'
275
+ });
276
+ }
277
+ }
278
+ },
279
+ // Or show a notification only on the last retry for 5xx errors
280
+ ({options, response, retryCount}) => {
281
+ if (response.status >= 500 && response.status <= 599) {
282
+ if (retryCount === options.retry.limit) {
283
+ showNotification('Request failed after all retries');
284
+ }
285
+ }
286
+ }
287
+ ]
288
+ }
289
+ });
290
+ ```
291
+ */
292
+ afterResponse?: AfterResponseHook[];
293
+ };
294
+ //#endregion
295
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/retry.d.ts
296
+ type ShouldRetryState = {
297
+ /**
298
+ The error that caused the request to fail.
299
+ */
300
+ error: Error;
301
+ /**
302
+ The number of retries attempted. Starts at 1 for the first retry.
303
+ */
304
+ retryCount: number;
305
+ };
306
+ type RetryOptions = {
307
+ /**
308
+ The number of times to retry failed requests.
309
+ @default 2
310
+ */
311
+ limit?: number;
312
+ /**
313
+ The HTTP methods allowed to retry.
314
+ @default ['get', 'put', 'head', 'delete', 'options', 'trace']
315
+ */
316
+ methods?: HttpMethod[];
317
+ /**
318
+ The HTTP status codes allowed to retry.
319
+ @default [408, 413, 429, 500, 502, 503, 504]
320
+ */
321
+ statusCodes?: number[];
322
+ /**
323
+ The HTTP status codes allowed to retry with a `Retry-After` header.
324
+ @default [413, 429, 503]
325
+ */
326
+ afterStatusCodes?: number[];
327
+ /**
328
+ If the `Retry-After` header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.
329
+ @default Infinity
330
+ */
331
+ maxRetryAfter?: number;
332
+ /**
333
+ The upper limit of the delay per retry in milliseconds.
334
+ To clamp the delay, set `backoffLimit` to 1000, for example.
335
+ By default, the delay is calculated in the following way:
336
+ ```
337
+ 0.3 * (2 ** (attemptCount - 1)) * 1000
338
+ ```
339
+ The delay increases exponentially.
340
+ @default Infinity
341
+ */
342
+ backoffLimit?: number;
343
+ /**
344
+ A function to calculate the delay in milliseconds between retries given `attemptCount` (starts from 1).
345
+ @default attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000
346
+ */
347
+ delay?: (attemptCount: number) => number;
348
+ /**
349
+ Add random jitter to retry delays to prevent thundering herd problems.
350
+ When many clients retry simultaneously (e.g., after hitting a rate limit), they can overwhelm the server again. Jitter adds randomness to break this synchronization.
351
+ Set to `true` to use full jitter, which randomizes the delay between 0 and the computed delay.
352
+ Alternatively, pass a function to implement custom jitter strategies.
353
+ Note: Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected.
354
+ @default undefined (no jitter)
355
+ @example
356
+ ```
357
+ import ky from 'ky';
358
+ const json = await ky('https://example.com', {
359
+ retry: {
360
+ limit: 5,
361
+ // Full jitter (randomizes delay between 0 and computed value)
362
+ jitter: true
363
+ // Percentage jitter (80-120% of delay)
364
+ // jitter: delay => delay * (0.8 + Math.random() * 0.4)
365
+ // Absolute jitter (±100ms)
366
+ // jitter: delay => delay + (Math.random() * 200 - 100)
367
+ }
368
+ }).json();
369
+ ```
370
+ */
371
+ jitter?: boolean | ((delay: number) => number) | undefined;
372
+ /**
373
+ Whether to retry when the request times out.
374
+ @default false
375
+ @example
376
+ ```
377
+ import ky from 'ky';
378
+ const json = await ky('https://example.com', {
379
+ retry: {
380
+ limit: 3,
381
+ retryOnTimeout: true
382
+ }
383
+ }).json();
384
+ ```
385
+ */
386
+ retryOnTimeout?: boolean;
387
+ /**
388
+ A function to determine whether a retry should be attempted.
389
+ This function takes precedence over the default retry checks (`retryOnTimeout`, status code checks, etc.) for retriable methods. It is only called after the retry limit and method checks pass.
390
+ **Note:** This is different from the `beforeRetry` hook:
391
+ - `shouldRetry`: Controls WHETHER to retry (called before the retry decision is made)
392
+ - `beforeRetry`: Called AFTER retry is confirmed, allowing you to modify the request
393
+ Should return:
394
+ - `true` to force a retry (bypasses `retryOnTimeout`, status code checks, and other validations)
395
+ - `false` to prevent a retry (no retry will occur)
396
+ - `undefined` to use the default retry logic (`retryOnTimeout`, status codes, network errors). Unrecognized error types are not retried.
397
+ @default undefined
398
+ @example
399
+ ```
400
+ import ky, {HTTPError} from 'ky';
401
+ const json = await ky('https://example.com', {
402
+ retry: {
403
+ limit: 3,
404
+ shouldRetry: ({error, retryCount}) => {
405
+ // Retry on specific business logic errors from API
406
+ if (error instanceof HTTPError) {
407
+ const status = error.response.status;
408
+ // Retry on 429 (rate limit) but only for first 2 attempts
409
+ if (status === 429 && retryCount <= 2) {
410
+ return true;
411
+ }
412
+ // Don't retry on 4xx errors except rate limits
413
+ if (status >= 400 && status < 500) {
414
+ return false;
415
+ }
416
+ }
417
+ // Use default retry logic for other errors
418
+ return undefined;
419
+ }
420
+ }
421
+ }).json();
422
+ ```
423
+ */
424
+ shouldRetry?: (state: ShouldRetryState) => boolean | undefined | Promise<boolean | undefined>;
425
+ };
426
+ //#endregion
427
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/options.d.ts
428
+ type SearchParamsInit = string | string[][] | Record<string, string> | URLSearchParams | undefined;
429
+ type SearchParamsOption = SearchParamsInit | Record<string, string | number | boolean | undefined> | Array<Array<string | number | boolean>>;
430
+ type RequestHttpMethod = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';
431
+ type HttpMethod = LiteralUnion<RequestHttpMethod | 'options' | 'trace', string>;
432
+ type Input = string | URL | Request;
433
+ type Progress = {
434
+ /**
435
+ A number between `0` and `1` representing the progress percentage.
436
+ */
437
+ percent: number;
438
+ /**
439
+ The number of bytes transferred so far.
440
+ */
441
+ transferredBytes: number;
442
+ /**
443
+ The total number of bytes to be transferred. This is an estimate and may be `0` if the total size cannot be determined.
444
+ */
445
+ totalBytes: number;
446
+ };
447
+ type KyHeadersInit = NonNullable<RequestInit['headers']> | Record<string, string | undefined>;
448
+ /**
449
+ Custom Ky options
450
+ */
451
+ type KyOptions = {
452
+ /**
453
+ Shortcut for sending JSON. Use this instead of the `body` option.
454
+ Accepts any plain object or value, which will be stringified using `JSON.stringify()` and sent in the body with the correct header set.
455
+ */
456
+ json?: unknown;
457
+ /**
458
+ User-defined JSON-parsing function.
459
+ The function receives the response text as the first argument and a context object as the second argument containing the `request` and `response`.
460
+ Use-cases:
461
+ 1. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.
462
+ 2. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
463
+ 3. Log or handle JSON parse errors with request context.
464
+ @default JSON.parse()
465
+ @example
466
+ ```
467
+ import ky from 'ky';
468
+ import bourne from '@hapijs/bourne';
469
+ const json = await ky('https://example.com', {
470
+ parseJson: text => bourne(text)
471
+ }).json();
472
+ ```
473
+ @example
474
+ ```
475
+ import ky from 'ky';
476
+ const json = await ky('https://example.com', {
477
+ parseJson: (text, {request, response}) => {
478
+ console.log(`Parsing JSON from ${request.url} (status: ${response.status})`);
479
+ return JSON.parse(text);
480
+ }
481
+ }).json();
482
+ ```
483
+ */
484
+ parseJson?: (text: string, context: {
485
+ request: Request;
486
+ response: Response;
487
+ }) => unknown;
488
+ /**
489
+ User-defined JSON-stringifying function.
490
+ Use-cases:
491
+ 1. Stringify JSON with a custom `replacer` function.
492
+ @default JSON.stringify()
493
+ @example
494
+ ```
495
+ import ky from 'ky';
496
+ import {DateTime} from 'luxon';
497
+ const json = await ky('https://example.com', {
498
+ stringifyJson: data => JSON.stringify(data, (key, value) => {
499
+ if (key.endsWith('_at')) {
500
+ return DateTime.fromISO(value).toSeconds();
501
+ }
502
+ return value;
503
+ })
504
+ }).json();
505
+ ```
506
+ */
507
+ stringifyJson?: (data: unknown) => string;
508
+ /**
509
+ Search parameters to include in the request URL. Setting this will merge with any existing search parameters in the input URL.
510
+ Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).
511
+ When passing an object, setting a value to `undefined` deletes the parameter, while `null` values are preserved and converted to the string `'null'`.
512
+ */
513
+ searchParams?: SearchParamsOption;
514
+ /**
515
+ A base URL to [resolve](https://developer.mozilla.org/en-US/docs/Web/API/URL_API/Resolving_relative_references) the `input` against. When the `input` (after applying the `prefix` option) is only a relative URL, such as `'users'`, `'/users'`, or `'//my-site.com'`, it will be resolved against the `baseUrl` to determine the destination of the request. Otherwise, the `input` is absolute, such as `'https://my-site.com'`, and it will bypass the `baseUrl`.
516
+ Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky instances.
517
+ If the `baseUrl` itself is relative, it will be resolved against the environment's base URL, such as [`document.baseURI`](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) in browsers or `location.href` in Deno (see the `--location` flag).
518
+ **Tip:** When setting a `baseUrl` that has a path, we recommend that it include a trailing slash `/`, as in `'/api/'` rather than `/api`. This ensures more intuitive behavior for page-relative `input` URLs, such as `'users'` or `'./users'`, where they will _extend_ from the full path of the `baseUrl` rather than _replacing_ its last path segment.
519
+ @example
520
+ ```
521
+ import ky from 'ky';
522
+ // On https://example.com
523
+ const response = await ky('users', {baseUrl: '/api/'});
524
+ //=> 'https://example.com/api/users'
525
+ const response = await ky('/users', {baseUrl: '/api/'});
526
+ //=> 'https://example.com/users'
527
+ ```
528
+ */
529
+ baseUrl?: URL | string;
530
+ /**
531
+ A prefix to prepend to the `input` before making the request (and before it is resolved against the `baseUrl`). It can be any valid path or URL, either relative or absolute. A trailing slash `/` is optional and will be added automatically, if needed, when it is joined with `input`. Only takes effect when `input` is a string.
532
+ Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky instances.
533
+ *In most cases, you should use the `baseUrl` option instead, as it is more consistent with web standards. However, `prefix` is useful if you want origin-relative `input` URLs, such as `/users`, to be treated as if they were page-relative. In other words, the leading slash of the `input` will essentially be ignored, because the `prefix` will become part of the `input` before URL resolution happens.*
534
+ Notes:
535
+ - The `prefix` and `input` are joined with a slash `/`, and slashes are normalized at the join boundary by trimming trailing slashes from `prefix` and leading slashes from `input`.
536
+ - After `prefix` and `input` are joined, the result is resolved against the `baseUrl` option, if present.
537
+ @example
538
+ ```
539
+ import ky from 'ky';
540
+ // On https://example.com
541
+ const response = await ky('users', {prefix: '/api/'});
542
+ //=> 'https://example.com/api/users'
543
+ const response = await ky('/users', {prefix: '/api/'});
544
+ //=> 'https://example.com/api/users'
545
+ ```
546
+ */
547
+ prefix?: URL | string;
548
+ /**
549
+ Controls retry behavior. Each field is documented in the `RetryOptions` type.
550
+ If `retry` is a number, it will be used as `limit` and other defaults will remain in place.
551
+ Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.
552
+ If the response provides an HTTP status contained in `afterStatusCodes`, Ky will wait until the date, timeout, or timestamp given in the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header has passed to retry the request. If `Retry-After` is missing, the non-standard [`RateLimit-Reset`](https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-05.html#section-3.3) header is used in its place as a fallback. If the provided status code is not in the list, the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header will be ignored.
553
+ If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.
554
+ @example
555
+ ```
556
+ import ky from 'ky';
557
+ const json = await ky('https://example.com', {
558
+ retry: {
559
+ limit: 10,
560
+ methods: ['get'],
561
+ statusCodes: [413]
562
+ }
563
+ }).json();
564
+ ```
565
+ */
566
+ retry?: RetryOptions | number;
567
+ /**
568
+ Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Cannot be greater than 2147483647. See also `totalTimeout`.
569
+ If set to `false`, there will be no per-attempt timeout.
570
+ @default 10000
571
+ */
572
+ timeout?: number | false;
573
+ /**
574
+ Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Cannot be greater than 2147483647.
575
+ If set to `false` or not specified, there is no overall timeout.
576
+ @default false
577
+ @example
578
+ ```
579
+ import ky from 'ky';
580
+ // Each attempt gets 5s, but the whole operation must complete within 30s
581
+ const json = await ky('https://example.com', {
582
+ timeout: 5000,
583
+ totalTimeout: 30_000,
584
+ retry: {
585
+ limit: 3,
586
+ retryOnTimeout: true,
587
+ }
588
+ }).json();
589
+ ```
590
+ */
591
+ totalTimeout?: number | false;
592
+ /**
593
+ Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.
594
+ */
595
+ hooks?: Hooks;
596
+ /**
597
+ Throw an `HTTPError` when, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set the [`redirect`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) option to `'manual'`.
598
+ Setting this to `false` may be useful if you are checking for resource availability and are expecting error responses.
599
+ You can also pass a function that accepts the HTTP status code and returns a boolean for selective error handling. Note that this can violate the principle of least surprise, so it's recommended to use the boolean form unless you have a specific use case like treating 404 responses differently.
600
+ Note: If `false`, error responses are considered successful and the request will not be retried.
601
+ Note: [Opaque responses](https://developer.mozilla.org/en-US/docs/Web/API/Response/type) from `no-cors` requests are returned as-is (without throwing `HTTPError`), since the actual status is hidden by the browser.
602
+ @default true
603
+ */
604
+ throwHttpErrors?: boolean | ((status: number) => boolean);
605
+ /**
606
+ Download progress event handler.
607
+ @param progress - Object containing download progress information.
608
+ @param chunk - Data that was received. Note: It's empty for the first call.
609
+ @example
610
+ ```
611
+ import ky from 'ky';
612
+ const response = await ky('https://example.com', {
613
+ onDownloadProgress: (progress, chunk) => {
614
+ // Example output:
615
+ // `0% - 0 of 1271 bytes`
616
+ // `100% - 1271 of 1271 bytes`
617
+ console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);
618
+ }
619
+ });
620
+ ```
621
+ */
622
+ onDownloadProgress?: (progress: Progress, chunk: Uint8Array) => void;
623
+ /**
624
+ Upload progress event handler.
625
+ Note: Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and HTTP/2 for HTTPS connections (in Chromium-based browsers). In unsupported environments, this handler is silently ignored.
626
+ @param progress - Object containing upload progress information.
627
+ @param chunk - Data that was sent. Note: It's empty for the last call.
628
+ @example
629
+ ```
630
+ import ky from 'ky';
631
+ const response = await ky.post('https://example.com/upload', {
632
+ body: largeFile,
633
+ onUploadProgress: (progress, chunk) => {
634
+ // Example output:
635
+ // `0% - 0 of 1271 bytes`
636
+ // `100% - 1271 of 1271 bytes`
637
+ console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);
638
+ }
639
+ });
640
+ ```
641
+ */
642
+ onUploadProgress?: (progress: Progress, chunk: Uint8Array) => void;
643
+ /**
644
+ User-defined `fetch` function.
645
+ Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard.
646
+ Use-cases:
647
+ 1. Use the `fetch` wrapper function provided by some frameworks that use server-side rendering (SSR).
648
+ 2. Add custom instrumentation or logging to all requests.
649
+ @default fetch
650
+ @example
651
+ ```
652
+ import ky from 'ky';
653
+ const api = ky.create({
654
+ fetch: async (request, init) => {
655
+ const start = performance.now();
656
+ const response = await fetch(request, init);
657
+ const duration = performance.now() - start;
658
+ console.log(`${request.method} ${request.url} - ${response.status} (${Math.round(duration)}ms)`);
659
+ return response;
660
+ }
661
+ });
662
+ const json = await api('https://example.com').json();
663
+ ```
664
+ */
665
+ fetch?: (input: Input, init?: RequestInit) => Promise<Response>;
666
+ /**
667
+ User-defined data passed to hooks.
668
+ This option allows you to pass arbitrary contextual data to hooks without polluting the request itself. The context is available in all hooks and is **guaranteed to always be an object** (never `undefined`), so you can safely access properties without optional chaining.
669
+ Use cases:
670
+ - Pass authentication tokens or API keys to hooks
671
+ - Attach request metadata for logging or debugging
672
+ - Implement conditional logic in hooks based on the request context
673
+ - Pass serverless environment bindings (e.g., Cloudflare Workers)
674
+ **Note:** Context is shallow merged. Top-level properties are merged, but nested objects are replaced. Only enumerable properties are copied.
675
+ @example
676
+ ```
677
+ import ky from 'ky';
678
+ // Pass data to hooks
679
+ const api = ky.create({
680
+ hooks: {
681
+ beforeRequest: [
682
+ ({request, options}) => {
683
+ const {token} = options.context;
684
+ if (token) {
685
+ request.headers.set('Authorization', `Bearer ${token}`);
686
+ }
687
+ }
688
+ ]
689
+ }
690
+ });
691
+ await api('https://example.com', {
692
+ context: {
693
+ token: 'secret123'
694
+ }
695
+ }).json();
696
+ // Shallow merge: only top-level properties are merged
697
+ const instance = ky.create({
698
+ context: {
699
+ a: 1,
700
+ b: {
701
+ nested: true
702
+ }
703
+ }
704
+ });
705
+ const extended = instance.extend({
706
+ context: {
707
+ b: {
708
+ updated: true
709
+ },
710
+ c: 3
711
+ }
712
+ });
713
+ // Result: {a: 1, b: {updated: true}, c: 3}
714
+ // Note: The original `b.nested` is gone (shallow merge)
715
+ ```
716
+ @default {}
717
+ */
718
+ context?: Record<string, unknown>;
719
+ };
720
+ /**
721
+ Options are the same as `window.fetch`, except for the KyOptions
722
+ */
723
+ interface Options extends KyOptions, Omit<RequestInit, 'headers'> {
724
+ /**
725
+ HTTP method used to make the request.
726
+ Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.
727
+ */
728
+ method?: LiteralUnion<HttpMethod, string>;
729
+ /**
730
+ HTTP headers used to make the request.
731
+ You can pass a `Headers` instance or a plain object.
732
+ You can remove a header with `.extend()` by passing the header with an `undefined` value. Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.
733
+ @example
734
+ ```
735
+ import ky from 'ky';
736
+ const url = 'https://sindresorhus.com';
737
+ const original = ky.create({
738
+ headers: {
739
+ rainbow: 'rainbow',
740
+ unicorn: 'unicorn'
741
+ }
742
+ });
743
+ const extended = original.extend({
744
+ headers: {
745
+ rainbow: undefined
746
+ }
747
+ });
748
+ const response = await extended(url).json();
749
+ console.log('rainbow' in response);
750
+ //=> false
751
+ console.log('unicorn' in response);
752
+ //=> true
753
+ ```
754
+ */
755
+ headers?: KyHeadersInit;
756
+ }
757
+ /**
758
+ Normalized options passed to the `fetch` call and hooks.
759
+ */
760
+ interface NormalizedOptions extends RequestInit {
761
+ method: NonNullable<RequestInit['method']>;
762
+ credentials?: NonNullable<RequestInit['credentials']>;
763
+ retry: RetryOptions;
764
+ baseUrl?: Options['baseUrl'];
765
+ prefix: string;
766
+ onDownloadProgress: Options['onDownloadProgress'];
767
+ onUploadProgress: Options['onUploadProgress'];
768
+ context: Record<string, unknown>;
769
+ }
770
+ //#endregion
771
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/core/constants.d.ts
772
+ /**
773
+ Symbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.
774
+ */
775
+ declare const stop: unique symbol;
776
+ /**
777
+ Options for forcing a retry via `ky.retry()`.
778
+ */
779
+ type ForceRetryOptions = {
780
+ /**
781
+ Custom delay in milliseconds before retrying.
782
+ If not provided, uses the default retry delay calculation based on `retry.delay` configuration.
783
+ **Note:** Custom delays bypass jitter and `backoffLimit`. This is intentional, as custom delays often come from server responses (e.g., `Retry-After` headers) and should be respected exactly as specified.
784
+ */
785
+ delay?: number;
786
+ /**
787
+ Error code for the retry.
788
+ This machine-readable identifier will be included in the error message passed to `beforeRetry` hooks, allowing you to distinguish between different types of forced retries.
789
+ @example
790
+ ```
791
+ return ky.retry({code: 'RATE_LIMIT'});
792
+ // Resulting error message: 'Forced retry: RATE_LIMIT'
793
+ ```
794
+ */
795
+ code?: string;
796
+ /**
797
+ Original error that caused the retry.
798
+ This allows you to preserve the error chain when forcing a retry based on caught exceptions. The error will be set as the `cause` of the `ForceRetryError`, enabling proper error chain traversal.
799
+ @example
800
+ ```
801
+ try {
802
+ const data = await response.json();
803
+ validateBusinessLogic(data);
804
+ } catch (error) {
805
+ return ky.retry({
806
+ code: 'VALIDATION_FAILED',
807
+ cause: error // Preserves original error in chain
808
+ });
809
+ }
810
+ ```
811
+ */
812
+ cause?: Error;
813
+ /**
814
+ Custom request to use for the retry.
815
+ This allows you to modify or completely replace the request during a forced retry. The custom request becomes the starting point for the retry - `beforeRetry` hooks can still further modify it if needed.
816
+ **Note:** The custom request's `signal` will be replaced with Ky's managed signal to handle timeouts and user-provided abort signals correctly. If the original request body has been consumed, you must provide a new body or clone the request before consuming.
817
+ **Warning:** Custom retry requests are not sanitized. If you reuse headers across origins, remove any credentials you do not want forwarded.
818
+ @example
819
+ ```
820
+ // Fallback to a different endpoint
821
+ return ky.retry({
822
+ request: new Request('https://backup-api.com/endpoint', {
823
+ method: request.method,
824
+ headers: request.headers,
825
+ }),
826
+ code: 'BACKUP_ENDPOINT'
827
+ });
828
+ // Retry with refreshed authentication token
829
+ const data = await response.json();
830
+ return ky.retry({
831
+ request: new Request(request, {
832
+ headers: {
833
+ ...Object.fromEntries(request.headers),
834
+ 'Authorization': `Bearer ${data.newToken}`
835
+ }
836
+ }),
837
+ code: 'TOKEN_REFRESHED'
838
+ });
839
+ ```
840
+ */
841
+ request?: Request;
842
+ };
843
+ /**
844
+ Marker returned by `ky.retry()` to signal a forced retry from `afterResponse` hooks.
845
+ */
846
+ declare class RetryMarker {
847
+ options: ForceRetryOptions | undefined;
848
+ constructor(options?: ForceRetryOptions);
849
+ }
850
+ /**
851
+ Force a retry from an `afterResponse` hook.
852
+
853
+ This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.
854
+
855
+ @param options - Optional configuration for the retry.
856
+
857
+ @example
858
+ ```
859
+ import ky, {isForceRetryError} from 'ky';
860
+
861
+ const api = ky.extend({
862
+ hooks: {
863
+ afterResponse: [
864
+ async ({request, response}) => {
865
+ // Retry based on response body content
866
+ if (response.status === 200) {
867
+ const data = await response.json();
868
+
869
+ // Simple retry with default delay
870
+ if (data.error?.code === 'TEMPORARY_ERROR') {
871
+ return ky.retry();
872
+ }
873
+
874
+ // Retry with custom delay from API response
875
+ if (data.error?.code === 'RATE_LIMIT') {
876
+ return ky.retry({
877
+ delay: data.error.retryAfter * 1000,
878
+ code: 'RATE_LIMIT'
879
+ });
880
+ }
881
+
882
+ // Retry with a modified request (e.g., fallback endpoint)
883
+ if (data.error?.code === 'FALLBACK_TO_BACKUP') {
884
+ return ky.retry({
885
+ request: new Request('https://backup-api.com/endpoint', {
886
+ method: request.method,
887
+ headers: request.headers,
888
+ }),
889
+ code: 'BACKUP_ENDPOINT'
890
+ });
891
+ }
892
+
893
+ // Retry with refreshed authentication
894
+ if (data.error?.code === 'TOKEN_REFRESH' && data.newToken) {
895
+ return ky.retry({
896
+ request: new Request(request, {
897
+ headers: {
898
+ ...Object.fromEntries(request.headers),
899
+ 'Authorization': `Bearer ${data.newToken}`
900
+ }
901
+ }),
902
+ code: 'TOKEN_REFRESHED'
903
+ });
904
+ }
905
+
906
+ // Retry with cause to preserve error chain
907
+ try {
908
+ validateResponse(data);
909
+ } catch (error) {
910
+ return ky.retry({
911
+ code: 'VALIDATION_FAILED',
912
+ cause: error
913
+ });
914
+ }
915
+ }
916
+ }
917
+ ],
918
+ beforeRetry: [
919
+ ({error, retryCount}) => {
920
+ // Observable in beforeRetry hooks
921
+ if (isForceRetryError(error)) {
922
+ console.log(`Forced retry #${retryCount}: ${error.message}`);
923
+ // Example output: "Forced retry #1: Forced retry: RATE_LIMIT"
924
+ }
925
+ }
926
+ ]
927
+ }
928
+ });
929
+
930
+ const response = await api.get('https://example.com/api');
931
+ ```
932
+ */
933
+ declare const retry: (options?: ForceRetryOptions) => RetryMarker;
934
+ //#endregion
935
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/response.d.ts
936
+ type KyResponse<T = unknown> = {
937
+ json: <J = T>() => Promise<J>;
938
+ } & Response;
939
+ //#endregion
940
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/standard-schema.d.ts
941
+ type StandardSchemaV1Issue = {
942
+ readonly message: string;
943
+ readonly path?: ReadonlyArray<PropertyKey | {
944
+ readonly key: PropertyKey;
945
+ }> | undefined;
946
+ };
947
+ type StandardSchemaV1SuccessResult<OutputType> = {
948
+ readonly value: OutputType;
949
+ readonly issues?: undefined;
950
+ };
951
+ type StandardSchemaV1FailureResult = {
952
+ readonly issues: readonly StandardSchemaV1Issue[];
953
+ readonly value?: undefined;
954
+ };
955
+ type StandardSchemaV1Result<OutputType> = StandardSchemaV1SuccessResult<OutputType> | StandardSchemaV1FailureResult;
956
+ type StandardSchemaV1Types<InputType, OutputType> = {
957
+ readonly input: InputType;
958
+ readonly output: OutputType;
959
+ };
960
+ type StandardSchemaV1Options = {
961
+ readonly libraryOptions?: Readonly<Record<string, unknown>> | undefined;
962
+ };
963
+ type StandardSchemaV1<InputType = unknown, OutputType = InputType> = {
964
+ readonly '~standard': {
965
+ readonly version: 1;
966
+ readonly vendor: string;
967
+ readonly validate: (value: unknown, options?: StandardSchemaV1Options) => StandardSchemaV1Result<OutputType> | Promise<StandardSchemaV1Result<OutputType>>;
968
+ readonly types?: StandardSchemaV1Types<InputType, OutputType> | undefined;
969
+ };
970
+ };
971
+ type StandardSchemaV1InferOutput<Schema extends StandardSchemaV1> = Schema['~standard'] extends {
972
+ readonly types: StandardSchemaV1Types<unknown, infer OutputType>;
973
+ } ? OutputType : Extract<Awaited<ReturnType<Schema['~standard']['validate']>>, StandardSchemaV1SuccessResult<unknown>> extends StandardSchemaV1SuccessResult<infer OutputType> ? OutputType : unknown;
974
+ //#endregion
975
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/ResponsePromise.d.ts
976
+ type ResponsePromise<T = unknown> = {
977
+ arrayBuffer: () => Promise<ArrayBuffer>;
978
+ blob: () => Promise<Blob>;
979
+ formData: () => Promise<FormData>;
980
+ /**
981
+ Get the response body as raw bytes.
982
+ Note: This shortcut is only available when the runtime supports `Response.prototype.bytes()`.
983
+ */
984
+ bytes: () => Promise<Uint8Array>;
985
+ json: {
986
+ /**
987
+ Get the response body as JSON.
988
+ @example
989
+ ```
990
+ import ky from 'ky';
991
+ const json = await ky(…).json();
992
+ ```
993
+ @example
994
+ ```
995
+ import ky from 'ky';
996
+ interface Result {
997
+ value: number;
998
+ }
999
+ const result1 = await ky(…).json<Result>();
1000
+ // or
1001
+ const result2 = await ky<Result>(…).json();
1002
+ ```
1003
+ */
1004
+ <JsonType = T>(): Promise<JsonType>;
1005
+ /**
1006
+ Get the response body as JSON and validate it with a Standard Schema.
1007
+ Use a Standard Schema compatible validator (for example, Zod 3.24+).
1008
+ Throws a `SchemaValidationError` when validation fails.
1009
+ @example
1010
+ ```
1011
+ import ky from 'ky';
1012
+ import {z} from 'zod';
1013
+ const userSchema = z.object({name: z.string()});
1014
+ const user = await ky('/api/user').json(userSchema);
1015
+ ```
1016
+ */
1017
+ <Schema extends StandardSchemaV1>(schema: Schema): Promise<StandardSchemaV1InferOutput<Schema>>;
1018
+ };
1019
+ text: () => Promise<string>;
1020
+ } & Promise<KyResponse<T>>;
1021
+ //#endregion
1022
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/ky.d.ts
1023
+ type KyInstance = {
1024
+ /**
1025
+ Fetch the given `url`.
1026
+ @param url - `Request` object, `URL` object, or URL string.
1027
+ @returns A promise with `Body` method added.
1028
+ @example
1029
+ ```
1030
+ import ky from 'ky';
1031
+ const json = await ky('https://example.com', {json: {foo: true}}).json();
1032
+ console.log(json);
1033
+ //=> `{data: '🦄'}`
1034
+ ```
1035
+ */
1036
+ <T>(url: Input, options?: Options): ResponsePromise<T>;
1037
+ /**
1038
+ Fetch the given `url` using the option `{method: 'get'}`.
1039
+ @param url - `Request` object, `URL` object, or URL string.
1040
+ @returns A promise with `Body` methods added.
1041
+ */
1042
+ get: <T>(url: Input, options?: Options) => ResponsePromise<T>;
1043
+ /**
1044
+ Fetch the given `url` using the option `{method: 'post'}`.
1045
+ @param url - `Request` object, `URL` object, or URL string.
1046
+ @returns A promise with `Body` methods added.
1047
+ */
1048
+ post: <T>(url: Input, options?: Options) => ResponsePromise<T>;
1049
+ /**
1050
+ Fetch the given `url` using the option `{method: 'put'}`.
1051
+ @param url - `Request` object, `URL` object, or URL string.
1052
+ @returns A promise with `Body` methods added.
1053
+ */
1054
+ put: <T>(url: Input, options?: Options) => ResponsePromise<T>;
1055
+ /**
1056
+ Fetch the given `url` using the option `{method: 'delete'}`.
1057
+ @param url - `Request` object, `URL` object, or URL string.
1058
+ @returns A promise with `Body` methods added.
1059
+ */
1060
+ delete: <T>(url: Input, options?: Options) => ResponsePromise<T>;
1061
+ /**
1062
+ Fetch the given `url` using the option `{method: 'patch'}`.
1063
+ @param url - `Request` object, `URL` object, or URL string.
1064
+ @returns A promise with `Body` methods added.
1065
+ */
1066
+ patch: <T>(url: Input, options?: Options) => ResponsePromise<T>;
1067
+ /**
1068
+ Fetch the given `url` using the option `{method: 'head'}`.
1069
+ @param url - `Request` object, `URL` object, or URL string.
1070
+ @returns A promise with `Body` methods added.
1071
+ */
1072
+ head: (url: Input, options?: Options) => ResponsePromise;
1073
+ /**
1074
+ Create a new Ky instance with complete new defaults, without inheriting from any parent instance.
1075
+ @returns A new Ky instance.
1076
+ */
1077
+ create: (defaultOptions?: Options) => KyInstance;
1078
+ /**
1079
+ Create a new Ky instance with some defaults overridden with your own.
1080
+ In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.
1081
+ You can pass headers as a `Headers` instance or a plain object.
1082
+ You can remove a header with `.extend()` by passing the header with an `undefined` value. Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.
1083
+ Similarly, you can remove existing `hooks` entries by extending the hook with an explicit `undefined`.
1084
+ By default, `.extend()` deep-merges options: hooks are appended, headers are merged, and search parameters are accumulated. Use `replaceOption` when you want to fully replace a merged property instead.
1085
+ You can also refer to parent defaults by providing a function to `.extend()`.
1086
+ @example
1087
+ ```
1088
+ import ky from 'ky';
1089
+ const api = ky.create({prefix: 'https://example.com/api'});
1090
+ const usersApi = api.extend((options) => ({prefix: `${options.prefix}/users`}));
1091
+ const response = await usersApi.get('123');
1092
+ //=> 'https://example.com/api/users/123'
1093
+ const response = await api.get('version');
1094
+ //=> 'https://example.com/api/version'
1095
+ ```
1096
+ @returns A new Ky instance.
1097
+ */
1098
+ extend: (defaultOptions: Options | ((parentOptions: Options) => Options)) => KyInstance;
1099
+ /**
1100
+ A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.
1101
+ Note: Returning this symbol makes Ky abort and return with an `undefined` response. Be sure to check for a response before accessing any properties on it or use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). It is also incompatible with body methods, such as `.json()` or `.text()`, because there is no response to parse. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.
1102
+ A valid use-case for `ky.stop` is to prevent retries when making requests for side effects, where the returned data is not important. For example, logging client activity to the server.
1103
+ @example
1104
+ ```
1105
+ import ky from 'ky';
1106
+ const options = {
1107
+ hooks: {
1108
+ beforeRetry: [
1109
+ async ({request, options, error, retryCount}) => {
1110
+ const shouldStopRetry = await ky('https://example.com/api');
1111
+ if (shouldStopRetry) {
1112
+ return ky.stop;
1113
+ }
1114
+ }
1115
+ ]
1116
+ }
1117
+ };
1118
+ // Note that response will be `undefined` in case `ky.stop` is returned.
1119
+ const response = await ky.post('https://example.com', options);
1120
+ // Using `.text()` or other body methods is not supported.
1121
+ const text = await ky('https://example.com', options).text();
1122
+ ```
1123
+ */
1124
+ readonly stop: typeof stop;
1125
+ /**
1126
+ Force a retry from an `afterResponse` hook.
1127
+ This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.
1128
+ @example
1129
+ ```
1130
+ import ky, {isForceRetryError} from 'ky';
1131
+ const api = ky.extend({
1132
+ hooks: {
1133
+ afterResponse: [
1134
+ async ({response}) => {
1135
+ // Retry based on response body content
1136
+ if (response.status === 200) {
1137
+ const data = await response.json();
1138
+ // Simple retry with default delay
1139
+ if (data.error?.code === 'TEMPORARY_ERROR') {
1140
+ return ky.retry();
1141
+ }
1142
+ // Retry with custom delay from API response
1143
+ if (data.error?.code === 'RATE_LIMIT') {
1144
+ return ky.retry({
1145
+ delay: data.error.retryAfter * 1000,
1146
+ code: 'RATE_LIMIT'
1147
+ });
1148
+ }
1149
+ }
1150
+ }
1151
+ ],
1152
+ beforeRetry: [
1153
+ ({error, retryCount}) => {
1154
+ // Observable in beforeRetry hooks
1155
+ if (isForceRetryError(error)) {
1156
+ console.log(`Forced retry #${retryCount}: ${error.message}`);
1157
+ // Example output: "Forced retry #1: Forced retry: RATE_LIMIT"
1158
+ }
1159
+ }
1160
+ ]
1161
+ }
1162
+ });
1163
+ const response = await api.get('https://example.com/api');
1164
+ ```
1165
+ */
1166
+ readonly retry: typeof retry;
1167
+ };
1168
+ //#endregion
1169
+ //#region ../../node_modules/.bun/ky@2.0.2/node_modules/ky/distribution/types/request.d.ts
1170
+ type KyRequest<T = unknown> = {
1171
+ json: <J = T>() => Promise<J>;
1172
+ } & Request;
1173
+ //#endregion
1174
+ //#region src/lib/validation.d.ts
1175
+ type ResourceResolutionRecord = {
1176
+ input: string;
1177
+ id: string;
1178
+ url?: string;
1179
+ source: ResourceResolutionSource;
1180
+ };
1181
+ type ResourceResolutionSource = "parsed" | "lookup" | "internal";
1182
+ type ResourceResolverPlatform = "linkedin" | "x";
1183
+ type TargetKind = "profile" | "post" | "list" | "chat" | "company" | "request";
1184
+ type TargetResolution = {
1185
+ kind: TargetKind;
1186
+ id: string;
1187
+ record: ResourceResolutionRecord;
1188
+ };
1189
+ //#endregion
1190
+ //#region src/lib/output.d.ts
1191
+ type ResultAccount = {
1192
+ platform: "linkedin" | "x";
1193
+ handle: string;
1194
+ selector?: string;
1195
+ };
1196
+ type PrintResultArgs = {
1197
+ account: ResultAccount;
1198
+ contract?: unknown;
1199
+ data: unknown;
1200
+ resolved?: ResourceResolutionRecord[];
1201
+ responseHeaders?: Headers;
1202
+ };
1203
+ //#endregion
1204
+ //#region src/lib/ui.d.ts
1205
+ type SpinnerHandle = {
1206
+ start: (msg?: string) => void;
1207
+ stop: (msg?: string) => void;
1208
+ error: (msg?: string) => void;
1209
+ message: (msg: string) => void;
1210
+ withElapsed: (base: string) => () => void;
1211
+ };
1212
+ type TextOptions = {
1213
+ message: string;
1214
+ placeholder?: string;
1215
+ initialValue?: string;
1216
+ validate?: (value: string | undefined) => string | Error | undefined;
1217
+ flag?: string;
1218
+ };
1219
+ type ConfirmOptions = {
1220
+ message: string;
1221
+ yes?: boolean;
1222
+ initialValue?: boolean;
1223
+ };
1224
+ type MultiselectOption = {
1225
+ value: string;
1226
+ label: string;
1227
+ hint?: string;
1228
+ disabled?: boolean;
1229
+ };
1230
+ type MultiselectOptions = {
1231
+ message: string;
1232
+ options: MultiselectOption[];
1233
+ initialValues?: string[];
1234
+ required?: boolean;
1235
+ flag?: string;
1236
+ };
1237
+ type UI = {
1238
+ intro: (msg: string) => void;
1239
+ outro: (msg: string) => void;
1240
+ info: (msg: string) => void;
1241
+ success: (msg: string) => void;
1242
+ warn: (msg: string) => void;
1243
+ error: (msg: string) => void;
1244
+ step: (msg: string) => void;
1245
+ note: (msg: string, title?: string) => void;
1246
+ text: (opts: TextOptions) => Promise<string>;
1247
+ confirm: (opts: ConfirmOptions) => Promise<boolean>;
1248
+ multiselect: (opts: MultiselectOptions) => Promise<string[]>;
1249
+ spinner: () => SpinnerHandle;
1250
+ spin: <T>(start: string, op: () => Promise<T>, success?: string) => Promise<T>;
1251
+ spinElapsed: <T>(start: string, op: () => Promise<T>, success?: string) => Promise<T>;
1252
+ };
1253
+ //#endregion
1
1254
  //#region ../../node_modules/.bun/citty@0.2.2/node_modules/citty/dist/index.d.mts
2
1255
  //#region src/types.d.ts
3
1256
  type ArgType = "boolean" | "string" | "enum" | "positional" | undefined;
@@ -77,6 +1330,25 @@ type CittyPlugin = {
77
1330
  type Resolvable<T> = T | Promise<T> | (() => T) | (() => Promise<T>); //#endregion
78
1331
  //#region src/command.d.ts
79
1332
  //#endregion
1333
+ //#region src/lib/analytics.d.ts
1334
+ /** Every analytics event name the CLI emits. */
1335
+ type AnalyticsEvent = "command_executed" | "cli_first_run" | "login_started" | "login_phase_completed" | "login_completed" | "login_failed" | "logout";
1336
+ type Analytics = {
1337
+ /** Queue an event. No-op when disabled. Never throws. */capture(event: AnalyticsEvent, properties?: Record<string, unknown>): void; /** True when telemetry is active (token present, not opted-out, not CI). */
1338
+ readonly enabled: boolean;
1339
+ /**
1340
+ * On login: alias(anonymousId → userId) once, persist userId as the
1341
+ * distinct_id, set person props. No-op when disabled.
1342
+ */
1343
+ identifyUser(userId: string, properties?: Record<string, unknown>): void; /** On logout: clear cached userId; revert distinct_id to anonymousId. */
1344
+ reset(): void;
1345
+ /**
1346
+ * Flush queued events, bounded by timeoutMs. Resolves immediately when
1347
+ * disabled. Never throws/rejects.
1348
+ */
1349
+ shutdown(timeoutMs: number): Promise<void>;
1350
+ };
1351
+ //#endregion
80
1352
  //#region src/index.d.ts
81
1353
  type MutableCommand = CommandDef<any> & {
82
1354
  args?: any;
@@ -94,5 +1366,126 @@ type MutableCommand = CommandDef<any> & {
94
1366
  * flag values.
95
1367
  */
96
1368
  declare const resolveCommandPath: (command: MutableCommand, rawArgs: string[]) => Promise<string[]>;
1369
+ declare const createSocialCommand: (deps?: {
1370
+ client: {
1371
+ listAccounts: any;
1372
+ createHostedAuthURL: any;
1373
+ disconnectAccount: any;
1374
+ accounts: {
1375
+ list: any;
1376
+ disconnect: any;
1377
+ };
1378
+ billing: {
1379
+ status: () => Promise<{
1380
+ canConnect: any;
1381
+ seats: any;
1382
+ }>;
1383
+ prepareAccountConnect: () => Promise<{
1384
+ canConnect: any;
1385
+ paymentURL: any;
1386
+ requiredAction: any;
1387
+ seats: any;
1388
+ }>;
1389
+ };
1390
+ usage: {
1391
+ summary: any;
1392
+ list: any;
1393
+ };
1394
+ };
1395
+ api: KyInstance;
1396
+ parseResourceId: (name: string, value: unknown) => string;
1397
+ parseQueryString: (name: string, value: unknown) => string;
1398
+ parseIntegerString: (name: string, value: unknown, options?: {
1399
+ min?: number;
1400
+ max?: number;
1401
+ }) => number;
1402
+ parseEnumString: <Values extends readonly [string, ...string[]]>(name: string, value: unknown, values: Values, options?: {
1403
+ message?: string;
1404
+ }) => Values[number];
1405
+ parseBooleanString: (name: string, value: unknown) => boolean;
1406
+ parseResourceIdList: (name: string, values: unknown[]) => string[];
1407
+ parseJSONObject: (name: string, value: unknown) => Record<string, unknown>;
1408
+ plainResourceRecord: (platform: ResourceResolverPlatform, kind: TargetKind, id: string, options?: {
1409
+ input?: string;
1410
+ }) => ResourceResolutionRecord;
1411
+ resolveTarget: (name: string, value: unknown, options: {
1412
+ account?: string;
1413
+ platform: ResourceResolverPlatform;
1414
+ expect: TargetKind[];
1415
+ recordInput?: string;
1416
+ }) => Promise<TargetResolution>;
1417
+ classifyMessageTarget: (name: string, value: unknown, options: {
1418
+ account?: string;
1419
+ platform: ResourceResolverPlatform;
1420
+ recordInput?: string;
1421
+ }) => Promise<{
1422
+ kind: "person" | "thread";
1423
+ id: string;
1424
+ record: ResourceResolutionRecord;
1425
+ }>;
1426
+ commandHeaders: (args: {
1427
+ headers?: unknown;
1428
+ rawArgs?: string[];
1429
+ }) => Promise<{
1430
+ [k: string]: string;
1431
+ }>;
1432
+ printData: (value: unknown) => void;
1433
+ printResult: (args: PrintResultArgs) => void;
1434
+ resolveAccount: ({
1435
+ account,
1436
+ platform
1437
+ }: {
1438
+ account?: string;
1439
+ platform: ResourceResolverPlatform;
1440
+ }) => Promise<ResultAccount>;
1441
+ resolveAccountId: (args: {
1442
+ account?: string;
1443
+ }) => Promise<string | undefined>;
1444
+ resolveOwnXAccount: ({
1445
+ account
1446
+ }: {
1447
+ account?: string;
1448
+ }) => Promise<{
1449
+ account: {
1450
+ platform: "x";
1451
+ handle: any;
1452
+ selector: string;
1453
+ };
1454
+ accountIdHeader: string;
1455
+ xUserId: any;
1456
+ }>;
1457
+ resolveOwnLinkedinAccount: ({
1458
+ account
1459
+ }: {
1460
+ account?: string;
1461
+ }) => Promise<{
1462
+ account: {
1463
+ platform: "linkedin";
1464
+ handle: any;
1465
+ selector: string;
1466
+ };
1467
+ accountIdHeader: string;
1468
+ providerId: string;
1469
+ }>;
1470
+ openBrowser: (url: string) => Promise<boolean>;
1471
+ isInteractiveTerminal: () => boolean;
1472
+ webBaseURL: () => string;
1473
+ openURL: (url: string) => Promise<{
1474
+ opened: boolean;
1475
+ url: string;
1476
+ }>;
1477
+ writeOutput: (value: unknown) => void;
1478
+ ui: UI;
1479
+ }) => MutableCommand;
1480
+ declare const runSocial: ({
1481
+ command,
1482
+ rawArgs,
1483
+ telemetry
1484
+ }?: {
1485
+ command?: MutableCommand;
1486
+ rawArgs?: string[];
1487
+ telemetry?: Analytics;
1488
+ }) => Promise<number>;
1489
+ declare const main: () => Promise<never>;
97
1490
  //#endregion
98
- export { resolveCommandPath };
1491
+ export { createSocialCommand, main, resolveCommandPath, runSocial };