Skip to content
Myr

retry.ts

This file

Path

test/retry.ts

5,414 lines · 140.3 KiB · TypeScript

Last changed by

Fix CISindre Sorhusbefore adoptiond9ddb03

History of this file

Take it

The walk stopped after 200 commits: lines older than 37fc250 point at it.

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 1why, one step back
1import process from 'node:process';

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 2why, one step back
2import {setTimeout as delay} from 'node:timers/promises';

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 3why, one step back
3import test, {type ExecutionContext} from 'ava';

Fix retry abort propagation and uploads without request stream supportSindre Sorhusbefore adoption6520f64

line 4why, one step back
4import LeakDetector from 'jest-leak-detector';

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 5why, one step back
5import ky, {

Fix extending an object `retry` with a number dropping the other retry optionsSindre Sorhusbefore adoptionee3dec1

line 6why, one step back
6 replaceOption,

Accept a cross-realm `beforeError` error and validate a `ky.retry({delay})`Sindre Sorhusbefore adoptionbd0e26f

line 7why, one step back
7 ForceRetryError,

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

lines 8–11why, one step back
8 NetworkError,
9 TimeoutError,10 isKyError,11 isNetworkError,

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 12why, one step back
12 type RetryOptions,

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 13why, one step back
13} from '../source/index.js';

Preserve non-Error values in retry errors and hooksSindre Sorhusbefore adoption87a96db

line 14why, one step back
14import {NonError} from '../source/errors/NonError.js';

Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2

line 15why, one step back
15import {validateAndMerge} from '../source/utils/merge.js';

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 16why, one step back
16import {createHttpTestServer} from './helpers/create-http-test-server.js';

Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd

line 17why, one step back
17import {parseRawBody} from './helpers/parse-body.js';

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 18–20why, one step back
18import {withPerformance} from './helpers/with-performance.js';
1920const fixture = 'fixture';

Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c

lines 21–120why, one step back
21
22for (const {title, elapsed, totalTimeout, errorType} of [23 {24 title: 'expired', elapsed: 100, totalTimeout: 50, errorType: TimeoutError,25 },26 {27 title: 'unexpired', elapsed: 25, totalTimeout: 50, errorType: NetworkError,28 },29 {30 title: 'disabled', elapsed: 100, totalTimeout: false, errorType: NetworkError,31 },32] as const) {33 test.serial(`body read failure respects ${title} totalTimeout`, async t => {34 const originalPerformanceNow = globalThis.performance.now;35 let currentTime = 0;36 globalThis.performance.now = () => currentTime;37 t.teardown(() => {38 globalThis.performance.now = originalPerformanceNow;39 });4041 let requestCount = 0;42 const hookErrors: Error[] = [];43 const error = await t.throwsAsync(ky('https://example.com', {44 timeout: false,45 totalTimeout,46 async fetch() {47 requestCount++;48 return new Response(new ReadableStream({49 pull(controller) {50 currentTime = elapsed;51 controller.error(new TypeError('terminated'));52 },53 }, {highWaterMark: 0}));54 },55 hooks: {56 beforeError: [({error}) => {57 hookErrors.push(error);58 return error;59 }],60 },61 }).text(), {instanceOf: errorType});6263 t.is(error.request.url, 'https://example.com/');64 t.deepEqual(hookErrors, [error]);65 t.is(requestCount, 1);66 });67}6869test.serial('totalTimeout takes precedence when fetch rejects after the deadline', async t => {70 const originalPerformanceNow = globalThis.performance.now;71 let currentTime = 0;72 globalThis.performance.now = () => currentTime;73 t.teardown(() => {74 globalThis.performance.now = originalPerformanceNow;75 });7677 let requestCount = 0;78 let errorHookCount = 0;79 await t.throwsAsync(ky('https://example.com', {80 timeout: false,81 totalTimeout: 50,82 retry: 0,83 async fetch() {84 requestCount++;85 currentTime = 100;86 throw new TypeError('fetch failed');87 },88 hooks: {89 beforeError: [({error}) => {90 errorHookCount++;91 t.true(error instanceof TimeoutError);92 return error;93 }],94 },95 }), {instanceOf: TimeoutError});96 t.is(requestCount, 1);97 t.is(errorHookCount, 1);9899 currentTime = 0;100 await t.throwsAsync(ky('https://example.com', {101 timeout: false,102 totalTimeout: 50,103 retry: 0,104 async fetch() {105 currentTime = 25;106 throw new TypeError('fetch failed');107 },108 }), {instanceOf: NetworkError});109110 await t.throwsAsync(ky('https://example.com', {111 timeout: false,112 totalTimeout: false,113 retry: 0,114 async fetch() {115 currentTime = 100;116 throw new TypeError('fetch failed');117 },118 }), {instanceOf: NetworkError});119});120

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 121–123why, one step back
121const defaultRetryCount = 2;
122const retryAfterOn500 = 2;123const retryAfterOn413 = 2;

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 124–128why, one step back
124const retryAfterTimestampText = '1704067200';
125const retryAfterTimestampScheduledDelay = 2_147_483_647;126const httpDateDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];127const httpDateLongDayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];128const httpDateMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 129why, one step back
129

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 130–191why, one step back
130const formatHttpTime = (date: Date) => [
131 date.getUTCHours(),132 date.getUTCMinutes(),133 date.getUTCSeconds(),134].map(value => value.toString().padStart(2, '0')).join(':');135136const formatAsctimeDate = (date: Date) => {137 const day = date.getUTCDate().toString().padStart(2, ' ');138139 return `${httpDateDayNames[date.getUTCDay()]} ${httpDateMonths[date.getUTCMonth()]} ${day} ${formatHttpTime(date)} ${date.getUTCFullYear()}`;140};141142const formatRfc850Date = (date: Date) => {143 const day = date.getUTCDate().toString().padStart(2, '0');144 const year = (date.getUTCFullYear() % 100).toString().padStart(2, '0');145146 return `${httpDateLongDayNames[date.getUTCDay()]}, ${day}-${httpDateMonths[date.getUTCMonth()]}-${year} ${formatHttpTime(date)} GMT`;147};148149const withCapturedTimeouts = async (body: (scheduledDelays: number[]) => Promise<void>) => {150 const originalSetTimeout = globalThis.setTimeout;151 const scheduledDelays: number[] = [];152153 globalThis.setTimeout = ((handler, delayMs, ...arguments_) => {154 if (typeof delayMs === 'number') {155 scheduledDelays.push(delayMs);156 }157158 const testDelayMs = typeof delayMs === 'number' && delayMs > 1_000_000 ? 0 : delayMs;159 return originalSetTimeout(handler, testDelayMs, ...arguments_);160 }) as typeof globalThis.setTimeout;161162 try {163 await body(scheduledDelays);164 } finally {165 globalThis.setTimeout = originalSetTimeout;166 }167};168169const createSingleRetryHeaderServer = async (t: ExecutionContext, headers: Record<string, string | number>) => {170 let requestCount = 0;171172 const server = await createHttpTestServer(t);173 server.get('/', (_request, response) => {174 requestCount++;175 if (requestCount === 2) {176 response.end(fixture);177 return;178 }179180 response.writeHead(429, headers);181 response.end('');182 });183184 return {185 server,186 get requestCount() {187 return requestCount;188 },189 };190};191

Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177

