Skip to content

Commit d6f8176

Browse files
sholladaysindresorhus
authored andcommitted
Fix relative URL resolution (#59)
Fixes #58 There was a regression introduced in a7c71b5 which broke the ability for `input` to be a relative URL like `foo` or `/foo`. The root cause is that [`window.URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) unfortunately does not support relative URLs without an explicit and absolute `base` argument. This fixes that and adds a test for it. Now that we have Cypress set up, we can properly test anything related to relative URLs. The goal is to follow the URL resolution rules the same way that `fetch` does. So we resolve `input` against [`document.baseURI`](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI#The_base_URL_of_a_document).
1 parent e800c7a commit d6f8176

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

cypress/integration/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,9 @@ describe('ky', () => {
66
ky('/foo', {prefixUrl: '/'});
77
}).to.throw(Error, /must not begin with a slash/);
88
});
9+
10+
it('resolves relative URLs for `input` and `prefixUrl`', async () => {
11+
expect(await ky('/cypress/fixtures/fixture.json').json()).to.deep.equal({foo: true});
12+
expect(await ky('fixtures/fixture.json', {prefixUrl: '/cypress/'}).json()).to.deep.equal({foo: true});
13+
});
914
});

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ class Ky {
135135
this._options.prefixUrl += '/';
136136
}
137137

138-
const url = new _globalThis.URL(this._options.prefixUrl + this._input);
138+
const url = new _globalThis.URL(this._options.prefixUrl + this._input, document.baseURI);
139139
if (typeof searchParams === 'string' || searchParams instanceof _globalThis.URLSearchParams) {
140140
url.search = searchParams;
141141
} else if (searchParams && Object.values(searchParams).every(param => typeof param === 'number' || typeof param === 'string')) {

test/_require.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,6 @@ global.Headers = Headers;
66
global.Response = Response;
77
global.URL = URL;
88
global.URLSearchParams = URLSearchParams;
9+
global.document = {
10+
baseURI: 'https://example.com'
11+
};

0 commit comments

Comments
 (0)