1 import { existsSync, readdirSync, readFileSync } from "fs"
2 import path from "path"
3 import type { Transformer } from "unified"
4 import type {
5 BrokenLinkCheckerOptions,
6 UnistNode,
7 UnistNodeWithData,
8 UnistTree,
9 } from "types"
10 import type { VFile } from "vfile"
11 import { parseCrossProjectLink } from "./utils/cross-project-link-utils.js"
12 import { SlugChange } from "types"
13 import getAttribute from "./utils/get-attribute.js"
14 import { estreeToJs } from "docs-utils"
15 import { performActionOnLiteral } from "./utils/perform-action-on-literal.js"
16 import { MD_LINK_REGEX } from "./constants.js"
17
18 function getErrorMessage({
19 link,
20 file,
21 additionalMessage = "",
22 }: {
23 link: string
24 file: VFile
25 additionalMessage?: string
26 }): string {
27 return `Broken link found! ${link} linked in ${file.history[0]}${
28 additionalMessage ? `: ${additionalMessage}` : ""
29 }`
30 }
31
32 function checkLocalLinkExists({
33 link,
34 file,
35 currentPageFilePath,
36 rootBasePath = { default: "app" },
37 slugChanges = [],
38 }: {
39 link: string
40 file: VFile
41 currentPageFilePath: string
42 rootBasePath?: BrokenLinkCheckerOptions["rootBasePath"]
43 slugChanges?: SlugChange[]
44 }) {
45 let fileToCheck = link
46 let basePath = currentPageFilePath
47 if (!fileToCheck.endsWith("page.mdx")) {
48 // if the link doesn't end with page.mdx, add it
49 // find route base path
50 let routeBasePath = rootBasePath.overrides
51 ? Object.entries(rootBasePath.overrides).find(([key]) =>
52 fileToCheck.startsWith(key)
53 )?.[1]
54 : rootBasePath.default
55 if (routeBasePath === undefined) {
56 routeBasePath = rootBasePath.default
57 }
58 fileToCheck = `${routeBasePath}${fileToCheck}/page.mdx`.replace(
59 /\/{2,}/g,
60 "/"
61 )
62 basePath = file.cwd
63 }
64 // remove leading slash if present
65 fileToCheck = fileToCheck.replace(/^\//, "")
66 // get absolute path of the URL
67 const linkedFilePath = path.resolve(basePath, fileToCheck).replace(/#.*$/, "")
68 // check if the file exists (references are the JSON doc-model, page.json)
69 if (
70 existsSync(linkedFilePath) ||
71 existsSync(
72 linkedFilePath.replace(/[\\/]page\.mdx$/, `${path.sep}page.json`)
73 )
74 ) {
75 return
76 }
77
78 // maybe check in slugs
79 if (!slugChanges.length) {
80 throw new Error(
81 getErrorMessage({
82 link,
83 file,
84 })
85 )
86 }
87
88 checkSlugExists({
89 slugChanges,
90 pathToCheck: link,
91 link,
92 file,
93 baseProjectPath: file.cwd,
94 })
95 }
96
97 function checkSlugExists({
98 slugChanges,
99 pathToCheck,
100 link,
101 file,
102 baseProjectPath,
103 }: {
104 slugChanges: SlugChange[]
105 pathToCheck: string
106 baseProjectPath: string
107 link: string
108 file: VFile
109 }) {
110 const slugChange = slugChanges.find(
111 (change) => change.newSlug === pathToCheck
112 )
113
114 if (
115 !slugChange ||
116 !mdxPageExists(path.join(baseProjectPath, slugChange.origSlug))
117 ) {
118 throw new Error(
119 getErrorMessage({
120 link,
121 file,
122 })
123 )
124 }
125 }
126
127 function mdxPageExists(pagePath: string): boolean {
128 if (!existsSync(pagePath)) {
129 // for projects that use a convention other than mdx
130 // check if an mdx file exists with the same name
131 if (existsSync(`${pagePath}.mdx`)) {
132 return true
133 }
134 return false
135 }
136
137 return (
138 existsSync(path.join(pagePath, "page.mdx")) ||
139 existsSync(path.join(pagePath, "page.tsx")) ||
140 // references use the JSON doc-model
141 existsSync(path.join(pagePath, "page.json"))
142 )
143 }
144
145 function componentChecker({
146 node,
147 ...rest
148 }: {
149 node: UnistNodeWithData
150 file: VFile
151 currentPageFilePath: string
152 options: BrokenLinkCheckerOptions
153 }) {
154 if (!node.name) {
155 return
156 }
157
158 let attributeName: string | undefined
159
160 const maybeCheckAttribute = () => {
161 if (!attributeName) {
162 return
163 }
164
165 const attribute = getAttribute(node, attributeName)
166
167 if (!attribute) {
168 return
169 }
170
171 if (typeof attribute.value === "string") {
172 checkLink({
173 link: attribute.value,
174 ...rest,
175 })
176 return
177 }
178
179 if (!attribute.value.data?.estree) {
180 return
181 }
182
183 const itemJsVar = estreeToJs(attribute.value.data.estree)
184
185 if (!itemJsVar || "name" in itemJsVar) {
186 return
187 }
188
189 performActionOnLiteral(itemJsVar, (item) => {
190 checkLink({
191 link: item.original.value as string,
192 ...rest,
193 })
194 })
195 }
196
197 switch (node.name) {
198 case "Prerequisites":
199 case "CardList":
200 attributeName = "items"
201 break
202 case "Card":
203 attributeName = "href"
204 break
205 case "WorkflowDiagram":
206 attributeName = "workflow"
207 break
208 case "TypeList":
209 attributeName = "types"
210 break
211 }
212
213 maybeCheckAttribute()
214 }
215
216 /**
217 * Checks the markdown links within a string, returning whether it had any.
218 */
219 function checkMarkdownLinks({
220 link,
221 ...rest
222 }: {
223 link: string
224 file: VFile
225 currentPageFilePath: string
226 options: BrokenLinkCheckerOptions
227 }): boolean {
228 MD_LINK_REGEX.lastIndex = 0
229
230 if (!MD_LINK_REGEX.test(link)) {
231 return false
232 }
233
234 let linkMatches
235 let tempLink = link
236 MD_LINK_REGEX.lastIndex = 0
237
238 while ((linkMatches = MD_LINK_REGEX.exec(tempLink)) !== null) {
239 if (!linkMatches.groups?.link) {
240 break
241 }
242
243 checkLink({
244 link: linkMatches.groups.link,
245 ...rest,
246 })
247
248 tempLink = tempLink.replace(linkMatches.groups.link, "")
249 // reset regex
250 MD_LINK_REGEX.lastIndex = 0
251 }
252
253 return true
254 }
255
256 function checkLink({
257 link,
258 file,
259 currentPageFilePath,
260 options,
261 }: {
262 link: unknown | undefined
263 file: VFile
264 currentPageFilePath: string
265 options: BrokenLinkCheckerOptions
266 }) {
267 if (!link || typeof link !== "string" || link === "/" || link === "#") {
268 return
269 }
270
271 /**
272 * A string can be prose holding markdown links, such as a `TypeList`
273 * description. Its links must be extracted before the checks below, since a
274 * link ending with an anchor would otherwise make the whole string look like
275 * a path to a local file.
276 */
277 if (checkMarkdownLinks({ link, file, currentPageFilePath, options })) {
278 return
279 }
280
281 // try to remove hash
282 const hashIndex = link.lastIndexOf("#")
283 const likeWithoutHash = hashIndex !== -1 ? link.substring(0, hashIndex) : link
284 if (likeWithoutHash.match(/page\.mdx?$/) || likeWithoutHash.startsWith("/")) {
285 checkLocalLinkExists({
286 link: likeWithoutHash,
287 file,
288 currentPageFilePath,
289 slugChanges: options.generatedSlugs,
290 rootBasePath: options.rootBasePath,
291 })
292 return
293 }
294
295 const parsedLink = parseCrossProjectLink(likeWithoutHash)
296
297 if (!parsedLink) {
298 return
299 } else if (!Object.hasOwn(options.crossProjects, parsedLink.area)) {
300 throw new Error(
301 getErrorMessage({
302 link,
303 file,
304 additionalMessage: `Unknown project area: ${parsedLink.area}`,
305 })
306 )
307 }
308
309 const projectOptions = options.crossProjects[parsedLink.area]
310
311 if (parsedLink.path.length && !parsedLink.path.startsWith("/")) {
312 throw new Error(
313 getErrorMessage({
314 link,
315 file,
316 additionalMessage: `Cross project paths must start with a slash.`,
317 })
318 )
319 }
320
321 if (projectOptions.skipSlugValidation) {
322 // if slug validation is skipped, just check if the file exists
323 return
324 }
325
326 const isReferenceLink =
327 parsedLink.path.startsWith("/references") &&
328 parsedLink.path !== "/references-overview"
329 const baseDir = isReferenceLink
330 ? "references"
331 : projectOptions.contentPath || "app"
332 const pagePath = isReferenceLink
333 ? parsedLink.path.replace(/^\/references/, "")
334 : parsedLink.path
335 // check if the file exists
336 if (mdxPageExists(path.join(projectOptions.projectPath, baseDir, pagePath))) {
337 return
338 }
339
340 // file doesn't exist, check if slugs are enabled and generated
341 if (!projectOptions.generatedSlugs) {
342 throw new Error(
343 getErrorMessage({
344 link,
345 file,
346 })
347 )
348 }
349
350 checkSlugExists({
351 slugChanges: projectOptions.generatedSlugs,
352 pathToCheck: parsedLink.path,
353 link,
354 file,
355 baseProjectPath: projectOptions.projectPath,
356 })
357 }
358
359 function loadSlugs(projectPath: string): SlugChange[] {
360 // file doesn't exist, check if slugs are enabled and generated
361 const generatedSlugsPath = path.join(
362 projectPath,
363 "generated",
364 "slug-changes.mjs"
365 )
366 if (!existsSync(generatedSlugsPath)) {
367 throw new Error(`Cross project ${projectPath} has no generated slugs file.`)
368 }
369
370 const generatedSlugContent = readFileSync(generatedSlugsPath, "utf-8")
371 return JSON.parse(
372 generatedSlugContent.substring(generatedSlugContent.indexOf("["))
373 ) as SlugChange[]
374 }
375
376 const allowedComponentNames = [
377 "Card",
378 "CardList",
379 "Prerequisites",
380 "WorkflowDiagram",
381 "TypeList",
382 ]
383
384 export function brokenLinkCheckerPlugin(
385 options: BrokenLinkCheckerOptions
386 ): Transformer {
387 return async (tree, file) => {
388 const { visit } = await import("unist-util-visit")
389
390 // load slug changes for the current project
391 if (options.hasGeneratedSlugs) {
392 options.generatedSlugs = loadSlugs(file.cwd)
393 }
394
395 // load slug changes for cross projects
396 if (options.crossProjects) {
397 for (const project of Object.values(options.crossProjects)) {
398 if (!project.hasGeneratedSlugs) {
399 continue
400 }
401
402 project.generatedSlugs = loadSlugs(project.projectPath)
403 }
404 }
405
406 const currentPageFilePath = path.dirname(file.history[0])
407
408 visit(
409 tree as UnistTree,
410 ["element", "mdxJsxFlowElement"],
411 (node: UnistNode) => {
412 if (node.tagName === "a" && node.properties?.href) {
413 checkLink({
414 link: node.properties.href,
415 file,
416 currentPageFilePath,
417 options,
418 })
419 } else if (node.name && allowedComponentNames.includes(node.name)) {
420 componentChecker({
421 node: node as UnistNodeWithData,
422 file,
423 currentPageFilePath,
424 options,
425 })
426 }
427 }
428 )
429 }
430 }