Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add baseUrl option, rename prefixUrl, and allow leading slashes in input #606

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
16 changes: 8 additions & 8 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ Returns a [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/R

Sets `options.method` to the method name and makes a request.

When using a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance as `input`, any URL altering options (such as `prefixUrl`) will be ignored.
When using a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance as `input`, any URL altering options (such as `startPath`) will be ignored.

#### options

Expand Down Expand Up @@ -181,7 +181,7 @@ Search parameters to include in the request URL. Setting this will override all

Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).

##### prefixUrl
##### startPath

Type: `string | URL`

Expand All @@ -194,16 +194,16 @@ import ky from 'ky';

// On https://example.com

const response = await ky('unicorn', {prefixUrl: '/api'});
const response = await ky('unicorn', {startPath: '/api'});
//=> 'https://example.com/api/unicorn'

const response2 = await ky('unicorn', {prefixUrl: 'https://cats.com'});
const response2 = await ky('unicorn', {startPath: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
```

Notes:
- After `prefixUrl` and `input` are joined, the result is resolved against the [base URL](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) of the page (if any).
- Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion about how the `input` URL is handled, given that `input` will not follow the normal URL resolution rules when `prefixUrl` is being used, which changes the meaning of a leading slash.
- After `startPath` and `input` are joined, the result is resolved against the [base URL](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) of the page (if any).
- Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion about how the `input` URL is handled, given that `input` will not follow the normal URL resolution rules when `startPath` is being used, which changes the meaning of a leading slash.

##### retry

Expand Down Expand Up @@ -519,12 +519,12 @@ import ky from 'ky';

// On https://my-site.com

const api = ky.create({prefixUrl: 'https://example.com/api'});
const api = ky.create({startPath: 'https://example.com/api'});

const response = await api.get('users/123');
//=> 'https://example.com/api/users/123'

const response = await api.get('/status', {prefixUrl: ''});
const response = await api.get('/status', {startPath: ''});
//=> 'https://my-site.com/status'
```

Expand Down
28 changes: 18 additions & 10 deletions source/core/Ky.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {HTTPError} from '../errors/HTTPError.js';
import {TimeoutError} from '../errors/TimeoutError.js';
import type {Hooks} from '../types/hooks.js';
import type {Input, InternalOptions, NormalizedOptions, Options, SearchParamsInit} from '../types/options.js';
import type {
Input, InternalOptions, NormalizedOptions, Options, SearchParamsInit,
} from '../types/options.js';
import {type ResponsePromise} from '../types/ResponsePromise.js';
import {deepMerge, mergeHeaders} from '../utils/merge.js';
import {normalizeRequestMethod, normalizeRetryOptions} from '../utils/normalize.js';
Expand Down Expand Up @@ -137,9 +139,9 @@ export class Ky {
options.hooks,
),
method: normalizeRequestMethod(options.method ?? (this._input as Request).method),
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
prefixUrl: String(options.prefixUrl || ''),
retry: normalizeRetryOptions(options.retry),
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
startPath: String(options.startPath || ''),
throwHttpErrors: options.throwHttpErrors !== false,
timeout: options.timeout ?? 10_000,
fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
Expand All @@ -149,16 +151,22 @@ export class Ky {
throw new TypeError('`input` must be a string, URL, or Request');
}

if (this._options.prefixUrl && typeof this._input === 'string') {
if (this._input.startsWith('/')) {
throw new Error('`input` must not begin with a slash when using `prefixUrl`');
}
if (typeof this._input === 'string') {
if (this._options.startPath) {
if (!this._options.startPath.endsWith('/')) {
this._options.startPath += '/';
}

if (!this._options.prefixUrl.endsWith('/')) {
this._options.prefixUrl += '/';
if (this._input.startsWith('/')) {
this._input = this._input.slice(1);
}

this._input = this._options.startPath + this._input;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think if _input starts with a protocol (or is a valid URL?) then we should ignore startPath in order to avoid an URL like http://foo.com/http://bar.com

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That kind of "double URL" construct is useful for reverse proxies. It should be supported.

Also, you would be surprised how hard URL parsing is. Especially for a library like Ky that supports non-browsers.

}

this._input = this._options.prefixUrl + this._input;
if (this._options.baseUrl) {
this._input = new URL(this._input, (new Request(options.baseUrl)).url);
}
}

if (supportsAbortController) {
Expand Down
2 changes: 1 addition & 1 deletion source/core/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export const kyOptionKeys: KyOptionsRegistry = {
parseJson: true,
stringifyJson: true,
searchParams: true,
prefixUrl: true,
startPath: true,
retry: true,
timeout: true,
hooks: true,
Expand Down
16 changes: 8 additions & 8 deletions source/types/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,23 +97,23 @@ export type KyOptions = {
Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky-instances.

Notes:
- After `prefixUrl` and `input` are joined, the result is resolved against the [base URL](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) of the page (if any).
- Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion about how the `input` URL is handled, given that `input` will not follow the normal URL resolution rules when `prefixUrl` is being used, which changes the meaning of a leading slash.
- After `startPath` and `input` are joined, the result is resolved against the [base URL](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) of the page (if any).
- Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion about how the `input` URL is handled, given that `input` will not follow the normal URL resolution rules when `startPath` is being used, which changes the meaning of a leading slash.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leading slashes in input are disallowed when using this option to enforce consistency and avoid confusion [...]

From what I can tell from the changed code, this is no longer the case?

I personally prefer it that way though and think that we should keep that behaviour

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed. As mentioned in the TODOs section, I haven't gotten around to updating the docs yet, other than a simple find & replace. But thank you for the reminder. 🙂


@example
```
import ky from 'ky';

// On https://example.com

const response = await ky('unicorn', {prefixUrl: '/api'});
const response = await ky('unicorn', {startPath: '/api'});
//=> 'https://example.com/api/unicorn'

const response = await ky('unicorn', {prefixUrl: 'https://cats.com'});
const response = await ky('unicorn', {startPath: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
```
*/
prefixUrl?: URL | string;
startPath?: URL | string;

/**
An object representing `limit`, `methods`, `statusCodes` and `maxRetryAfter` fields for maximum retry count, allowed methods, allowed status codes and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.
Expand Down Expand Up @@ -265,12 +265,12 @@ export interface Options extends KyOptions, Omit<RequestInit, 'headers'> { // es

export type InternalOptions = Required<
Omit<Options, 'hooks' | 'retry'>,
'fetch' | 'prefixUrl' | 'timeout'
'fetch' | 'startPath' | 'timeout'
> & {
headers: Required<Headers>;
hooks: Required<Hooks>;
retry: Required<RetryOptions>;
prefixUrl: string;
startPath: string;
};

/**
Expand All @@ -283,7 +283,7 @@ export interface NormalizedOptions extends RequestInit { // eslint-disable-line

// Extended from custom `KyOptions`, but ensured to be set (not optional).
retry: RetryOptions;
prefixUrl: string;
startPath: string;
onDownloadProgress: Options['onDownloadProgress'];
}

Expand Down
39 changes: 39 additions & 0 deletions test/base-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import test from 'ava';
import ky from '../source/index.js';
import {createHttpTestServer} from './helpers/create-http-test-server.js';

test('baseUrl option', async t => {
const server = await createHttpTestServer();
server.get('/', (_request, response) => {
response.end('/');
});
server.get('/foo', (_request, response) => {
response.end('/foo');
});
server.get('/bar', (_request, response) => {
response.end('/bar');
});
server.get('/foo/bar', (_request, response) => {
response.end('/foo/bar');
});

t.is(
// @ts-expect-error {baseUrl: boolean} isn't officially supported
await ky(`${server.url}/foo/bar`, {baseUrl: false}).text(),
'/foo/bar',
);
t.is(await ky(`${server.url}/foo/bar`, {baseUrl: ''}).text(), '/foo/bar');
t.is(await ky(new URL(`${server.url}/foo/bar`), {baseUrl: ''}).text(), '/foo/bar');
t.is(await ky('foo/bar', {baseUrl: server.url}).text(), '/foo/bar');
t.is(await ky('foo/bar', {baseUrl: new URL(server.url)}).text(), '/foo/bar');
t.is(await ky('/bar', {baseUrl: `${server.url}/foo/`}).text(), '/bar');
t.is(await ky('/bar', {baseUrl: `${server.url}/foo`}).text(), '/bar');
t.is(await ky('bar', {baseUrl: `${server.url}/foo/`}).text(), '/foo/bar');
t.is(await ky('bar', {baseUrl: `${server.url}/foo`}).text(), '/bar');
t.is(await ky('bar', {baseUrl: new URL(`${server.url}/foo`)}).text(), '/bar');
t.is(await ky('', {baseUrl: server.url}).text(), '/');
t.is(await ky('', {baseUrl: `${server.url}/`}).text(), '/');
t.is(await ky('', {baseUrl: new URL(server.url)}).text(), '/');

await server.close();
});
14 changes: 7 additions & 7 deletions test/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ test.afterEach(async () => {
await server.close();
});

defaultBrowsersTest('prefixUrl option', async (t: ExecutionContext, page: Page) => {
defaultBrowsersTest('startPath option', async (t: ExecutionContext, page: Page) => {
server.get('/', (_request, response) => {
response.end('zebra');
});
Expand All @@ -60,16 +60,16 @@ defaultBrowsersTest('prefixUrl option', async (t: ExecutionContext, page: Page)
await addKyScriptToPage(page);

await t.throwsAsync(
page.evaluate(async () => window.ky('/foo', {prefixUrl: '/'})),
{message: /`input` must not begin with a slash when using `prefixUrl`/},
page.evaluate(async () => window.ky('/foo', {startPath: '/'})),
{message: /`input` must not begin with a slash when using `startPath`/},
);

const results = await page.evaluate(async (url: string) => Promise.all([
window.ky(`${url}/api/unicorn`).text(),
// @ts-expect-error unsupported {prefixUrl: null} type
window.ky(`${url}/api/unicorn`, {prefixUrl: null}).text(),
window.ky('api/unicorn', {prefixUrl: url}).text(),
window.ky('api/unicorn', {prefixUrl: `${url}/`}).text(),
// @ts-expect-error unsupported {startPath: null} type
window.ky(`${url}/api/unicorn`, {startPath: null}).text(),
window.ky('api/unicorn', {startPath: url}).text(),
window.ky('api/unicorn', {startPath: `${url}/`}).text(),
]), server.url);

t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow']);
Expand Down
2 changes: 1 addition & 1 deletion test/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ test('fetch option takes a custom fetch function', async t => {
}).text(),
`${fixture}?new#hash`,
);
t.is(await ky('unicorn', {fetch: customFetch, prefixUrl: `${fixture}/api/`}).text(), `${fixture}/api/unicorn`);
t.is(await ky('unicorn', {fetch: customFetch, startPath: `${fixture}/api/`}).text(), `${fixture}/api/unicorn`);
});

test('options are correctly passed to Fetch #1', async t => {
Expand Down
40 changes: 0 additions & 40 deletions test/prefix-url.ts

This file was deleted.

39 changes: 39 additions & 0 deletions test/start-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import test from 'ava';
import ky from '../source/index.js';
import {createHttpTestServer} from './helpers/create-http-test-server.js';

test('startPath option', async t => {
const server = await createHttpTestServer();
server.get('/', (_request, response) => {
response.end('/');
});
server.get('/foo', (_request, response) => {
response.end('/foo');
});
server.get('/bar', (_request, response) => {
response.end('/bar');
});
server.get('/foo/bar', (_request, response) => {
response.end('/foo/bar');
});

t.is(
// @ts-expect-error {startPath: boolean} isn't officially supported
await ky(`${server.url}/foo/bar`, {startPath: false}).text(),
'/foo/bar',
);
t.is(await ky(`${server.url}/foo/bar`, {startPath: ''}).text(), '/foo/bar');
t.is(await ky(new URL(`${server.url}/foo/bar`), {startPath: ''}).text(), '/foo/bar');
t.is(await ky('foo/bar', {startPath: server.url}).text(), '/foo/bar');
t.is(await ky('foo/bar', {startPath: new URL(server.url)}).text(), '/foo/bar');
t.is(await ky('/bar', {startPath: `${server.url}/foo/`}).text(), '/foo/bar');
t.is(await ky('/bar', {startPath: `${server.url}/foo`}).text(), '/foo/bar');
t.is(await ky('bar', {startPath: `${server.url}/foo/`}).text(), '/foo/bar');
t.is(await ky('bar', {startPath: `${server.url}/foo`}).text(), '/foo/bar');
t.is(await ky('bar', {startPath: new URL(`${server.url}/foo`)}).text(), '/foo/bar');
t.is(await ky('', {startPath: server.url}).text(), '/');
t.is(await ky('', {startPath: `${server.url}/`}).text(), '/');
t.is(await ky('', {startPath: new URL(server.url)}).text(), '/');

await server.close();
});
Loading