Skip to content

Commit

Permalink
Add fallback validation for Safari 14.0
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandrHoroshih committed Jan 30, 2025
1 parent f13a916 commit b3868e5
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
20 changes: 19 additions & 1 deletion packages/core/src/fetch/__tests__/lib.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, test, expect } from 'vitest';

import { mergeRecords } from '../lib';
import { mergeRecords, splitUrl } from '../lib';

describe('mergeRecords', () => {
test('empty to empty object', () => {
Expand Down Expand Up @@ -41,3 +41,21 @@ describe('mergeRecords', () => {
});
});
});

describe('Safari 14.0 bug', () => {
test('splitUrl', () => {
const url = 'https://example.com/api?foo=bar';

const split = splitUrl(url);

expect(split).toEqual({
base: 'https://example.com',
path: '/api?foo=bar',
});

const url1 = new URL(url);
const url2 = new URL(split.path, split.base);

expect(url1.href).toBe(url2.href);
});
});
37 changes: 37 additions & 0 deletions packages/core/src/fetch/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,27 @@ export function formatUrl(
try {
return new URL(urlString, urlBase);
} catch (e) {
if (!urlBase) {
try {
/**
* Fallback branch for Safari 14.0
* @see https://github.com/igorkamyshev/farfetched/issues/528
*
* If url is full path, but we're in Safari 14.0, we will have a TypeError for new URL(urlString, undefined)
*
* So we have to manually split url into base and path parts first
*/
const { base, path } = splitUrl(urlString);

return new URL(path, base);
} catch (_e) {
throw configurationError({
reason: 'Invalid URL',
validationErrors: [`"${urlString}" is not valid URL`],
});
}
}

throw configurationError({
reason: 'Invalid URL',
validationErrors: [`"${urlString}" is not valid URL`],
Expand Down Expand Up @@ -129,3 +150,19 @@ function clearValue(

return value ?? null;
}

/**
* @see https://github.com/igorkamyshev/farfetched/issues/528
*/
export function splitUrl(urlString: string): { base: string; path: string } {
const urlPattern = /^(https?:\/\/[^\/]+)(\/.*)?$/;
const match = urlString.match(urlPattern);

if (!match) {
throw new Error(`Invalid URL: ${urlString}`);
}

const base = match[1];
const path = match[2] || '';
return { base, path };
}

0 comments on commit b3868e5

Please sign in to comment.