Skip to content

Commit

Permalink
fix(shared): check markdown links correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
meteorlxy committed Jun 11, 2022
1 parent ea1d09c commit 252f4ac
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
24 changes: 21 additions & 3 deletions packages/@vuepress/shared/__tests__/utils/isLinkExternal.spec.ts
Expand Up @@ -33,6 +33,9 @@ const testCases: [
[['/foo/bar/baz.md'], false],
[['/foo/bar/baz.md', '/base/'], false],
[['/foo/bar/baz.md', '/foo/'], false],
[['/foo/bar/baz.html'], false],
[['/foo/bar/baz.html', '/base/'], true],
[['/foo/bar/baz.html', '/foo/'], false],

// relative links
[['foobar.com'], false],
Expand All @@ -43,13 +46,28 @@ const testCases: [
[['foo/bar/baz.md'], false],
[['foo/bar/baz.md', '/base/'], false],
[['foo/bar/baz.md', '/foo/'], false],
[['foo/bar/baz.html'], false],
[['foo/bar/baz.html', '/base/'], false],
[['foo/bar/baz.html', '/foo/'], false],
[['./foo/bar'], false],
[['./foo/bar', '/base/'], false],
[['./foo/bar', '/foo/'], false],
[['./foo/bar/baz.md'], false],
[['./foo/bar/baz.md', '/base/'], false],
[['./foo/bar/baz.md', '/foo/'], false],
[['./foo/bar/baz.html'], false],
[['./foo/bar/baz.html', '/base/'], false],
[['./foo/bar/baz.html', '/foo/'], false],
]

describe('shared > isLinkExternal', () => {
describe('should determine external link correctly', () => {
testCases.forEach(([source, expected]) => {
it(`link: ${source[0]}, base: ${source[1] || '/'}`, () => {
expect(isLinkExternal(...source)).toBe(expected)
testCases.forEach(([[link, base = '/'], expected]) => {
it(`link: ${link}, base: ${base}`, () => {
expect(isLinkExternal(link, base)).toBe(expected)
expect(isLinkExternal(`${link}#foobar`, base)).toBe(expected)
expect(isLinkExternal(`${link}?foo=bar`, base)).toBe(expected)
expect(isLinkExternal(`${link}?foo=bar#foobar`, base)).toBe(expected)
})
})
})
Expand Down
8 changes: 7 additions & 1 deletion packages/@vuepress/shared/src/utils/isLinkExternal.ts
@@ -1,6 +1,8 @@
import { isLinkFtp } from './isLinkFtp'
import { isLinkHttp } from './isLinkHttp'

const markdownLinkRegexp = /.md((\?|#).*)?$/

/**
* Determine a link is external or not
*/
Expand All @@ -11,7 +13,11 @@ export const isLinkExternal = (link: string, base = '/'): boolean => {
}

// absolute link that does not start with `base` and does not end with `.md`
if (link.startsWith('/') && !link.startsWith(base) && !link.endsWith('.md')) {
if (
link.startsWith('/') &&
!link.startsWith(base) &&
!markdownLinkRegexp.test(link)
) {
return true
}

Expand Down

0 comments on commit 252f4ac

Please sign in to comment.