Skip to content

Commit

Permalink
fix(shared): check external link correctly (#1543)
Browse files Browse the repository at this point in the history
Co-authored-by: Xinyu Liu <meteor.lxy@foxmail.com>
  • Loading branch information
Mister-Hope and meteorlxy committed Apr 17, 2024
1 parent 8b1ab67 commit 34e240c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 22 deletions.
20 changes: 5 additions & 15 deletions packages/shared/src/utils/isLinkExternal.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,13 @@
import { isLinkHttp } from './isLinkHttp.js'
import { isLinkWithProtocol } from './isLinkWithProtocol.js'

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

/**
* Determine a link is external or not
*/
export const isLinkExternal = (link: string, base = '/'): boolean => {
if (isLinkHttp(link)) {
return true
}

export const isLinkExternal = (link: string, base = '/'): boolean =>
isLinkWithProtocol(link) ||
// absolute link that does not start with `base` and does not end with `.md`
if (
link.startsWith('/') &&
(link.startsWith('/') &&
!link.startsWith(base) &&
!markdownLinkRegexp.test(link)
) {
return true
}

return false
}
!markdownLinkRegexp.test(link))
14 changes: 7 additions & 7 deletions packages/shared/tests/isLinkExternal.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ const testCases: [
[['//foobar.com/base/README.md', '/base/'], true],

// links with other protocols
[['mailto:foobar', '/base/'], false],
[['tel:foobar', '/base/'], false],
[['ftp://foobar.com'], false],
[['ftp://foobar.com', '/base/'], false],
[['ftp://foobar.com/base/README.md'], false],
[['ftp://foobar.com/base/README.md', '/base/'], false],
[['ms-windows-store://home', '/base/'], false],
[['mailto:foobar', '/base/'], true],
[['tel:foobar', '/base/'], true],
[['ftp://foobar.com'], true],
[['ftp://foobar.com', '/base/'], true],
[['ftp://foobar.com/base/README.md'], true],
[['ftp://foobar.com/base/README.md', '/base/'], true],
[['ms-windows-store://home', '/base/'], true],

// absolute links
[['/foo/bar'], false],
Expand Down

0 comments on commit 34e240c

Please sign in to comment.