1 import { createRequire } from "node:module"
2 import path from "node:path"
3 import markdown from "eslint-plugin-markdown"
4
5 const require = createRequire(import.meta.url)
6 const baseProcessor = markdown.processors.markdown
7
8 /**
9 * `eslint-plugin-markdown` parses with its own nested copy of
10 * `mdast-util-from-markdown`; resolving from there keeps this processor on the
11 * exact parser (and version) that produced the blocks it renames.
12 */
13 const fromMarkdown = createRequire(
14 require.resolve("eslint-plugin-markdown/lib/processor.js")
15 )("mdast-util-from-markdown")
16
17 const TITLE_RE = /(?:^|\s)title=(?:"([^"]+)"|'([^']+)')/
18 const DISABLE_RE = /^\{\/\*\s*eslint-disable\s*([^*]*?)\s*\*\/\}$/
19
20 /** Suppressed rules per block, keyed by the MDX file being linted. */
21 const suppressionsByFile = new Map()
22
23 /**
24 * Collects the fenced code blocks `eslint-plugin-markdown` would emit — every
25 * `code` node carrying a language — in the same depth-first order, so index `i`
26 * here is index `i` there. Each is paired with the node that precedes it, which
27 * is where an `{/* eslint-disable *\/}` directive would sit.
28 */
29 function collectCodeNodes(text) {
30 const found = []
31 const visit = (node) => {
32 const children = node.children ?? []
33 children.forEach((child, index) => {
34 if (child.type === "code" && child.lang) {
35 found.push({ node: child, previous: children[index - 1] ?? null })
36 }
37 visit(child)
38 })
39 }
40 visit(fromMarkdown(text))
41 return found
42 }
43
44 /**
45 * The rules an `{/* eslint-disable a, b *\/}` MDX comment directly above a block
46 * turns off, `"all"` when it names none, or `null` when there's no directive.
47 *
48 * MDX has no HTML comments, so `eslint-plugin-markdown`'s own
49 * `<!-- eslint-disable -->` escape hatch is unavailable here — it fails the MDX
50 * compile. Messages are dropped in `postprocess` rather than by injecting an
51 * ESLint comment into the block, which would shift every reported line.
52 */
53 function suppressedRules(previous) {
54 if (!previous || previous.type !== "paragraph") {
55 return null
56 }
57 const [child, ...rest] = previous.children ?? []
58 if (rest.length || child?.type !== "text") {
59 return null
60 }
61 const match = DISABLE_RE.exec(child.value.trim())
62 if (!match) {
63 return null
64 }
65 const named = match[1]
66 .split(",")
67 .map((rule) => rule.trim())
68 .filter(Boolean)
69 return named.length ? new Set(named) : "all"
70 }
71
72 /**
73 * The path a block's `title=` meta names, or `null` when the title isn't a
74 * source path for this block's language (prose titles, `title="Example"`, a
75 * `.json` title on a ```ts fence).
76 */
77 function titlePath(node, blockExtension) {
78 const match = TITLE_RE.exec(node.meta ?? "")
79 const raw = match?.[1] ?? match?.[2]
80 if (!raw) {
81 return null
82 }
83 const normalized = raw.trim().replace(/^\.\//, "")
84 if (
85 !normalized ||
86 normalized.startsWith("/") ||
87 normalized.split("/").includes("..") ||
88 /\s/.test(normalized)
89 ) {
90 return null
91 }
92 if (path.extname(normalized) !== `.${blockExtension}`) {
93 return null
94 }
95 return normalized
96 }
97
98 /**
99 * Wraps `markdown/markdown` with two things the docs need.
100 *
101 * 1. A code block titled with a path is linted under that path instead of under
102 * `<n>.<ext>`. `@medusajs/eslint-plugin` scopes most of its rules by where a
103 * file lives — `src/api/**`, `src/subscribers/*`, `src/admin/widgets/**` —
104 * and under the stock processor every block is `page.mdx/7.ts`, so those
105 * rules can never match. The docs already state the path in the fence meta:
106 *
107 * ```ts title="src/api/custom/route.ts"
108 *
109 * so the block becomes `page.mdx/7/src/api/custom/route.ts`. The leading
110 * index keeps two blocks that share a title distinct, and leaves the
111 * `src/...` segments intact for `**`-anchored patterns to match. Blocks
112 * without a usable title keep their original name and stay out of every
113 * path-scoped rule.
114 *
115 * 2. An `{/* eslint-disable *\/}` MDX comment above a block turns rules off for
116 * it — the escape hatch a page needs when a block is a deliberate
117 * counter-example.
118 *
119 * Renaming is all-or-nothing per file: if the local parse doesn't line up with
120 * the base processor's blocks one-for-one, the base names are used unchanged
121 * and no suppression is applied.
122 */
123 export const titledMarkdownProcessor = {
124 meta: {
125 name: "medusa-docs/titled-markdown",
126 version: baseProcessor.meta?.version,
127 },
128 supportsAutofix: true,
129 preprocess(text, filename) {
130 const blocks = baseProcessor.preprocess(text, filename)
131 const found = collectCodeNodes(text)
132
133 suppressionsByFile.delete(filename)
134
135 if (found.length !== blocks.length) {
136 return blocks
137 }
138
139 suppressionsByFile.set(
140 filename,
141 found.map(({ previous }) => suppressedRules(previous))
142 )
143
144 return blocks.map((block, index) => {
145 const extension = path.extname(block.filename).slice(1)
146 const titled = titlePath(found[index].node, extension)
147 return titled ? { ...block, filename: `${index}/${titled}` } : block
148 })
149 },
150 postprocess(messages, filename) {
151 const suppressions = suppressionsByFile.get(filename)
152 suppressionsByFile.delete(filename)
153
154 const kept = suppressions
155 ? messages.map((blockMessages, index) => {
156 const suppressed = suppressions[index]
157 if (!suppressed) {
158 return blockMessages
159 }
160 return blockMessages.filter(
161 (message) =>
162 suppressed !== "all" && !suppressed.has(message.ruleId ?? "")
163 )
164 })
165 : messages
166
167 return baseProcessor.postprocess(kept, filename)
168 },
169 }
170
171 export default titledMarkdownProcessor