Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ packages/comark/
│ │ ├── binding.ts # Inline interpolation + shared conditional rendering rules
│ │ ├── breaks.ts # Hard line breaks (`<br>`) from newlines
│ │ ├── emoji.ts # Emoji shortcodes
│ │ ├── external-links.ts # `rel` and `target` on external links
│ │ ├── footnotes.ts # GFM footnotes
│ │ ├── heading-links.ts # Links headings to their own `id`
│ │ ├── headings.ts # Deprecated alias → title-description (remove next major)
Expand Down Expand Up @@ -550,6 +551,7 @@ import breaks from 'comark/plugins/breaks'
import footnotes from 'comark/plugins/footnotes'
import titleDescription from 'comark/plugins/title-description'
// import headings from 'comark/plugins/headings' // deprecated alias → title-description
import externalLinks from 'comark/plugins/external-links'
import headingLinks from 'comark/plugins/heading-links'
import punctuation from 'comark/plugins/punctuation'
import jsonRender from 'comark/plugins/json-render'
Expand Down
95 changes: 95 additions & 0 deletions docs/content/4.plugins/1.built-in/external-links.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
---
title: External Links
description: Plugin for adding rel and target attributes to external links.
seo:
title: External Links Plugin
navigation:
icon: i-lucide-external-link
links:
- label: Parse API
icon: i-lucide-file-code
to: /reference/parse
color: neutral
variant: soft
- label: Document Model
icon: i-lucide-braces
to: /getting-started/document-model
color: neutral
variant: soft
---

The `comark/plugins/external-links` plugin adds `rel="nofollow"` to external links, which tells search engines not to pass ranking to the sites you link to.

It can also add a `target`, such as `_blank`, to open them in a new tab. Both are added to the document tree, so the HTML, Vue, React, Svelte, and Angular renderers output them without a custom link component.

## Usage

```typescript
import { parseMarkdown } from 'comark'
import externalLinks from 'comark/plugins/external-links'

const result = await parseMarkdown('[Nuxt](https://nuxt.com)', {
plugins: [externalLinks()]
})
```

```html [Output]
<p><a href="https://nuxt.com" rel="nofollow">Nuxt</a></p>
```

---

## API

### `externalLinks(options?)`

Returns a `ComarkPlugin` that adds a `rel`, and optionally a `target`, to external links.

**Parameters:**

