@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.
@@ -1,100 +1,100 @@
1
- // Per-component option schemas — the props whose wrong value would otherwise
2
- // render incorrectly *silently*. Deliberately small and high-signal; extend a
3
- // component's entry here when it gains a new constrained option.
4
- //
5
- // Pure data + a pure validator (no React, no other imports) so BOTH sides can
6
- // use it: the live MDX registry (velu-ui/mdx-components.jsx) validates at
7
- // render time, and `velu validate` (velu-cli) imports this same module to
8
- // statically check literal attributes — one source of truth, no drift.
9
-
10
- // Canonical accepted values (must match the components):
11
- // Callout — VARIANTS keys; the component is CASE-SENSITIVE (VARIANTS[type]).
12
- // MethodBadge — METHODS; the component lower-cases the input first.
13
- export const CALLOUT_TYPES = ['note', 'warning', 'info', 'tip', 'check', 'danger', 'callout'];
14
- export const METHOD_NAMES = ['get', 'post', 'put', 'patch', 'delete'];
15
-
16
- // schema: { enums: { prop: { values, caseSensitive } }, required: [prop, …] }
17
- const SCHEMAS = {
18
- Callout: { enums: { type: { values: CALLOUT_TYPES, caseSensitive: true } } },
19
- MethodBadge: { enums: { method: { values: METHOD_NAMES, caseSensitive: false } } },
20
- ApiPath: { enums: { method: { values: METHOD_NAMES, caseSensitive: false } } },
21
- Image: { required: ['src'] },
22
- };
23
-
24
- // Smallest edit distance match within a set (for "did you mean"). Tiny inputs.
25
- function closest(value, values) {
26
- const v = String(value).toLowerCase();
27
- let best = null;
28
- let bestD = Infinity;
29
- for (const cand of values) {
30
- const a = v;
31
- const b = cand.toLowerCase();
32
- // inline Levenshtein
33
- const m = a.length;
34
- const n = b.length;
35
- const d = Array.from({ length: n + 1 }, (_, i) => i);
36
- for (let i = 1; i <= m; i++) {
37
- let prev = d[0];
38
- d[0] = i;
39
- for (let j = 1; j <= n; j++) {
40
- const tmp = d[j];
41
- d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
42
- prev = tmp;
43
- }
44
- }
45
- if (d[n] < bestD) {
46
- bestD = d[n];
47
- best = cand;
48
- }
49
- }
50
- return bestD <= 3 ? best : null;
51
- }
52
-
53
- /**
54
- * Validate a component's props against its schema.
55
- * @param {string} name component tag name
56
- * @param {object} props props passed to it
57
- * @param {{ checkRequired?: boolean }} [opts] static callers pass
58
- * checkRequired:false because a prop supplied via a {expression}
59
- * isn't a literal they can see, so "missing required" would be a
60
- * false positive.
61
- * @returns an issue-shaped object (category 'invalid-props') or null if valid.
62
- * { category, title, detail, hint, suggestion }
63
- */
64
- export function validateProps(name, props = {}, opts = {}) {
65
- const { checkRequired = true } = opts;
66
- const schema = SCHEMAS[name];
67
- if (!schema) return null;
68
-
69
- for (const req of checkRequired ? schema.required || [] : []) {
70
- const v = props[req];
71
- if (v == null || v === '') {
72
- return {
73
- category: 'invalid-props',
74
- title: `<${name}> is missing the required "${req}" prop`,
75
- hint: `Add ${req}="…" to the component.`,
76
- };
77
- }
78
- }
79
-
80
- for (const [prop, rule] of Object.entries(schema.enums || {})) {
81
- if (!(prop in props) || props[prop] == null) continue;
82
- const raw = props[prop];
83
- const ok = rule.caseSensitive
84
- ? rule.values.includes(raw)
85
- : rule.values.map((s) => s.toLowerCase()).includes(String(raw).toLowerCase());
86
- if (!ok) {
87
- const guess = closest(raw, rule.values);
88
- return {
89
- category: 'invalid-props',
90
- title: `Invalid "${prop}" on <${name}>: "${raw}"`,
91
- detail: `Expected one of: ${rule.values.join(', ')}.`,
92
- hint: guess ? `Did you mean "${guess}"?` : '',
93
- };
94
- }
95
- }
96
-
97
- return null;
98
- }
99
-
100
- export default validateProps;
1
+ // Per-component option schemas — the props whose wrong value would otherwise
2
+ // render incorrectly *silently*. Deliberately small and high-signal; extend a
3
+ // component's entry here when it gains a new constrained option.
4
+ //
5
+ // Pure data + a pure validator (no React, no other imports) so BOTH sides can
6
+ // use it: the live MDX registry (velu-ui/mdx-components.jsx) validates at
7
+ // render time, and `velu validate` (velu-cli) imports this same module to
8
+ // statically check literal attributes — one source of truth, no drift.
9
+
10
+ // Canonical accepted values (must match the components):
11
+ // Callout — VARIANTS keys; the component is CASE-SENSITIVE (VARIANTS[type]).
12
+ // MethodBadge — METHODS; the component lower-cases the input first.
13
+ export const CALLOUT_TYPES = ['note', 'warning', 'info', 'tip', 'check', 'danger', 'callout'];
14
+ export const METHOD_NAMES = ['get', 'post', 'put', 'patch', 'delete'];
15
+
16
+ // schema: { enums: { prop: { values, caseSensitive } }, required: [prop, …] }
17
+ const SCHEMAS = {
18
+ Callout: { enums: { type: { values: CALLOUT_TYPES, caseSensitive: true } } },
19
+ MethodBadge: { enums: { method: { values: METHOD_NAMES, caseSensitive: false } } },
20
+ ApiPath: { enums: { method: { values: METHOD_NAMES, caseSensitive: false } } },
21
+ Image: { required: ['src'] },
22
+ };
23
+
24
+ // Smallest edit distance match within a set (for "did you mean"). Tiny inputs.
25
+ function closest(value, values) {
26
+ const v = String(value).toLowerCase();
27
+ let best = null;
28
+ let bestD = Infinity;
29
+ for (const cand of values) {
30
+ const a = v;
31
+ const b = cand.toLowerCase();
32
+ // inline Levenshtein
33
+ const m = a.length;
34
+ const n = b.length;
35
+ const d = Array.from({ length: n + 1 }, (_, i) => i);
36
+ for (let i = 1; i <= m; i++) {
37
+ let prev = d[0];
38
+ d[0] = i;
39
+ for (let j = 1; j <= n; j++) {
40
+ const tmp = d[j];
41
+ d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
42
+ prev = tmp;
43
+ }
44
+ }
45
+ if (d[n] < bestD) {
46
+ bestD = d[n];
47
+ best = cand;
48
+ }
49
+ }
50
+ return bestD <= 3 ? best : null;
51
+ }
52
+
53
+ /**
54
+ * Validate a component's props against its schema.
55
+ * @param {string} name component tag name
56
+ * @param {object} props props passed to it
57
+ * @param {{ checkRequired?: boolean }} [opts] static callers pass
58
+ * checkRequired:false because a prop supplied via a {expression}
59
+ * isn't a literal they can see, so "missing required" would be a
60
+ * false positive.
61
+ * @returns an issue-shaped object (category 'invalid-props') or null if valid.
62
+ * { category, title, detail, hint, suggestion }
63
+ */
64
+ export function validateProps(name, props = {}, opts = {}) {
65
+ const { checkRequired = true } = opts;
66
+ const schema = SCHEMAS[name];
67
+ if (!schema) return null;
68
+
69
+ for (const req of checkRequired ? schema.required || [] : []) {
70
+ const v = props[req];
71
+ if (v == null || v === '') {
72
+ return {
73
+ category: 'invalid-props',
74
+ title: `<${name}> is missing the required "${req}" prop`,
75
+ hint: `Add ${req}="…" to the component.`,
76
+ };
77
+ }
78
+ }
79
+
80
+ for (const [prop, rule] of Object.entries(schema.enums || {})) {
81
+ if (!(prop in props) || props[prop] == null) continue;
82
+ const raw = props[prop];
83
+ const ok = rule.caseSensitive
84
+ ? rule.values.includes(raw)
85
+ : rule.values.map((s) => s.toLowerCase()).includes(String(raw).toLowerCase());
86
+ if (!ok) {
87
+ const guess = closest(raw, rule.values);
88
+ return {
89
+ category: 'invalid-props',
90
+ title: `Invalid "${prop}" on <${name}>: "${raw}"`,
91
+ detail: `Expected one of: ${rule.values.join(', ')}.`,
92
+ hint: guess ? `Did you mean "${guess}"?` : '',
93
+ };
94
+ }
95
+ }
96
+
97
+ return null;
98
+ }
99
+
100
+ export default validateProps;
@@ -1,64 +1,64 @@
1
- /**
2
- * copyText — copy a string to the clipboard, working in BOTH secure and
3
- * insecure contexts.
4
- *
5
- * `navigator.clipboard` only exists in a secure context (HTTPS or
6
- * localhost). On a plain-HTTP origin — e.g. previewing the dev server
7
- * over the LAN at http://<ip>:8358 on a phone — it's `undefined`, so a
8
- * `if (!navigator.clipboard) return` guard makes copy buttons silently
9
- * no-op. This util falls back to the legacy `execCommand('copy')` via a
10
- * hidden textarea so copy still works on those origins.
11
- *
12
- * Must be called from a user gesture (click) — both paths require it.
13
- * Returns a Promise: resolves on success, rejects on failure.
14
- */
15
- export default function copyText(text) {
16
- const str = String(text ?? '');
17
-
18
- // Preferred path — async Clipboard API (secure contexts only).
19
- if (
20
- typeof navigator !== 'undefined' &&
21
- navigator.clipboard &&
22
- typeof window !== 'undefined' &&
23
- window.isSecureContext
24
- ) {
25
- return navigator.clipboard.writeText(str);
26
- }
27
-
28
- // Fallback — hidden <textarea> + execCommand, for insecure origins.
29
- return new Promise((resolve, reject) => {
30
- if (typeof document === 'undefined') {
31
- reject(new Error('copyText: no document'));
32
- return;
33
- }
34
- const ta = document.createElement('textarea');
35
- ta.value = str;
36
- ta.setAttribute('readonly', '');
37
- // Keep it out of view and inert, but still selectable.
38
- ta.style.position = 'fixed';
39
- ta.style.top = '0';
40
- ta.style.left = '0';
41
- ta.style.inlineSize = '1px';
42
- ta.style.blockSize = '1px';
43
- ta.style.padding = '0';
44
- ta.style.border = 'none';
45
- ta.style.opacity = '0';
46
- document.body.appendChild(ta);
47
- ta.focus();
48
- ta.select();
49
- try {
50
- ta.setSelectionRange(0, str.length);
51
- } catch {
52
- /* some browsers reject setSelectionRange on a readonly field */
53
- }
54
- let ok = false;
55
- try {
56
- ok = document.execCommand('copy');
57
- } catch {
58
- ok = false;
59
- }
60
- document.body.removeChild(ta);
61
- if (ok) resolve();
62
- else reject(new Error('copyText: execCommand copy failed'));
63
- });
64
- }
1
+ /**
2
+ * copyText — copy a string to the clipboard, working in BOTH secure and
3
+ * insecure contexts.
4
+ *
5
+ * `navigator.clipboard` only exists in a secure context (HTTPS or
6
+ * localhost). On a plain-HTTP origin — e.g. previewing the dev server
7
+ * over the LAN at http://<ip>:8358 on a phone — it's `undefined`, so a
8
+ * `if (!navigator.clipboard) return` guard makes copy buttons silently
9
+ * no-op. This util falls back to the legacy `execCommand('copy')` via a
10
+ * hidden textarea so copy still works on those origins.
11
+ *
12
+ * Must be called from a user gesture (click) — both paths require it.
13
+ * Returns a Promise: resolves on success, rejects on failure.
14
+ */
15
+ export default function copyText(text) {
16
+ const str = String(text ?? '');
17
+
18
+ // Preferred path — async Clipboard API (secure contexts only).
19
+ if (
20
+ typeof navigator !== 'undefined' &&
21
+ navigator.clipboard &&
22
+ typeof window !== 'undefined' &&
23
+ window.isSecureContext
24
+ ) {
25
+ return navigator.clipboard.writeText(str);
26
+ }
27
+
28
+ // Fallback — hidden <textarea> + execCommand, for insecure origins.
29
+ return new Promise((resolve, reject) => {
30
+ if (typeof document === 'undefined') {
31
+ reject(new Error('copyText: no document'));
32
+ return;
33
+ }
34
+ const ta = document.createElement('textarea');
35
+ ta.value = str;
36
+ ta.setAttribute('readonly', '');
37
+ // Keep it out of view and inert, but still selectable.
38
+ ta.style.position = 'fixed';
39
+ ta.style.top = '0';
40
+ ta.style.left = '0';
41
+ ta.style.inlineSize = '1px';
42
+ ta.style.blockSize = '1px';
43
+ ta.style.padding = '0';
44
+ ta.style.border = 'none';
45
+ ta.style.opacity = '0';
46
+ document.body.appendChild(ta);
47
+ ta.focus();
48
+ ta.select();
49
+ try {
50
+ ta.setSelectionRange(0, str.length);
51
+ } catch {
52
+ /* some browsers reject setSelectionRange on a readonly field */
53
+ }
54
+ let ok = false;
55
+ try {
56
+ ok = document.execCommand('copy');
57
+ } catch {
58
+ ok = false;
59
+ }
60
+ document.body.removeChild(ta);
61
+ if (ok) resolve();
62
+ else reject(new Error('copyText: execCommand copy failed'));
63
+ });
64
+ }
@@ -1,105 +1,105 @@
1
- import React from 'react';
2
- import Callout from './components/Callout.jsx';
3
- import Card, { CardGroup } from './components/Card.jsx';
4
- import Accordion, { AccordionGroup } from './components/Accordion.jsx';
5
- import Columns from './components/Columns.jsx';
6
- import Field from './components/Field.jsx';
7
- import Prompt from './components/Prompt.jsx';
8
- import Steps, { Step } from './components/Steps.jsx';
9
- import Tree, { Folder, File } from './components/Tree.jsx';
10
- import Image from './components/Image.jsx';
11
- import CodeBlock, { CodeGroup } from './components/CodeBlock.jsx';
12
- import MethodBadge from './components/MethodBadge.jsx';
13
- import ApiPath from './components/ApiPath.jsx';
14
- import TryItBar from './components/TryItBar.jsx';
15
- import ApiField from './components/ApiField.jsx';
16
- import ApiClient from './components/ApiClient.jsx';
17
- import ApiSidebar from './components/ApiSidebar.jsx';
18
- import { validateProps } from './lib/component-schemas.js';
19
-
20
- /**
21
- * defaultMdxComponents — the registry the MDXProvider consumes.
22
- *
23
- * Two kinds of entries:
24
- *
25
- * 1. Lowercase keys ('pre', 'h1', …) override the HTML tags that
26
- * Markdown produces. We use these to upgrade plain ``` fenced
27
- * code blocks into our CodeBlock component, etc.
28
- *
29
- * 2. Capitalised keys ('Callout', 'Card', …) match the exact tag
30
- * names authors write in their .mdx, e.g. `<Callout type="warn">`.
31
- * MDX looks up the name in this map and renders our component
32
- * instead of treating it as an unknown HTML element.
33
- *
34
- * Tag-name → component is the only contract here. SSR-safe by
35
- * construction: identical map on server + client → identical render.
36
- */
37
-
38
- /* `pre > code` is how Markdown renders ``` blocks. We pull the
39
- language out of the code-element's className ("language-js" → "js")
40
- and forward children verbatim to CodeBlock. */
41
- function PreOverride({ children }) {
42
- const child = React.Children.only(children);
43
- const className = child?.props?.className || '';
44
- const m = /language-(\S+)/.exec(className);
45
- const language = m ? m[1] : undefined;
46
- const code =
47
- typeof child?.props?.children === 'string'
48
- ? child.props.children.replace(/\n$/, '')
49
- : child?.props?.children;
50
- return (
51
- <CodeBlock language={language}>
52
- {code}
53
- </CodeBlock>
54
- );
55
- }
56
-
57
- /* Wrap a component so its constrained options (see component-schemas.js)
58
- are validated at render time. An invalid option throws a marked error
59
- (`err.veluIssue`) that the dev server turns into a friendly card on the
60
- page AND a clean block in the terminal — the same surface as an unknown
61
- component. Components without a schema pass straight through. */
62
- function checked(name, Comp) {
63
- function Checked(props) {
64
- const issue = validateProps(name, props);
65
- if (issue) {
66
- const err = new Error(issue.title);
67
- err.veluIssue = issue;
68
- throw err;
69
- }
70
- return <Comp {...props} />;
71
- }
72
- Checked.displayName = `Checked(${name})`;
73
- return Checked;
74
- }
75
-
76
- export const defaultMdxComponents = {
77
- /* HTML-tag overrides (lowercase keys). */
78
- pre: PreOverride,
79
-
80
- /* Authored component tags (capitalised keys). */
81
- Callout: checked('Callout', Callout),
82
- Card,
83
- CardGroup,
84
- Accordion,
85
- AccordionGroup,
86
- Columns,
87
- Field,
88
- Prompt,
89
- Steps,
90
- Step,
91
- Tree,
92
- Folder,
93
- File,
94
- Image: checked('Image', Image),
95
- CodeBlock,
96
- CodeGroup,
97
- MethodBadge: checked('MethodBadge', MethodBadge),
98
- ApiPath: checked('ApiPath', ApiPath),
99
- TryItBar,
100
- ApiField,
101
- ApiClient,
102
- ApiSidebar,
103
- };
104
-
105
- export default defaultMdxComponents;
1
+ import React from 'react';
2
+ import Callout from './components/Callout.jsx';
3
+ import Card, { CardGroup } from './components/Card.jsx';
4
+ import Accordion, { AccordionGroup } from './components/Accordion.jsx';
5
+ import Columns from './components/Columns.jsx';
6
+ import Field from './components/Field.jsx';
7
+ import Prompt from './components/Prompt.jsx';
8
+ import Steps, { Step } from './components/Steps.jsx';
9
+ import Tree, { Folder, File } from './components/Tree.jsx';
10
+ import Image from './components/Image.jsx';
11
+ import CodeBlock, { CodeGroup } from './components/CodeBlock.jsx';
12
+ import MethodBadge from './components/MethodBadge.jsx';
13
+ import ApiPath from './components/ApiPath.jsx';
14
+ import TryItBar from './components/TryItBar.jsx';
15
+ import ApiField from './components/ApiField.jsx';
16
+ import ApiClient from './components/ApiClient.jsx';
17
+ import ApiSidebar from './components/ApiSidebar.jsx';
18
+ import { validateProps } from './lib/component-schemas.js';
19
+
20
+ /**
21
+ * defaultMdxComponents — the registry the MDXProvider consumes.
22
+ *
23
+ * Two kinds of entries:
24
+ *
25
+ * 1. Lowercase keys ('pre', 'h1', …) override the HTML tags that
26
+ * Markdown produces. We use these to upgrade plain ``` fenced
27
+ * code blocks into our CodeBlock component, etc.
28
+ *
29
+ * 2. Capitalised keys ('Callout', 'Card', …) match the exact tag
30
+ * names authors write in their .mdx, e.g. `<Callout type="warn">`.
31
+ * MDX looks up the name in this map and renders our component
32
+ * instead of treating it as an unknown HTML element.
33
+ *
34
+ * Tag-name → component is the only contract here. SSR-safe by
35
+ * construction: identical map on server + client → identical render.
36
+ */
37
+
38
+ /* `pre > code` is how Markdown renders ``` blocks. We pull the
39
+ language out of the code-element's className ("language-js" → "js")
40
+ and forward children verbatim to CodeBlock. */
41
+ function PreOverride({ children }) {
42
+ const child = React.Children.only(children);
43
+ const className = child?.props?.className || '';
44
+ const m = /language-(\S+)/.exec(className);
45
+ const language = m ? m[1] : undefined;
46
+ const code =
47
+ typeof child?.props?.children === 'string'
48
+ ? child.props.children.replace(/\n$/, '')
49
+ : child?.props?.children;
50
+ return (
51
+ <CodeBlock language={language}>
52
+ {code}
53
+ </CodeBlock>
54
+ );
55
+ }
56
+
57
+ /* Wrap a component so its constrained options (see component-schemas.js)
58
+ are validated at render time. An invalid option throws a marked error
59
+ (`err.veluIssue`) that the dev server turns into a friendly card on the
60
+ page AND a clean block in the terminal — the same surface as an unknown
61
+ component. Components without a schema pass straight through. */
62
+ function checked(name, Comp) {
63
+ function Checked(props) {
64
+ const issue = validateProps(name, props);
65
+ if (issue) {
66
+ const err = new Error(issue.title);
67
+ err.veluIssue = issue;
68
+ throw err;
69
+ }
70
+ return <Comp {...props} />;
71
+ }
72
+ Checked.displayName = `Checked(${name})`;
73
+ return Checked;
74
+ }
75
+
76
+ export const defaultMdxComponents = {
77
+ /* HTML-tag overrides (lowercase keys). */
78
+ pre: PreOverride,
79
+
80
+ /* Authored component tags (capitalised keys). */
81
+ Callout: checked('Callout', Callout),
82
+ Card,
83
+ CardGroup,
84
+ Accordion,
85
+ AccordionGroup,
86
+ Columns,
87
+ Field,
88
+ Prompt,
89
+ Steps,
90
+ Step,
91
+ Tree,
92
+ Folder,
93
+ File,
94
+ Image: checked('Image', Image),
95
+ CodeBlock,
96
+ CodeGroup,
97
+ MethodBadge: checked('MethodBadge', MethodBadge),
98
+ ApiPath: checked('ApiPath', ApiPath),
99
+ TryItBar,
100
+ ApiField,
101
+ ApiClient,
102
+ ApiSidebar,
103
+ };
104
+
105
+ export default defaultMdxComponents;