@sakaniui/mcp 0.0.0-stage → 0.8.11
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/LICENSE +21 -0
- package/README.md +64 -2
- package/bin/sakaniui-mcp.mjs +830 -0
- package/data/AGENTS.md +273 -0
- package/data/CHANGELOG.md +555 -0
- package/data/dist/icon-index.json +1 -0
- package/data/dist/manifest.json +10725 -0
- package/data/package.json +5 -0
- package/package.json +43 -4
|
@@ -0,0 +1,830 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* SakaniUI MCP server -- lets an AI editor/agent look up the design system instead of guessing.
|
|
4
|
+
*
|
|
5
|
+
* npx -y @sakaniui/mcp [--project <dir>] (or: npx -y -p @sakaniui/react sakaniui-mcp)
|
|
6
|
+
*
|
|
7
|
+
* Zero dependencies: speaks newline-delimited JSON-RPC (MCP stdio transport).
|
|
8
|
+
*
|
|
9
|
+
* Read-only by construction. It reads five fixed files (package.json, dist/manifest.json,
|
|
10
|
+
* dist/icon-index.json, AGENTS.md, CHANGELOG.md) from a @sakaniui/react install and writes nothing,
|
|
11
|
+
* runs nothing and opens no network connection. No tool takes a path; every argument is validated.
|
|
12
|
+
* Code passed to check_code is only read as text, never executed.
|
|
13
|
+
*
|
|
14
|
+
* Version-aware. `npx` may fetch a newer release than the project uses, so the server looks for
|
|
15
|
+
* the project's own installed @sakaniui/react (walking up from --project or the working
|
|
16
|
+
* directory). If it has a manifest, answers come from that copy. If it is older than the
|
|
17
|
+
* manifest era, answers come from this copy but every component is checked against its `since`
|
|
18
|
+
* release and flagged when the project does not have it yet.
|
|
19
|
+
*/
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import readline from 'node:readline';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
|
|
25
|
+
const ownRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
26
|
+
|
|
27
|
+
/* ---------- reading an install (fixed file names only) ---------- */
|
|
28
|
+
const readText = (root, rel) => { try { return fs.readFileSync(path.join(root, rel), 'utf8'); } catch { return null; } };
|
|
29
|
+
const readJson = (root, rel) => { try { return JSON.parse(readText(root, rel)); } catch { return null; } };
|
|
30
|
+
|
|
31
|
+
function loadInstall(root) {
|
|
32
|
+
const pkg = readJson(root, 'package.json');
|
|
33
|
+
if (!pkg || pkg.name !== '@sakaniui/react') return null;
|
|
34
|
+
return { root, version: pkg.version, manifest: readJson(root, 'dist/manifest.json'), icons: readJson(root, 'dist/icon-index.json'), guide: readText(root, 'AGENTS.md'), changelog: readText(root, 'CHANGELOG.md') };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function findProjectInstall() {
|
|
38
|
+
const i = process.argv.indexOf('--project');
|
|
39
|
+
let dir = path.resolve(i > -1 && process.argv[i + 1] ? process.argv[i + 1] : process.cwd());
|
|
40
|
+
for (let depth = 0; depth < 12; depth++) {
|
|
41
|
+
const candidate = path.join(dir, 'node_modules', '@sakaniui', 'react');
|
|
42
|
+
if (fs.existsSync(path.join(candidate, 'package.json'))) return loadInstall(candidate);
|
|
43
|
+
const up = path.dirname(dir);
|
|
44
|
+
if (up === dir) break;
|
|
45
|
+
dir = up;
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// inside @sakaniui/react the data sits next to bin/; inside @sakaniui/mcp it is copied into data/
|
|
51
|
+
const bundled = loadInstall(fs.existsSync(path.join(ownRoot, 'dist', 'manifest.json')) ? ownRoot : path.join(ownRoot, 'data'));
|
|
52
|
+
if (!bundled || !bundled.manifest) {
|
|
53
|
+
process.stderr.write('sakaniui-mcp: dist/manifest.json not found. Run `npm run build:lib` (or install a published version).\n');
|
|
54
|
+
process.exit(1);
|
|
55
|
+
}
|
|
56
|
+
const project = findProjectInstall();
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Answer from the project's own copy when it can (it is what the code will run against) -- but only
|
|
60
|
+
* if its manifest is at least as complete as this one. Older manifest schemas are known to omit
|
|
61
|
+
* things that exist (components, tokens), and "not in the manifest" must mean "does not exist".
|
|
62
|
+
* In that case the newer data is used and checked against the project's version instead.
|
|
63
|
+
*/
|
|
64
|
+
const schemaOf = (i) => (i && i.manifest && Number.isInteger(i.manifest.schemaVersion) ? i.manifest.schemaVersion : 0);
|
|
65
|
+
const active = project && project.manifest && schemaOf(project) >= schemaOf(bundled) ? project : bundled;
|
|
66
|
+
const manifest = active.manifest;
|
|
67
|
+
const guide = active.guide || bundled.guide || '';
|
|
68
|
+
const changelog = active.changelog || bundled.changelog || '';
|
|
69
|
+
const iconIndex = (active.icons && active.icons.icons) || (bundled.icons && bundled.icons.icons) || [];
|
|
70
|
+
const projectVersion = project ? project.version : null;
|
|
71
|
+
|
|
72
|
+
// The HTML attributes React accepts (shipped in the manifest since 0.8.10; older manifests use the fallback list).
|
|
73
|
+
const nativeAttrs = new Set(manifest.nativeAttributes || []);
|
|
74
|
+
const NATIVE = { test: (n) => /^(aria-|data-)/.test(n) || /^on[A-Z]/.test(n) || n === 'key' || n === 'ref' || n === 'children' || (nativeAttrs.size ? nativeAttrs.has(n) : NATIVE_FALLBACK.test(n)) };
|
|
75
|
+
/** What to say about a prop the component does not declare: an error when nothing accepts it, else a note. */
|
|
76
|
+
function unknownProp(c, name) {
|
|
77
|
+
if (NATIVE.test(name)) {
|
|
78
|
+
// a real HTML attribute (placeholder, href, name, defaultChecked...): passed to the element, and fine.
|
|
79
|
+
// `color` is the one people mistake for a styling prop: it does not colour the component.
|
|
80
|
+
return name === 'color' ? { level: 'warning', message: `"color" is not a ${c.name} prop: it is the old HTML colour attribute and does not change the component's colours. Use the component's own props, or design tokens (get_tokens).` } : null;
|
|
81
|
+
}
|
|
82
|
+
// close spellings, plus the usual synonyms (leftIcon -> leadingIcon, onChange vs onValueChange is left to the list)
|
|
83
|
+
const canon = (x) => x.toLowerCase().replace(/left|start|before|prefix/g, 'leading').replace(/right|end|after|suffix/g, 'trailing').replace(/colou?r|tone|kind|type/g, 'variant');
|
|
84
|
+
const near = c.props.map((p) => p.name).filter((p) => similar(p, name) || canon(p) === canon(name));
|
|
85
|
+
return { level: 'error', message: `"${name}" is not a ${c.name} prop${near.length ? ` (did you mean ${near.map((x) => `"${x}"`).join(', ')}?)` : ''}. ${c.name} accepts: ${c.props.map((p) => p.name).join(', ') || 'no props of its own'}.` };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/* ---------- versions ---------- */
|
|
89
|
+
const SEMVER = /^\d+\.\d+\.\d+/;
|
|
90
|
+
const parse = (v) => String(v).split('-')[0].split('.').map(Number);
|
|
91
|
+
const cmp = (a, b) => { const x = parse(a), y = parse(b); for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i]; return 0; };
|
|
92
|
+
|
|
93
|
+
const refVersion = manifest.version;
|
|
94
|
+
const answeringFromProject = active === project;
|
|
95
|
+
|
|
96
|
+
function versionNote(installed = projectVersion) {
|
|
97
|
+
if (answeringFromProject) return null;
|
|
98
|
+
if (!installed) {
|
|
99
|
+
return `The project's installed @sakaniui/react version could not be detected, so this describes ${refVersion}. Confirm it (npm ls @sakaniui/react) and call check_compatibility with installedVersion before suggesting a component.`;
|
|
100
|
+
}
|
|
101
|
+
if (installed !== refVersion) {
|
|
102
|
+
return `The project has @sakaniui/react ${installed} installed; this reference describes ${refVersion}. Entries marked availableInInstalled: false were added after ${installed}. Props can also differ between releases: check get_changelog.`;
|
|
103
|
+
}
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Is this component in the project's install? null = cannot tell. */
|
|
108
|
+
function inInstalled(c, installed = projectVersion) {
|
|
109
|
+
if (!installed || !c.since) return null;
|
|
110
|
+
return cmp(c.since, installed) <= 0;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Is this prop (or this value of it) in the project's install? Returns a message when it is not. */
|
|
114
|
+
function propTooNew(c, p, value, installed = projectVersion) {
|
|
115
|
+
if (!installed) return null;
|
|
116
|
+
if (p.since && cmp(p.since, installed) > 0) return `"${p.name}" was added to ${c.name} in ${p.since}; the project has ${installed}, where it does not exist. Upgrade (npm install @sakaniui/react@latest) or leave it out.`;
|
|
117
|
+
const vs = p.valuesSince && typeof value === 'string' ? p.valuesSince[value] : null;
|
|
118
|
+
if (vs && cmp(vs, installed) > 0) return `${p.name}=${JSON.stringify(value)} was added in ${vs}; the project has ${installed}, where it does not exist.`;
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/* ---------- helpers ---------- */
|
|
123
|
+
const byName = new Map(manifest.components.map((c) => [c.name.toLowerCase(), c]));
|
|
124
|
+
const brief = (c) => {
|
|
125
|
+
const out = { name: c.name, kind: c.kind, category: c.category, import: c.import, since: c.since, summary: c.summary, requiredProps: c.contract.requiredProps };
|
|
126
|
+
if (inInstalled(c) === false) out.availableInInstalled = false;
|
|
127
|
+
return out;
|
|
128
|
+
};
|
|
129
|
+
const text = (obj) => ({ content: [{ type: 'text', text: typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2) }] });
|
|
130
|
+
const fail = (msg) => ({ isError: true, content: [{ type: 'text', text: msg }] });
|
|
131
|
+
|
|
132
|
+
const MAX_STR = 200;
|
|
133
|
+
function strArg(args, key, { required = false } = {}) {
|
|
134
|
+
const v = args[key];
|
|
135
|
+
if (v === undefined || v === null) return required ? { err: `"${key}" is required.` } : { value: undefined };
|
|
136
|
+
if (typeof v !== 'string') return { err: `"${key}" must be a string.` };
|
|
137
|
+
if (v.length > MAX_STR) return { err: `"${key}" is too long (max ${MAX_STR} characters).` };
|
|
138
|
+
return { value: v };
|
|
139
|
+
}
|
|
140
|
+
function enumArg(args, key, allowed) {
|
|
141
|
+
const v = args[key];
|
|
142
|
+
if (v === undefined || v === null) return { value: undefined };
|
|
143
|
+
if (!allowed.includes(v)) return { err: `"${key}" must be one of: ${allowed.join(', ')}.` };
|
|
144
|
+
return { value: v };
|
|
145
|
+
}
|
|
146
|
+
const verArg = (args, key) => {
|
|
147
|
+
const s = strArg(args, key);
|
|
148
|
+
if (s.err || s.value === undefined) return s;
|
|
149
|
+
return SEMVER.test(s.value) ? s : { err: `"${key}" must be a version like 0.8.7.` };
|
|
150
|
+
};
|
|
151
|
+
const firstError = (...rs) => rs.find((r) => r.err);
|
|
152
|
+
|
|
153
|
+
function score(c, terms) {
|
|
154
|
+
const hay = `${c.name} ${c.category ?? ''} ${c.summary} ${c.props.map((p) => p.name).join(' ')}`.toLowerCase();
|
|
155
|
+
let s = 0;
|
|
156
|
+
for (const t of terms) {
|
|
157
|
+
if (c.name.toLowerCase() === t) s += 20;
|
|
158
|
+
else if (c.name.toLowerCase().includes(t)) s += 8;
|
|
159
|
+
if ((c.category ?? '').toLowerCase().includes(t)) s += 3;
|
|
160
|
+
if (c.summary.toLowerCase().includes(t)) s += 3;
|
|
161
|
+
else if (hay.includes(t)) s += 1;
|
|
162
|
+
}
|
|
163
|
+
return s;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function distance(a, b) {
|
|
167
|
+
const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
|
|
168
|
+
for (let j = 1; j <= b.length; j++) d[0][j] = j;
|
|
169
|
+
for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
170
|
+
return d[a.length][b.length];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** `pct` for `percent`, `desc` for `description`: same first letter, every letter in order. */
|
|
174
|
+
function isAbbreviation(short, full) {
|
|
175
|
+
const a = short.toLowerCase(), b = full.toLowerCase();
|
|
176
|
+
if (a.length < 2 || a.length >= b.length || a[0] !== b[0]) return false;
|
|
177
|
+
let i = 0;
|
|
178
|
+
for (const ch of b) if (ch === a[i]) i++;
|
|
179
|
+
return i === a.length;
|
|
180
|
+
}
|
|
181
|
+
const similar = (a, b) => distance(a.toLowerCase(), b.toLowerCase()) <= 2 || isAbbreviation(a, b) || isAbbreviation(b, a);
|
|
182
|
+
|
|
183
|
+
function closest(name) {
|
|
184
|
+
const n = name.toLowerCase();
|
|
185
|
+
return manifest.components
|
|
186
|
+
.map((c) => [c.name.toLowerCase().includes(n) || n.includes(c.name.toLowerCase()) ? 0 : distance(n, c.name.toLowerCase()), c.name])
|
|
187
|
+
.filter(([d]) => d <= 2)
|
|
188
|
+
.sort((a, b) => a[0] - b[0])
|
|
189
|
+
.slice(0, 5)
|
|
190
|
+
.map(([, c]) => c);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/* ---------- icons ---------- */
|
|
194
|
+
const iconNames = new Set();
|
|
195
|
+
for (const i of iconIndex) { iconNames.add(i.name); if (i.filled) iconNames.add(i.filled); }
|
|
196
|
+
const iconOtherExports = new Set(((active.icons && active.icons.other) || (bundled.icons && bundled.icons.other)) || []);
|
|
197
|
+
const iconWords = (name) => name.replace(/^Icon/, '').replace(/Filled$/, '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Za-z])(\d)/g, '$1 $2').toLowerCase();
|
|
198
|
+
|
|
199
|
+
// The conventional icon for common UI intents, ranked first (tags alone rank e.g. IconHttpDelete above IconTrash for "delete").
|
|
200
|
+
const COMMON = {
|
|
201
|
+
delete: ['IconTrash'], remove: ['IconTrash', 'IconX'], trash: ['IconTrash'], bin: ['IconTrash'], edit: ['IconPencil', 'IconEdit'], rename: ['IconPencil'],
|
|
202
|
+
close: ['IconX'], dismiss: ['IconX'], cancel: ['IconX'], add: ['IconPlus'], new: ['IconPlus'], create: ['IconPlus'], plus: ['IconPlus'],
|
|
203
|
+
search: ['IconSearch'], find: ['IconSearch'], settings: ['IconSettings', 'IconAdjustments'], preferences: ['IconSettings'], menu: ['IconMenu2'],
|
|
204
|
+
more: ['IconDots', 'IconDotsVertical'], options: ['IconDots', 'IconDotsVertical'], user: ['IconUser'], profile: ['IconUser', 'IconUserCircle'], account: ['IconUserCircle'],
|
|
205
|
+
home: ['IconHome'], back: ['IconArrowLeft', 'IconChevronLeft'], next: ['IconArrowRight', 'IconChevronRight'], forward: ['IconArrowRight'], previous: ['IconArrowLeft', 'IconChevronLeft'],
|
|
206
|
+
expand: ['IconChevronDown'], collapse: ['IconChevronUp'], dropdown: ['IconChevronDown'], upload: ['IconUpload'], download: ['IconDownload'], share: ['IconShare'],
|
|
207
|
+
copy: ['IconCopy'], duplicate: ['IconCopy'], save: ['IconDeviceFloppy'], filter: ['IconFilter'], sort: ['IconArrowsSort'], calendar: ['IconCalendar'], date: ['IconCalendar'],
|
|
208
|
+
notification: ['IconBell'], notifications: ['IconBell'], bell: ['IconBell'], mail: ['IconMail'], email: ['IconMail'], message: ['IconMessage'], chat: ['IconMessageCircle'],
|
|
209
|
+
phone: ['IconPhone'], call: ['IconPhone'], logout: ['IconLogout'], signout: ['IconLogout'], login: ['IconLogin'], help: ['IconHelpCircle', 'IconHelp'], info: ['IconInfoCircle'],
|
|
210
|
+
warning: ['IconAlertTriangle'], error: ['IconAlertCircle'], success: ['IconCircleCheck'], check: ['IconCheck'], done: ['IconCheck'], favorite: ['IconHeart', 'IconStar'],
|
|
211
|
+
like: ['IconHeart', 'IconThumbUp'], star: ['IconStar'], rating: ['IconStar'], cart: ['IconShoppingCart'], refresh: ['IconRefresh'], reload: ['IconRefresh'], link: ['IconLink'],
|
|
212
|
+
attach: ['IconPaperclip'], attachment: ['IconPaperclip'], lock: ['IconLock'], password: ['IconLock'], view: ['IconEye'], show: ['IconEye'], hide: ['IconEyeOff'],
|
|
213
|
+
play: ['IconPlayerPlay'], pause: ['IconPlayerPause'], stop: ['IconPlayerStop'], theme: ['IconSun', 'IconMoon'], dark: ['IconMoon'], light: ['IconSun'],
|
|
214
|
+
external: ['IconExternalLink'], drag: ['IconGripVertical'], sidebar: ['IconLayoutSidebar'], dashboard: ['IconLayoutDashboard'], analytics: ['IconChartBar'], chart: ['IconChartBar'],
|
|
215
|
+
money: ['IconCurrencyDollar'], payment: ['IconCreditCard'], card: ['IconCreditCard'], location: ['IconMapPin'], time: ['IconClock'], clock: ['IconClock'], file: ['IconFile'],
|
|
216
|
+
folder: ['IconFolder'], image: ['IconPhoto'], photo: ['IconPhoto'], video: ['IconVideo'],
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
function searchIcons(query, limit = 12) {
|
|
220
|
+
const terms = String(query).toLowerCase().replace(/icon/g, ' ').split(/[^a-z0-9]+/).filter(Boolean);
|
|
221
|
+
if (!terms.length) return [];
|
|
222
|
+
const boosted = new Map();
|
|
223
|
+
for (const t of terms) (COMMON[t] || []).forEach((n, k) => boosted.set(n, Math.max(boosted.get(n) || 0, 40 - k * 5)));
|
|
224
|
+
return iconIndex
|
|
225
|
+
.map((i) => {
|
|
226
|
+
const words = iconWords(i.name).split(' ');
|
|
227
|
+
const tags = (i.tags || []).map((t) => t.toLowerCase());
|
|
228
|
+
let s = boosted.get(i.name) || 0;
|
|
229
|
+
for (const t of terms) {
|
|
230
|
+
if (words.join(' ') === t) s += 30;
|
|
231
|
+
else if (words[0] === t) s += 12;
|
|
232
|
+
else if (words.includes(t)) s += 8;
|
|
233
|
+
else if (words.some((w) => w.startsWith(t))) s += 4;
|
|
234
|
+
if (tags.includes(t)) s += 6;
|
|
235
|
+
else if (tags.some((g) => g.includes(t))) s += 2;
|
|
236
|
+
if ((i.category || '').toLowerCase() === t) s += 2;
|
|
237
|
+
}
|
|
238
|
+
return [s - words.length * 0.1, i];
|
|
239
|
+
})
|
|
240
|
+
.filter(([s]) => s > 0.5)
|
|
241
|
+
.sort((a, b) => b[0] - a[0])
|
|
242
|
+
.slice(0, limit)
|
|
243
|
+
.map(([, i]) => i);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Checks a value given for an icon prop. Returns an error string, or null. */
|
|
247
|
+
function iconProblem(propName, raw, importedElsewhere = new Set(), localNames = new Set()) {
|
|
248
|
+
const v = String(raw).trim().replace(/^\{|\}$/g, '').trim();
|
|
249
|
+
if (/^</.test(v)) {
|
|
250
|
+
const tag = (/^<\s*([A-Za-z][\w.]*)/.exec(v) || [])[1] || 'Icon';
|
|
251
|
+
const real = iconNames.has(tag) || importedElsewhere.has(tag) ? tag : (searchIcons(tag, 1)[0] || {}).name;
|
|
252
|
+
const unknown = real && real !== tag ? ` ${tag} is not a SakaniUI icon either.` : '';
|
|
253
|
+
return `"${propName}" takes the icon component itself, not an element: write ${propName}={${real || 'IconName'}}, not ${propName}={<${tag} />}.${unknown}${!real ? ' Use search_icons to find the real name.' : ''}`;
|
|
254
|
+
}
|
|
255
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(v)) return null; // an expression we cannot judge
|
|
256
|
+
if (iconNames.has(v) || importedElsewhere.has(v) || localNames.has(v)) return null;
|
|
257
|
+
// a local name (alias, parameter, constant): the import line was already checked, and we cannot see the rest
|
|
258
|
+
if (!/^Icon[A-Z0-9]/.test(v)) return null;
|
|
259
|
+
const hint = searchIcons(v, 3).map((i) => i.name);
|
|
260
|
+
return `"${v}" is not a SakaniUI icon.${hint.length ? ` Did you mean: ${hint.join(', ')}?` : ''} Use search_icons to find the real name.`;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Attributes every component forwards to its root element. A prop outside this list and the contract is worth a warning.
|
|
264
|
+
const NATIVE_FALLBACK = /^(className|style|id|ref|key|children|role|tabIndex|title|hidden|lang|dir|slot|on[A-Z].*|aria-.*|data-.*|href|target|rel|download|name|type|value|defaultValue|checked|defaultChecked|disabled|required|readOnly|placeholder|htmlFor|form|autoFocus|autoComplete|autoCapitalize|spellCheck|inputMode|pattern|min|max|step|minLength|maxLength|rows|cols|multiple|accept|src|srcSet|alt|width|height|loading|draggable|tabindex|ariaLabel)$/;
|
|
265
|
+
|
|
266
|
+
/** Release notes: [{version, body}] newest first, from the CHANGELOG that matches the answering install. */
|
|
267
|
+
function releases() {
|
|
268
|
+
const parts = changelog.split(/^## (\d+\.\d+\.\d+[^\n]*)\n/m);
|
|
269
|
+
const out = [];
|
|
270
|
+
for (let i = 1; i < parts.length; i += 2) out.push({ version: parts[i].trim(), body: (parts[i + 1] || '').trim() });
|
|
271
|
+
return out.sort((a, b) => cmp(b.version, a.version));
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/* ---------- check_code: a small, read-only JSX scanner (the code is never executed) ---------- */
|
|
275
|
+
/** Line number lookup in O(log n): a precomputed index of line starts per code string. */
|
|
276
|
+
function lineIndex(code) {
|
|
277
|
+
const starts = [0];
|
|
278
|
+
for (let i = 0; i < code.length; i++) if (code.charCodeAt(i) === 10) starts.push(i + 1);
|
|
279
|
+
return (pos) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= pos) lo = mid; else hi = mid - 1; } return lo + 1; };
|
|
280
|
+
}
|
|
281
|
+
let lineAt = (code, i) => code.slice(0, i).split('\n').length;
|
|
282
|
+
|
|
283
|
+
function parseImports(code) {
|
|
284
|
+
const out = [];
|
|
285
|
+
const re = /import\s+(type\s+)?(?:([A-Za-z_$][\w$]*)\s*,?\s*)?(?:\{([^}]*)\})?\s*from\s*['"]([^'"]+)['"]/g;
|
|
286
|
+
let m;
|
|
287
|
+
while ((m = re.exec(code))) {
|
|
288
|
+
const names = (m[3] || '').split(',').map((x) => x.trim()).filter(Boolean).map((x) => {
|
|
289
|
+
const typeOnly = /^type\s+/.test(x);
|
|
290
|
+
const [imported, local] = x.replace(/^type\s+/, '').split(/\s+as\s+/).map((y) => y.trim());
|
|
291
|
+
return { imported, local: local || imported, typeOnly: typeOnly || !!m[1] };
|
|
292
|
+
});
|
|
293
|
+
out.push({ from: m[4], names, line: lineAt(code, m.index), def: m[2] || null });
|
|
294
|
+
}
|
|
295
|
+
return out;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Reads a balanced {...} starting at code[i] === '{'. Returns the index after the closing brace. */
|
|
299
|
+
function skipBraces(code, i) {
|
|
300
|
+
let depth = 0;
|
|
301
|
+
for (; i < code.length; i++) {
|
|
302
|
+
const ch = code[i];
|
|
303
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
304
|
+
const q = ch;
|
|
305
|
+
for (i++; i < code.length && code[i] !== q; i++) if (code[i] === '\\') i++;
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
if (ch === '{') depth++;
|
|
309
|
+
else if (ch === '}') { depth--; if (depth === 0) return i + 1; }
|
|
310
|
+
}
|
|
311
|
+
return code.length;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const ATTR_NAME = /[A-Za-z_][\w:.-]*/y;
|
|
315
|
+
|
|
316
|
+
function parseElements(code, wanted) {
|
|
317
|
+
const els = [];
|
|
318
|
+
const re = /<([A-Z][\w]*(?:\.[A-Z][\w]*)?)(?=[\s/>])/g;
|
|
319
|
+
let m;
|
|
320
|
+
while ((m = re.exec(code))) {
|
|
321
|
+
const tag = m[1];
|
|
322
|
+
if (!wanted(tag)) continue;
|
|
323
|
+
let i = m.index + m[0].length;
|
|
324
|
+
const attrs = [];
|
|
325
|
+
let spread = false;
|
|
326
|
+
let selfClosing = false;
|
|
327
|
+
// every pass must move forward; an unterminated attribute ends the element instead of looping
|
|
328
|
+
for (let guard = 0; i < code.length && guard < 5000; guard++) {
|
|
329
|
+
while (/\s/.test(code[i])) i++;
|
|
330
|
+
if (code[i] === '/' && code[i + 1] === '>') { selfClosing = true; i += 2; break; }
|
|
331
|
+
if (code[i] === '>') { i++; break; }
|
|
332
|
+
if (code[i] === '<') break; // a new tag before this one closed: malformed, stop here
|
|
333
|
+
if (code[i] === '{') { const end = skipBraces(code, i); if (/^\{\s*\.\.\./.test(code.slice(i, end))) spread = true; i = end; continue; }
|
|
334
|
+
ATTR_NAME.lastIndex = i;
|
|
335
|
+
const nm = ATTR_NAME.exec(code);
|
|
336
|
+
if (!nm) { i++; continue; }
|
|
337
|
+
const name = nm[0];
|
|
338
|
+
i += name.length;
|
|
339
|
+
while (/\s/.test(code[i])) i++;
|
|
340
|
+
if (code[i] !== '=') { attrs.push({ name, kind: 'boolean', value: true }); continue; }
|
|
341
|
+
i++;
|
|
342
|
+
while (/\s/.test(code[i])) i++;
|
|
343
|
+
if (code[i] === '"' || code[i] === "'") {
|
|
344
|
+
const q = code[i];
|
|
345
|
+
const end = code.indexOf(q, i + 1);
|
|
346
|
+
if (end === -1) { attrs.push({ name, kind: 'string', value: code.slice(i + 1) }); i = code.length; break; }
|
|
347
|
+
attrs.push({ name, kind: 'string', value: code.slice(i + 1, end) });
|
|
348
|
+
i = end + 1;
|
|
349
|
+
} else if (code[i] === '{') {
|
|
350
|
+
const end = skipBraces(code, i);
|
|
351
|
+
const expr = code.slice(i + 1, end - 1).trim();
|
|
352
|
+
attrs.push({ name, ...classify(expr) });
|
|
353
|
+
i = end;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
els.push({ tag, attrs, spread, selfClosing, line: lineAt(code, m.index) });
|
|
357
|
+
if (els.length >= 5000) break;
|
|
358
|
+
re.lastIndex = Math.max(re.lastIndex, i);
|
|
359
|
+
}
|
|
360
|
+
return els;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function classify(expr) {
|
|
364
|
+
let m;
|
|
365
|
+
if ((m = /^(['"])([\s\S]*)\1$/.exec(expr))) return { kind: 'string', value: m[2], raw: expr };
|
|
366
|
+
if ((m = /^`([^`$]*)`$/.exec(expr))) return { kind: 'string', value: m[1], raw: expr };
|
|
367
|
+
if (/^-?\d+(\.\d+)?$/.test(expr)) return { kind: 'number', value: Number(expr), raw: expr };
|
|
368
|
+
if (expr === 'true' || expr === 'false') return { kind: 'boolean', value: expr === 'true', raw: expr };
|
|
369
|
+
if (/^</.test(expr)) return { kind: 'element', raw: expr };
|
|
370
|
+
if (/^[A-Za-z_$][\w$]*$/.test(expr)) return { kind: 'identifier', value: expr, raw: expr };
|
|
371
|
+
return { kind: 'expression', raw: expr };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const TYPE_LIKE = /(Props|Type|Variant|Size|Item|Option|Datum|Column|Link|Plan|Post|Action|Step|Image|Author|Change|Data|Tab|Color|Category|Job|Member|Testimonial|Transaction)$/;
|
|
375
|
+
|
|
376
|
+
/** Replaces the contents of template literals with spaces (newlines kept): code shown inside a string is not code. */
|
|
377
|
+
function blankTemplates(code) {
|
|
378
|
+
let out = '';
|
|
379
|
+
for (let i = 0; i < code.length; i++) {
|
|
380
|
+
const ch = code[i];
|
|
381
|
+
if (ch === '`') {
|
|
382
|
+
let j = i + 1, depth = 0;
|
|
383
|
+
for (; j < code.length; j++) {
|
|
384
|
+
if (code[j] === '\\') { j++; continue; }
|
|
385
|
+
if (code[j] === '$' && code[j + 1] === '{') { depth++; j++; continue; }
|
|
386
|
+
if (code[j] === '}' && depth > 0) { depth--; continue; }
|
|
387
|
+
if (code[j] === '`' && depth === 0) break;
|
|
388
|
+
}
|
|
389
|
+
out += '`' + code.slice(i + 1, j).replace(/[^\n]/g, ' ') + '`';
|
|
390
|
+
i = j;
|
|
391
|
+
} else out += ch;
|
|
392
|
+
}
|
|
393
|
+
return out;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function checkCode(source) {
|
|
397
|
+
const code = blankTemplates(source);
|
|
398
|
+
lineAt = ((idx) => (_c, pos) => idx(pos))(lineIndex(code));
|
|
399
|
+
const errors = [];
|
|
400
|
+
const warnings = [];
|
|
401
|
+
const imports = parseImports(code);
|
|
402
|
+
const importedFrom = new Map(); // local name -> module
|
|
403
|
+
for (const imp of imports) { for (const n of imp.names) importedFrom.set(n.local, imp.from); if (imp.def) importedFrom.set(imp.def, imp.from); }
|
|
404
|
+
const importedElsewhere = new Set([...importedFrom].filter(([, from]) => !from.startsWith('@sakaniui/react')).map(([n]) => n));
|
|
405
|
+
// anything the snippet declares itself (const Icon = ..., function X, class Y) or aliases: not ours to judge
|
|
406
|
+
const localNames = new Set([...code.matchAll(/\b(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/g)].map((m) => m[1]));
|
|
407
|
+
for (const imp of imports) for (const n of imp.names) if (n.local !== n.imported) localNames.add(n.local);
|
|
408
|
+
|
|
409
|
+
for (const imp of imports) {
|
|
410
|
+
if (!imp.from.startsWith('@sakaniui/react')) continue;
|
|
411
|
+
const entry = imp.from;
|
|
412
|
+
if (!['@sakaniui/react', '@sakaniui/react/blocks', '@sakaniui/react/icons'].includes(entry)) {
|
|
413
|
+
if (imp.names.length) errors.push({ line: imp.line, message: `"${entry}" has no named exports. Import components from @sakaniui/react, blocks from @sakaniui/react/blocks and icons from @sakaniui/react/icons.` });
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
if (imp.def) errors.push({ line: imp.line, message: `${entry} has no default export; use a named import: import { ${imp.def} } from '${entry}';` });
|
|
417
|
+
for (const n of imp.names) {
|
|
418
|
+
if (n.typeOnly) continue;
|
|
419
|
+
const c = byName.get(n.imported.toLowerCase());
|
|
420
|
+
const isUtility = manifest.utilities?.some((u) => u.name === n.imported);
|
|
421
|
+
if (entry === '@sakaniui/react/icons') {
|
|
422
|
+
if (!iconNames.has(n.imported) && !iconOtherExports.has(n.imported)) {
|
|
423
|
+
const hint = searchIcons(n.imported, 3).map((i) => i.name);
|
|
424
|
+
errors.push({ line: imp.line, message: `${n.imported} is not exported by @sakaniui/react/icons.${hint.length ? ` Did you mean: ${hint.join(', ')}?` : ''}` });
|
|
425
|
+
}
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
if (c && c.name !== n.imported) { errors.push({ line: imp.line, message: `${n.imported} has the wrong casing; the export is ${c.name}.` }); continue; }
|
|
429
|
+
if (entry === '@sakaniui/react/blocks') {
|
|
430
|
+
if (!c || c.kind !== 'block') errors.push({ line: imp.line, message: c ? `${n.imported} is a component: import it from @sakaniui/react.` : `${n.imported} is not a SakaniUI block.` });
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
if (c && c.kind === 'block') { errors.push({ line: imp.line, message: `${n.imported} is a block: import it from @sakaniui/react/blocks.` }); continue; }
|
|
434
|
+
if (!c && !isUtility) {
|
|
435
|
+
if (TYPE_LIKE.test(n.imported)) continue; // most likely a type export
|
|
436
|
+
const near = closest(n.imported);
|
|
437
|
+
errors.push({ line: imp.line, message: `${n.imported} is not exported by @sakaniui/react.${near.length ? ` Did you mean: ${near.join(', ')}?` : ''} Use search_components.` });
|
|
438
|
+
}
|
|
439
|
+
if (c && inInstalled(c) === false) errors.push({ line: imp.line, message: `${c.name} was added in ${c.since}; the project has ${projectVersion}.` });
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// elements: anything imported from @sakaniui, plus manifest names used without an import
|
|
444
|
+
const isSakani = (tag) => importedFrom.get(tag)?.startsWith('@sakaniui/react') || (!importedFrom.has(tag) && byName.has(tag.toLowerCase()) && byName.get(tag.toLowerCase()).name === tag);
|
|
445
|
+
const elements = parseElements(code, isSakani);
|
|
446
|
+
for (const el of elements) {
|
|
447
|
+
const c = byName.get(el.tag.toLowerCase());
|
|
448
|
+
if (!c) continue;
|
|
449
|
+
const at = (message) => ({ line: el.line, message: `<${el.tag}>: ${message}` });
|
|
450
|
+
if (inInstalled(c) === false && !importedFrom.has(el.tag)) errors.push(at(`${c.name} was added in ${c.since}; the project has ${projectVersion}, where it does not exist.`));
|
|
451
|
+
if (!importedFrom.has(el.tag)) warnings.push(at(`not imported. Add: import { ${c.name} } from '${c.import}';`));
|
|
452
|
+
const given = new Map(el.attrs.map((a) => [a.name, a]));
|
|
453
|
+
if (!el.selfClosing) given.set('children', { kind: 'expression' });
|
|
454
|
+
for (const r of c.contract.requiredProps) {
|
|
455
|
+
if (given.has(r)) continue;
|
|
456
|
+
if (el.spread) warnings.push(at(`required prop "${r}" is not written out (it may come from the spread).`));
|
|
457
|
+
else errors.push(at(`missing required prop "${r}".`));
|
|
458
|
+
}
|
|
459
|
+
const known = new Map(c.props.map((p) => [p.name, p]));
|
|
460
|
+
for (const a of el.attrs) {
|
|
461
|
+
const p = known.get(a.name);
|
|
462
|
+
if (!p) { const u = unknownProp(c, a.name); if (u) (u.level === 'error' ? errors : warnings).push(at(u.message)); continue; }
|
|
463
|
+
if (p.values && ['string', 'number', 'boolean'].includes(a.kind) && !p.values.includes(a.value)) {
|
|
464
|
+
errors.push(at(`${a.name}=${JSON.stringify(a.value)} is not allowed. Use one of: ${p.values.map((x) => JSON.stringify(x)).join(', ')}.`));
|
|
465
|
+
}
|
|
466
|
+
{ const tooNew = propTooNew(c, p, a.kind === 'string' ? a.value : undefined); if (tooNew) errors.push(at(tooNew)); }
|
|
467
|
+
for (const m of checkShape(c, p, a, new Map(el.attrs.map((x) => [x.name, x])))) errors.push(at(m));
|
|
468
|
+
if (p.type === 'IconComponent') {
|
|
469
|
+
if (a.kind === 'string') errors.push(at(`"${a.name}" takes an icon component, not a string: ${a.name}={IconName}.`));
|
|
470
|
+
else if (a.kind === 'element' || a.kind === 'identifier') {
|
|
471
|
+
const e = iconProblem(a.name, a.raw, importedElsewhere, localNames);
|
|
472
|
+
if (e) errors.push(at(e));
|
|
473
|
+
else if (a.kind === 'identifier' && iconNames.has(a.value) && !importedFrom.has(a.value) && !localNames.has(a.value)) warnings.push(at(`${a.value} is not imported. Add: import { ${a.value} } from '@sakaniui/react/icons';`));
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
if (!elements.length && !imports.some((i) => i.from.startsWith('@sakaniui/react'))) warnings.push({ line: 1, message: 'No SakaniUI imports or elements found in this code.' });
|
|
479
|
+
const out = { ok: errors.length === 0, checkedElements: elements.length, errors, warnings };
|
|
480
|
+
const note = versionNote(); if (note) out.versionNote = note;
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/* ---------- literal shapes: field names inside inline object literals ---------- */
|
|
485
|
+
/** Splits `text` at top-level commas (ignores commas inside brackets, braces, parentheses and strings). */
|
|
486
|
+
function splitTopLevel(text) {
|
|
487
|
+
const parts = [];
|
|
488
|
+
let depth = 0, start = 0, quote = null;
|
|
489
|
+
for (let i = 0; i < text.length && parts.length < 2000; i++) {
|
|
490
|
+
const ch = text[i];
|
|
491
|
+
if (quote) { if (ch === '\\') i++; else if (ch === quote) quote = null; continue; }
|
|
492
|
+
if (ch === '"' || ch === "'" || ch === '`') { quote = ch; continue; }
|
|
493
|
+
if (ch === '{' || ch === '[' || ch === '(') depth++;
|
|
494
|
+
else if (ch === '}' || ch === ']' || ch === ')') depth--;
|
|
495
|
+
else if (ch === ',' && depth === 0) { parts.push(text.slice(start, i)); start = i + 1; }
|
|
496
|
+
}
|
|
497
|
+
parts.push(text.slice(start));
|
|
498
|
+
return parts.map((x) => x.trim()).filter(Boolean);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** The keys written in an object literal `{ a: 1, 'b': 2, c, ...d }`. spread: it also contains `...x`. */
|
|
502
|
+
function objectKeys(literal) {
|
|
503
|
+
const inner = literal.trim().slice(1, -1);
|
|
504
|
+
const keys = []; let spread = false;
|
|
505
|
+
for (const entry of splitTopLevel(inner)) {
|
|
506
|
+
if (entry.startsWith('...')) { spread = true; continue; }
|
|
507
|
+
const m = /^(?:'([^']+)'|"([^"]+)"|([A-Za-z_$][\w$]*))\s*(?::|\(|$)/.exec(entry);
|
|
508
|
+
if (m) keys.push(m[1] || m[2] || m[3]);
|
|
509
|
+
else spread = true; // computed key or something we cannot read: do not judge this object
|
|
510
|
+
}
|
|
511
|
+
return { keys, spread };
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** The object literals in an inline `[ {...}, {...} ]` (or a single `{...}`). Null when it is not an inline literal. */
|
|
515
|
+
function inlineObjects(raw, collection) {
|
|
516
|
+
const t = raw.trim();
|
|
517
|
+
if (collection === 'array') {
|
|
518
|
+
if (!(t.startsWith('[') && t.endsWith(']'))) return null;
|
|
519
|
+
const items = splitTopLevel(t.slice(1, -1));
|
|
520
|
+
if (items.some((x) => !x.startsWith('{') || !x.endsWith('}'))) return items.filter((x) => x.startsWith('{') && x.endsWith('}')).length ? items.filter((x) => x.startsWith('{') && x.endsWith('}')) : null;
|
|
521
|
+
return items;
|
|
522
|
+
}
|
|
523
|
+
return t.startsWith('{') && t.endsWith('}') ? [t] : null;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** Checks inline object literals against the prop's `shape`. Returns messages. */
|
|
527
|
+
function checkShape(c, prop, attr, siblings) {
|
|
528
|
+
const sh = prop.shape;
|
|
529
|
+
if (!sh || attr.kind !== 'expression' || !attr.raw) return [];
|
|
530
|
+
const objs = inlineObjects(attr.raw, sh.collection);
|
|
531
|
+
if (!objs || !objs.length) return [];
|
|
532
|
+
const out = [];
|
|
533
|
+
const known = new Map(sh.fields.map((f) => [f.name, f]));
|
|
534
|
+
const list = sh.fields.map((f) => f.name + (f.required ? '' : '?')).join(', ');
|
|
535
|
+
objs.forEach((lit, idx) => {
|
|
536
|
+
const { keys, spread } = objectKeys(lit);
|
|
537
|
+
const where = sh.collection === 'array' ? `${prop.name}[${idx}]` : prop.name;
|
|
538
|
+
for (const k of keys) {
|
|
539
|
+
if (!known.has(k)) {
|
|
540
|
+
const near = sh.fields.map((f) => f.name).filter((f) => similar(f, k));
|
|
541
|
+
out.push(`${where}: "${k}" is not a field of ${sh.type}${near.length ? ` (did you mean "${near[0]}"?)` : ''}. Fields: ${list}.`);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (!spread) for (const f of sh.fields) if (f.required && !keys.includes(f.name)) out.push(`${where}: missing required field "${f.name}" of ${sh.type}. Fields: ${list}.`);
|
|
545
|
+
});
|
|
546
|
+
// `key: keyof T`: the key must be a field of the rows given next to it (T[] sibling), when both are written inline
|
|
547
|
+
const keyField = sh.fields.find((f) => /^keyof T\b/.test(f.type));
|
|
548
|
+
if (keyField && sh.typeParameters && sh.typeParameters[0] === 'T') {
|
|
549
|
+
const rowsProp = c.props.find((p) => p.type === 'T[]');
|
|
550
|
+
const rowsAttr = rowsProp && siblings.get(rowsProp.name);
|
|
551
|
+
const rowObjs = rowsAttr && rowsAttr.kind === 'expression' ? inlineObjects(rowsAttr.raw || '', 'array') : null;
|
|
552
|
+
if (rowObjs && rowObjs.length) {
|
|
553
|
+
const rowKeys = new Set();
|
|
554
|
+
let rowsOpen = false;
|
|
555
|
+
for (const r of rowObjs) { const o = objectKeys(r); o.keys.forEach((k) => rowKeys.add(k)); if (o.spread) rowsOpen = true; }
|
|
556
|
+
if (!rowsOpen) {
|
|
557
|
+
for (const lit of objs) {
|
|
558
|
+
const kv = new RegExp(`(?:^|[{,\\s])${keyField.name}\\s*:\\s*['"]([^'"]+)['"]`).exec(lit);
|
|
559
|
+
if (kv && !rowKeys.has(kv[1])) out.push(`${prop.name}: ${keyField.name} "${kv[1]}" is not a field of the ${rowsProp.name} (${[...rowKeys].join(', ')}). It must be a key of the row type; for a column that is not data, add an optional field to the row type (see the recipe in get_component ${c.name}).`);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return out;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
568
|
+
|
|
569
|
+
/* ---------- tools ---------- */
|
|
570
|
+
const tools = {
|
|
571
|
+
search_components: {
|
|
572
|
+
description: 'Find SakaniUI components/blocks by what you need (e.g. "date picker", "sidebar navigation", "pricing"). Returns the best matches with import path, the release that added them and required props.',
|
|
573
|
+
inputSchema: { type: 'object', properties: { query: { type: 'string' }, kind: { type: 'string', enum: ['component', 'block'] }, limit: { type: 'number' } }, required: ['query'] },
|
|
574
|
+
run(args) {
|
|
575
|
+
const q = strArg(args, 'query', { required: true }); const k = enumArg(args, 'kind', ['component', 'block']);
|
|
576
|
+
const e = firstError(q, k); if (e) return fail(e.err);
|
|
577
|
+
const limit = Number.isInteger(args.limit) ? Math.min(Math.max(args.limit, 1), 25) : 8;
|
|
578
|
+
const terms = q.value.toLowerCase().split(/\s+/).filter(Boolean);
|
|
579
|
+
const hits = manifest.components
|
|
580
|
+
.filter((c) => !k.value || c.kind === k.value)
|
|
581
|
+
.map((c) => [score(c, terms), c])
|
|
582
|
+
.filter(([s]) => s > 0)
|
|
583
|
+
.sort((a, b) => b[0] - a[0])
|
|
584
|
+
.slice(0, limit)
|
|
585
|
+
.map(([, c]) => brief(c));
|
|
586
|
+
const note = versionNote();
|
|
587
|
+
const body = hits.length ? hits : `No match for "${q.value}". If nothing fits, follow AGENTS.md section 3 ("When nothing fits"): compose from tokens and say so. Try list_components to browse.`;
|
|
588
|
+
return text(note && hits.length ? { versionNote: note, results: hits } : body);
|
|
589
|
+
},
|
|
590
|
+
},
|
|
591
|
+
get_component: {
|
|
592
|
+
description: 'Full contract for one component or block: import path, the release that added it, every prop with type / allowed values / default / required, and the accessible-name rule. Use this before writing JSX.',
|
|
593
|
+
inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
|
|
594
|
+
run(args) {
|
|
595
|
+
const n = strArg(args, 'name', { required: true }); if (n.err) return fail(n.err);
|
|
596
|
+
const c = byName.get(n.value.toLowerCase());
|
|
597
|
+
if (!c) return fail(`No component named "${n.value}". Did you mean: ${closest(n.value).join(', ') || '(none close)'}? Use search_components.`);
|
|
598
|
+
const out = { ...c, note: 'Native HTML attributes (className, style, aria-*, event handlers) are also accepted on the root element.' };
|
|
599
|
+
if (c.props.some((p) => p.shape)) out.shapeNote = 'A prop with a `shape` takes an object (or an array of objects) with exactly those fields; `required` fields must be present. In a generic shape, `keyof T & string` means the value must be a field of your own data type.';
|
|
600
|
+
if (c.recipes && c.recipes.length) out.recipeNote = 'See `recipes`: patterns the types alone do not teach, compiled against this release.';
|
|
601
|
+
if (c.example) out.exampleNote = 'Start from `example`: it is type-checked against this release. Replace the placeholder text and values; keep the prop names and shapes.';
|
|
602
|
+
if (c.props.some((p) => p.type === 'IconComponent')) out.iconNote = 'Icon props take the component itself (icon={IconTrash}), not an element. The example uses IconStar as a placeholder: find the real icon with search_icons.';
|
|
603
|
+
if (inInstalled(c) === false) out.availableInInstalled = false;
|
|
604
|
+
if (projectVersion) {
|
|
605
|
+
out.props = c.props.map((p) => {
|
|
606
|
+
const tooNew = propTooNew(c, p);
|
|
607
|
+
const newerValues = p.valuesSince ? Object.entries(p.valuesSince).filter(([, v]) => cmp(v, projectVersion) > 0).map(([k]) => k) : [];
|
|
608
|
+
if (!tooNew && !newerValues.length) return p;
|
|
609
|
+
const q = { ...p };
|
|
610
|
+
if (tooNew) q.availableInInstalled = false;
|
|
611
|
+
if (newerValues.length) q.valuesNotInInstalled = newerValues;
|
|
612
|
+
return q;
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
const note = versionNote();
|
|
616
|
+
if (note) out.versionNote = note;
|
|
617
|
+
if (inInstalled(c) === false) out.warning = `${c.name} was added in ${c.since} but the project has ${projectVersion}. Do not use it without upgrading (npm install @sakaniui/react@latest).`;
|
|
618
|
+
return text(out);
|
|
619
|
+
},
|
|
620
|
+
},
|
|
621
|
+
list_components: {
|
|
622
|
+
description: 'List all components and blocks (name + one-line summary), optionally filtered by kind or category (e.g. Forms, Core, Marketing).',
|
|
623
|
+
inputSchema: { type: 'object', properties: { kind: { type: 'string', enum: ['component', 'block'] }, category: { type: 'string' } } },
|
|
624
|
+
run(args) {
|
|
625
|
+
const k = enumArg(args, 'kind', ['component', 'block']); const cat = strArg(args, 'category');
|
|
626
|
+
const e = firstError(k, cat); if (e) return fail(e.err);
|
|
627
|
+
const list = manifest.components
|
|
628
|
+
.filter((c) => (!k.value || c.kind === k.value) && (!cat.value || (c.category ?? '').toLowerCase().includes(cat.value.toLowerCase())))
|
|
629
|
+
.map((c) => { const o = { name: c.name, kind: c.kind, category: c.category, since: c.since, summary: c.summary }; if (inInstalled(c) === false) o.availableInInstalled = false; return o; });
|
|
630
|
+
const categories = [...new Set(manifest.components.map((c) => c.category).filter(Boolean))].sort();
|
|
631
|
+
const out = { version: refVersion, count: list.length, categories, components: list };
|
|
632
|
+
const note = versionNote(); if (note) out.versionNote = note;
|
|
633
|
+
return text(out);
|
|
634
|
+
},
|
|
635
|
+
},
|
|
636
|
+
get_tokens: {
|
|
637
|
+
description: 'Design tokens (CSS custom properties). Pass a group (color, space, radius, shadow, font, motion, glass, surface, liquid, ...) and/or a substring to filter. Only these tokens exist.',
|
|
638
|
+
inputSchema: { type: 'object', properties: { group: { type: 'string' }, query: { type: 'string' } } },
|
|
639
|
+
run(args) {
|
|
640
|
+
const g = strArg(args, 'group'); const q = strArg(args, 'query');
|
|
641
|
+
const e = firstError(g, q); if (e) return fail(e.err);
|
|
642
|
+
const groups = manifest.tokens.groups;
|
|
643
|
+
if (g.value && !Object.hasOwn(groups, g.value)) return fail(`Unknown token group "${g.value}". Groups: ${Object.keys(groups).join(', ')}`);
|
|
644
|
+
const needle = q.value?.toLowerCase();
|
|
645
|
+
const out = {};
|
|
646
|
+
for (const [name, toks] of Object.entries(groups)) {
|
|
647
|
+
if (g.value && name !== g.value) continue;
|
|
648
|
+
const sel = Object.entries(toks).filter(([k, v]) => !needle || k.includes(needle) || String(v).toLowerCase().includes(needle));
|
|
649
|
+
if (sel.length) out[name] = Object.fromEntries(sel);
|
|
650
|
+
}
|
|
651
|
+
return text(Object.keys(out).length ? out : `No tokens match. Groups: ${Object.keys(groups).join(', ')}`);
|
|
652
|
+
},
|
|
653
|
+
},
|
|
654
|
+
check_usage: {
|
|
655
|
+
description: 'Validate props you are about to use against the contract: reports missing required props, values outside an enum, props that do not exist, and components the project\'s installed version does not have. Run it on each component you write.',
|
|
656
|
+
inputSchema: { type: 'object', properties: { component: { type: 'string' }, props: { type: 'object', description: 'prop name -> value (use true/false/numbers/strings; for non-literal values pass any placeholder)' } }, required: ['component'] },
|
|
657
|
+
run(args) {
|
|
658
|
+
const n = strArg(args, 'component', { required: true }); if (n.err) return fail(n.err);
|
|
659
|
+
const props = args.props === undefined || args.props === null ? {} : args.props;
|
|
660
|
+
if (typeof props !== 'object' || Array.isArray(props)) return fail('"props" must be an object of prop name -> value.');
|
|
661
|
+
if (Object.keys(props).length > 200) return fail('"props" has too many entries (max 200).');
|
|
662
|
+
const c = byName.get(n.value.toLowerCase());
|
|
663
|
+
if (!c) return fail(`No component named "${n.value}". Did you mean: ${closest(n.value).join(', ') || '(none close)'}?`);
|
|
664
|
+
const known = new Map(c.props.map((p) => [p.name, p]));
|
|
665
|
+
const errors = [];
|
|
666
|
+
const warnings = [];
|
|
667
|
+
if (inInstalled(c) === false) errors.push(`${c.name} was added in ${c.since}; the project has ${projectVersion}. It does not exist there.`);
|
|
668
|
+
for (const r of c.contract.requiredProps) if (!Object.hasOwn(props, r)) errors.push(`Missing required prop "${r}".`);
|
|
669
|
+
for (const [k, v] of Object.entries(props)) {
|
|
670
|
+
const p = known.get(k);
|
|
671
|
+
if (!p) { const u = unknownProp(c, k); if (u) (u.level === 'error' ? errors : warnings).push(u.message); continue; }
|
|
672
|
+
if (p.values && (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') && !p.values.includes(v)) {
|
|
673
|
+
errors.push(`"${k}" = ${JSON.stringify(v)} is not allowed. Use one of: ${p.values.map((x) => JSON.stringify(x)).join(', ')}.`);
|
|
674
|
+
}
|
|
675
|
+
if (p.type === 'IconComponent' && typeof v === 'string') { const e = iconProblem(k, v); if (e) errors.push(e); }
|
|
676
|
+
const tooNew = propTooNew(c, p, v); if (tooNew) errors.push(tooNew);
|
|
677
|
+
}
|
|
678
|
+
if (c.contract.requiresAccessibleName && !errors.length) warnings.push('This control has no visible text of its own: keep its accessible-name prop set.');
|
|
679
|
+
const out = { component: c.name, ok: errors.length === 0, errors, warnings };
|
|
680
|
+
const note = versionNote(); if (note) out.versionNote = note;
|
|
681
|
+
return text(out);
|
|
682
|
+
},
|
|
683
|
+
},
|
|
684
|
+
check_compatibility: {
|
|
685
|
+
description: 'Compare the version this reference describes with the version installed in the project, and list what the project does not have yet. Call this first when you cannot tell which @sakaniui/react version the project uses (pass installedVersion, from `npm ls @sakaniui/react` or package.json).',
|
|
686
|
+
inputSchema: { type: 'object', properties: { installedVersion: { type: 'string', description: 'e.g. 0.7.0' } } },
|
|
687
|
+
run(args) {
|
|
688
|
+
const v = verArg(args, 'installedVersion'); if (v.err) return fail(v.err.err);
|
|
689
|
+
const installed = v.value ? v.value.match(SEMVER)[0] : projectVersion;
|
|
690
|
+
const source = v.value ? 'provided' : projectVersion ? 'detected' : 'unknown';
|
|
691
|
+
if (!installed) {
|
|
692
|
+
return text({ reference: refVersion, installed: null, source, advice: 'The project version is unknown. Run `npm ls @sakaniui/react`, then call this tool again with installedVersion.' });
|
|
693
|
+
}
|
|
694
|
+
const missing = manifest.components.filter((c) => c.since && cmp(c.since, installed) > 0).map((c) => ({ name: c.name, since: c.since }));
|
|
695
|
+
const newer = releases().filter((r) => cmp(r.version, installed) > 0).map((r) => r.version);
|
|
696
|
+
const relation = cmp(installed, refVersion) === 0 ? 'same' : cmp(installed, refVersion) < 0 ? 'project is older' : 'project is newer than this reference';
|
|
697
|
+
const advice = relation === 'same' ? 'The reference matches the installed version.'
|
|
698
|
+
: relation === 'project is older' ? `Do not suggest the components listed under missingInInstalled, and check get_changelog (since ${installed}) before relying on newer props. Or upgrade: npm install @sakaniui/react@latest.`
|
|
699
|
+
: 'The project has a newer release than this reference. Run the server from the project root (or pass --project) so it answers from the installed copy.';
|
|
700
|
+
return text({ reference: refVersion, installed, source, relation, missingInInstalled: missing, releasesAfterInstalled: newer, advice });
|
|
701
|
+
},
|
|
702
|
+
},
|
|
703
|
+
get_changelog: {
|
|
704
|
+
description: 'Release notes that match a version. With `version`: that release. With `since`: every release after it, up to the version this reference describes. With neither: the releases between the project\'s installed version and this reference (or the latest release when they match or the project version is unknown).',
|
|
705
|
+
inputSchema: { type: 'object', properties: { version: { type: 'string' }, since: { type: 'string' } } },
|
|
706
|
+
run(args) {
|
|
707
|
+
const ver = verArg(args, 'version'); const since = verArg(args, 'since');
|
|
708
|
+
const e = firstError(ver, since); if (e) return fail(e.err);
|
|
709
|
+
const all = releases();
|
|
710
|
+
if (!all.length) return fail('No release notes are bundled with this install.');
|
|
711
|
+
let pick;
|
|
712
|
+
if (ver.value) {
|
|
713
|
+
pick = all.filter((r) => cmp(r.version, ver.value) === 0 && r.version.startsWith(ver.value.match(SEMVER)[0]));
|
|
714
|
+
if (!pick.length) return fail(`No release notes for ${ver.value}. Releases: ${all.map((r) => r.version).join(', ')}`);
|
|
715
|
+
} else {
|
|
716
|
+
const from = since.value ?? (projectVersion && cmp(projectVersion, refVersion) < 0 ? projectVersion : null);
|
|
717
|
+
pick = from ? all.filter((r) => cmp(r.version, from) > 0 && cmp(r.version, refVersion) <= 0) : all.slice(0, 1);
|
|
718
|
+
if (!pick.length) return text(`No releases after ${from}. This reference describes ${refVersion}.`);
|
|
719
|
+
}
|
|
720
|
+
return text(pick.map((r) => `## ${r.version}\n\n${r.body}`).join('\n\n'));
|
|
721
|
+
},
|
|
722
|
+
},
|
|
723
|
+
search_icons: {
|
|
724
|
+
description: 'Find real icon names (Tabler set, exported from @sakaniui/react/icons) by meaning, e.g. "delete", "settings", "arrow right". Never guess an icon name: only names returned here exist.',
|
|
725
|
+
inputSchema: { type: 'object', properties: { query: { type: 'string' }, limit: { type: 'number' } }, required: ['query'] },
|
|
726
|
+
run(args) {
|
|
727
|
+
const q = strArg(args, 'query', { required: true }); if (q.err) return fail(q.err);
|
|
728
|
+
if (!iconIndex.length) return fail('The icon index is not available in this install.');
|
|
729
|
+
const limit = Number.isInteger(args.limit) ? Math.min(Math.max(args.limit, 1), 30) : 12;
|
|
730
|
+
const hits = searchIcons(q.value, limit).map((i) => { const o = { name: i.name }; if (i.filled) o.filled = i.filled; if (i.category) o.category = i.category; if (i.tags) o.tags = i.tags.slice(0, 5); return o; });
|
|
731
|
+
if (!hits.length) return text(`No icon matches "${q.value}". Try a simpler word (e.g. "delete" rather than "remove item").`);
|
|
732
|
+
return text({ import: "import { IconName } from '@sakaniui/react/icons';", usage: 'icon={IconName} (the component, not <IconName />)', icons: hits });
|
|
733
|
+
},
|
|
734
|
+
},
|
|
735
|
+
check_code: {
|
|
736
|
+
description: 'Check a JSX/TSX snippet you wrote: imports from @sakaniui/react (and /blocks, /icons) must exist, every SakaniUI element must have its required props, prop values must be allowed, and icon props must be real icon components passed as components. The code is only read, never run. Run it on every snippet before you answer.',
|
|
737
|
+
inputSchema: { type: 'object', properties: { code: { type: 'string', description: 'The snippet, including its import lines.' } }, required: ['code'] },
|
|
738
|
+
run(args) {
|
|
739
|
+
const code = args.code;
|
|
740
|
+
if (typeof code !== 'string' || !code.trim()) return fail('"code" must be a non-empty string.');
|
|
741
|
+
if (code.length > 50000) return fail('"code" is too long (max 50,000 characters).');
|
|
742
|
+
return text(checkCode(code));
|
|
743
|
+
},
|
|
744
|
+
},
|
|
745
|
+
get_guide: {
|
|
746
|
+
description: 'The AGENTS.md guide (principles, token rules, when nothing fits, glass, icons, per-component "why / when not to use", checklist). Pass a section number or heading text to get just that section; omit for the section list.',
|
|
747
|
+
inputSchema: { type: 'object', properties: { section: { type: 'string', description: 'A section number ("3") or words from its heading ("icons").' } } },
|
|
748
|
+
run(args) {
|
|
749
|
+
// agents sometimes call it with `query`; treat that as the section
|
|
750
|
+
const s0 = strArg(args.section === undefined && args.query !== undefined ? { section: args.query } : args, 'section'); if (s0.err) return fail(s0.err);
|
|
751
|
+
if (!guide) return fail('AGENTS.md is not available in this install.');
|
|
752
|
+
const parts = guide.split(/^(?=## )/m).filter((p) => p.startsWith('## '));
|
|
753
|
+
const heads = parts.map((p) => p.split('\n')[0].replace(/^## /, ''));
|
|
754
|
+
if (!s0.value) return text({ version: refVersion, sections: heads, hint: 'Call again with a number (e.g. "5") or heading text.' });
|
|
755
|
+
const s = s0.value.toLowerCase().trim();
|
|
756
|
+
const hit = parts.filter((p) => { const h = p.split('\n')[0].replace(/^## /, '').toLowerCase(); return h === s || h.startsWith(s + '.') || h.startsWith(s + ' ') || h.includes(s); });
|
|
757
|
+
return hit.length ? text(hit.join('\n')) : fail(`No section "${s0.value}". Sections: ${heads.join(' | ')}`);
|
|
758
|
+
},
|
|
759
|
+
},
|
|
760
|
+
};
|
|
761
|
+
|
|
762
|
+
/* ---------- JSON-RPC over stdio ---------- */
|
|
763
|
+
// Protocol versions this server implements; the client's is used when it is one of them.
|
|
764
|
+
const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
765
|
+
|
|
766
|
+
let stdoutClosed = false;
|
|
767
|
+
process.stdout.on('error', () => { stdoutClosed = true; process.exit(0); }); // the client went away (EPIPE)
|
|
768
|
+
const write = (payload) => { if (!stdoutClosed) process.stdout.write(JSON.stringify(payload) + '\n'); };
|
|
769
|
+
const reply = (id, body) => ({ jsonrpc: '2.0', id, ...body });
|
|
770
|
+
|
|
771
|
+
/** Handles one message. Returns the response, or null for notifications. */
|
|
772
|
+
function handle(msg) {
|
|
773
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return reply(null, { error: { code: -32600, message: 'Invalid request' } });
|
|
774
|
+
const { id, method, params } = msg;
|
|
775
|
+
const isRequest = id !== undefined && id !== null;
|
|
776
|
+
if (typeof method !== 'string') return isRequest ? reply(id, { error: { code: -32600, message: 'Invalid request: method must be a string' } }) : null;
|
|
777
|
+
if (!isRequest) return null; // notifications (initialized, cancelled, ...) need no answer
|
|
778
|
+
try {
|
|
779
|
+
switch (method) {
|
|
780
|
+
case 'initialize': {
|
|
781
|
+
const note = versionNote();
|
|
782
|
+
const asked = params && typeof params.protocolVersion === 'string' ? params.protocolVersion : null;
|
|
783
|
+
return reply(id, { result: {
|
|
784
|
+
protocolVersion: asked && PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
|
|
785
|
+
capabilities: { tools: { listChanged: false } },
|
|
786
|
+
serverInfo: { name: 'sakaniui', title: 'SakaniUI', version: refVersion },
|
|
787
|
+
instructions: `SakaniUI ${refVersion}${projectVersion ? ` (project has ${projectVersion})` : ''}. Read-only reference. Look components up with search_components / get_component and start from their \`example\`; find icon names with search_icons (never guess them); run check_code on every snippet before you answer; style anything beyond props with the design tokens from get_tokens (CSS variables), not hard-coded colours or utility classes the project may not have; read get_guide when nothing fits.${note ? ` ${note}` : ''}`,
|
|
788
|
+
} });
|
|
789
|
+
}
|
|
790
|
+
case 'ping':
|
|
791
|
+
return reply(id, { result: {} });
|
|
792
|
+
case 'tools/list':
|
|
793
|
+
return reply(id, { result: { tools: Object.entries(tools).map(([name, t]) => ({ name, description: t.description, inputSchema: t.inputSchema, annotations: READ_ONLY })) } });
|
|
794
|
+
case 'tools/call': {
|
|
795
|
+
const t = typeof params?.name === 'string' && Object.hasOwn(tools, params.name) ? tools[params.name] : null;
|
|
796
|
+
if (!t) return reply(id, { error: { code: -32602, message: `Unknown tool: ${String(params?.name).slice(0, 60)}` } });
|
|
797
|
+
const args = params.arguments;
|
|
798
|
+
if (args !== undefined && args !== null && (typeof args !== 'object' || Array.isArray(args))) return reply(id, { result: fail('Tool arguments must be an object.') });
|
|
799
|
+
return reply(id, { result: t.run(args || {}) });
|
|
800
|
+
}
|
|
801
|
+
// Some clients ask for these even when only tools are offered; an empty list is the polite answer.
|
|
802
|
+
case 'resources/list': return reply(id, { result: { resources: [] } });
|
|
803
|
+
case 'resources/templates/list': return reply(id, { result: { resourceTemplates: [] } });
|
|
804
|
+
case 'prompts/list': return reply(id, { result: { prompts: [] } });
|
|
805
|
+
case 'logging/setLevel': return reply(id, { result: {} });
|
|
806
|
+
default:
|
|
807
|
+
return reply(id, { error: { code: -32601, message: `Method not found: ${method.slice(0, 60)}` } });
|
|
808
|
+
}
|
|
809
|
+
} catch (e) {
|
|
810
|
+
return reply(id, { error: { code: -32603, message: String(e?.message || e) } });
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
815
|
+
rl.on('line', (line) => {
|
|
816
|
+
if (!line.trim()) return;
|
|
817
|
+
let msg;
|
|
818
|
+
try { msg = JSON.parse(line); } catch { return write(reply(null, { error: { code: -32700, message: 'Parse error' } })); }
|
|
819
|
+
if (Array.isArray(msg)) { // a batch (older protocol versions): answer with one array
|
|
820
|
+
if (!msg.length) return write(reply(null, { error: { code: -32600, message: 'Invalid request: empty batch' } }));
|
|
821
|
+
const out = msg.map(handle).filter(Boolean);
|
|
822
|
+
if (out.length) write(out);
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
const r = handle(msg);
|
|
826
|
+
if (r) write(r);
|
|
827
|
+
});
|
|
828
|
+
// the editor closed the connection: exit instead of lingering as an orphan process
|
|
829
|
+
// (flush first: on macOS and Windows, writes to a pipe are asynchronous)
|
|
830
|
+
rl.on('close', () => { if (stdoutClosed) process.exit(0); else process.stdout.write('', () => process.exit(0)); });
|