lines 192–267why, one step back
192test('undefined resets inherited retry fields without changing the parent', async t => {
193 const inheritedRetry = {194 limit: 5,195 methods: ['post'] as const,196 statusCodes: [418],197 afterStatusCodes: [418],198 maxRetryAfter: 10,199 backoffLimit: 10,200 retryOnTimeout: true,201 };202 const parent = ky.create({203 retry: inheritedRetry,204 fetch: async () => new Response(fixture),205 });206 const child = parent.extend({207 retry: {208 limit: undefined,209 methods: undefined,210 statusCodes: undefined,211 afterStatusCodes: undefined,212 maxRetryAfter: undefined,213 backoffLimit: undefined,214 retryOnTimeout: undefined,215 },216 });217218 t.is(await child('https://example.com', {219 hooks: {220 beforeRequest: [({options}) => {221 t.like(options.retry, {222 limit: 2,223 methods: ['get', 'put', 'head', 'delete', 'options', 'trace', 'query'],224 statusCodes: [408, 413, 429, 500, 502, 503, 504],225 afterStatusCodes: [413, 429, 503],226 maxRetryAfter: Number.POSITIVE_INFINITY,227 backoffLimit: Number.POSITIVE_INFINITY,228 retryOnTimeout: false,229 });230 }],231 },232 }).text(), fixture);233 t.is(await parent('https://example.com', {234 hooks: {235 beforeRequest: [({options}) => {236 t.like(options.retry, inheritedRetry);237 }],238 },239 }).text(), fixture);240});241242test('undefined resets an inherited retry delay without changing the parent', async t => {243 const server = await createHttpTestServer(t);244 let requestCount = 0;245 server.get('/', (_request, response) => {246 requestCount++;247 response.status(requestCount % 2 === 1 ? 503 : 200).end(fixture);248 });249 let customDelayCalls = 0;250 const parent = ky.create({251 retry: {252 backoffLimit: 0,253 delay() {254 customDelayCalls++;255 return 0;256 },257 },258 });259 const child = parent.extend({retry: {delay: undefined}});260261 t.is(await child(server.url).text(), fixture);262 t.is(customDelayCalls, 0);263 t.is(await parent(server.url).text(), fixture);264 t.is(customDelayCalls, 1);265 t.is(requestCount, 4);266});267

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 268–270why, one step back
268test('network error', async t => {
269 let requestCount = 0;270

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 271why, one step back
271 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 272–288why, one step back
272 server.get('/', (_request, response) => {
273 requestCount++;274275 if (requestCount === defaultRetryCount + 1) {276 response.end(fixture);277 } else {278 response.status(99_999).end();279 }280 });281282 t.is(await ky(server.url).text(), fixture);283 t.is(requestCount, defaultRetryCount + 1);284});285286test('status code 500', async t => {287 let requestCount = 0;288

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 289why, one step back
289 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 290–306why, one step back
290 server.get('/', (_request, response) => {
291 requestCount++;292293 if (requestCount === defaultRetryCount + 1) {294 response.end(fixture);295 } else {296 response.sendStatus(500);297 }298 });299300 t.is(await ky(server.url).text(), fixture);301 t.is(requestCount, defaultRetryCount + 1);302});303304test('only on defined status codes', async t => {305 let requestCount = 0;306

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 307why, one step back
307 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 308–324why, one step back
308 server.get('/', (_request, response) => {
309 requestCount++;310311 if (requestCount === defaultRetryCount + 1) {312 response.end(fixture);313 } else {314 response.sendStatus(400);315 }316 });317318 await t.throwsAsync(ky(server.url).text(), {message: /Bad Request/});319 t.is(requestCount, 1);320});321322test('not on POST', async t => {323 let requestCount = 0;324

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 325why, one step back
325 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 326–341why, one step back
326 server.post('/', (_request, response) => {
327 requestCount++;328329 if (requestCount === defaultRetryCount + 1) {330 response.end(fixture);331 } else {332 response.sendStatus(500);333 }334 });335336 await t.throwsAsync(ky.post(server.url).text(), {337 message: /Internal Server Error/,338 });339 t.is(requestCount, 1);340});341

