@veluai/velu 0.1.11 → 0.1.13

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.
@@ -0,0 +1,170 @@
1
+ // Normalize a thrown error — from a Vite/MDX transform, an SSR render, or a
2
+ // React error boundary — into the shared `issue` shape (see ./issues.js).
3
+ //
4
+ // Isomorphic: no Node `path` import (path handling is string-based) so the
5
+ // browser ErrorBoundary can reuse it. The single hard rule is PATH SAFETY:
6
+ // never surface an absolute path that isn't under the user's project — those
7
+ // are Velu/Vite internals and must be stripped.
8
+ import { makeIssue, suggestComponent } from './issues.js';
9
+
10
+ // Unwrap a few layers of `err.cause` when the outer message is generic.
11
+ function unwrap(err) {
12
+ let e = err;
13
+ let depth = 0;
14
+ while (e && e.cause && depth < 3) {
15
+ // Stop if the current layer already carries useful location info.
16
+ if (e.loc || e.line || /`[^`]+` to be defined/.test(e.message || '')) break;
17
+ e = e.cause;
18
+ depth += 1;
19
+ }
20
+ return e || err;
21
+ }
22
+
23
+ const toPosix = (p) => String(p).replace(/\\/g, '/');
24
+
25
+ // Make an absolute path project-relative; return null for anything that isn't
26
+ // inside the project (i.e. our internals — never shown).
27
+ function rel(rawPath, projectDir) {
28
+ if (!rawPath) return null;
29
+ let p = toPosix(rawPath).replace(/[?#].*$/, ''); // drop ?query / #hash
30
+ const root = projectDir ? toPosix(projectDir).replace(/\/+$/, '') : '';
31
+ if (root && p.toLowerCase().startsWith(root.toLowerCase())) {
32
+ return p.slice(root.length).replace(/^\/+/, '');
33
+ }
34
+ // Already-relative, project-owned path (no drive letter, no node_modules).
35
+ if (!/^([a-zA-Z]:\/|\/)/.test(p) && !/node_modules/.test(p)) return p;
36
+ return null; // absolute and outside the project → hide it
37
+ }
38
+
39
+ // Strip any absolute path (and node_modules refs) from a message so internals
40
+ // never leak; collapse them to "…".
41
+ function cleanMessage(msg) {
42
+ if (!msg) return '';
43
+ return String(msg)
44
+ .replace(/([a-zA-Z]:\\|\/)[^\s'"()]+/g, (m) => (/node_modules|[\\/]vite[\\/]|@veluai|velu-cli|velu-ui/.test(m) ? '…' : m))
45
+ .trim();
46
+ }
47
+
48
+ // Pull a "(line:col)" / "(line:col-line:col)" position out of a message tail.
49
+ // MDX/vfile errors often carry the location only in the message string, with
50
+ // err.line/err.loc left undefined.
51
+ function parseLocFromMessage(msg) {
52
+ const m = /\((\d+):(\d+)(?:-\d+:\d+)?\)\s*$/.exec(String(msg || ''));
53
+ return m ? { line: Number(m[1]), column: Number(m[2]) } : null;
54
+ }
55
+
56
+ // Drop a trailing "(line:col-…)" from a message once we've surfaced it as a
57
+ // separate location, so it isn't shown twice.
58
+ function stripLocSuffix(msg) {
59
+ return String(msg || '').replace(/\s*\(\d+:\d+(?:-\d+:\d+)?\)\s*$/, '').trim();
60
+ }
61
+
62
+ // Phrases that mark a genuine MDX *parse* error (vs a runtime throw).
63
+ const MDX_SYNTAX_RE =
64
+ /closing tag|unexpected closing|could not parse (?:expression|import|export)|unexpected character|unexpected end of|expected a closing|expected the closing|unexpected `|in expression|misnested|before name/i;
65
+
66
+ // Keep a code frame only when it clearly belongs to a project file; otherwise
67
+ // drop it (an internal frame would leak paths and confuse the author).
68
+ function safeFrame(frame, fileIsProjectOwned) {
69
+ if (!frame || !fileIsProjectOwned) return null;
70
+ const text = String(frame);
71
+ if (/node_modules|[\\/]vite[\\/]|@veluai[\\/]/.test(text)) return null;
72
+ return text;
73
+ }
74
+
75
+ export function extractMdxError(rawErr, opts = {}) {
76
+ const { projectDir = '', knownComponents = [], file: fileHint = null } = opts;
77
+
78
+ // A component (runtime) or the compile-time prop check attaches a ready-made
79
+ // issue. Trust it directly — it already carries plain-language wording, a
80
+ // suggestion, and (from the compile-time check) a file:line. Walk the cause
81
+ // chain since Vite/rollup may re-wrap the thrown error.
82
+ let tagged = null;
83
+ for (let e = rawErr, depth = 0; e && depth < 6; e = e.cause, depth += 1) {
84
+ if (e.veluIssue) {
85
+ tagged = e.veluIssue;
86
+ break;
87
+ }
88
+ }
89
+ if (tagged) return makeIssue({ ...tagged, file: tagged.file || fileHint });
90
+
91
+ const err = unwrap(rawErr) || {};
92
+ const message = err.message || String(rawErr || '');
93
+
94
+ // 1) Unknown component (MDX render: `_missingMdxReference`). The message
95
+ // tail carries the spot: "...referenced in your code at `7:1-7:54` in
96
+ // `<abs path>`" — pull the line/column + file out so the author knows
97
+ // exactly where to look (path relative-ized for safety).
98
+ const missing = /Expected component `([^`]+)` to be defined/.exec(message);
99
+ if (missing) {
100
+ const name = missing[1];
101
+ const at = /referenced in your code at `(\d+):(\d+)/.exec(message);
102
+ const inFile = /\bin `([^`]+)`/.exec(message);
103
+ const relFile = inFile ? rel(inFile[1], projectDir) : null;
104
+ return makeIssue({
105
+ category: 'unknown-component',
106
+ file: relFile || fileHint,
107
+ line: at ? Number(at[1]) : null,
108
+ column: at ? Number(at[2]) : null,
109
+ title: `<${name}> is not a built-in component`,
110
+ detail: '',
111
+ hint: 'Components are built in — check the spelling and capitalization (you don’t import them).',
112
+ suggestion: suggestComponent(name, knownComponents),
113
+ });
114
+ }
115
+
116
+ // 2) Compile error carrying a source location (Vite plugin / MDX / vfile).
117
+ // The location may be on err.loc, on err.line/column, or only inside the
118
+ // message text — try all three.
119
+ const loc =
120
+ err.loc ||
121
+ (err.line != null ? { line: err.line, column: err.column, file: err.file } : null) ||
122
+ parseLocFromMessage(err.reason || message);
123
+ const rawFile = err.id || (loc && loc.file) || err.file || null;
124
+ const file = rel(rawFile, projectDir) || fileHint;
125
+ const fileIsProjectOwned = Boolean(file) && rel(rawFile, projectDir) != null;
126
+ const frame = safeFrame(err.frame, fileIsProjectOwned || Boolean(fileHint));
127
+ const detail = cleanMessage(stripLocSuffix(err.reason || message));
128
+ const isSyntax = MDX_SYNTAX_RE.test(message);
129
+ const isFrontmatter =
130
+ err.source === 'remark-frontmatter' ||
131
+ /\byaml\b|frontmatter/i.test(message) ||
132
+ (loc && loc.line === 1 && /unexpected|expected/i.test(message) && /---/.test(message));
133
+
134
+ if (loc || isSyntax || (frame && fileIsProjectOwned)) {
135
+ return makeIssue({
136
+ category: isFrontmatter ? 'frontmatter' : 'mdx-syntax',
137
+ file,
138
+ line: loc ? loc.line : null,
139
+ column: loc ? loc.column : null,
140
+ frame,
141
+ title: detail || (isFrontmatter ? 'Invalid frontmatter' : 'MDX syntax error'),
142
+ detail: '',
143
+ hint: isFrontmatter
144
+ ? 'Check the YAML between the --- markers — indentation, quotes, and colons.'
145
+ : 'Make sure every <Component> has a matching closing tag and that { } braces are balanced.',
146
+ });
147
+ }
148
+
149
+ // 3) Bad prop / option that threw at render time.
150
+ if (/\.map is not a function|is not iterable|reading '|undefined \(reading/i.test(message)) {
151
+ return makeIssue({
152
+ category: 'invalid-props',
153
+ file,
154
+ title: 'A component received an invalid value',
155
+ detail,
156
+ hint: 'Check the props/options you passed to a component on this page.',
157
+ });
158
+ }
159
+
160
+ // 4) Anything else that threw while rendering.
161
+ return makeIssue({
162
+ category: 'render-crash',
163
+ file,
164
+ title: 'This page failed to render',
165
+ detail,
166
+ hint: 'Set VELU_DEBUG=1 for the full stack trace.',
167
+ });
168
+ }
169
+
170
+ export default extractMdxError;
@@ -0,0 +1,159 @@
1
+ // The shared "issue" model used by BOTH the live `velu dev` error surface and
2
+ // the `velu validate` command — so an author sees the same wording whether a
3
+ // problem shows up live in the browser/terminal or in a batch validation run.
4
+ //
5
+ // An issue is a plain object:
6
+ // {
7
+ // category, // see CATEGORY_LABEL keys below
8
+ // severity, // 'error' (default) | 'warning' | 'info'
9
+ // file, // project-relative path (posix), or null
10
+ // line, column,// 1-based numbers, or null
11
+ // frame, // a caret-annotated code-frame string, or null
12
+ // title, // short, plain-language headline
13
+ // detail, // the underlying message (already path-stripped)
14
+ // hint, // how to fix it
15
+ // suggestion, // a "did you mean <X>" component name, or null
16
+ // }
17
+ //
18
+ // This module is dependency-free and isomorphic (no Node-only imports), so the
19
+ // browser ErrorBoundary can reuse `levenshtein`/`suggestComponent`.
20
+
21
+ export const CATEGORY_LABEL = {
22
+ 'mdx-syntax': 'MDX syntax',
23
+ frontmatter: 'Frontmatter',
24
+ 'unknown-component': 'Unknown component',
25
+ 'invalid-props': 'Invalid options',
26
+ 'render-crash': 'Render error',
27
+ 'config-json': 'velu.json',
28
+ 'config-schema': 'velu.json',
29
+ 'config-nav': 'Navigation',
30
+ 'config-asset': 'Asset',
31
+ };
32
+
33
+ // Fill in defaults so callers only set what they know.
34
+ export function makeIssue(partial) {
35
+ return {
36
+ category: 'render-crash',
37
+ severity: 'error',
38
+ file: null,
39
+ line: null,
40
+ column: null,
41
+ frame: null,
42
+ title: 'Something went wrong',
43
+ detail: '',
44
+ hint: '',
45
+ suggestion: null,
46
+ ...partial,
47
+ };
48
+ }
49
+
50
+ // Classic Levenshtein edit distance (small inputs — component names).
51
+ export function levenshtein(a, b) {
52
+ a = String(a);
53
+ b = String(b);
54
+ if (a === b) return 0;
55
+ if (!a.length) return b.length;
56
+ if (!b.length) return a.length;
57
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
58
+ let cur = new Array(b.length + 1);
59
+ for (let i = 1; i <= a.length; i++) {
60
+ cur[0] = i;
61
+ for (let j = 1; j <= b.length; j++) {
62
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
63
+ cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
64
+ }
65
+ [prev, cur] = [cur, prev];
66
+ }
67
+ return prev[b.length];
68
+ }
69
+
70
+ // Closest known component to `name` within a small edit distance, else null.
71
+ // Compared case-insensitively (so a capitalization typo still matches) but the
72
+ // correctly-cased known name is returned.
73
+ export function suggestComponent(name, known = []) {
74
+ if (!name) return null;
75
+ const lower = String(name).toLowerCase();
76
+ let best = null;
77
+ let bestD = Infinity;
78
+ for (const k of known) {
79
+ const d = levenshtein(lower, String(k).toLowerCase());
80
+ if (d < bestD) {
81
+ bestD = d;
82
+ best = k;
83
+ }
84
+ }
85
+ // Allow a little more slack for longer names, capped at 3 edits.
86
+ const threshold = Math.min(3, Math.max(2, Math.floor(lower.length / 4)));
87
+ return bestD <= threshold ? best : null;
88
+ }
89
+
90
+ // ── Terminal formatting ─────────────────────────────────────────────────────
91
+
92
+ const COLORS = {
93
+ reset: '\x1b[0m',
94
+ red: '\x1b[31m',
95
+ yellow: '\x1b[33m',
96
+ cyan: '\x1b[36m',
97
+ dim: '\x1b[2m',
98
+ bold: '\x1b[1m',
99
+ };
100
+ const paint = (on, code, s) => (on ? `${code}${s}${COLORS.reset}` : s);
101
+
102
+ function severityMark(sev, color) {
103
+ if (sev === 'warning') return paint(color, COLORS.yellow, '⚠');
104
+ if (sev === 'info') return paint(color, COLORS.cyan, 'ℹ');
105
+ return paint(color, COLORS.red, '✖');
106
+ }
107
+
108
+ // Format a single issue as a multi-line terminal block.
109
+ export function formatIssue(issue, { color = false } = {}) {
110
+ const label = CATEGORY_LABEL[issue.category] || issue.category;
111
+ const lineCol = issue.line
112
+ ? `${issue.line}${issue.column ? `:${issue.column}` : ''}`
113
+ : '';
114
+ // Keep the line:col even when grouped output has nulled the file (so the
115
+ // position still shows under a per-file heading in formatReport).
116
+ const where = issue.file ? `${issue.file}${lineCol ? `:${lineCol}` : ''}` : lineCol;
117
+ const lines = [];
118
+ lines.push(
119
+ `${severityMark(issue.severity, color)} ${paint(color, COLORS.bold, label)}` +
120
+ (where ? ` ${paint(color, COLORS.dim, where)}` : ''),
121
+ );
122
+ if (issue.title) lines.push(` ${issue.title}`);
123
+ if (issue.detail && issue.detail !== issue.title) lines.push(` ${paint(color, COLORS.dim, issue.detail)}`);
124
+ if (issue.frame) {
125
+ for (const f of String(issue.frame).split('\n')) lines.push(` ${f}`);
126
+ }
127
+ if (issue.suggestion) lines.push(` ${paint(color, COLORS.cyan, `Did you mean <${issue.suggestion}>?`)}`);
128
+ if (issue.hint) lines.push(` ${paint(color, COLORS.dim, `→ ${issue.hint}`)}`);
129
+ return lines.join('\n');
130
+ }
131
+
132
+ // Format a list of issues as a grouped report (used by `velu validate`).
133
+ export function formatReport(issues, { color = false } = {}) {
134
+ if (!issues.length) {
135
+ return paint(color, COLORS.cyan, '✓ No issues found.');
136
+ }
137
+ // Group by file (config issues with no file group under "velu.json").
138
+ const groups = new Map();
139
+ for (const issue of issues) {
140
+ const key = issue.file || 'velu.json';
141
+ if (!groups.has(key)) groups.set(key, []);
142
+ groups.get(key).push(issue);
143
+ }
144
+ const out = [];
145
+ for (const [file, group] of groups) {
146
+ out.push(paint(color, COLORS.bold, file));
147
+ for (const issue of group) {
148
+ out.push(formatIssue({ ...issue, file: null }, { color }).replace(/^/gm, ' '));
149
+ }
150
+ out.push('');
151
+ }
152
+ const errors = issues.filter((i) => i.severity !== 'warning' && i.severity !== 'info').length;
153
+ const warnings = issues.length - errors;
154
+ const summary =
155
+ `${errors} error${errors === 1 ? '' : 's'}` +
156
+ (warnings ? `, ${warnings} warning${warnings === 1 ? '' : 's'}` : '');
157
+ out.push(paint(color, errors ? COLORS.red : COLORS.yellow, summary));
158
+ return out.join('\n');
159
+ }
@@ -0,0 +1,34 @@
1
+ // The capitalized component tags an author may use in `.mdx` content.
2
+ //
3
+ // Kept in sync with velu-ui's `defaultMdxComponents`
4
+ // (packages/velu-ui/src/mdx-components.jsx). Used for "did you mean"
5
+ // suggestions and unknown-component detection on the Node side (dev server +
6
+ // `velu validate`). The browser ErrorBoundary derives the same set directly
7
+ // from `defaultMdxComponents`, so this list only needs to stay roughly in
8
+ // step (a missing entry just costs a suggestion, never correctness).
9
+ export const KNOWN_COMPONENTS = [
10
+ 'Callout',
11
+ 'Card',
12
+ 'CardGroup',
13
+ 'Accordion',
14
+ 'AccordionGroup',
15
+ 'Columns',
16
+ 'Field',
17
+ 'Prompt',
18
+ 'Steps',
19
+ 'Step',
20
+ 'Tree',
21
+ 'Folder',
22
+ 'File',
23
+ 'Image',
24
+ 'CodeBlock',
25
+ 'CodeGroup',
26
+ 'MethodBadge',
27
+ 'ApiPath',
28
+ 'TryItBar',
29
+ 'ApiField',
30
+ 'ApiClient',
31
+ 'ApiSidebar',
32
+ ];
33
+
34
+ export default KNOWN_COMPONENTS;