- `options?` - Optional configuration, see [Options](#options)

**Returns:** `ComarkPlugin`

A link is external when its `href` starts with `http://`, `https://`, or `//`. This covers Markdown links, autolinks, bare URLs, and HTML `<a>` tags. A `rel` or `target` the link already has, written or bound (`:rel`, `:target`), is kept, such as in `[Nuxt](https://nuxt.com){rel="sponsored"}`.

Added values are recorded in the tree as `$.autoRel` and `$.autoTarget`. Renderers don't output `$`, and Markdown output leaves out a `rel` or `target` that still has its added value. A tree parsed with this plugin can be saved back to Markdown unchanged, while the values the author wrote are kept.

---

## Options

| Option | Type | Default | Description |
|---|---|---|---|
| [`rel`](#rel) | `string` | `'nofollow'` | `rel` added to external links |
| [`target`](#target) | `string` | - | `target` added to external links |

### `rel`

`rel` added to external links that don't set one.

```typescript
externalLinks({ rel: 'nofollow noopener' })
```

```html [Output]
<p><a href="https://nuxt.com" rel="nofollow noopener">Nuxt</a></p>
```

**Default:** `'nofollow'`, or `'nofollow noopener noreferrer'` on links that open a new tab

### `target`

`target` added to external links that don't set one. Not set by default, so links open in the same tab.

```typescript
externalLinks({ target: '_blank' })
```

```html [Output]
<p><a href="https://nuxt.com" rel="nofollow noopener noreferrer" target="_blank">Nuxt</a></p>
```

On a link that opens a new tab, from this option or a `target` the author wrote, the default `rel` adds `noopener` and `noreferrer`. The opened page can't reach your page through `window.opener` and doesn't receive it as the referrer. If you set [`rel`](#rel) yourself, include them.

**Default:** none
4 changes: 4 additions & 0 deletions docs/content/4.plugins/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ Optional plugins you register via `plugins: [...]`.
Convert emoji shortcodes like `:smile:` into emoji characters
::

::card{icon="i-lucide-external-link" title="External Links" to="/plugins/built-in/external-links"}
Plugin for adding `rel="nofollow"`, and optionally a `target`, to external links.
::

::card{icon="i-lucide-footprints" title="Footnotes" to="/plugins/built-in/footnotes"}
Plugin for adding footnote references and definitions to your Comark documents.
::
Expand Down
3 changes: 3 additions & 0 deletions packages/comark/src/internal/stringify/handlers/a.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export async function a(node: ElementNode, state: State, parent?: ElementNode) {
if (attrs.$?.permalink === 'wrap') return state.flow(node, state, parent)

const { href, ...rest } = attrs
// A `rel` or `target` added by `external-links` isn't part of the source
if (attrs.$?.autoRel !== undefined && rest.rel === attrs.$.autoRel) delete rest.rel
if (attrs.$?.autoTarget !== undefined && rest.target === attrs.$.autoTarget) delete rest.target
const attrsString = Object.keys(rest).length > 0 ? comarkAttributes(rest) : ''
const content = await state.flow(node, state)

Expand Down
5 changes: 5 additions & 0 deletions packages/comark/src/internal/stringify/handlers/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ const blockTags = new Set([
export async function html(node: ElementNode, state: State, parent?: ElementNode) {
const [tag, attr, ...children] = node
const { $ = {}, ...rawAttributes } = attr
// A `rel` or `target` added by `external-links` isn't part of the source
if (!state.context.html) {
if ($.autoRel !== undefined && rawAttributes.rel === $.autoRel) delete rawAttributes.rel
if ($.autoTarget !== undefined && rawAttributes.target === $.autoTarget) delete rawAttributes.target
}

// In text/html mode, `one()` has already resolved this element's `:prefix`
// bindings against the parent's render context and stored the result in
Expand Down
74 changes: 74 additions & 0 deletions packages/comark/src/plugins/external-links.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import type { ElementNode, ElementNodeAttributes } from 'comark'
import { defineComarkPlugin } from 'comark'
import { visit } from 'comark/utils'

export interface ExternalLinksOptions {
/**
* `rel` added to external links that don't set one.
* @default 'nofollow', or 'nofollow noopener noreferrer' on links that open a new tab
*/
rel?: string
/**
* `target` added to external links that don't set one, such as `'_blank'`.
* @default undefined
*/
target?: string
}

// `http://`, `https://`, and protocol-relative `//` URLs
const EXTERNAL_LINK_RE = /^(?:https?:)?\/\//i
// Targets that navigate an existing browsing context, so `window.opener` isn't set (keywords are case-insensitive)
const SAME_CONTEXT_TARGETS = new Set(['', '_self', '_parent', '_top'])

/**
* Adds a `rel` to external (`http://`, `https://`, and `//`) links that don't set one, `nofollow` by default.
*
* `[Nuxt](https://nuxt.com)` becomes `<a href="https://nuxt.com" rel="nofollow">Nuxt</a>`.
* With `target`, links also get that `target`. On links that open a new tab, the default `rel` adds `noopener noreferrer`.
* A `rel` or `target` the author wrote, such as `{rel="sponsored"}`, is kept. Added values are recorded
* in `$.autoRel` and `$.autoTarget`, so Markdown output leaves them out and the source round-trips unchanged.
*
* @example
* ```ts
* externalLinks()
*
* externalLinks({ target: '_blank' })
* ```
*/
export default defineComarkPlugin<ExternalLinksOptions>((options = {}) => {
const { target, rel } = options

return {
name: 'external-links',
post(state) {
visit(
state.tree,
(node) => Array.isArray(node) && node[0] === 'a',
(node) => {
const [tag, attrs, ...children] = node as ElementNode
if (typeof attrs.href !== 'string' || !EXTERNAL_LINK_RE.test(attrs.href)) return
// A bound `:rel` or `:target` resolves at render time, so the author set it
const addRel = attrs.rel === undefined && attrs[':rel'] === undefined
const addTarget = target !== undefined && attrs.target === undefined && attrs[':target'] === undefined
if (!addRel && !addTarget) return

const $ = { ...attrs.$ }
const next: ElementNodeAttributes = { ...attrs, $ }
if (addRel) {
// A bound `:target` can't be checked at parse time, so it counts as a new tab
const linkTarget = addTarget ? target : (attrs.target ?? attrs[':target'])
const newContext = linkTarget !== undefined && !SAME_CONTEXT_TARGETS.has(String(linkTarget).toLowerCase())
const linkRel = rel ?? (newContext ? 'nofollow noopener noreferrer' : 'nofollow')
next.rel = linkRel
$.autoRel = linkRel
}
if (addTarget) {
next.target = target
$.autoTarget = target
}
return [tag, next, ...children]
}
)
},
}
})
4 changes: 4 additions & 0 deletions packages/comark/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export type ElementNodeAttributes = {
* before or after it. Markdown output leaves both out.
*/
permalink?: 'wrap' | 'separate'
/** The `rel` `external-links` added to a link. Markdown output leaves `rel` out while it still has this value. */
autoRel?: string
/** The `target` `external-links` added to a link. Markdown output leaves `target` out while it still has this value. */
autoTarget?: string
}
}

Expand Down
75 changes: 75 additions & 0 deletions packages/comark/test/plugins/external-links.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest'
import { parseMarkdown } from '../../src/index'
import externalLinks from '../../src/plugins/external-links'
import { renderMarkdown } from '../../src/render'
import { renderHtmlForTest } from '../utils/render-html'

const LINKS = `[External](https://nuxt.com) [Insecure](http://nuxt.com) [Internal](/about) [Hash](#top) <https://auto.dev> [Relative](//relative.dev)

[Sponsored](https://sponsor.dev){rel="sponsored"} [Nofollow](https://nofollow.dev){rel="nofollow"} [Blank](https://blank.dev){target="_blank"} [Upper](https://upper.dev){target="_SELF"} [Empty](https://empty.dev){target=""}

Raw <a href="https://html.dev">HTML</a> link`

describe('external-links plugin', () => {
it('adds `rel="nofollow"` to external links without a `rel`, plus `noopener noreferrer` on links that open a new tab', async () => {
const tree = await parseMarkdown(LINKS, { plugins: [externalLinks()] })

expect(await renderHtmlForTest(tree)).toBe(
[
'<p><a href="https://nuxt.com" rel="nofollow">External</a> <a href="http://nuxt.com" rel="nofollow">Insecure</a> <a href="/about">Internal</a> <a href="#top">Hash</a> <a href="https://auto.dev" rel="nofollow">https://auto.dev</a> <a href="//relative.dev" rel="nofollow">Relative</a></p>',
'<p><a href="https://sponsor.dev" rel="sponsored">Sponsored</a> <a href="https://nofollow.dev" rel="nofollow">Nofollow</a> <a href="https://blank.dev" target="_blank" rel="nofollow noopener noreferrer">Blank</a> <a href="https://upper.dev" target="_SELF" rel="nofollow">Upper</a> <a href="https://empty.dev" target="" rel="nofollow">Empty</a></p>',
'<p>Raw <a href="https://html.dev" rel="nofollow">HTML</a> link</p>',
].join('\n')
)
})

it('adds a custom `rel`', async () => {
const tree = await parseMarkdown('[Nuxt](https://nuxt.com)', {
plugins: [externalLinks({ rel: 'nofollow noopener' })],
})

expect(tree.nodes[0]).toEqual([
'p',
{},
['a', { href: 'https://nuxt.com', rel: 'nofollow noopener', $: { autoRel: 'nofollow noopener' } }, 'Nuxt'],
])
})

it('leaves the added `rel` out of Markdown output, so round-trips stay stable', async () => {
const plugins = [externalLinks()]
const once = await renderMarkdown(await parseMarkdown(LINKS, { plugins }))

expect(once).toBe(LINKS)
expect(await renderMarkdown(await parseMarkdown(once, { plugins }))).toBe(LINKS)
})

it('adds a `target` with `noopener noreferrer`, and keeps the `rel` and `target` the author wrote', async () => {
const source = `[Nuxt](https://nuxt.com) [Internal](/about) [Sponsored](https://sponsor.dev){rel="sponsored"} [Self](https://self.dev){target="_self"}

Raw <a href="https://html.dev">HTML</a> link`
const plugins = [externalLinks({ target: '_blank' })]
const tree = await parseMarkdown(source, { plugins })

expect(await renderHtmlForTest(tree)).toBe(
[
'<p><a href="https://nuxt.com" rel="nofollow noopener noreferrer" target="_blank">Nuxt</a> <a href="/about">Internal</a> <a href="https://sponsor.dev" rel="sponsored" target="_blank">Sponsored</a> <a href="https://self.dev" target="_self" rel="nofollow">Self</a></p>',
'<p>Raw <a href="https://html.dev" rel="nofollow noopener noreferrer" target="_blank">HTML</a> link</p>',
].join('\n')
)
expect(await renderMarkdown(tree)).toBe(source)
})

it('keeps a bound `:rel`', async () => {
const source = '---\nlinkRel: sponsored\n---\n\n[Nuxt](https://nuxt.com){:rel="frontmatter.linkRel"}'
const tree = await parseMarkdown(source, { plugins: [externalLinks()] })

expect(await renderHtmlForTest(tree)).toBe('<p><a href="https://nuxt.com" rel="sponsored">Nuxt</a></p>')
})

it('writes a `rel` changed after parsing', async () => {
const tree = await parseMarkdown('[Nuxt](https://nuxt.com)', { plugins: [externalLinks()] })
;(tree.nodes[0] as any[])[2][1].rel = 'sponsored'

expect(await renderMarkdown(tree)).toBe('[Nuxt](https://nuxt.com){rel="sponsored"}')
})
})
16 changes: 8 additions & 8 deletions test/bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,14 @@ describe('package bundle size', { timeout: 60_000 }, () => {

expect(report).toMatchInlineSnapshot(`
{
"@comark/angular": "69.6k (59 files)",
"@comark/ansi": "41.7k (105 files)",
"@comark/html": "17.3k (65 files)",
"@comark/nuxt": "10.6k (65 files)",
"@comark/react": "42.9k (83 files)",
"@comark/svelte": "50.3k (91 files)",
"@comark/vue": "62.6k (89 files)",
"comark": "440k (171 files)",
"@comark/angular": "70.0k (61 files)",
"@comark/ansi": "41.9k (107 files)",
"@comark/html": "17.5k (67 files)",
"@comark/nuxt": "10.8k (67 files)",
"@comark/react": "43.1k (85 files)",
"@comark/svelte": "50.5k (93 files)",
"@comark/vue": "62.8k (91 files)",
"comark": "444k (173 files)",
}
`)
})
Expand Down
Loading