Add QUERY method support (#873)Sindre Sorhusbefore adoption6edddd9

lines 342–376why, one step back
342test('QUERY retries by default', async t => {
343 let requestCount = 0;344 const receivedBodies: unknown[] = [];345 const receivedMethods: string[] = [];346347 const server = await createHttpTestServer(t);348 server.all('/', (request, response) => {349 requestCount++;350 receivedMethods.push(request.method);351 receivedBodies.push(request.body);352353 if (requestCount === defaultRetryCount + 1) {354 response.json(request.body);355 } else {356 response.sendStatus(500);357 }358 });359360 const json = {361 foo: true,362 };363364 const result = await ky.query(server.url, {365 json,366 retry: {367 delay: () => 0,368 },369 }).json();370371 t.deepEqual(result, json);372 t.is(requestCount, defaultRetryCount + 1);373 t.deepEqual(receivedMethods, ['QUERY', 'QUERY', 'QUERY']);374 t.deepEqual(receivedBodies, [json, json, json]);375});376

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

line 377why, one step back
377test.serial('respect Retry-After: 0 and retry immediately', async t => {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 378–380why, one step back
378 const retryCount = 4;
379 let requestCount = 0;380

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 381why, one step back
381 await withCapturedTimeouts(async scheduledDelays => {

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

line 382why, one step back
382 t.is(await ky('https://example.com', {

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 383why, one step back
383 timeout: false,

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

line 384why, one step back
384 retry: retryCount,

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

lines 385–386why, one step back
385 async fetch() {
386 requestCount++;

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

lines 387–389why, one step back
387 return requestCount === retryCount + 1
388 ? new Response(fixture)389 : new Response('', {status: 413, headers: {'Retry-After': '0'}});

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 390why, one step back
390 },

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

line 391why, one step back
391 }).text(), fixture);

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 392why, one step back
392

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

lines 393–394why, one step back
393 // Error-body reads also schedule a 10-second timeout; check retry timing separately from response consumption.
394 t.deepEqual(scheduledDelays.filter(milliseconds => milliseconds !== 10_000), [0, 0, 0, 0]);

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

line 395why, one step back
395 });

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

lines 396–397why, one step back
396
397 t.is(requestCount, 5);

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

lines 398–402why, one step back
398});
399400// RFC 9110 §10.2.3 separates the server's requested waiting time from the decision to retry.401// https://www.rfc-editor.org/rfc/rfc9110.html#section-10.2.3402for (const scenario of [

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

line 403why, one step back
403 {title: 'Retry-After seconds', headers: {'Retry-After': '2000'}, expected: 2_000_000},

Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f

lines 404–456why, one step back
404 {
405 title: 'maxRetryAfter cap', headers: {'Retry-After': '3000'}, retry: {maxRetryAfter: 2_000_000}, expected: 2_000_000,406 },407 {408 title: 'missing header fallback', headers: {}, expected: 7, backoff: true,409 },410 {411 title: 'excluded afterStatusCodes', headers: {'Retry-After': '2000'}, retry: {afterStatusCodes: []}, expected: 7, backoff: true,412 },413 {414 title: 'statusCodes override', headers: {'Retry-After': '2000'}, retry: {statusCodes: []}, expected: 2_000_000,415 },416 {417 title: '413 without a header', status: 413, headers: {}, expected: 7, backoff: true,418 },419] satisfies Array<{title: string; headers: Record<string, string>; status?: number; retry?: RetryOptions; expected: number; backoff?: boolean}>) {420 test.serial(`shouldRetry true preserves timing rules: ${scenario.title}`, async t => {421 let requestCount = 0;422 let backoffCalls = 0;423 let jitterCalls = 0;424 await withCapturedTimeouts(async scheduledDelays => {425 const result = await ky('https://example.com', {426 timeout: false,427 retry: {428 limit: 1,429 shouldRetry: async () => true,430 delay() {431 backoffCalls++;432 return 10;433 },434 jitter() {435 jitterCalls++;436 return 7;437 },438 ...scenario.retry,439 },440 async fetch() {441 requestCount++;442 return requestCount === 1443 ? new Response('', {status: scenario.status ?? 429, headers: scenario.headers})444 : new Response(fixture);445 },446 }).text();447448 t.is(result, fixture);449 // Error-data consumption also schedules a 10-second timeout.450 t.deepEqual(scheduledDelays.filter(milliseconds => milliseconds !== 10_000), [scenario.expected]);451 });452 t.is(requestCount, 2);453 t.is(backoffCalls, scenario.backoff ? 1 : 0);454 t.is(jitterCalls, scenario.backoff ? 1 : 0);455 });456}

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 457why, one step back
457

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 458–757why, one step back
458test.serial('Retry-After number is treated as delay seconds, not timestamp', async t => {
459 const retryServer = await createSingleRetryHeaderServer(t, {460 'Retry-After': retryAfterTimestampText,461 });462463 await withCapturedTimeouts(async scheduledDelays => {464 t.is(await ky(retryServer.server.url, {465 retry: {466 limit: 1,467 },468 }).text(), fixture);469470 t.true(scheduledDelays.includes(retryAfterTimestampScheduledDelay));471 });472473 t.is(retryServer.requestCount, 2);474});475476test.serial('invalid Retry-After number 0x10 falls back to retry delay', async t => {477 const retryServer = await createSingleRetryHeaderServer(t, {478 'Retry-After': '0x10',479 });480481 await withCapturedTimeouts(async scheduledDelays => {482 t.is(await ky(retryServer.server.url, {483 timeout: false,484 retry: {485 limit: 1,486 delay: () => 10,487 },488 }).text(), fixture);489490 t.true(scheduledDelays.includes(10));491 });492493 t.is(retryServer.requestCount, 2);494});495496test.serial('X-RateLimit-Retry-After number is treated as delay seconds, not timestamp', async t => {497 const retryServer = await createSingleRetryHeaderServer(t, {498 'X-RateLimit-Retry-After': retryAfterTimestampText,499 });500501 await withCapturedTimeouts(async scheduledDelays => {502 t.is(await ky(retryServer.server.url, {503 retry: {504 limit: 1,505 },506 }).text(), fixture);507508 t.true(scheduledDelays.includes(retryAfterTimestampScheduledDelay));509 });510511 t.is(retryServer.requestCount, 2);512});513514test.serial('Retry-After takes precedence over RateLimit-Reset', async t => {515 const retryServer = await createSingleRetryHeaderServer(t, {516 'Retry-After': '1',517 'RateLimit-Reset': retryAfterTimestampText,518 });519520 await withCapturedTimeouts(async scheduledDelays => {521 t.is(await ky(retryServer.server.url, {522 retry: {523 limit: 1,524 },525 }).text(), fixture);526527 t.true(scheduledDelays.includes(1000));528 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));529 });530531 t.is(retryServer.requestCount, 2);532});533534test.serial('invalid Retry-After does not fall back to RateLimit-Reset', async t => {535 const retryServer = await createSingleRetryHeaderServer(t, {536 'Retry-After': '1e3',537 'RateLimit-Reset': retryAfterTimestampText,538 });539540 await withCapturedTimeouts(async scheduledDelays => {541 t.is(await ky(retryServer.server.url, {542 retry: {543 limit: 1,544 delay: () => 23,545 },546 }).text(), fixture);547548 t.true(scheduledDelays.includes(23));549 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));550 });551552 t.is(retryServer.requestCount, 2);553});554555test.serial('empty Retry-After does not fall back to RateLimit-Reset', async t => {556 const retryServer = await createSingleRetryHeaderServer(t, {557 'Retry-After': '',558 'RateLimit-Reset': retryAfterTimestampText,559 });560561 await withCapturedTimeouts(async scheduledDelays => {562 t.is(await ky(retryServer.server.url, {563 retry: {564 limit: 1,565 delay: () => 31,566 },567 }).text(), fixture);568569 t.true(scheduledDelays.includes(31));570 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));571 });572573 t.is(retryServer.requestCount, 2);574});575576test.serial('non-standard Retry-After date falls back to retry delay', async t => {577 const retryServer = await createSingleRetryHeaderServer(t, {578 'Retry-After': 'Sun Nov 06 1994 08:49:37 GMT',579 });580581 await withCapturedTimeouts(async scheduledDelays => {582 t.is(await ky(retryServer.server.url, {583 retry: {584 limit: 1,585 delay: () => 29,586 },587 }).text(), fixture);588589 t.true(scheduledDelays.includes(29));590 });591592 t.is(retryServer.requestCount, 2);593});594595for (const [dateFormat, formatDate] of [596 ['RFC 850', formatRfc850Date],597 ['asctime', formatAsctimeDate],598] as const) {599 test.serial(`Retry-After supports obsolete HTTP-date format: ${dateFormat}`, async t => {600 const retryAfterDate = formatDate(new Date(Date.now() + 2_000_000));601 const retryServer = await createSingleRetryHeaderServer(t, {602 'Retry-After': retryAfterDate,603 });604605 await withCapturedTimeouts(async scheduledDelays => {606 t.is(await ky(retryServer.server.url, {607 retry: {608 limit: 1,609 delay: () => 13,610 },611 }).text(), fixture);612613 t.true(scheduledDelays.some(delay => delay > 1_000_000));614 t.false(scheduledDelays.includes(13));615 });616617 t.is(retryServer.requestCount, 2);618 });619}620621test.serial('Retry-After asctime HTTP-date is parsed as GMT', async t => {622 const retryAfterDate = formatAsctimeDate(new Date(Date.now() + 2_000_000));623 const retryServer = await createSingleRetryHeaderServer(t, {624 'Retry-After': retryAfterDate,625 });626627 const timeZone = process.env.TZ;628 try {629 process.env.TZ = 'Pacific/Kiritimati';630 await withCapturedTimeouts(async scheduledDelays => {631 t.is(await ky(retryServer.server.url, {632 retry: {633 limit: 1,634 delay: () => 13,635 },636 }).text(), fixture);637638 t.true(scheduledDelays.some(delay => delay > 1_000_000));639 t.false(scheduledDelays.includes(13));640 });641 } finally {642 if (timeZone === undefined) {643 delete process.env.TZ;644 } else {645 process.env.TZ = timeZone;646 }647 }648649 t.is(retryServer.requestCount, 2);650});651652test.serial('Retry-After HTTP-date supports a leap second', async t => {653 const now = Date.now();654 const retryAfterInstant = new Date(now + 2_000_000);655 retryAfterInstant.setUTCSeconds(59, 0);656 const day = retryAfterInstant.getUTCDate().toString().padStart(2, '0');657 const hours = retryAfterInstant.getUTCHours().toString().padStart(2, '0');658 const minutes = retryAfterInstant.getUTCMinutes().toString().padStart(2, '0');659 const dayName = httpDateDayNames[retryAfterInstant.getUTCDay()];660 const month = httpDateMonths[retryAfterInstant.getUTCMonth()];661 const retryAfterDate = `${dayName}, ${day} ${month} ${retryAfterInstant.getUTCFullYear()} ${hours}:${minutes}:60 GMT`;662 const expectedDelay = retryAfterInstant.getTime() + 1000 - now;663664 const retryServer = await createSingleRetryHeaderServer(t, {665 'Retry-After': retryAfterDate,666 });667668 const dateNow = Date.now;669 try {670 Date.now = () => now;671 await withCapturedTimeouts(async scheduledDelays => {672 t.is(await ky(retryServer.server.url, {673 retry: {674 limit: 1,675 delay: () => 13,676 },677 }).text(), fixture);678679 t.true(scheduledDelays.includes(expectedDelay));680 t.false(scheduledDelays.includes(expectedDelay - 1000));681 t.false(scheduledDelays.includes(13));682 });683 } finally {684 Date.now = dateNow;685 }686687 t.is(retryServer.requestCount, 2);688});689690test.serial('Retry-After RFC 850 HTTP-date applies the two-digit year rule', async t => {691 const retryAfterDate = new Date(Date.now() + 2000);692 retryAfterDate.setUTCFullYear(retryAfterDate.getUTCFullYear() + 49);693694 const retryServer = await createSingleRetryHeaderServer(t, {695 'Retry-After': formatRfc850Date(retryAfterDate),696 });697698 await withCapturedTimeouts(async scheduledDelays => {699 t.is(await ky(retryServer.server.url, {700 retry: {701 limit: 1,702 delay: () => 13,703 },704 }).text(), fixture);705706 t.true(scheduledDelays.some(delay => delay > 1_000_000));707 t.false(scheduledDelays.includes(13));708 });709710 t.is(retryServer.requestCount, 2);711});712713test.serial('Retry-After RFC 850 HTTP-date more than 50 years in the future is interpreted as past', async t => {714 const retryAfterDate = new Date(Date.now() + 2000);715 retryAfterDate.setUTCFullYear(retryAfterDate.getUTCFullYear() + 51);716717 const retryServer = await createSingleRetryHeaderServer(t, {718 'Retry-After': formatRfc850Date(retryAfterDate),719 });720721 await withCapturedTimeouts(async scheduledDelays => {722 t.is(await ky(retryServer.server.url, {723 retry: {724 limit: 1,725 delay: () => 13,726 maxRetryAfter: 1,727 },728 }).text(), fixture);729730 t.true(scheduledDelays.includes(0));731 t.false(scheduledDelays.includes(1));732 t.false(scheduledDelays.includes(13));733 });734735 t.is(retryServer.requestCount, 2);736});737738test.serial('invalid Retry-After HTTP-date components fall back to retry delay', async t => {739 const retryServer = await createSingleRetryHeaderServer(t, {740 'Retry-After': 'Sun, 32 Dec 2030 25:99:99 GMT',741 });742743 await withCapturedTimeouts(async scheduledDelays => {744 t.is(await ky(retryServer.server.url, {745 retry: {746 limit: 1,747 delay: () => 17,748 },749 }).text(), fixture);750751 t.true(scheduledDelays.includes(17));752 });753754 t.is(retryServer.requestCount, 2);755});756757test('RateLimit-Reset delay seconds are respected like Retry-After', async t => {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 758–759why, one step back
758 let requestCount = 0;
759

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 760why, one step back
760 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 761–786why, one step back
761 server.get('/', (_request, response) => {
762 requestCount++;763764 if (requestCount === defaultRetryCount + 1) {765 response.end(fixture);766 } else {767 const header = (requestCount < 2) ? 'RateLimit-Reset' : 'Retry-After';768 response.writeHead(429, {769 [header]: 1,770 });771772 response.end('');773 }774 });775776 await withPerformance({777 t,778 expectedDuration: 1000 + 1000,779 async test() {780 t.is(await ky(server.url).text(), fixture);781 },782 });783784 t.is(requestCount, 3);785});786

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 787–788why, one step back
787test.serial('RateLimit-Reset with time since epoch', async t => {
788 const now = Date.UTC(2026, 0, 1);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 789–790why, one step back
789 let requestCount = 0;
790

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 791why, one step back
791 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 792–797why, one step back
792 server.get('/', (_request, response) => {
793 requestCount++;794795 if (requestCount === defaultRetryCount + 1) {796 response.end(fixture);797 } else {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 798–799why, one step back
798 const oneSecondByDelta = 1;
799 const threeSecondsByEpoch = (now / 1000) + 3;

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 800why, one step back
800 response.writeHead(429, {

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 801why, one step back
801 'RateLimit-Reset': (requestCount < 2) ? oneSecondByDelta : threeSecondsByEpoch,

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 802–807why, one step back
802 });
803804 response.end('');805 }806 });807

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 808–811why, one step back
808 const dateNow = Date.now;
809 try {810 Date.now = () => now;811 await withCapturedTimeouts(async scheduledDelays => {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 812–813why, one step back
812 t.is(await ky(server.url).text(), fixture);
813

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 814–822why, one step back
814 t.true(scheduledDelays.includes(1000));
815 t.true(scheduledDelays.includes(3000));816 t.true(scheduledDelays.indexOf(1000) < scheduledDelays.indexOf(3000));817 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));818 });819 } finally {820 Date.now = dateNow;821 }822

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 823–825why, one step back
823 t.is(requestCount, 3);
824});825

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 826–896why, one step back
826test.serial('empty RateLimit-Reset falls back to retry delay', async t => {
827 const retryServer = await createSingleRetryHeaderServer(t, {828 'RateLimit-Reset': '',829 });830831 await withCapturedTimeouts(async scheduledDelays => {832 t.is(await ky(retryServer.server.url, {833 retry: {834 limit: 1,835 delay: () => 37,836 },837 }).text(), fixture);838839 t.true(scheduledDelays.includes(37));840 });841842 t.is(retryServer.requestCount, 2);843});844845test.serial('empty RateLimit-Reset does not fall back to lower-priority reset alias', async t => {846 const retryServer = await createSingleRetryHeaderServer(t, {847 'RateLimit-Reset': '',848 'X-RateLimit-Reset': retryAfterTimestampText,849 });850851 await withCapturedTimeouts(async scheduledDelays => {852 t.is(await ky(retryServer.server.url, {853 retry: {854 limit: 1,855 delay: () => 41,856 },857 }).text(), fixture);858859 t.true(scheduledDelays.includes(41));860 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));861 });862863 t.is(retryServer.requestCount, 2);864});865866for (const rateLimitResetHeader of ['X-RateLimit-Reset', 'X-Rate-Limit-Reset']) {867 test.serial(`${rateLimitResetHeader} supports time since epoch`, async t => {868 const now = Date.UTC(2026, 0, 1);869 const retryServer = await createSingleRetryHeaderServer(t, {870 [rateLimitResetHeader]: (now / 1000) + 2,871 });872873 const dateNow = Date.now;874 try {875 Date.now = () => now;876 await withCapturedTimeouts(async scheduledDelays => {877 t.is(await ky(retryServer.server.url, {878 retry: {879 limit: 1,880 delay: () => 7,881 maxRetryAfter: 3500,882 },883 }).text(), fixture);884885 t.true(scheduledDelays.includes(2000));886 t.false(scheduledDelays.includes(3500));887 t.false(scheduledDelays.includes(7));888 });889 } finally {890 Date.now = dateNow;891 }892893 t.is(retryServer.requestCount, 2);894 });895}896

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 897–900why, one step back
897test('respect 413 Retry-After', async t => {
898 const startTime = Date.now();899 let requestCount = 0;900

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 901why, one step back
901 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 902–919why, one step back
902 server.get('/', (_request, response) => {
903 requestCount++;904905 if (requestCount === defaultRetryCount + 1) {906 response.end((Date.now() - startTime).toString());907 } else {908 response.writeHead(413, {909 'Retry-After': retryAfterOn413,910 });911 response.end('');912 }913 });914915 const timeElapsedInMs = Number(await ky(server.url).text());916 t.true(timeElapsedInMs >= retryAfterOn413 * 1000);917 t.is(requestCount, retryAfterOn413 + 1);918});919

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 920why, one step back
920test('respect 413 Retry-After with HTTP date', async t => {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 921–923why, one step back
921 const startTime = Date.now();
922 let requestCount = 0;923

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 924why, one step back
924 const server = await createHttpTestServer(t, {bodyParser: false});

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 925–946why, one step back
925 server.get('/', (_request, response) => {
926 requestCount++;927 if (requestCount === defaultRetryCount + 1) {928 response.end((Date.now() - startTime).toString());929 } else {930 // @NOTE we need to round up to the next second due to http-date resolution931 const date = new Date(Date.now() + ((retryAfterOn413 + 1) * 1000)).toUTCString();932 response.writeHead(413, {933 'Retry-After': date,934 });935 response.end('');936 }937 });938939 const timeElapsedInMs = Number(await ky(server.url).text());940 t.true(timeElapsedInMs >= retryAfterOn413 * 1000);941 t.is(requestCount, retryAfterOn413 + 1);942});943944test('doesn\'t retry on 413 without Retry-After header', async t => {945 let requestCount = 0;946

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 947why, one step back
947 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 948–962why, one step back
948 server.get('/', (_request, response) => {
949 requestCount++;950 response.sendStatus(413);951 });952953 await t.throwsAsync(ky(server.url).text(), {message: /Payload Too Large/});954 t.is(requestCount, 1);955 await ky(server.url, {throwHttpErrors: false}).text();956 t.is(requestCount, 2);957});958959test('respect custom `afterStatusCodes` (500) with Retry-After header', async t => {960 const startTime = Date.now();961 let requestCount = 0;962

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 963why, one step back
963 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 964–981why, one step back
964 server.get('/', (_request, response) => {
965 requestCount++;966967 if (requestCount === defaultRetryCount + 1) {968 response.end((Date.now() - startTime).toString());969 } else {970 response.writeHead(500, {971 'Retry-After': retryAfterOn500,972 });973 response.end('');974 }975 });976977 const timeElapsedInMs = Number(await ky(server.url, {retry: {afterStatusCodes: [500]}}).text());978 t.true(timeElapsedInMs >= retryAfterOn500 * 1000);979 t.is(requestCount, retryAfterOn500 + 1);980});981

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 982–1006why, one step back
982test('custom `afterStatusCodes` does not retry statuses missing from `statusCodes`', async t => {
983 let requestCount = 0;984985 const server = await createHttpTestServer(t);986 server.get('/', (_request, response) => {987 requestCount++;988 response.writeHead(400, {989 'Retry-After': 1,990 });991 response.end('');992 });993994 await t.throwsAsync(995 ky(server.url, {996 retry: {997 afterStatusCodes: [400],998 },999 }).text(),1000 {1001 message: /Bad Request/,1002 },1003 );1004 t.is(requestCount, 1);1005});1006

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1007–1009why, one step back
1007test('respect number of retries', async t => {
1008 let requestCount = 0;1009

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1010why, one step back
1010 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1011–1028why, one step back
1011 server.get('/', (_request, response) => {
1012 requestCount++;1013 response.sendStatus(408);1014 });10151016 await t.throwsAsync(1017 ky(server.url, {1018 retry: {1019 limit: 3,1020 },1021 }).text(),1022 {1023 message: /Request Timeout/,1024 },1025 );1026 t.is(requestCount, 4);1027});1028

TweaksSindre Sorhusbefore adoption3ded2aa

line 1029why, one step back
1029test('rejects invalid retry limits', async t => {

Harden retrySindre Sorhusbefore adoptionc426f19

line 1030why, one step back
1030 for (const limit of [Number.NaN, Number.POSITIVE_INFINITY, -1, 1.5]) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 1031–1036why, one step back
1031 // eslint-disable-next-line no-await-in-loop
1032 await t.throwsAsync(ky('https://example.com', {1033 retry: {1034 limit,1035 },1036 }), {

Harden retrySindre Sorhusbefore adoptionc426f19

lines 1037–1040why, one step back
1037 instanceOf: TypeError,
1038 message: '`retry.limit` must be a finite, non-negative integer',1039 });1040

TweaksSindre Sorhusbefore adoption3ded2aa

lines 1041–1042why, one step back
1041 // eslint-disable-next-line no-await-in-loop
1042 await t.throwsAsync(ky('https://example.com', {retry: limit}), {

Harden retrySindre Sorhusbefore adoptionc426f19

lines 1043–1048why, one step back
1043 instanceOf: TypeError,
1044 message: '`retry.limit` must be a finite, non-negative integer',1045 });1046 }1047});1048

TweaksSindre Sorhusbefore adoption3ded2aa

line 1049why, one step back
1049test('rejects non-number retry limits', async t => {

Harden retrySindre Sorhusbefore adoptionc426f19

line 1050why, one step back
1050 for (const limit of ['NaN', true, null]) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 1051–1056why, one step back
1051 // eslint-disable-next-line no-await-in-loop
1052 await t.throwsAsync(ky('https://example.com', {1053 retry: {1054 limit: limit as never,1055 },1056 }), {

Harden retrySindre Sorhusbefore adoptionc426f19

lines 1057–1148why, one step back
1057 instanceOf: TypeError,
1058 message: '`retry.limit` must be a finite, non-negative integer',1059 });1060 }1061});10621063test('does not enable retries after sending an uncloned request body', async t => {1064 let requestCount = 0;10651066 await t.throwsAsync(1067 ky('https://example.com', {1068 method: 'put',1069 body: 'body',1070 async fetch(input) {1071 requestCount++;1072 await (input as Request).text();1073 return new Response(null, {status: 500});1074 },1075 retry: {1076 limit: 0,1077 methods: ['put'],1078 },1079 hooks: {1080 afterResponse: [({options}) => {1081 options.retry.limit = 1;1082 }],1083 },1084 }).text(),1085 {1086 message: /status code 500/,1087 },1088 );10891090 t.is(requestCount, 1);1091});10921093test('allows response hooks to disable retries', async t => {1094 let requestCount = 0;10951096 await t.throwsAsync(1097 ky('https://example.com', {1098 async fetch() {1099 requestCount++;1100 return new Response(null, {status: 500});1101 },1102 retry: {1103 limit: 1,1104 delay: () => 0,1105 },1106 hooks: {1107 afterResponse: [({options}) => {1108 options.retry.limit = 0;1109 }],1110 },1111 }).text(),1112 {1113 message: /status code 500/,1114 },1115 );11161117 t.is(requestCount, 1);1118});11191120test('uses the retry limit set by a beforeRequest hook that returns a response', async t => {1121 let requestCount = 0;11221123 const response = await ky('https://example.com', {1124 async fetch() {1125 requestCount++;1126 return new Response('ok');1127 },1128 retry: {1129 limit: 0,1130 delay: () => 0,1131 },1132 hooks: {1133 beforeRequest: [({options}) => {1134 options.retry.limit = 1;1135 return new Response(null, {status: 500});1136 }],1137 afterResponse: [({response, retryCount}) => {1138 if (retryCount === 0 && response.status === 500) {1139 return ky.retry();1140 }1141 }],1142 },1143 }).text();11441145 t.is(response, 'ok');1146 t.is(requestCount, 1);1147});1148

Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8

lines 1149–1176why, one step back
1149// The limit is read again when each attempt starts, and `beforeRetry` runs before that, so it can raise the limit.
1150test('allows beforeRetry hooks to raise the retry limit', async t => {1151 let requestCount = 0;11521153 await t.throwsAsync(1154 ky('https://example.com', {1155 async fetch() {1156 requestCount++;1157 return new Response(null, {status: 500});1158 },1159 retry: {1160 limit: 1,1161 delay: () => 0,1162 },1163 hooks: {1164 beforeRetry: [({options}) => {1165 options.retry.limit = 3;1166 }],1167 },1168 }).text(),1169 {1170 message: /status code 500/,1171 },1172 );11731174 t.is(requestCount, 4);1175});1176

Harden retrySindre Sorhusbefore adoptionc426f19

lines 1177–1211why, one step back
1177test('uses the normalized retry limit when cloning request bodies', async t => {
1178 let requestCount = 0;11791180 await t.throwsAsync(1181 ky('https://example.com', {1182 method: 'put',1183 body: 'body',1184 async fetch(input) {1185 requestCount++;1186 await (input as Request).text();1187 return new Response(null, {status: 500});1188 },1189 retry: {1190 limit: 1,1191 methods: ['put'],1192 delay: () => 0,1193 },1194 hooks: {1195 init: [options => {1196 options.retry = {1197 limit: undefined,1198 methods: ['put'],1199 delay: () => 0,1200 };1201 }],1202 },1203 }).text(),1204 {1205 message: /status code 500/,1206 },1207 );12081209 t.is(requestCount, 3);1210});1211

TweaksSindre Sorhusbefore adoption3ded2aa

line 1212why, one step back
1212test('rejects invalid retry option values', async t => {

Harden retrySindre Sorhusbefore adoptionc426f19

line 1213why, one step back
1213 for (const retry of [true, 'NaN', []]) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 1214–1215why, one step back
1214 // eslint-disable-next-line no-await-in-loop
1215 await t.throwsAsync(ky('https://example.com', {retry: retry as never}), {

Harden retrySindre Sorhusbefore adoptionc426f19

lines 1216–1219why, one step back
1216 instanceOf: TypeError,
1217 message: '`retry` must be a number or an object',1218 });1219

TweaksSindre Sorhusbefore adoption3ded2aa

lines 1220–1226why, one step back
1220 // eslint-disable-next-line no-await-in-loop
1221 await t.throwsAsync(ky('https://example.com', {1222 retry: retry as never,1223 hooks: {1224 init: [() => undefined],1225 },1226 }), {

Harden retrySindre Sorhusbefore adoptionc426f19

lines 1227–1254why, one step back
1227 instanceOf: TypeError,
1228 message: '`retry` must be a number or an object',1229 });1230 }1231});12321233test('init hooks can sanitize retry options before validation', async t => {1234 let requestCount = 0;12351236 await t.throwsAsync(1237 ky('https://example.com', {1238 async fetch() {1239 requestCount++;1240 return new Response(null, {status: 500});1241 },1242 retry: {1243 limit: Number.NaN,1244 },1245 hooks: {1246 init: [options => {1247 options.retry = 0;1248 }],1249 },1250 }).text(),1251 );1252 t.is(requestCount, 1);1253});1254

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1255–1257why, one step back
1255test('respect retry methods', async t => {
1256 let requestCount = 0;1257

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1258why, one step back
1258 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1259–1297why, one step back
1259 server.post('/', (_request, response) => {
1260 requestCount++;1261 response.sendStatus(408);1262 });12631264 server.get('/', (_request, response) => {1265 requestCount++;1266 response.sendStatus(408);1267 });12681269 await t.throwsAsync(1270 ky(server.url, {1271 method: 'post',1272 retry: {1273 limit: 3,1274 methods: ['get'],1275 },1276 }).text(),1277 {1278 message: /Request Timeout/,1279 },1280 );1281 t.is(requestCount, 1);12821283 requestCount = 0;1284 await t.throwsAsync(1285 ky(server.url, {1286 retry: {1287 limit: 2,1288 methods: ['get'],1289 },1290 }).text(),1291 {1292 message: /Request Timeout/,1293 },1294 );1295 t.is(requestCount, defaultRetryCount + 1);1296});1297

Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63

