-
Notifications
You must be signed in to change notification settings - Fork 71
feat: add no-missing-link-fragments rule #380
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SwetaTanwar
wants to merge
24
commits into
eslint:main
Choose a base branch
from
SwetaTanwar:feat/no-missing-link-fragments
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 10 commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
52d5cf5
feat: add no-missing-link-fragments rule
SwetaTanwar 9a4a870
test: added more tests
SwetaTanwar b051c1a
fix: review comments
SwetaTanwar 97d8a3c
docs: review comments
SwetaTanwar aa94245
Merge branch 'main' of github.com:SwetaTanwar/markdown into feat/no-m…
SwetaTanwar f21dcd1
chore: review comments
SwetaTanwar 8356bc5
fix: covered all test cases for no-missing-link-fragments rule
SwetaTanwar 3027e41
refactor: moved regex to top scope
SwetaTanwar 7960dc8
refactor: renamed ignorePattern with allowPattern
SwetaTanwar 587e32a
fix: removed extra code
SwetaTanwar 84f74c6
fix: review comments
SwetaTanwar ae59bf6
docs: update readme
SwetaTanwar c4fdda3
revert: moving slug to global scope
SwetaTanwar a36b406
fix: add node check for emoji test | fixed escaping of backslash
SwetaTanwar 485529c
fix: update readme
SwetaTanwar 364b8ac
fix: review comments
SwetaTanwar 77ce41e
fix: review comments
SwetaTanwar a3ee316
fix: review comments
SwetaTanwar d8b1d08
Merge branch 'main' into feat/no-missing-link-fragments
SwetaTanwar 56fb763
fix: merge conflict
SwetaTanwar b7d1ee3
fix: review comments
SwetaTanwar 5e57917
refactor: removed indentation from dedent
SwetaTanwar 4df0427
feat: review comments
SwetaTanwar d54f48b
fix: review comments
SwetaTanwar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
# no-missing-link-fragments | ||
|
||
Ensures that link fragments (URLs that start with `#`) reference valid headings or anchors in the document. This rule helps prevent broken internal links. | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
## Rule Details | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
This rule is triggered when a link fragment does not match any of the fragments that are automatically generated for headings in a document or explicitly defined via HTML anchors or custom heading IDs. | ||
|
||
Examples of **incorrect** code for this rule: | ||
|
||
```markdown | ||
<!-- eslint markdown/no-missing-link-fragments: "error" --> | ||
|
||
[Invalid Link](#non-existent-heading) | ||
|
||
# Some Heading | ||
[Case Mismatch](#SOME-HEADING) <!-- Default: case-sensitive --> | ||
``` | ||
|
||
### Correct Code Examples | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```markdown | ||
<!-- eslint markdown/no-missing-link-fragments: "error" --> | ||
|
||
# Introduction | ||
[Valid Link](#introduction) | ||
|
||
# Another Section {#custom-id} | ||
[Link to custom ID](#custom-id) | ||
|
||
<p id="html-anchor">HTML Anchor</p> | ||
[Link to HTML anchor](#html-anchor) | ||
|
||
<a name="named-anchor">Named Anchor</a> | ||
[Link to named anchor](#named-anchor) | ||
|
||
[Link to top of page](#top) | ||
|
||
<!-- With ignoreCase: true --> | ||
<!-- eslint markdown/no-missing-link-fragments: ["error", { "ignoreCase": true }] --> | ||
# Case Test | ||
[Valid Link with different case](#CASE-TEST) | ||
|
||
<!-- With allowPattern: "^figure-" --> | ||
<!-- eslint markdown/no-missing-link-fragments: ["error", { "allowPattern": "^figure-" }] --> | ||
[Ignored Link](#figure-123) | ||
``` | ||
|
||
## Options | ||
|
||
This rule supports the following options: | ||
|
||
* `ignoreCase` (boolean, default: `false`): | ||
When `true`, link fragments are compared with heading and anchor IDs in a case-insensitive manner. | ||
|
||
```json | ||
{ | ||
"ignoreCase": true | ||
} | ||
``` | ||
|
||
* `allowPattern` (string, default: `""`): | ||
A regular expression string. If a link fragment matches this pattern, it will be ignored by the rule. This is useful for fragments that are dynamically generated or handled by other tools. | ||
|
||
```json | ||
{ | ||
"allowPattern": "^figure-" | ||
} | ||
``` | ||
|
||
Example: If `allowPattern` is `"^temp-"`, links like `[Link](#temp-section)` will not be checked. | ||
|
||
## When Not To Use It | ||
|
||
You might consider disabling this rule if: | ||
|
||
* You are using a Markdown processor or static site generator that has a significantly different algorithm for generating heading IDs, and this rule produces too many false positives. | ||
* You have many dynamically generated links or fragments that cannot be easily covered by the `allowPattern` option. | ||
|
||
## Further Reading | ||
|
||
* [GitHub's heading anchor links](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#section-links) | ||
* [CommonMark Specification](https://spec.commonmark.org/) | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,180 @@ | ||
/** | ||
* @fileoverview Rule to ensure link fragments (URLs that start with #) reference valid headings | ||
* @author Sweta Tanwar (@SwetaTanwar) | ||
*/ | ||
|
||
import GithubSlugger from "github-slugger"; | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
//----------------------------------------------------------------------------- | ||
// Type Definitions | ||
//----------------------------------------------------------------------------- | ||
|
||
/** | ||
* @typedef {import("../types.ts").MarkdownRuleDefinition<{ | ||
* RuleOptions: [{ | ||
* ignoreCase?: boolean; | ||
* allowPattern?: string; | ||
* }]; | ||
* }>} NoMissingLinkFragmentsRuleDefinition | ||
*/ | ||
|
||
/** | ||
* @typedef {import("mdast").Node & { | ||
* children?: Array<import("mdast").Node>; | ||
* value?: string; | ||
* }} NodeWithChildren | ||
*/ | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
//----------------------------------------------------------------------------- | ||
// Helpers | ||
//----------------------------------------------------------------------------- | ||
|
||
const githubLineReferencePattern = /^L\d+(?:C\d+)?(?:-L\d+(?:C\d+)?)?$/u; | ||
const customHeadingIdPattern = /\{#([a-z0-9_-]+)\}\s*$/u; | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const markdownInlineFormattingPattern = /[*_~`]/gu; | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const htmlIdNamePattern = /<(?:[^>]+)\s+(?:id|name)="([^"]+)"/gu; | ||
const headingPrefixPattern = /^#+\s*/u; | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Checks if the fragment is a valid GitHub line reference | ||
* @param {string} fragment The fragment to check | ||
* @returns {boolean} Whether the fragment is a valid GitHub line reference | ||
*/ | ||
function isGitHubLineReference(fragment) { | ||
return githubLineReferencePattern.test(fragment); | ||
} | ||
|
||
//----------------------------------------------------------------------------- | ||
// Rule Definition | ||
//----------------------------------------------------------------------------- | ||
|
||
/** @type {NoMissingLinkFragmentsRuleDefinition} */ | ||
export default { | ||
meta: { | ||
type: "problem", | ||
|
||
docs: { | ||
recommended: true, | ||
lumirlumir marked this conversation as resolved.
Show resolved
Hide resolved
|
||
description: | ||
"Disallow link fragments that do not reference valid headings", | ||
url: "https://github.com/eslint/markdown/blob/main/docs/rules/no-missing-link-fragments.md", | ||
}, | ||
|
||
schema: [ | ||
{ | ||
type: "object", | ||
properties: { | ||
ignoreCase: { | ||
type: "boolean", | ||
default: false, | ||
}, | ||
allowPattern: { | ||
type: "string", | ||
default: "", | ||
}, | ||
}, | ||
additionalProperties: false, | ||
}, | ||
], | ||
|
||
messages: { | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
invalidFragment: | ||
"Link fragment '{{fragment}}' does not reference a valid heading or anchor.", | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}, | ||
}, | ||
|
||
create(context) { | ||
const options = context.options[0] || {}; | ||
const ignoreCase = options.ignoreCase || false; | ||
const allowPattern = options.allowPattern | ||
? new RegExp(options.allowPattern, "u") | ||
: null; | ||
|
||
const slugger = new GithubSlugger(); | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const fragmentIds = new Set(); | ||
|
||
fragmentIds.add("top"); | ||
|
||
/** | ||
* Generates a heading ID using the shared slugger instance. | ||
* Handles custom IDs and plain text slugging. | ||
* @param {string} headingText The heading text. | ||
* @returns {string} The normalized heading ID. | ||
*/ | ||
function getHeadingId(headingText) { | ||
const customIdMatch = headingText.match(customHeadingIdPattern); | ||
if (customIdMatch) { | ||
return customIdMatch[1]; | ||
} | ||
const plainText = headingText | ||
.replace(markdownInlineFormattingPattern, "") | ||
.trim(); | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return slugger.slug(plainText); | ||
} | ||
|
||
return { | ||
heading(node) { | ||
const headingText = context.sourceCode | ||
.getText(node) | ||
.replace(headingPrefixPattern, "") | ||
.trim(); | ||
const id = getHeadingId(headingText); | ||
fragmentIds.add(ignoreCase ? id.toLowerCase() : id); | ||
}, | ||
|
||
html(node) { | ||
if (node.value) { | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const htmlText = node.value.trim(); | ||
if ( | ||
htmlText.startsWith("<!--") && | ||
htmlText.endsWith("-->") | ||
) { | ||
return; | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you use a stricter check? Maybe we can use a negative lookbehind regex to find invalid comments. Here’s another edge case: <div>
<!-- comment -->
</div> References: |
||
|
||
const idMatches = htmlText.matchAll(htmlIdNamePattern); | ||
for (const match of idMatches) { | ||
const extractedId = match[1]; | ||
fragmentIds.add( | ||
ignoreCase | ||
? extractedId.toLowerCase() | ||
: extractedId, | ||
); | ||
} | ||
} | ||
}, | ||
|
||
link(node) { | ||
const url = node.url; | ||
if (!url || !url.startsWith("#")) { | ||
return; | ||
} | ||
|
||
const fragment = url.slice(1); | ||
if (!fragment) { | ||
return; | ||
} | ||
|
||
if (allowPattern && allowPattern.test(fragment)) { | ||
SwetaTanwar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return; | ||
} | ||
|
||
if (isGitHubLineReference(fragment)) { | ||
return; | ||
} | ||
|
||
const normalizedFragment = ignoreCase | ||
? fragment.toLowerCase() | ||
: fragment; | ||
|
||
if (!fragmentIds.has(normalizedFragment)) { | ||
context.report({ | ||
loc: node.position, | ||
messageId: "invalidFragment", | ||
data: { fragment }, | ||
}); | ||
} | ||
}, | ||
}; | ||
}, | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.