@mintlify/cli 4.0.1739 → 4.0.1740

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.
@@ -1,4 +1,5 @@
1
1
  import { checkFiles } from './files.js';
2
+ import { buildFindings } from './rules/build.js';
2
3
  import { RULES } from './rules/index.js';
3
4
  import { PARSE_ERROR } from './rules/parseError.js';
4
5
  import { loadSite } from './site.js';
@@ -63,6 +64,29 @@ const sortDiagnostics = (diagnostics: Diagnostic[]) =>
63
64
  (RULE_ORDER.get(a.rule) ?? 0) - (RULE_ORDER.get(b.rule) ?? 0)
64
65
  );
65
66
 
67
+ /** Adds findings for a rule unless a diagnostic of that rule already has the same key. */
68
+ const merge = (
69
+ diagnostics: Diagnostic[],
70
+ source: DiagnosticSource,
71
+ extra: Finding[],
72
+ key: (item: Pick<Diagnostic, 'file' | 'message'>) => string
73
+ ) => {
74
+ const reported = new Set(diagnostics.filter((item) => item.rule === source.id).map(key));
75
+ for (const finding of extra) {
76
+ if (reported.has(key(finding))) continue;
77
+ reported.add(key(finding));
78
+ diagnostics.push(toDiagnostic(source, finding));
79
+ }
80
+ };
81
+
82
+ const addParseErrors = (site: Site, diagnostics: Diagnostic[], extra: Finding[]) =>
83
+ merge(
84
+ diagnostics,
85
+ PARSE_ERROR,
86
+ extra.filter(({ file }) => !site.selected || site.selected.has(file)),
87
+ ({ file }) => file
88
+ );
89
+
66
90
  /** Runs every selected rule that doesn't need the build. */
