validate-mdx-links 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js ADDED
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file This script validates the internal links in the MDX files.
4
+ * Note that it does not validate external links (e.g. to GitHub).
5
+ *
6
+ * Usage:
7
+ * validate-mdx-links --cwd <path> --files "content/**\/*.mdx" --verbose
8
+ */
9
+ import { parseArgs } from "node:util";
10
+ import { validateMdxLinks, printErrors } from "./index.js";
11
+ const args = parseArgs({
12
+ options: {
13
+ cwd: { type: "string", default: process.cwd() },
14
+ files: { type: "string" },
15
+ verbose: { type: "boolean", default: false },
16
+ help: { type: "boolean", default: false },
17
+ },
18
+ strict: true,
19
+ });
20
+ if (args.values.help) {
21
+ console.log('Usage: validate-mdx-links --cwd <path> --files "content/**/*.mdx" --verbose');
22
+ process.exit(0);
23
+ }
24
+ if (!args.values.files) {
25
+ console.error("No files passed. Please pass the --files option.");
26
+ process.exit(1);
27
+ }
28
+ try {
29
+ const errors = await validateMdxLinks({
30
+ cwd: args.values.cwd,
31
+ files: args.values.files,
32
+ });
33
+ if (errors.length > 0) {
34
+ printErrors(errors);
35
+ process.exit(1);
36
+ }
37
+ console.log("No broken links found!");
38
+ process.exit(0);
39
+ }
40
+ catch (error) {
41
+ console.error(error instanceof Error ? error.message : error);
42
+ process.exit(1);
43
+ }
package/dist/index.js ADDED
@@ -0,0 +1,56 @@
1
+ import { globSync } from "node:fs";
2
+ import { stat } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import { scanURLs, validateFiles, } from "next-validate-link";
5
+ export { printErrors } from "next-validate-link";
6
+ export async function validateMdxLinks({ cwd = process.cwd(), files: filesGlob, verbose = false, }) {
7
+ const originalCwd = process.cwd();
8
+ process.chdir(cwd);
9
+ const files = globSync(filesGlob);
10
+ if (files.length === 0) {
11
+ process.chdir(originalCwd);
12
+ throw new Error("No files found matching the glob pattern");
13
+ }
14
+ else if (verbose) {
15
+ console.log(`Found ${files.length} markdown files to validate.\n`);
16
+ }
17
+ const scanned = await scanURLs();
18
+ console.log("\n" +
19
+ "Scanned routes from the file system:\n" +
20
+ [...scanned.urls.keys(), ...scanned.fallbackUrls.map((x) => x.url)]
21
+ .map((x) => `"${x}"`)
22
+ .join(", ") +
23
+ "\n");
24
+ const validations = await validateFiles(files, { scanned });
25
+ const withoutFalsePositives = await Promise.all(validations.map(async ({ file, detected }) => {
26
+ const filteredDetected = [];
27
+ for (const error of detected) {
28
+ let link = error[0];
29
+ if (link.startsWith("./") || link.startsWith("../")) {
30
+ // If there is a hash #id, we don't parse the file to find the heading,
31
+ // just assume it exists and check if the file exists.
32
+ link = link.split("#")[0] || "";
33
+ // relative links inside of JSX lose the .mdx extension
34
+ if (!link.endsWith(".mdx")) {
35
+ link = `${link}.mdx`;
36
+ }
37
+ const path = resolve(dirname(file), link);
38
+ const stats = await stat(path).catch(() => false);
39
+ if (stats) {
40
+ // file exists, the error is a false positive
41
+ continue;
42
+ }
43
+ }
44
+ filteredDetected.push(error);
45
+ }
46
+ if (filteredDetected.length === 0) {
47
+ return null;
48
+ }
49
+ return {
50
+ file,
51
+ detected: filteredDetected,
52
+ };
53
+ }));
54
+ process.chdir(originalCwd);
55
+ return withoutFalsePositives.filter((validation) => validation !== null);
56
+ }
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "validate-mdx-links",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "type": "module",
6
+ "bin": {
7
+ "validate-mdx-links": "./dist/bin.js"
8
+ },
9
+ "exports": {
10
+ ".": "./dist/index.js"
11
+ },
12
+ "author": {
13
+ "name": "Piotr Monwid-Olechnowicz",
14
+ "email": "hasparus@gmail.com",
15
+ "url": "https://haspar.us"
16
+ },
17
+ "license": "ISC",
18
+ "dependencies": {
19
+ "next-validate-link": "^1.4.1"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^22.10.7",
23
+ "typescript": "^5.7.3"
24
+ },
25
+ "scripts": {
26
+ "build": "tsc"
27
+ }
28
+ }
package/src/bin.ts ADDED
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * @file This script validates the internal links in the MDX files.
5
+ * Note that it does not validate external links (e.g. to GitHub).
6
+ *
7
+ * Usage:
8
+ * validate-mdx-links --cwd <path> --files "content/**\/*.mdx" --verbose
9
+ */
10
+ import { parseArgs } from "node:util";
11
+ import { validateMdxLinks, printErrors } from "./index.js";
12
+
13
+ const args = parseArgs({
14
+ options: {
15
+ cwd: { type: "string", default: process.cwd() },
16
+ files: { type: "string" },
17
+ verbose: { type: "boolean", default: false },
18
+ help: { type: "boolean", default: false },
19
+ },
20
+ strict: true,
21
+ });
22
+
23
+ if (args.values.help) {
24
+ console.log(
25
+ 'Usage: validate-mdx-links --cwd <path> --files "content/**/*.mdx" --verbose'
26
+ );
27
+ process.exit(0);
28
+ }
29
+
30
+ if (!args.values.files) {
31
+ console.error("No files passed. Please pass the --files option.");
32
+ process.exit(1);
33
+ }
34
+
35
+ try {
36
+ const errors = await validateMdxLinks({
37
+ cwd: args.values.cwd,
38
+ files: args.values.files,
39
+ });
40
+
41
+ if (errors.length > 0) {
42
+ printErrors(errors);
43
+ process.exit(1);
44
+ }
45
+
46
+ console.log("No broken links found!");
47
+ process.exit(0);
48
+ } catch (error) {
49
+ console.error(error instanceof Error ? error.message : error);
50
+ process.exit(1);
51
+ }
package/src/index.ts ADDED
@@ -0,0 +1,98 @@
1
+ import { globSync } from "node:fs";
2
+ import { stat } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import {
5
+ scanURLs,
6
+ validateFiles,
7
+ type DetectedError,
8
+ } from "next-validate-link";
9
+
10
+ export { printErrors } from "next-validate-link";
11
+
12
+ export type ValidationResult = {
13
+ file: string;
14
+ detected: DetectedError[];
15
+ };
16
+
17
+ export interface ValidateMdxLinksOptions {
18
+ cwd?: string;
19
+ files: string;
20
+ verbose?: boolean;
21
+ }
22
+
23
+ export async function validateMdxLinks({
24
+ cwd = process.cwd(),
25
+ files: filesGlob,
26
+ verbose = false,
27
+ }: ValidateMdxLinksOptions): Promise<ValidationResult[]> {
28
+ const originalCwd = process.cwd();
29
+ process.chdir(cwd);
30
+
31
+ const files = globSync(filesGlob);
32
+ if (files.length === 0) {
33
+ process.chdir(originalCwd);
34
+ throw new Error("No files found matching the glob pattern");
35
+ } else if (verbose) {
36
+ console.log(`Found ${files.length} markdown files to validate.\n`);
37
+ }
38
+
39
+ const scanned = await scanURLs();
40
+
41
+ console.log(
42
+ "\n" +
43
+ "Scanned routes from the file system:\n" +
44
+ [...scanned.urls.keys(), ...scanned.fallbackUrls.map((x) => x.url)]
45
+ .map((x) => `"${x}"`)
46
+ .join(", ") +
47
+ "\n"
48
+ );
49
+
50
+ const validations = await validateFiles(files, { scanned });
51
+
52
+ const withoutFalsePositives = await Promise.all(
53
+ validations.map(async ({ file, detected }) => {
54
+ const filteredDetected: DetectedError[] = [];
55
+
56
+ for (const error of detected) {
57
+ let link = error[0];
58
+
59
+ if (link.startsWith("./") || link.startsWith("../")) {
60
+ // If there is a hash #id, we don't parse the file to find the heading,
61
+ // just assume it exists and check if the file exists.
62
+ link = link.split("#")[0] || "";
63
+
64
+ // relative links inside of JSX lose the .mdx extension
65
+ if (!link.endsWith(".mdx")) {
66
+ link = `${link}.mdx`;
67
+ }
68
+
69
+ const path = resolve(dirname(file), link);
70
+ const stats = await stat(path).catch(() => false);
71
+
72
+ if (stats) {
73
+ // file exists, the error is a false positive
74
+ continue;
75
+ }
76
+ }
77
+
78
+ filteredDetected.push(error);
79
+ }
80
+
81
+ if (filteredDetected.length === 0) {
82
+ return null;
83
+ }
84
+
85
+ return {
86
+ file,
87
+ detected: filteredDetected,
88
+ };
89
+ })
90
+ );
91
+
92
+ process.chdir(originalCwd);
93
+
94
+ return withoutFalsePositives.filter(
95
+ (validation): validation is NonNullable<typeof validation> =>
96
+ validation !== null
97
+ );
98
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "NodeNext",
5
+ "esModuleInterop": true,
6
+ "forceConsistentCasingInFileNames": true,
7
+ "strict": true,
8
+ "noUncheckedIndexedAccess": true,
9
+ "skipLibCheck": true,
10
+ "lib": ["ESNext"],
11
+ "outDir": "./dist"
12
+ }
13
+ }