Spaces:
Paused
Paused
File size: 6,378 Bytes
c1243f9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | #!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
const ROOT = process.cwd();
const DOCS_DIR = path.join(ROOT, "docs");
const DOCS_JSON_PATH = path.join(DOCS_DIR, "docs.json");
if (!fs.existsSync(DOCS_DIR) || !fs.statSync(DOCS_DIR).isDirectory()) {
console.error("docs:check-links: missing docs directory; run from repo root.");
process.exit(1);
}
if (!fs.existsSync(DOCS_JSON_PATH)) {
console.error("docs:check-links: missing docs/docs.json.");
process.exit(1);
}
/** @param {string} dir */
function walk(dir) {
/** @type {string[]} */
const out = [];
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith(".")) {
continue;
}
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
out.push(...walk(full));
} else if (entry.isFile()) {
out.push(full);
}
}
return out;
}
/** @param {string} p */
function normalizeSlashes(p) {
return p.replace(/\\/g, "/");
}
/** @param {string} p */
function normalizeRoute(p) {
const stripped = p.replace(/^\/+|\/+$/g, "");
return stripped ? `/${stripped}` : "/";
}
/** @param {string} text */
function stripInlineCode(text) {
return text.replace(/`[^`]+`/g, "");
}
const docsConfig = JSON.parse(fs.readFileSync(DOCS_JSON_PATH, "utf8"));
const redirects = new Map();
for (const item of docsConfig.redirects || []) {
const source = normalizeRoute(String(item.source || ""));
const destination = normalizeRoute(String(item.destination || ""));
redirects.set(source, destination);
}
const allFiles = walk(DOCS_DIR);
const relAllFiles = new Set(allFiles.map((abs) => normalizeSlashes(path.relative(DOCS_DIR, abs))));
const markdownFiles = allFiles.filter((abs) => /\.(md|mdx)$/i.test(abs));
const routes = new Set();
for (const abs of markdownFiles) {
const rel = normalizeSlashes(path.relative(DOCS_DIR, abs));
const text = fs.readFileSync(abs, "utf8");
const slug = rel.replace(/\.(md|mdx)$/i, "");
const route = normalizeRoute(slug);
routes.add(route);
if (slug.endsWith("/index")) {
routes.add(normalizeRoute(slug.slice(0, -"/index".length)));
}
if (!text.startsWith("---")) {
continue;
}
const end = text.indexOf("\n---", 3);
if (end === -1) {
continue;
}
const frontMatter = text.slice(3, end);
const match = frontMatter.match(/^permalink:\s*(.+)\s*$/m);
if (!match) {
continue;
}
const permalink = String(match[1])
.trim()
.replace(/^['"]|['"]$/g, "");
routes.add(normalizeRoute(permalink));
}
/** @param {string} route */
function resolveRoute(route) {
let current = normalizeRoute(route);
if (current === "/") {
return { ok: true, terminal: "/" };
}
const seen = new Set([current]);
while (redirects.has(current)) {
current = redirects.get(current);
if (seen.has(current)) {
return { ok: false, terminal: current, loop: true };
}
seen.add(current);
}
return { ok: routes.has(current), terminal: current };
}
const markdownLinkRegex = /!?\[[^\]]*\]\(([^)]+)\)/g;
/** @type {{file: string; line: number; link: string; reason: string}[]} */
const broken = [];
let checked = 0;
for (const abs of markdownFiles) {
const rel = normalizeSlashes(path.relative(DOCS_DIR, abs));
const baseDir = normalizeSlashes(path.dirname(rel));
const rawText = fs.readFileSync(abs, "utf8");
const lines = rawText.split("\n");
// Track if we're inside a code fence
let inCodeFence = false;
for (let lineNum = 0; lineNum < lines.length; lineNum++) {
let line = lines[lineNum];
// Toggle code fence state
if (line.trim().startsWith("```")) {
inCodeFence = !inCodeFence;
continue;
}
if (inCodeFence) {
continue;
}
// Strip inline code to avoid false positives
line = stripInlineCode(line);
for (const match of line.matchAll(markdownLinkRegex)) {
const raw = match[1]?.trim();
if (!raw) {
continue;
}
// Skip external links, mailto, tel, data, and same-page anchors
if (/^(https?:|mailto:|tel:|data:|#)/i.test(raw)) {
continue;
}
const [pathPart] = raw.split("#");
const clean = pathPart.split("?")[0];
if (!clean) {
// Same-page anchor only (already skipped above)
continue;
}
checked++;
if (clean.startsWith("/")) {
const route = normalizeRoute(clean);
const resolvedRoute = resolveRoute(route);
if (!resolvedRoute.ok) {
const staticRel = route.replace(/^\//, "");
if (!relAllFiles.has(staticRel)) {
broken.push({
file: rel,
line: lineNum + 1,
link: raw,
reason: `route/file not found (terminal: ${resolvedRoute.terminal})`,
});
continue;
}
}
// Skip anchor validation - Mintlify generates anchors from MDX components,
// accordions, and config schemas that we can't reliably extract from markdown.
continue;
}
// Relative placeholder strings used in code examples (for example "url")
// are intentionally skipped.
if (!clean.startsWith(".") && !clean.includes("/")) {
continue;
}
const normalizedRel = normalizeSlashes(path.normalize(path.join(baseDir, clean)));
if (/\.[a-zA-Z0-9]+$/.test(normalizedRel)) {
if (!relAllFiles.has(normalizedRel)) {
broken.push({
file: rel,
line: lineNum + 1,
link: raw,
reason: "relative file not found",
});
}
continue;
}
const candidates = [
normalizedRel,
`${normalizedRel}.md`,
`${normalizedRel}.mdx`,
`${normalizedRel}/index.md`,
`${normalizedRel}/index.mdx`,
];
if (!candidates.some((candidate) => relAllFiles.has(candidate))) {
broken.push({
file: rel,
line: lineNum + 1,
link: raw,
reason: "relative doc target not found",
});
}
}
}
}
console.log(`checked_internal_links=${checked}`);
console.log(`broken_links=${broken.length}`);
for (const item of broken) {
console.log(`${item.file}:${item.line} :: ${item.link} :: ${item.reason}`);
}
if (broken.length > 0) {
process.exit(1);
}
|