67
91
  export const runChecks = async (site: Site, rules: Rule[]) => {
68
92
  const fileRules = rules.filter((rule): rule is FileRule => rule.scope === 'file');
@@ -75,6 +99,17 @@ export const runChecks = async (site: Site, rules: Rule[]) => {
75
99
  return sortDiagnostics(diagnostics);
76
100
  };
77
101
 
102
+ /** Adds the build's findings to a site whose build has run. */
103
+ export const runBuildChecks = async (site: Site, rules: Rule[], diagnostics: Diagnostic[]) => {
104
+ for (const rule of rules) {
105
+ if (rule.scope !== 'site' || !rule.needsBuild) continue;
106
+ for (const finding of await rule.check(site)) diagnostics.push(toDiagnostic(rule, finding));
107
+ }
108
+ // The file pass already reported files it couldn't parse; the build adds the rest
109
+ addParseErrors(site, diagnostics, buildFindings(site, 'parse-error'));
110
+ return sortDiagnostics(diagnostics);
111
+ };
112
+
78
113
  /** Loads the site and runs the selected rules. */
79
114
  export const checkSite = async (
80
115
  baseDir: string,
@@ -1,6 +1,7 @@
1
- import { addLog, ErrorLog } from '@mintlify/previewing';
1
+ import { addLog, ErrorLog, InfoLog, SuccessLog } from '@mintlify/previewing';
2
2
  import { Box, Text } from 'ink';
3
3
 
4
+ import type { Report } from './report.js';
4
5
  import type { Diagnostic } from './types.js';
5
6
 
6
7
  const location = ({ line, column }: Pick<Diagnostic, 'line' | 'column'>) =>
@@ -25,9 +26,9 @@ const DiagnosticLine = ({ diagnostic }: { diagnostic: Diagnostic }) => {
25
26
 
26
27
  const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`;
27
28
 
28
- export const logDiagnostics = (all: Diagnostic[]) => {
29
+ export const logReport = (report: Report) => {
29
30
  const byFile = new Map<string, Diagnostic[]>();
30
- for (const diagnostic of all) {
31
+ for (const diagnostic of report.diagnostics) {
31
32
  byFile.get(diagnostic.file)?.push(diagnostic) ?? byFile.set(diagnostic.file, [diagnostic]);
32
33
  }
33
34
  for (const [file, diagnostics] of byFile) {
@@ -41,16 +42,17 @@ export const logDiagnostics = (all: Diagnostic[]) => {
41
42
  );
42
43
  }
43
44
 
44
- const errors = all.filter(({ severity }) => severity === 'error').length;
45
- const warnings = all.length - errors;
46
- if (errors > 0) {
47
- addLog(
48
- <ErrorLog
49
- message={`${plural(errors, 'error')}${warnings > 0 ? `, ${plural(warnings, 'warning')}` : ''}`}
50
- />
51
- );
52
- } else if (warnings > 0) {
53
- addLog(<Text dimColor>{plural(warnings, 'warning')}</Text>);
54
- }
55
- return errors > 0;
45
+ const { build } = report;
46
+ if (build.ran && build.passed) addLog(<SuccessLog message="build passed" />);
47
+ else if (build.ran && report.passed)
48
+ addLog(<InfoLog message="build failed only on disabled rules" />);
49
+ else if (build.ran) addLog(<ErrorLog message="build failed" />);
50
+ else if (build.reason === 'errors found')
51
+ addLog(<InfoLog message="build skipped until the errors above are fixed" />);
52
+
53
+ const { errors, warnings } = report.summary;
54
+ const warned = plural(warnings, 'warning');
55
+ const passed = warnings > 0 ? `passed with ${warned}` : 'validation passed';
56
+ const failed = `${plural(errors, 'error')}${warnings > 0 ? `, ${warned}` : ''}`;
57
+ addLog(report.passed ? <SuccessLog message={passed} /> : <ErrorLog message={failed} />);
56
58
  };
@@ -0,0 +1,33 @@
1
+ import type { Diagnostic } from './types.js';
2
+
3
+ export type BuildStatus =
4
+ | { ran: true; passed: boolean }
5
+ | { ran: false; reason: 'disabled' | 'errors found' | 'no build rules' };
6
+
7
+ export type Report = {
8
+ passed: boolean;
9
+ summary: { errors: number; warnings: number; byRule: Record<string, number> };
10
+ diagnostics: Diagnostic[];
11
+ build: BuildStatus;
12
+ };
13
+
14
+ export const toReport = (diagnostics: Diagnostic[], build: BuildStatus): Report => {
15
+ const byRule: Record<string, number> = {};
16
+ for (const { rule } of diagnostics) byRule[rule] = (byRule[rule] ?? 0) + 1;
17
+ const errors = diagnostics.filter(({ severity }) => severity === 'error').length;
18
+ return {
19
+ passed: errors === 0,
20
+ summary: { errors, warnings: diagnostics.length - errors, byRule },
21
+ diagnostics: diagnostics.map(({ rule, group, severity, file, line, column, message, fix }) => ({
22
+ rule,
23
+ group,
24
+ severity,
25
+ file,
26
+ ...(line !== undefined && { line }),
27
+ ...(column !== undefined && { column }),
28
+ message,
29
+ ...(fix && { fix }),
30
+ })),
31
+ build,
32
+ };
33
+ };
@@ -0,0 +1,132 @@
1
+ import { normalizeRelativePath, toPosixPath } from '@mintlify/common';
2
+ import type { Warning } from '@mintlify/prebuild';
3
+ import { stripVTControlCharacters } from 'node:util';
4
+
5
+ import type { Finding, Group, Site, SiteRule } from '../types.js';
6
+
7
+ const FILE = String.raw`[\w@.\\/-]+\.(?:mdx?|jsx?|tsx?|json|ya?ml)\b`;
8
+
9
+ const FILE_IN_MESSAGE = new RegExp(FILE);
10
+
11
+ const IMPORTERS = [
12
+ new RegExp(String.raw`\(in (${FILE}),`),
13
+ new RegExp(String.raw`(?:\bin|imported from) (${FILE})`),
14
+ ];
15
+
16
+ const IMPORT_TYPES = new Set<Warning['type']>([
17
+ 'missing-file',
18
+ 'invalid-import-path',
19
+ 'import-resolution-error',
20
+ 'default-import-no-default-export',
21
+ 'export-collision',
22
+ 'undeclared-package',
23
+ 'package-import-conflict',
24
+ ]);
25
+
26
+ const POSITION = /^:(\d+)(?::(\d+))?/;
27
+
28
+ const QUOTED = /"([^"]+)"/;
29
+
30
+ const toFinding = (site: Site, { type, message }: Warning): Finding => {
31
+ const clean = stripVTControlCharacters(message).trim();
32
+ const importer = IMPORT_TYPES.has(type)
33
+ ? IMPORTERS.map((pattern) => pattern.exec(clean)?.[1]).find(Boolean)
34
+ : undefined;
35
+ // Missing nav pages are always about the config, even when the page looks like a file
36
+ const match = importer || type === 'missing-nav-page' ? null : FILE_IN_MESSAGE.exec(clean);
37
+ const found = importer ?? match?.[0];
38
+ const file = found ? normalizeRelativePath(toPosixPath(found)) : site.configFile;
39
+ const position = match ? POSITION.exec(clean.slice(match.index + match[0].length)) : null;
40
+ // Config warnings quote the entry they're about, such as a navigation page
41
+ const quoted = file === site.configFile ? QUOTED.exec(clean)?.[0] : undefined;
42
+ return {
43
+ file,
44
+ ...(position && {
45
+ line: Number(position[1]),
46
+ ...(position[2] && { column: Number(position[2]) }),
47
+ }),
48
+ ...(quoted && site.locate(file, quoted)),
49
+ message: clean,
50
+ };
51
+ };
52
+
53
+ /** Warning types some rule turns into diagnostics, so a strict-build failure is explained. */
54
+ const COVERED_TYPES = new Set<Warning['type']>(['parse-error']);
55
+
56
+ const buildRule = (
57
+ id: string,
58
+ group: Group,
59
+ types: Warning['type'][],
60
+ description: string
61
+ ): SiteRule => {
62
+ for (const type of types) COVERED_TYPES.add(type);
63
+ return {
64
+ id,
65
+ group,
66
+ severity: 'error',
67
+ needsBuild: true,
68
+ scope: 'site',
69
+ description,
70
+ check: (site) =>
71
+ (site.build?.warnings ?? [])
72
+ .filter(({ type }) => types.includes(type))
73
+ .map((warning) => toFinding(site, warning)),
74
+ };
75
+ };
76
+
77
+ export const BUILD_RULES: SiteRule[] = [
78
+ buildRule(
79
+ 'missing-nav-page',
80
+ 'nav',
81
+ ['missing-nav-page'],
82
+ 'pages in the navigation that have no file'
83
+ ),
84
+ buildRule('missing-file', 'content', ['missing-file'], "imported files that don't exist"),
85
+ buildRule(
86
+ 'import-error',
87
+ 'content',
88
+ [
89
+ 'invalid-import-path',
90
+ 'import-resolution-error',
91
+ 'default-import-no-default-export',
92
+ 'export-collision',
93
+ ],
94
+ "imports in pages and snippets that don't resolve"
95
+ ),
96
+ buildRule(
97
+ 'package-import',
98
+ 'config',
99
+ ['undeclared-package', 'package-import-conflict'],
100
+ 'npm package imports that are undeclared or conflict'
101
+ ),
102
+ buildRule('openapi-build', 'openapi', ['openapi'], 'OpenAPI pages the build could not generate'),
103
+ {
104
+ id: 'build-failed',
105
+ group: 'config',
106
+ severity: 'error',
107
+ needsBuild: true,
108
+ scope: 'site',
109
+ description: 'the strict build failed for a reason no rule reports',
110
+ check: (site) => {
111
+ if (!site.build || site.build.passed) return [];
112
+ const unreported = (warning: Warning) =>
113
+ warning.type === 'parse-error' &&
114
+ site.selected !== undefined &&
115
+ !site.selected.has(toFinding(site, warning).file);
116
+ const uncovered = site.build.warnings.filter(
117
+ (warning) => !COVERED_TYPES.has(warning.type) || unreported(warning)
118
+ );
119
+ const findings = uncovered.map((warning) => toFinding(site, warning));
120
+ // Covered warnings are the selected rules' to report; disabled ones are meant to pass
121
+ return site.build.strict
122
+ ? findings
123
+ : [...findings, { file: site.configFile, message: site.build.error }];
124
+ },
125
+ },
126
+ ];
127
+
128
+ /** Build warnings of one type, which the engine merges into the static rule that covers them. */
129
+ export const buildFindings = (site: Site, type: Warning['type']): Finding[] =>
130
+ (site.build?.warnings ?? [])
131
+ .filter((warning) => warning.type === type)
132
+ .map((warning) => toFinding(site, warning));
@@ -1,5 +1,7 @@
1
1
  import type { Rule } from '../types.js';
2
+ import { BUILD_RULES } from './build.js';
2
3
  import { voidTags } from './content/voidTags.js';
4
+ import { openApiSpec } from './openapi.js';
3
5
 
4
6
  /** Every check mint validate runs, in report order. */
5
- export const RULES: Rule[] = [voidTags];
7
+ export const RULES: Rule[] = [voidTags, openApiSpec, ...BUILD_RULES];
@@ -0,0 +1,59 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ import { errorMessage } from '../../helpers.js';
5
+ import {
6
+ buildOverlayRegistryForCheck,
7
+ checkOpenApiFile,
8
+ getOpenApiFilenamesFromDocsConfig,
9
+ type OpenApiCheckMessage,
10
+ } from '../../openApiCheck.js';
11
+ import type { Finding, SiteRule } from '../types.js';
12
+
13
+ export const openApiSpec: SiteRule = {
14
+ id: 'openapi-spec',
15
+ group: 'openapi',
16
+ severity: 'error',
17
+ scope: 'site',
18
+ description:
19
+ "OpenAPI specs in docs.json or mint.json that don't parse or validate, with overlays applied",
20
+ check: async (site) => {
21
+ let filenames: string[] = [];
22
+ try {
23
+ const config = JSON.parse(
24
+ await fs.readFile(path.join(site.baseDir, site.configFile), 'utf-8')
25
+ );
26
+ // mint.json lists its specs under a top-level openapi key
27
+ filenames = getOpenApiFilenamesFromDocsConfig(
28
+ site.configFile === 'mint.json' ? { api: { openapi: config.openapi } } : config
29
+ );
30
+ } catch {
31
+ // A missing or invalid config file is the build's to report
32
+ }
33
+ if (filenames.length === 0) return [];
34
+
35
+ let overlayRegistry;
36
+ try {
37
+ overlayRegistry = await buildOverlayRegistryForCheck(site.localSchema);
38
+ } catch (error) {
39
+ return [{ file: site.configFile, message: `OpenAPI overlays: ${errorMessage(error)}` }];
40
+ }
41
+
42
+ const perFile = await Promise.all(
43
+ filenames.map(async (file) => {
44
+ const messages: OpenApiCheckMessage[] = [];
45
+ await checkOpenApiFile(file, site.localSchema, overlayRegistry, (message) =>
46
+ messages.push(message)
47
+ );
48
+ return messages.flatMap(({ level, message }): Finding[] =>
49
+ level === 'error'
50
+ ? [{ file, message }]
51
+ : level === 'warning'
52
+ ? [{ file, message, severity: 'warning' }]
53
+ : []
54
+ );
55
+ })
56
+ );
57
+ return perFile.flat();
58
+ },
59
+ };