1/**
 2 * Rehype plugin to enhance links with security attributes.
 3 *
 4 * Adds target="_blank" and rel="noopener noreferrer" to all anchor elements,
 5 * ensuring external links open in new tabs safely.
 6 */
 7
 8import type { Plugin } from 'unified';
 9import type { Root, Element } from 'hast';
10import { visit } from 'unist-util-visit';
11
12/**
13 * Rehype plugin that adds security attributes to all links.
14 * This plugin ensures external links open in new tabs safely by adding:
15 * - target="_blank"
16 * - rel="noopener noreferrer"
17 */
18export const rehypeEnhanceLinks: Plugin<[], Root> = () => {
19	return (tree: Root) => {
20		visit(tree, 'element', (node: Element) => {
21			if (node.tagName !== 'a') return;
22
23			const props = node.properties ?? {};
24
25			// Only modify if href exists
26			if (!props.href) return;
27
28			props.target = '_blank';
29			props.rel = 'noopener noreferrer';
30			node.properties = props;
31		});
32	};
33};