forked from holamgadol/markdownlint-foliant-rules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate-internal-links.js
66 lines (60 loc) · 2.34 KB
/
validate-internal-links.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// @ts-check
'use strict'
const path = require('path')
const fs = require('fs')
const findExternalAnchors = require('./validate-internal-links-tools/find-etxrenal-anchors')
const resolvedLink = require('./validate-internal-links-tools/link-resolver')
const {
addError,
forEachInlineChild
} = require('markdownlint-rule-helpers')
const urlCheck = /^http/
module.exports = {
names: ['validate-internal-links'],
description: 'Broken link',
information: new URL('https://github.com/holamgadol/markdownlint-foliant-rules#validate-internal-links'),
tags: ['internal', 'local', 'links'],
function: function validateInternalLinks (params, onError) {
const refs = new Set()
const base = path.normalize(params.name)
const dir = path.dirname(base)
const cwd = path.normalize(process.cwd().toString())
const src = String(params.config.src || './src/')
const project = params.config.project
const srcDir = path.resolve(cwd, src)
findExternalAnchors(base, refs)
forEachInlineChild(params, 'link_open', async function forToken (token) {
const originalLink = decodeURIComponent(token.attrs[0][1])
if (!urlCheck.test(originalLink) && originalLink !== '') {
const link = resolvedLink(originalLink, base, dir, project, srcDir)
const file = link.split('#')[0]
const anchor = link.split('#')[1]
if (!refs.has(link)) {
if (file === base) {
addError(onError, token.lineNumber, 'invalid local anchor', originalLink)
} else {
if (fs.existsSync(file)) {
if (anchor) {
findExternalAnchors(file, refs)
if (!refs.has(link)) {
addError(onError, token.lineNumber, 'file exists, but invalid anchor', originalLink)
}
}
} else {
addError(onError, token.lineNumber, 'file does not exist', originalLink)
}
}
}
}
})
forEachInlineChild(params, 'image', async function forToken (token) {
const originalLink = decodeURIComponent(token.attrs[0][1])
if (!urlCheck.test(originalLink) && originalLink !== '') {
const link = resolvedLink(originalLink, base, dir)
if (!fs.existsSync(link)) {
addError(onError, token.lineNumber, 'image does not exist', originalLink)
}
}
})
}
}