Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

verify-links.ts

190 lines5.1 KB

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