feat(v2): absolute slugs and slug resolution system (#3084)

* rework slug to allow absolute slugs and slug resolution

* add slug metadata tests

* refactor docs metadata test + fix slug bugs

* fix tests

* fix docs tests failing due to randomness + update snapshot

* add test for addLeadingSlash
This commit is contained in:
Sébastien Lorber 2020-07-21 18:26:30 +02:00 committed by GitHub
parent 6730590c1e
commit f4434b2e42
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
39 changed files with 791 additions and 255 deletions

View file

@ -25,6 +25,7 @@ import {
removeSuffix,
removePrefix,
getFilePathForRoutePath,
addLeadingSlash,
} from '../index';
describe('load utils', () => {
@ -412,6 +413,15 @@ describe('addTrailingSlash', () => {
});
});
describe('addLeadingSlash', () => {
test('should no-op', () => {
expect(addLeadingSlash('/abc')).toEqual('/abc');
});
test('should add /', () => {
expect(addLeadingSlash('abc')).toEqual('/abc');
});
});
describe('removeTrailingSlash', () => {
test('should no-op', () => {
expect(removeTrailingSlash('/abcd')).toEqual('/abcd');

View file

@ -14,6 +14,9 @@ import escapeStringRegexp from 'escape-string-regexp';
import fs from 'fs-extra';
import {URL} from 'url';
// @ts-expect-error: no typedefs :s
import resolvePathnameUnsafe from 'resolve-pathname';
const fileHash = new Map();
export async function generate(
generatedFilesDir: string,
@ -361,12 +364,20 @@ export function isValidPathname(str: string): boolean {
return false;
}
try {
// weird, but is there a better way?
return new URL(str, 'https://domain.com').pathname === str;
} catch (e) {
return false;
}
}
// resolve pathname and fail fast if resolution fails
export function resolvePathname(to: string, from?: string) {
return resolvePathnameUnsafe(to, from);
}
export function addLeadingSlash(str: string): string {
return str.startsWith('/') ? str : `/${str}`;
}
export function addTrailingSlash(str: string): string {
return str.endsWith('/') ? str : `${str}/`;
}