Open History to see the last commit
1import { existsSync, readFileSync, statSync } from 'node:fs'
2import { extname, relative, resolve, sep } from 'node:path'
3import { glob } from 'tinyglobby'
4// @ts-ignore Could not find a declaration file for module 'markdown-link-extractor'.
5import markdownLinkExtractor from 'markdown-link-extractor'
6β
7const errors: Array<{
8 file: string
9 link: string
10 resolvedPath: string
11 reason: string
12 nav?: string
13}> = []
14β
15function isRelativeLink(link: string) {
16 return (
17 !link.startsWith('/') &&
18 !link.startsWith('http://') &&
19 !link.startsWith('https://') &&
20 !link.startsWith('//') &&
21 !link.startsWith('#') &&
22 !link.startsWith('mailto:')
23 )
24}
25β
26/** Remove any trailing .md */
27function stripExtension(p: string): string {
28 return p.replace(`${extname(p)}`, '')
29}
30β
31/**
32 * Map a resolved `/docs` path to the file or directory that actually serves it,
33 * and report whether that target exists.
34 */
35function resolveDocTarget(absPath: string): { path: string; exists: boolean } {
36 // Examples live outside /docs: /docs/framework/{framework}/examples/{name}
37 // is served from /examples/{framework}/{name}
38 const [root, framework, section, ...rest] = relative(
39 resolve('docs'),
40 absPath,
41 ).split(sep)
42β
43 if (root === 'framework' && framework && section === 'examples') {
44 const examplePath = resolve('examples', framework, ...rest)
45 return {
46 path: examplePath,
47 exists: existsSync(examplePath) && statSync(examplePath).isDirectory(),
48 }
49 }
50β
51 // Everything else is a markdown page
52 const mdPath = absPath.endsWith('.md') ? absPath : `${absPath}.md`
53 return { path: mdPath, exists: existsSync(mdPath) }
54}
55β
56function relativeLinkExists(link: string, file: string): boolean {
57 // Remove hash if present
58 const linkWithoutHash = link.split('#')[0]
59 // If the link is empty after removing hash, it's not a file
60 if (!linkWithoutHash) return false
61β
62 // Strip the file/link extensions
63 const filePath = stripExtension(file)
64 const linkPath = stripExtension(linkWithoutHash)
65β
66 // Resolve the path relative to the markdown file's directory
67 // Nav up a level to simulate how links are resolved on the web
68 const absPath = resolve(filePath, '..', linkPath)
69β
70 // Ensure the resolved path is within /docs
71 const docsRoot = resolve('docs')
72 if (!absPath.startsWith(docsRoot)) {
73 errors.push({
74 link,
75 file,
76 resolvedPath: absPath,
77 reason: 'Path outside /docs',
78 })
79 return false
80 }
81β
82 const { path: resolvedPath, exists } = resolveDocTarget(absPath)
83β
84 if (!exists) {
85 errors.push({
86 link,
87 file,
88 resolvedPath,
89 reason: 'Not found',
90 })
91 }
92 return exists
93}
94β
95async function verifyMarkdownLinks() {
96 // Find all markdown files in docs directory
97 const markdownFiles = await glob('docs/**/*.md', {
98 ignore: ['**/node_modules/**'],
99 })
100β
101 console.log(`Found ${markdownFiles.length} markdown files\n`)
102β
103 // Process each file
104 for (const file of markdownFiles) {
105 const content = readFileSync(file, 'utf-8')
106 const links: Array<string> = markdownLinkExtractor(content)
107β
108 const relativeLinks = links.filter((link: string) => {
109 return isRelativeLink(link)
110 })
111β
112 if (relativeLinks.length > 0) {
113 relativeLinks.forEach((link) => {
114 relativeLinkExists(link, file)
115 })
116 }
117 }
118}
119β
120interface ConfigNode {
121 label?: string
122 to?: string
123 children?: Array<ConfigNode>
124 frameworks?: Array<ConfigNode>
125}
126β
127/**
128 * Every `to` in docs/config.json becomes a sidebar link on tanstack.com, so an
129 * entry pointing at a page that no longer exists renders as a 404. These are
130 * invisible to the markdown scan above, which only reads links written inside
131 * .md files.
132 */
133function verifyConfigLinks() {
134 const configPath = 'docs/config.json'
135 const config = JSON.parse(readFileSync(configPath, 'utf-8')) as {
136 sections?: Array<ConfigNode>
137 }
138β
139 const docsRoot = resolve('docs')
140 let checked = 0
141β
142 function walk(node: ConfigNode, breadcrumb: Array<string>) {
143 const trail = node.label ? [...breadcrumb, node.label] : breadcrumb
144β
145 if (node.to) {
146 checked++
147 const { path: resolvedPath, exists } = resolveDocTarget(
148 resolve(docsRoot, node.to),
149 )
150β
151 if (!exists) {
152 errors.push({
153 file: configPath,
154 link: node.to,
155 resolvedPath,
156 reason: 'Not found',
157 nav: trail.join(' > '),
158 })
159 }
160 }
161β
162 node.children?.forEach((child) => walk(child, trail))
163 node.frameworks?.forEach((framework) => walk(framework, trail))
164 }
165β
166 const sections = config.sections ?? []
167 sections.forEach((section) => walk(section, []))
168β
169 console.log(`Found ${checked} nav entries in ${configPath}\n`)
170}
171β
172async function verifyLinks() {
173 await verifyMarkdownLinks()
174 verifyConfigLinks()
175β
176 if (errors.length > 0) {
177 console.log(`\nβ Found ${errors.length} broken links:`)
178 errors.forEach((err) => {
179 console.log(
180 `${err.file}${err.nav ? `\n nav: ${err.nav}` : ''}\n link: ${err.link}\n resolved: ${err.resolvedPath}\n why: ${err.reason}\n`,
181 )
182 })
183 process.exit(1)
184 } else {
185 console.log('\nβ
No broken links found!')
186 }
187}
188β
189verifyLinks().catch((error) => {
190 console.error(error)
191 process.exitCode = 1
192})