Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion source/core/Ky.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,22 @@ const isRequestInstance = (value: unknown): value is Request =>
const isResponseInstance = (value: unknown): value is Response =>
value instanceof globalThis.Response || objectToString.call(value) === '[object Response]';

const cloneSearchParametersForInitHook = (searchParameters: SearchParamsOption | undefined): SearchParamsOption | undefined => {
if (Array.isArray(searchParameters)) {
return searchParameters.map(parameter => [...parameter]) as SearchParamsOption;
}

return cloneShallow(searchParameters) as SearchParamsOption | undefined;
};

// Shallow-clone mutable option properties so init hook mutations don't leak across requests.
function cloneInitHookOptions(options: Options): Options {
const clonedOptions: Options = {
...options,
json: cloneShallow(options.json),
context: cloneShallow(options.context)!,
headers: cloneShallow(options.headers)!,
searchParams: cloneShallow(options.searchParams) as SearchParamsOption | undefined,
searchParams: cloneSearchParametersForInitHook(options.searchParams),
};

if (options.retry !== undefined) {
Expand Down
30 changes: 30 additions & 0 deletions test/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4900,6 +4900,36 @@ test('init hook in-place mutations do not leak across requests', async t => {
t.deepEqual(seenRequestIdentifiers, ['1', '2']);
});

test('init hook tuple searchParams mutations do not leak across requests', async t => {
let requestIdentifier = 0;
const seenInitialValues: string[] = [];
const seenRequestIdentifiers: string[] = [];

const api = ky.extend({
searchParams: [['requestId', 'seed']],
hooks: {
init: [
options => {
const searchParameters = options.searchParams as string[][];
seenInitialValues.push(searchParameters[0]![1]!);
searchParameters[0]![1] = String(++requestIdentifier);
},
],
},
});

const fetch: typeof globalThis.fetch = async request => {
seenRequestIdentifiers.push(new URL(request.url).searchParams.get('requestId')!);
return new Response('ok');
};

await api.get('https://example.com', {fetch});
await api.get('https://example.com', {fetch});

t.deepEqual(seenInitialValues, ['seed', 'seed']);
t.deepEqual(seenRequestIdentifiers, ['1', '2']);
});

test('init hook in-place retry mutations do not leak across requests', async t => {
const seenLimits: number[] = [];

Expand Down