line 1298why, one step back
1298test.serial('respect maxRetryAfter', async t => {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1299why, one step back
1299 let requestCount = 0;

Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63

line 1300why, one step back
1300 const customFetch = async () => {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1301why, one step back
1301 requestCount++;

Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63

lines 1302–1306why, one step back
1302 return requestCount === 2
1303 ? new Response(fixture)1304 : new Response(null, {1305 status: 413,1306 headers: {'Retry-After': '2000'},

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1307why, one step back
1307 });

Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63

line 1308why, one step back
1308 };

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1309why, one step back
1309

Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63

lines 1310–1319why, one step back
1310 await withCapturedTimeouts(async scheduledDelays => {
1311 t.is(await ky('https://example.com', {1312 timeout: false,1313 fetch: customFetch,1314 retry: {1315 limit: 1,1316 maxRetryAfter: 1_500_000,1317 },1318 }).text(), fixture);1319 t.is(requestCount, 2);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1320why, one step back
1320

Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63

lines 1321–1330why, one step back
1321 requestCount = 0;
1322 t.is(await ky('https://example.com', {1323 timeout: false,1324 fetch: customFetch,1325 retry: {1326 limit: 1,1327 maxRetryAfter: 3_000_000,1328 },1329 }).text(), fixture);1330 t.is(requestCount, 2);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1331why, one step back
1331

Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63

lines 1332–1333why, one step back
1332 const relevantScheduledDelays = scheduledDelays.filter(delay => delay === 1_500_000 || delay === 2_000_000);
1333 t.deepEqual(relevantScheduledDelays, [1_500_000, 2_000_000]);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1334–1336why, one step back
1334 });
1335});1336

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 1337why, one step back
1337test.serial('invalid Retry-After header falls back to retry delay', async t => {

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

lines 1338–1353why, one step back
1338 let requestCount = 0;
13391340 const server = await createHttpTestServer(t);1341 server.get('/', (_request, response) => {1342 requestCount++;1343 if (requestCount === 1) {1344 response.writeHead(429, {1345 'Retry-After': 'not-a-valid-value',1346 });1347 response.end('');1348 return;1349 }13501351 response.end(fixture);1352 });1353

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 1354–1355why, one step back
1354 await withCapturedTimeouts(async scheduledDelays => {
1355 t.is(await ky(server.url, {

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

lines 1356–1358why, one step back
1356 timeout: false,
1357 retry: {1358 limit: 1,

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 1359–1360why, one step back
1359 delay: () => 50,
1360 maxRetryAfter: 10,

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

line 1361why, one step back
1361 },

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 1362why, one step back
1362 }).text(), fixture);

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

line 1363why, one step back
1363

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 1364–1367why, one step back
1364 t.true(scheduledDelays.includes(50));
1365 t.false(scheduledDelays.includes(10));1366 });1367

Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa

lines 1368–1370why, one step back
1368 t.is(requestCount, 2);
1369});1370

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 1371–1404why, one step back
1371test.serial('invalid 413 Retry-After header falls back to retry delay', async t => {
1372 let requestCount = 0;13731374 const server = await createHttpTestServer(t);1375 server.get('/', (_request, response) => {1376 requestCount++;1377 if (requestCount === 1) {1378 response.writeHead(413, {1379 'Retry-After': 'not-a-valid-value',1380 });1381 response.end('');1382 return;1383 }13841385 response.end(fixture);1386 });13871388 await withCapturedTimeouts(async scheduledDelays => {1389 t.is(await ky(server.url, {1390 timeout: false,1391 retry: {1392 limit: 1,1393 delay: () => 50,1394 maxRetryAfter: 10,1395 },1396 }).text(), fixture);13971398 t.true(scheduledDelays.includes(50));1399 t.false(scheduledDelays.includes(10));1400 });14011402 t.is(requestCount, 2);1403});1404

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1405–1407why, one step back
1405test('retry - can provide retry as number', async t => {
1406 let requestCount = 0;1407

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1408why, one step back
1408 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1409–1419why, one step back
1409 server.get('/', async (_request, response) => {
1410 requestCount++;1411 response.sendStatus(408);1412 });14131414 await t.throwsAsync(ky(server.url, {retry: 4}).text(), {1415 message: /Request Timeout/,1416 });1417 t.is(requestCount, 5);1418});1419

