add isValidPathname

This commit is contained in:
slorber 2020-06-03 15:40:10 +02:00
parent 4e8b361d00
commit da8ccd0419
2 changed files with 29 additions and 0 deletions

View file

@ -18,6 +18,7 @@ import {
objectWithKeySorted, objectWithKeySorted,
aliasedSitePath, aliasedSitePath,
createExcerpt, createExcerpt,
isValidPathname,
} from '../index'; } from '../index';
describe('load utils', () => { describe('load utils', () => {
@ -363,4 +364,20 @@ describe('load utils', () => {
expect(createExcerpt(testCase.input)).toEqual(testCase.output); expect(createExcerpt(testCase.input)).toEqual(testCase.output);
}); });
}); });
test('isValidPathname', () => {
expect(isValidPathname('/')).toBe(true);
expect(isValidPathname('/hey')).toBe(true);
expect(isValidPathname('/hey/ho')).toBe(true);
expect(isValidPathname('/hey/ho/')).toBe(true);
expect(isValidPathname('/hey/h%C3%B4/')).toBe(true);
expect(isValidPathname('/hey///ho///')).toBe(true); // Unexpected but valid
//
expect(isValidPathname('')).toBe(false);
expect(isValidPathname('hey')).toBe(false);
expect(isValidPathname('/hey/hô')).toBe(false);
expect(isValidPathname('/hey?qs=ho')).toBe(false);
expect(isValidPathname('https://fb.com/hey')).toBe(false);
expect(isValidPathname('//hey')).toBe(false);
});
}); });

View file

@ -12,6 +12,7 @@ import camelCase from 'lodash.camelcase';
import kebabCase from 'lodash.kebabcase'; import kebabCase from 'lodash.kebabcase';
import escapeStringRegexp from 'escape-string-regexp'; import escapeStringRegexp from 'escape-string-regexp';
import fs from 'fs-extra'; import fs from 'fs-extra';
import {URL} from 'url';
const fileHash = new Map(); const fileHash = new Map();
export async function generate( export async function generate(
@ -327,3 +328,14 @@ export function getEditUrl(fileRelativePath: string, editUrl?: string) {
? normalizeUrl([editUrl, posixPath(fileRelativePath)]) ? normalizeUrl([editUrl, posixPath(fileRelativePath)])
: undefined; : undefined;
} }
export function isValidPathname(str: string): boolean {
if (!str.startsWith('/')) {
return false;
}
try {
return new URL(str, 'https://domain.com').pathname === str;
} catch (e) {
return false;
}
}