Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export default defineConfig([
| [`no-missing-label-refs`](./docs/rules/no-missing-label-refs.md) | Disallow missing label references | yes |
| [`no-missing-link-fragments`](./docs/rules/no-missing-link-fragments.md) | Disallow link fragments that do not reference valid headings | yes |
| [`no-multiple-h1`](./docs/rules/no-multiple-h1.md) | Disallow multiple H1 headings in the same document | yes |
| [`no-reference-like-urls`](./docs/rules/no-reference-like-urls.md) | Disallow URLs that match defined reference identifiers | yes |
| [`no-reversed-media-syntax`](./docs/rules/no-reversed-media-syntax.md) | Disallow reversed link and image syntax | yes |
| [`require-alt-text`](./docs/rules/require-alt-text.md) | Require alternative text for images | yes |
| [`table-column-count`](./docs/rules/table-column-count.md) | Disallow data rows in a GitHub Flavored Markdown table from having more cells than the header row | yes |
Expand Down
52 changes: 52 additions & 0 deletions docs/rules/no-reference-like-urls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# no-reference-like-urls

Disallow URLs that match defined reference identifiers.

## Background

In Markdown, you can create links using either inline syntax `[text](url)` or reference syntax `[text][id]` with a separate definition `[id]: url`. This rule encourages the use of reference syntax when a link's URL matches an existing reference identifier.

For example, if you have a definition like `[mercury]: https://example.com/mercury/`, then using `[text](mercury)` should be written as `[text][mercury]` instead.

Please note that autofix is not performed for links or images that include a title. For example:

```markdown
[Mercury](mercury "The planet Mercury")
![Venus](venus "The planet Venus")
```

## Rule Details

This rule flags URLs that match defined reference identifiers.

Examples of **incorrect** code for this rule:

```markdown
<!-- eslint markdown/no-reference-like-urls: "error" -->

[**Mercury**](mercury) is the first planet from the sun.
![**Venus** is a planet](venus).

[mercury]: https://example.com/mercury/
[venus]: https://example.com/venus.jpg
```

Examples of **correct** code for this rule:

```markdown
<!-- eslint markdown/no-reference-like-urls: "error" -->

[**Mercury**][mercury] is the first planet from the sun.
![**Venus** is a planet][venus].

[mercury]: https://example.com/mercury/
[venus]: https://example.com/venus.jpg
```

## When Not to Use It

If you prefer inline link syntax even when reference definitions are available, or if you're working in an environment where reference syntax is not preferred, you can safely disable this rule.

## Prior Art

* [remark-lint-no-reference-like-url](https://github.com/remarkjs/remark-lint/tree/main/packages/remark-lint-no-reference-like-url)
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@
"mdast-util-frontmatter": "^2.0.1",
"mdast-util-gfm": "^3.0.0",
"micromark-extension-frontmatter": "^2.0.0",
"micromark-extension-gfm": "^3.0.0"
"micromark-extension-gfm": "^3.0.0",
"micromark-util-normalize-identifier": "^2.0.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
Expand Down
216 changes: 216 additions & 0 deletions src/rules/no-reference-like-urls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
/**
* @fileoverview Rule to enforce reference-style links when URL matches a defined identifier.
* @author TKDev7
*/

//-----------------------------------------------------------------------------
// Imports
//-----------------------------------------------------------------------------

import { normalizeIdentifier } from "micromark-util-normalize-identifier";
import { findOffsets } from "../util.js";

//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------

/**
* @import { Heading, Node, Paragraph, TableCell } from "mdast";
* @import { MarkdownRuleDefinition } from "../types.js";
* @typedef {"referenceLikeUrl"} NoReferenceLikeUrlMessageIds
* @typedef {[]} NoReferenceLikeUrlOptions
* @typedef {MarkdownRuleDefinition<{ RuleOptions: NoReferenceLikeUrlOptions, MessageIds: NoReferenceLikeUrlMessageIds }>} NoReferenceLikeUrlRuleDefinition
*/

//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------

/** Pattern to match both inline links: `[text](url)` and images: `![alt](url)`, with optional title */
const linkOrImagePattern =
/(?<!(?<!\\)\\)(?<imageBang>!)?\[(?<label>(?:\\.|[^()\\]|\([\s\S]*\))*?)\]\((?<destination>(?:<[^>]*>)|(?:[^ \t)]+))(?:[ \t]+(?<title>"[^"]*"|'[^']*'|\([^)]*\)))?\)(?!\()/gu;

/**
* Checks if a given index is within any skip range.
* @param {number} index The index to check
* @param {Array<{startOffset: number, endOffset: number}>} skipRanges The skip ranges
* @returns {boolean} True if index is in a skip range
*/
function isInSkipRange(index, skipRanges) {
return skipRanges.some(
range => range.startOffset <= index && index < range.endOffset,
);
}

/**
* Finds ranges of inline code and HTML nodes within a given node
* @param {Heading | Paragraph | TableCell} node The node to search
* @returns {Array<{startOffset: number, endOffset: number}>} Array of skip ranges
*/
function findSkipRanges(node) {
/** @type {Array<{startOffset: number, endOffset: number}>} */
const skipRanges = [];

/**
* Recursively traverses the AST to find inline code and HTML nodes.
* @param {Node} currentNode The current node being traversed
* @returns {void}
*/
function traverse(currentNode) {
if (currentNode.type === "inlineCode" || currentNode.type === "html") {
skipRanges.push({
startOffset: currentNode.position.start.offset,
endOffset: currentNode.position.end.offset,
});
return;
}

if ("children" in currentNode && Array.isArray(currentNode.children)) {
currentNode.children.forEach(traverse);
}
}

traverse(node);
return skipRanges;
}

//-----------------------------------------------------------------------------
// Rule Definition
//-----------------------------------------------------------------------------

/** @type {NoReferenceLikeUrlRuleDefinition} */
export default {
meta: {
type: "problem",

docs: {
recommended: true,
description:
"Disallow URLs that match defined reference identifiers",
url: "https://github.com/eslint/markdown/blob/main/docs/rules/no-reference-like-urls.md",
},

fixable: "code",

messages: {
referenceLikeUrl:
"Unexpected resource {{type}} ('{{prefix}}[text](url)') with URL that matches a definition identifier. Use '[text][id]' syntax instead.",
},
},

create(context) {
const { sourceCode } = context;
/** @type {Set<string>} */
const definitionIdentifiers = new Set();
/** @type {Array<Heading | Paragraph | TableCell>} */
const relevantNodes = [];

return {
definition(node) {
definitionIdentifiers.add(node.identifier);
},

heading(node) {
relevantNodes.push(node);
},

paragraph(node) {
relevantNodes.push(node);
},

tableCell(node) {
relevantNodes.push(node);
},

"root:exit"() {
for (const node of relevantNodes) {
const text = sourceCode.getText(node);
const skipRanges = findSkipRanges(node);

let match;
while ((match = linkOrImagePattern.exec(text)) !== null) {
const {
imageBang,
label,
destination,
title: titleRaw,
} = match.groups;
const title = titleRaw?.slice(1, -1);
const matchIndex = match.index;
const matchLength = match[0].length;

if (
isInSkipRange(
matchIndex + node.position.start.offset,
skipRanges,
)
) {
continue;
}

const isImage = !!imageBang;
const type = isImage ? "image" : "link";
const prefix = isImage ? "!" : "";
const url =
normalizeIdentifier(destination).toLowerCase();

if (definitionIdentifiers.has(url)) {
const {
lineOffset: startLineOffset,
columnOffset: startColumnOffset,
} = findOffsets(text, matchIndex);
const {
lineOffset: endLineOffset,
columnOffset: endColumnOffset,
} = findOffsets(text, matchIndex + matchLength);

const baseColumn = 1;
const nodeStartLine = node.position.start.line;
const nodeStartColumn = node.position.start.column;
const startLine = nodeStartLine + startLineOffset;
const endLine = nodeStartLine + endLineOffset;
const startColumn =
(startLine === nodeStartLine
? nodeStartColumn
: baseColumn) + startColumnOffset;
const endColumn =
(endLine === nodeStartLine
? nodeStartColumn
: baseColumn) + endColumnOffset;

context.report({
loc: {
start: {
line: startLine,
column: startColumn,
},
end: { line: endLine, column: endColumn },
},
messageId: "referenceLikeUrl",
data: {
type,
prefix,
},
fix(fixer) {
// The AST treats both missing and empty titles as null, so it's safe to auto-fix in both cases.
if (title) {
return null;
}

const startOffset =
node.position.start.offset + matchIndex;
const endOffset = startOffset + matchLength;

return fixer.replaceTextRange(
[startOffset, endOffset],
`${prefix}[${label}][${destination}]`,
);
},
});
}
}
}
},
};
},
};
Loading
Loading