Fix `extend()` dropping numeric `retry` limit when merging with an object (#867)Alexander Kireyevbefore adoption06375ef

lines 1420–1436why, one step back
1420test('retry - extending a numeric `retry` with an object keeps the limit', async t => {
1421 let requestCount = 0;14221423 const server = await createHttpTestServer(t);1424 server.get('/', async (_request, response) => {1425 requestCount++;1426 response.sendStatus(408);1427 });14281429 // `retry: 3` is shorthand for `{limit: 3}`. Extending it with an object1430 // should preserve that limit instead of falling back to the default.1431 const extended = ky.create({retry: 3}).extend({retry: {methods: ['get']}});14321433 await t.throwsAsync(extended(server.url).text(), {1434 message: /Request Timeout/,1435 });1436 t.is(requestCount, 4);

Fix extending an object `retry` with a number dropping the other retry optionsSindre Sorhusbefore adoptionee3dec1

lines 1437–1598why, one step back
1437});
14381439test('retry - extending an object `retry` with a number keeps the other options', async t => {1440 let requestCount = 0;14411442 const server = await createHttpTestServer(t);1443 server.post('/', async (_request, response) => {1444 requestCount++;1445 response.sendStatus(500);1446 });14471448 // `retry: 3` is shorthand for `{limit: 3}`, so extending an object with it1449 // should only change the limit and keep `methods` and `delay`.1450 const extended = ky.create({retry: {methods: ['post'], delay: () => 0}}).extend({retry: 3});14511452 await t.throwsAsync(extended.post(server.url).text(), {1453 message: /Internal Server Error/,1454 });1455 t.is(requestCount, 4);1456});14571458test('retry - numeric `retry` in per-request options keeps object defaults', async t => {1459 let requestCount = 0;14601461 const server = await createHttpTestServer(t);1462 server.post('/', async (_request, response) => {1463 requestCount++;1464 response.sendStatus(500);1465 });14661467 const instance = ky.create({retry: {methods: ['post'], delay: () => 0}});14681469 await t.throwsAsync(instance.post(server.url, {retry: 1}).text(), {1470 message: /Internal Server Error/,1471 });1472 t.is(requestCount, 2);1473});14741475test('retry - numeric `retry: 0` in per-request options disables retries over object defaults', async t => {1476 let requestCount = 0;14771478 const server = await createHttpTestServer(t);1479 server.post('/', async (_request, response) => {1480 requestCount++;1481 response.sendStatus(500);1482 });14831484 const instance = ky.create({retry: {methods: ['post'], delay: () => 0}});14851486 await t.throwsAsync(instance.post(server.url, {retry: 0}).text(), {1487 message: /Internal Server Error/,1488 });1489 t.is(requestCount, 1);1490});14911492test('retry - number, object, number chain keeps the object options and the last limit', async t => {1493 let normalizedRetry: {limit: number; methods: string[]} | undefined;14941495 const client = ky1496 .create({retry: 5})1497 .extend({retry: {methods: ['post']}})1498 .extend({retry: 1});14991500 await client.post('https://example.com', {1501 async fetch() {1502 return new Response('ok');1503 },1504 hooks: {1505 beforeRequest: [1506 ({options}) => {1507 normalizedRetry = {limit: options.retry.limit, methods: options.retry.methods};1508 },1509 ],1510 },1511 });15121513 t.deepEqual(normalizedRetry, {limit: 1, methods: ['post']});1514});15151516test('retry - extending an object `retry` with a number keeps custom status codes', async t => {1517 let requestCount = 0;15181519 const server = await createHttpTestServer(t);1520 server.get('/', async (_request, response) => {1521 requestCount++;1522 response.sendStatus(418);1523 });15241525 const extended = ky.create({retry: {statusCodes: [418], delay: () => 0}}).extend({retry: 2});15261527 await t.throwsAsync(extended(server.url).text(), {1528 message: /I'm a Teapot/,1529 });1530 t.is(requestCount, 3);1531});15321533test('retry - extending an object `retry` with a number keeps `shouldRetry`', async t => {1534 let requestCount = 0;1535 let shouldRetryCalls = 0;15361537 const server = await createHttpTestServer(t);1538 server.get('/', async (_request, response) => {1539 requestCount++;1540 response.sendStatus(500);1541 });15421543 const extended = ky.create({1544 retry: {1545 delay: () => 0,1546 shouldRetry() {1547 shouldRetryCalls++;1548 return false;1549 },1550 },1551 }).extend({retry: 3});15521553 await t.throwsAsync(extended(server.url).text(), {1554 message: /Internal Server Error/,1555 });1556 t.is(requestCount, 1);1557 t.is(shouldRetryCalls, 1);1558});15591560test('retry - `replaceOption` with a number replaces the whole object', async t => {1561 let requestCount = 0;15621563 const server = await createHttpTestServer(t);1564 server.post('/', async (_request, response) => {1565 requestCount++;1566 response.sendStatus(500);1567 });15681569 // Replacing drops the custom `methods`, so POST falls back to the default non-retriable behavior.1570 const extended = ky.create({retry: {methods: ['post'], delay: () => 0}}).extend({retry: replaceOption(3)});15711572 await t.throwsAsync(extended.post(server.url).text(), {1573 message: /Internal Server Error/,1574 });1575 t.is(requestCount, 1);1576});15771578test('retry - init hook sees a numeric `retry` merged into the object defaults', async t => {1579 let initRetry: unknown;15801581 const client = ky.create({retry: {methods: ['post']}}).extend({retry: 3});15821583 await client.post('https://example.com', {1584 async fetch() {1585 return new Response('ok');1586 },1587 hooks: {1588 init: [1589 options => {1590 initRetry = options.retry;1591 },1592 ],1593 },1594 });15951596 t.deepEqual(initRetry, {methods: ['post'], limit: 3});1597});1598

TweaksSindre Sorhusbefore adoption3ded2aa

line 1599why, one step back
1599test('retry - invalid numeric `retry` extending an object still throws', async t => {

Fix extending an object `retry` with a number dropping the other retry optionsSindre Sorhusbefore adoptionee3dec1

lines 1600–1601why, one step back
1600 const client = ky.create({retry: {methods: ['post']}}).extend({retry: -1});
1601

TweaksSindre Sorhusbefore adoption3ded2aa

line 1602why, one step back
1602 await t.throwsAsync(client.post('https://example.com'), {

Fix extending an object `retry` with a number dropping the other retry optionsSindre Sorhusbefore adoptionee3dec1

lines 1603–1617why, one step back
1603 instanceOf: TypeError,
1604 message: '`retry.limit` must be a finite, non-negative integer',1605 });1606});16071608test('retry - numeric shorthand over an object does not rewrite nested user data with a `retry` key', async t => {1609 const server = await createHttpTestServer(t);1610 server.post('/', (request, response) => {1611 response.json({body: request.body});1612 });16131614 const client = ky.create({json: {retry: {foo: 'bar'}}}).extend({json: {retry: 3}});16151616 const {body} = await client.post(server.url).json<{body: {retry: unknown}}>();1617 t.is(body.retry, 3);

Fix `extend()` dropping numeric `retry` limit when merging with an object (#867)Alexander Kireyevbefore adoption06375ef

lines 1618–1633why, one step back
1618});
16191620test('retry - shorthand expansion does not rewrite nested user data with a `retry` key', async t => {1621 const server = await createHttpTestServer(t);1622 server.post('/', (request, response) => {1623 response.json({body: request.body});1624 });16251626 // A `retry` key inside the `json` body is user data, not the `retry` option,1627 // so the number-to-`{limit}` shorthand must not touch it.1628 const client = ky.create({json: {retry: 3}}).extend({json: {retry: {foo: 'bar'}}});16291630 const {body} = await client.post(server.url).json<{body: {retry: unknown}}>();1631 t.deepEqual(body.retry, {foo: 'bar'});1632});1633

Fix option merging rewriting nested user data and flattening class instancesSindre Sorhusbefore adoptione06d351

lines 1634–1749why, one step back
1634test('merging does not rewrite nested user data with a `searchParams` key', async t => {
1635 let receivedBody: unknown;1636 const client = ky.create({json: {searchParams: 'a=1'}}).extend({json: {searchParams: 'b=2'}});16371638 // A `searchParams` key inside the `json` body is user data, not the `searchParams` option,1639 // so option merging must not convert it to `URLSearchParams`.1640 await client.post('https://example.com', {1641 async fetch(request) {1642 receivedBody = await (request as Request).json();1643 return new Response('ok');1644 },1645 });16461647 t.deepEqual(receivedBody, {searchParams: 'b=2'});1648});16491650test('merging does not rewrite nested user data with a `hooks` key', async t => {1651 let receivedBody: unknown;1652 const client = ky.create({json: {hooks: ['a']}}).extend({json: {hooks: ['b']}});16531654 // A `hooks` key inside the `json` body is user data, not the `hooks` option,1655 // so option merging must not replace it with a hooks object.1656 await client.post('https://example.com', {1657 async fetch(request) {1658 receivedBody = await (request as Request).json();1659 return new Response('ok');1660 },1661 });16621663 t.deepEqual(receivedBody, {hooks: ['a', 'b']});1664});16651666test('merging does not rewrite nested user data with a `context` key', async t => {1667 let receivedBody: unknown;1668 const client = ky.create({json: {context: {a: {x: 1}}}}).extend({json: {context: {a: {y: 2}, b: 3}}});16691670 // A `context` key inside the `json` body is user data, not the `context` option,1671 // so option merging must deep-merge it like any other user data instead of1672 // shallow-merging it or rejecting non-object values.1673 await client.post('https://example.com', {1674 async fetch(request) {1675 receivedBody = await (request as Request).json();1676 return new Response('ok');1677 },1678 });16791680 t.deepEqual(receivedBody, {context: {a: {x: 1, y: 2}, b: 3}});1681});16821683test('merging replaces class instances inside nested user data instead of merging them into plain objects', async t => {1684 let receivedBody: unknown;1685 const client = ky.create({json: {date: new Date(0)}});16861687 // A `Date` is not a plain object, so it must be replaced as a whole rather than having its (non-existent) own properties merged into `{}`.1688 await client.post('https://example.com', {1689 json: {date: new Date(1000)},1690 async fetch(request) {1691 receivedBody = await (request as Request).json();1692 return new Response('ok');1693 },1694 });16951696 t.deepEqual(receivedBody, {date: '1970-01-01T00:00:01.000Z'});1697});16981699test('merging replaces class instances inside nested user data when extending', async t => {1700 let receivedBody: unknown;1701 const client = ky.create({json: {date: new Date(0), keep: true}}).extend({json: {date: new Date(1000)}});17021703 await client.post('https://example.com', {1704 async fetch(request) {1705 receivedBody = await (request as Request).json();1706 return new Response('ok');1707 },1708 });17091710 t.deepEqual(receivedBody, {date: '1970-01-01T00:00:01.000Z', keep: true});1711});17121713test('merging still deep-merges null-prototype objects inside nested user data', async t => {1714 let receivedBody: unknown;1715 const nested = Object.create(null) as Record<string, unknown>;1716 nested.b = 2;1717 const client = ky.create({json: {nested: {a: 1}}});17181719 await client.post('https://example.com', {1720 json: {nested},1721 async fetch(request) {1722 receivedBody = await (request as Request).json();1723 return new Response('ok');1724 },1725 });17261727 t.deepEqual(receivedBody, {nested: {a: 1, b: 2}});1728});17291730test('merging still concatenates arrays inside nested options', async t => {1731 let retryMethods: string[] | undefined;1732 const client = ky.create({retry: {methods: ['get']}}).extend({retry: {methods: ['post']}});17331734 await client('https://example.com', {1735 async fetch() {1736 return new Response('ok');1737 },1738 hooks: {1739 beforeRequest: [1740 ({options}) => {1741 retryMethods = options.retry.methods;1742 },1743 ],1744 },1745 });17461747 t.deepEqual(retryMethods, ['get', 'post']);1748});1749

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1750–1752why, one step back
1750test('doesn\'t retry on 413 with empty statusCodes and methods', async t => {
1751 let requestCount = 0;1752

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1753why, one step back
1753 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1754–1778why, one step back
1754
1755 server.get('/', async (_request, response) => {1756 requestCount++;1757 response.sendStatus(413);1758 });17591760 await t.throwsAsync(1761 ky(server.url, {1762 retry: {1763 limit: 10,1764 statusCodes: [],1765 methods: [],1766 },1767 }).text(),1768 {1769 message: /Payload Too Large/,1770 },1771 );17721773 t.is(requestCount, 1);1774});17751776test('doesn\'t retry on 413 with empty methods', async t => {1777 let requestCount = 0;1778

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1779why, one step back
1779 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1780–1802why, one step back
1780 server.get('/', async (_request, response) => {
1781 requestCount++;1782 response.sendStatus(413);1783 });17841785 await t.throwsAsync(1786 ky(server.url, {1787 retry: {1788 limit: 10,1789 methods: [],1790 },1791 }).text(),1792 {1793 message: /Payload Too Large/,1794 },1795 );17961797 t.is(requestCount, 1);1798});17991800test('does retry on 408 with methods provided as array', async t => {1801 let requestCount = 0;1802

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1803why, one step back
1803 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1804–1823why, one step back
1804 server.get('/', async (_request, response) => {
1805 requestCount++;1806 response.sendStatus(408);1807 });18081809 await t.throwsAsync(1810 ky(server.url, {1811 retry: {1812 limit: 3,1813 methods: ['get'],1814 },1815 }).text(),1816 {1817 message: /Request Timeout/,1818 },1819 );18201821 t.is(requestCount, 4);1822});1823

Respect custom HTTP method case when matching retriesSindre Sorhusbefore adoptione4269f0

lines 1824–1853why, one step back
1824for (const [method, retryMethod, expectedAttempts] of [
1825 ['REPORT', 'report', 1],1826 ['report', 'REPORT', 1],1827 ['REPORT', 'REPORT', 2],1828 ['report', 'report', 2],1829 ['GET', 'get', 2],1830 ['OPTIONS', 'options', 2],1831 ['PATCH', 'patch', 2],1832] as const) {1833 test(`retry method matching respects ${method} with ${retryMethod}`, async t => {1834 let attempts = 0;18351836 await t.throwsAsync(ky('https://example.com', {1837 method,1838 retry: {1839 limit: 1,1840 methods: [retryMethod],1841 delay: () => 0,1842 },1843 async fetch(request) {1844 attempts++;1845 t.is(request.method, method);1846 return new Response('failure', {status: 500});1847 },1848 }), {name: 'HTTPError'});18491850 t.is(attempts, expectedAttempts);1851 });1852}1853

Fix handling of uppercase `retry.methods` and improve typing (#789)Martin Vokrinekbefore adoptioncec10a9

lines 1854–1856why, one step back
1854test('does retry on 408 with methods provided as uppercase array', async t => {
1855 let requestCount = 0;1856

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1857why, one step back
1857 const server = await createHttpTestServer(t);

Fix handling of uppercase `retry.methods` and improve typing (#789)Martin Vokrinekbefore adoptioncec10a9

lines 1858–1877why, one step back
1858 server.get('/', async (_request, response) => {
1859 requestCount++;1860 response.sendStatus(408);1861 });18621863 await t.throwsAsync(1864 ky(server.url, {1865 retry: {1866 limit: 3,1867 methods: ['GET'],1868 },1869 }).text(),1870 {1871 message: /Request Timeout/,1872 },1873 );18741875 t.is(requestCount, 4);1876});1877

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1878–1880why, one step back
1878test('does retry on 408 with statusCodes provided as array', async t => {
1879 let requestCount = 0;1880

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1881why, one step back
1881 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1882–1904why, one step back
1882 server.get('/', async (_request, response) => {
1883 requestCount++;1884 response.sendStatus(408);1885 });18861887 await t.throwsAsync(1888 ky(server.url, {1889 retry: {1890 limit: 3,1891 statusCodes: [408],1892 },1893 }).text(),1894 {1895 message: /Request Timeout/,1896 },1897 );18981899 t.is(requestCount, 4);1900});19011902test('doesn\'t retry when retry.limit is set to 0', async t => {1903 let requestCount = 0;1904

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 1905why, one step back
1905 const server = await createHttpTestServer(t);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1906–1922why, one step back
1906 server.get('/', (_request, response) => {
1907 requestCount++;1908 response.sendStatus(408);1909 });19101911 await t.throwsAsync(1912 ky(server.url, {1913 retry: {1914 limit: 0,1915 },1916 }).text(),1917 {1918 message: /Request Timeout/,1919 },1920 );19211922 t.is(requestCount, 1);

Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd

lines 1923–2012why, one step back
1923});
19241925test('streaming body POST succeeds when retry.limit is 0', async t => {1926 const server = await createHttpTestServer(t, {bodyParser: false});1927 server.post('/', async (request, response) => {1928 response.send(await parseRawBody(request));1929 });19301931 const body = 'hello stream';1932 const stream = new ReadableStream({1933 start(controller) {1934 controller.enqueue(new TextEncoder().encode(body));1935 controller.close();1936 },1937 });19381939 const result = await ky.post(server.url, {1940 // @ts-expect-error - Types are outdated.1941 duplex: 'half',1942 body: stream,1943 retry: {limit: 0},1944 }).text();19451946 t.is(result, body);1947});19481949test('streaming body is canceled once when retry.limit is 0 and fetch throws', async t => {1950 let cancelCount = 0;1951 const stream = new ReadableStream({1952 start(controller) {1953 controller.enqueue(new TextEncoder().encode('cancel me'));1954 },1955 cancel() {1956 cancelCount++;1957 },1958 });19591960 const expectedError = new Error('fetch failed');1961 let fetchCallCount = 0;1962 await t.throwsAsync(ky.post('https://example.com', {1963 // @ts-expect-error - Types are outdated.1964 duplex: 'half',1965 body: stream,1966 retry: {limit: 0},1967 async fetch() {1968 fetchCallCount++;1969 throw expectedError;1970 },1971 }).text(), {1972 is: expectedError,1973 });19741975 t.is(fetchCallCount, 1);1976 t.is(cancelCount, 1);1977});19781979test('streaming body POST retries and succeeds when retry.limit is above 0', async t => {1980 let requestCount = 0;1981 const server = await createHttpTestServer(t, {bodyParser: false});1982 server.post('/', async (request, response) => {1983 requestCount++;1984 if (requestCount === 1) {1985 response.sendStatus(408);1986 return;1987 }19881989 response.send(await parseRawBody(request));1990 });19911992 const body = 'retry stream body';1993 const stream = new ReadableStream({1994 start(controller) {1995 controller.enqueue(new TextEncoder().encode(body));1996 controller.close();1997 },1998 });19992000 const result = await ky.post(server.url, {

The first 2,000 of 5,414 lines.