@min98/ui 1.3.57 → 1.3.58

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/lib/cli.mjs ADDED
@@ -0,0 +1,503 @@
1
+ #!/usr/bin/env node
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import {
8
+ callTool,
9
+ startHttpServer,
10
+ startStdioServer,
11
+ } from "./min98-ui-mcp.mjs";
12
+
13
+ const DEFAULT_ORIGIN = "https://ui.min-services.com";
14
+ const SAFE_ORIGIN_RE = /^https?:\/\/[a-zA-Z0-9.-]+(:\d{1,5})?$/;
15
+ const CLI_DIR = path.dirname(fileURLToPath(import.meta.url));
16
+
17
+ const FALLBACK_SKILL_MD = `---
18
+ name: min98-ui
19
+ description: "Build React and Next.js interfaces using @min98/ui (90 components) with Tailwind CSS v4 CSS-first tokens, 15 semantic colors, 12 sizes, RHF+Zod form controls, TanStack DataTable, CodeBlock, Trace, MessageScroller, and Questionnaire. Use when building UI in a project using @min98/ui or @iconify/react."
20
+ origin: "@min98/ui"
21
+ ---
22
+
23
+ # @min98/ui Frontend Development Skill
24
+
25
+ Use this skill whenever implementing, refactoring, or reviewing UI components in React / Next.js projects powered by \`@min98/ui\`.
26
+
27
+ ## Core Rules
28
+
29
+ 1. **Import Exclusively from \`@min98/ui\` & \`@iconify/react\`**:
30
+ - Always import UI primitives from \`"@min98/ui"\` — NEVER scaffold duplicate \`src/components/ui/\` files.
31
+ - Use \`<Icon icon="lucide:..." className="size-4" />\` from \`@iconify/react\` (or \`AppIcon\` from \`@min98/ui\`) for all icons.
32
+ 2. **Tailwind CSS v4 Only (CSS-First Configuration)**:
33
+ - Never create legacy Tailwind v3 \`tailwind.config.js\` / \`tailwind.config.ts\` files.
34
+ - Import \`@import "@min98/ui/styles.css";\` after \`@import "tailwindcss";\` in \`src/app/globals.css\`.
35
+ `;
36
+
37
+ function printHelp() {
38
+ console.log(`@min98/ui CLI — MCP Server + MCP CLI + Agent Setup
39
+
40
+ Usage:
41
+ npx @min98/ui@latest <command> [options]
42
+
43
+ Setup & MCP Server Commands:
44
+ setup [options] Install Skill, ~/.min98-ui/mcp & auto-configure AI Agents
45
+ mcp [--stdio | --http] Run MCP Server (Stdio default, or Streamable HTTP --port 3333)
46
+
47
+ MCP CLI Commands (Direct Terminal Tool Access):
48
+ list [category] [--colors] [--variants] [--json]
49
+ Call min98_ui_list_components (all or filtered by category)
50
+ get <slug> [--json] Call min98_ui_get_component (Markdown API docs + JSX example)
51
+ search <query> [--limit N] [--json]
52
+ Call min98_ui_search_components
53
+ guide [topic] [--json] Call min98_ui_get_setup_guide (all|tailwind-v4|colors-sizes|forms|datatable)
54
+ skill [--json] Call min98_ui_get_skill_markdown
55
+ tool <name> [json_args] [--json]
56
+ Invoke any MCP tool directly by exact name
57
+
58
+ Setup Options:
59
+ --http Register Streamable HTTP MCP (/api/mcp) [default in setup]
60
+ --stdio Register local offline Node.js stdio MCP (~/.min98-ui/mcp/min98-ui-mcp.mjs)
61
+ --url <origin> Override docs server origin (default: ${DEFAULT_ORIGIN})
62
+ --client <list> Comma-separated: antigravity,claude,cursor,windsurf,agents,all
63
+ --all Force install skills and MCP config for all supported clients
64
+ --skill-only Only install SKILL.md and references/components-catalog.md
65
+ --mcp-only Only install offline MCP runtime and register min98-ui-docs
66
+ --dry-run Preview planned changes without writing files
67
+ --uninstall Remove min98-ui skill folders, ~/.min98-ui/mcp & MCP entries
68
+ -h, --help Show this help message
69
+ `);
70
+ }
71
+
72
+ function parseSetupArgs(argv) {
73
+ const opts = {
74
+ mode: "http",
75
+ origin: DEFAULT_ORIGIN,
76
+ clients: [],
77
+ all: false,
78
+ skillOnly: false,
79
+ mcpOnly: false,
80
+ dryRun: false,
81
+ uninstall: false,
82
+ help: false,
83
+ };
84
+
85
+ for (let i = 0; i < argv.length; i += 1) {
86
+ const arg = argv[i];
87
+ if (arg === "-h" || arg === "--help") { opts.help = true; continue; }
88
+ if (arg === "--http") { opts.mode = "http"; continue; }
89
+ if (arg === "--stdio") { opts.mode = "stdio"; continue; }
90
+ if (arg === "--all") { opts.all = true; continue; }
91
+ if (arg === "--skill-only") { opts.skillOnly = true; continue; }
92
+ if (arg === "--mcp-only") { opts.mcpOnly = true; continue; }
93
+ if (arg === "--dry-run") { opts.dryRun = true; continue; }
94
+ if (arg === "--uninstall") { opts.uninstall = true; continue; }
95
+ if (arg === "--url" && argv[i + 1]) {
96
+ opts.origin = argv[++i].replace(/\/+$/, "");
97
+ continue;
98
+ }
99
+ if (arg.startsWith("--url=")) {
100
+ opts.origin = arg.slice(6).replace(/\/+$/, "");
101
+ continue;
102
+ }
103
+ if ((arg === "--client" || arg === "--clients") && argv[i + 1]) {
104
+ opts.clients.push(...argv[++i].split(",").map((s) => s.trim().toLowerCase()).filter(Boolean));
105
+ continue;
106
+ }
107
+ if (arg.startsWith("--client=") || arg.startsWith("--clients=")) {
108
+ const val = arg.slice(arg.indexOf("=") + 1);
109
+ opts.clients.push(...val.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean));
110
+ continue;
111
+ }
112
+ }
113
+
114
+ if (opts.clients.includes("all")) {
115
+ opts.all = true;
116
+ }
117
+ return opts;
118
+ }
119
+
120
+ function ensureDir(dirPath, dryRun) {
121
+ if (dryRun || fs.existsSync(dirPath)) return;
122
+ fs.mkdirSync(dirPath, { recursive: true });
123
+ }
124
+
125
+ function backupFile(filePath, rawBytes) {
126
+ const primary = `${filePath}.min98-ui.backup`;
127
+ if (!fs.existsSync(primary)) {
128
+ fs.writeFileSync(primary, rawBytes, "utf8");
129
+ return primary;
130
+ }
131
+ if (fs.readFileSync(primary, "utf8") === rawBytes) {
132
+ return primary;
133
+ }
134
+ const hash = crypto.createHash("sha256").update(rawBytes).digest("hex").slice(0, 12);
135
+ const recovery = `${filePath}.min98-ui.${hash}.recovery`;
136
+ if (!fs.existsSync(recovery)) {
137
+ fs.writeFileSync(recovery, rawBytes, "utf8");
138
+ }
139
+ return recovery;
140
+ }
141
+
142
+ function loadBundledCatalog() {
143
+ const catalogFile = path.join(CLI_DIR, "min98-ui-catalog.json");
144
+ if (!fs.existsSync(catalogFile)) return null;
145
+ try {
146
+ return JSON.parse(fs.readFileSync(catalogFile, "utf8"));
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ async function fetchMarkdownDoc(url, kind) {
153
+ try {
154
+ const res = await fetch(url, { headers: { Accept: "text/markdown, text/plain" } });
155
+ if (!res.ok) return null;
156
+ const text = await res.text();
157
+ const trimmed = text.trimStart();
158
+ if (trimmed.startsWith("<!") || trimmed.startsWith("<html")) return null;
159
+ if (kind === "skill" && !trimmed.startsWith("---")) return null;
160
+ if (kind === "catalog" && !trimmed.startsWith("#")) return null;
161
+ return text;
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+
167
+ async function resolveSkillDocs(origin, dryRun, uninstall) {
168
+ const bundled = loadBundledCatalog();
169
+ const bundledSkill = typeof bundled?.skillMd === "string" && bundled.skillMd.trimStart().startsWith("---")
170
+ ? bundled.skillMd
171
+ : FALLBACK_SKILL_MD;
172
+ const bundledCatalog = typeof bundled?.llmsFullTxt === "string" && bundled.llmsFullTxt.trimStart().startsWith("#")
173
+ ? bundled.llmsFullTxt
174
+ : null;
175
+
176
+ if (dryRun || uninstall) {
177
+ return { skillMd: bundledSkill, catalogMd: bundledCatalog, source: "dry-run" };
178
+ }
179
+
180
+ const skillUrl = `${origin}/.well-known/skills/min98-ui/SKILL.md`;
181
+ const catalogUrl = `${origin}/.well-known/skills/min98-ui/references/components-catalog.md`;
182
+ const [remoteSkill, remoteCatalog] = await Promise.all([
183
+ fetchMarkdownDoc(skillUrl, "skill"),
184
+ fetchMarkdownDoc(catalogUrl, "catalog"),
185
+ ]);
186
+
187
+ return {
188
+ skillMd: remoteSkill ?? bundledSkill,
189
+ catalogMd: remoteCatalog ?? bundledCatalog,
190
+ source: remoteSkill ? origin : bundled ? "bundled-catalog" : "built-in-fallback",
191
+ };
192
+ }
193
+
194
+ function writeSkillTarget(targetDir, docs, dryRun, uninstall) {
195
+ if (uninstall) {
196
+ if (!fs.existsSync(targetDir)) return { status: "skipped", path: targetDir };
197
+ if (!dryRun) fs.rmSync(targetDir, { recursive: true, force: true });
198
+ return { status: dryRun ? "would-remove" : "removed", path: targetDir };
199
+ }
200
+ const refDir = path.join(targetDir, "references");
201
+ ensureDir(refDir, dryRun);
202
+ if (!dryRun) {
203
+ fs.writeFileSync(path.join(targetDir, "SKILL.md"), docs.skillMd, "utf8");
204
+ if (docs.catalogMd) {
205
+ fs.writeFileSync(path.join(refDir, "components-catalog.md"), docs.catalogMd, "utf8");
206
+ }
207
+ }
208
+ return { status: dryRun ? "would-install" : "installed", path: targetDir };
209
+ }
210
+
211
+ function installOfflineMcpRuntime(home, dryRun, uninstall) {
212
+ const runtimeDir = path.join(home, ".min98-ui", "mcp");
213
+ const scriptDest = path.join(runtimeDir, "min98-ui-mcp.mjs");
214
+ const catalogDest = path.join(runtimeDir, "min98-ui-catalog.json");
215
+
216
+ if (uninstall) {
217
+ if (!fs.existsSync(runtimeDir)) return { scriptPath: scriptDest, status: "skipped" };
218
+ if (!dryRun) fs.rmSync(runtimeDir, { recursive: true, force: true });
219
+ return { scriptPath: scriptDest, status: dryRun ? "would-remove" : "removed" };
220
+ }
221
+
222
+ const scriptSrc = path.join(CLI_DIR, "min98-ui-mcp.mjs");
223
+ const catalogSrc = path.join(CLI_DIR, "min98-ui-catalog.json");
224
+ if (!fs.existsSync(scriptSrc) || !fs.existsSync(catalogSrc)) {
225
+ return { scriptPath: scriptDest, status: "bundled-assets-missing" };
226
+ }
227
+
228
+ ensureDir(runtimeDir, dryRun);
229
+ if (!dryRun) {
230
+ fs.copyFileSync(scriptSrc, scriptDest);
231
+ fs.copyFileSync(catalogSrc, catalogDest);
232
+ }
233
+ return { scriptPath: scriptDest, status: dryRun ? "would-install" : "installed" };
234
+ }
235
+
236
+ function buildServerEntry(clientId, mode, origin, offlineScriptPath) {
237
+ if (mode === "stdio") {
238
+ if (clientId === "claude") return { type: "stdio", command: process.execPath, args: [offlineScriptPath] };
239
+ return { command: process.execPath, args: [offlineScriptPath] };
240
+ }
241
+ const httpUrl = `${origin}/api/mcp`;
242
+ if (clientId === "claude") return { type: "http", url: httpUrl };
243
+ if (clientId === "cursor") return { url: httpUrl };
244
+ return { serverUrl: httpUrl };
245
+ }
246
+
247
+ function updateMcpConfig(target, mode, origin, offlineScriptPath, dryRun, uninstall) {
248
+ const exists = fs.existsSync(target.configPath);
249
+ let doc = {};
250
+ let raw = "";
251
+
252
+ if (exists) {
253
+ raw = fs.readFileSync(target.configPath, "utf8");
254
+ const trimmed = raw.trim();
255
+ if (trimmed) {
256
+ try {
257
+ const parsed = JSON.parse(trimmed);
258
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
259
+ return { id: target.id, status: "blocked-non-object", path: target.configPath };
260
+ }
261
+ doc = parsed;
262
+ } catch {
263
+ return { id: target.id, status: "blocked-invalid-json", path: target.configPath };
264
+ }
265
+ }
266
+ } else if (uninstall) {
267
+ return { id: target.id, status: "skipped", path: target.configPath };
268
+ }
269
+
270
+ const servers =
271
+ doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers)
272
+ ? { ...doc.mcpServers }
273
+ : {};
274
+
275
+ if (uninstall) {
276
+ if (!("min98-ui-docs" in servers)) return { id: target.id, status: "skipped", path: target.configPath };
277
+ delete servers["min98-ui-docs"];
278
+ } else {
279
+ servers["min98-ui-docs"] = buildServerEntry(target.id, mode, origin, offlineScriptPath);
280
+ }
281
+ doc.mcpServers = servers;
282
+
283
+ if (dryRun) {
284
+ return { id: target.id, status: uninstall ? "would-remove" : "would-configure", path: target.configPath };
285
+ }
286
+
287
+ if (exists && raw.trim()) backupFile(target.configPath, raw);
288
+ ensureDir(path.dirname(target.configPath), false);
289
+ fs.writeFileSync(target.configPath, JSON.stringify(doc, null, 2) + "\n", "utf8");
290
+ return { id: target.id, status: uninstall ? "removed" : "configured", path: target.configPath };
291
+ }
292
+
293
+ async function runSetup(argv) {
294
+ const opts = parseSetupArgs(argv);
295
+ if (opts.help) {
296
+ printHelp();
297
+ return;
298
+ }
299
+
300
+ if (!SAFE_ORIGIN_RE.test(opts.origin)) {
301
+ console.error(`Invalid docs server URL: ${opts.origin}`);
302
+ process.exitCode = 1;
303
+ return;
304
+ }
305
+
306
+ const home = os.homedir();
307
+ const explicitSet = new Set(opts.clients);
308
+ const hasExplicit = explicitSet.size > 0;
309
+
310
+ const skillTargets = [
311
+ { id: "antigravity", dir: path.join(home, ".gemini", "config", "skills", "min98-ui"), detected: fs.existsSync(path.join(home, ".gemini")) },
312
+ { id: "claude", dir: path.join(home, ".claude", "skills", "min98-ui"), detected: fs.existsSync(path.join(home, ".claude")) },
313
+ { id: "agents", dir: path.join(home, ".agents", "skills", "min98-ui"), detected: true },
314
+ ];
315
+
316
+ const mcpTargets = [
317
+ { id: "antigravity", configPath: path.join(home, ".gemini", "antigravity", "mcp_config.json"), detected: fs.existsSync(path.join(home, ".gemini")) },
318
+ { id: "claude", configPath: path.join(home, ".claude.json"), detected: fs.existsSync(path.join(home, ".claude")) || fs.existsSync(path.join(home, ".claude.json")) },
319
+ { id: "cursor", configPath: path.join(home, ".cursor", "mcp.json"), detected: fs.existsSync(path.join(home, ".cursor")) },
320
+ { id: "windsurf", configPath: path.join(home, ".codeium", "windsurf", "mcp_config.json"), detected: fs.existsSync(path.join(home, ".codeium")) },
321
+ ];
322
+
323
+ console.log(`\n@min98/ui Setup (${opts.dryRun ? "dry-run" : opts.uninstall ? "uninstall" : opts.mode.toUpperCase()}): ${opts.origin}`);
324
+
325
+ if (!opts.mcpOnly) {
326
+ const docs = await resolveSkillDocs(opts.origin, opts.dryRun, opts.uninstall);
327
+ console.log(`\n[1/2] Agent Skills (source: ${docs.source}):`);
328
+ for (const target of skillTargets) {
329
+ const selected = opts.all || (hasExplicit ? explicitSet.has(target.id) : target.detected);
330
+ if (!selected && !opts.uninstall) continue;
331
+ const res = writeSkillTarget(target.dir, docs, opts.dryRun, opts.uninstall);
332
+ console.log(` - ${target.id.padEnd(12)} [${res.status}] ${res.path}`);
333
+ }
334
+ }
335
+
336
+ if (!opts.skillOnly) {
337
+ console.log("\n[2/2] MCP Runtime & Agent Configuration (min98-ui-docs):");
338
+ const runtimeRes = installOfflineMcpRuntime(home, opts.dryRun, opts.uninstall);
339
+ if (runtimeRes.status !== "skipped") {
340
+ console.log(` - stdio-runtime [${runtimeRes.status}] ${runtimeRes.scriptPath}`);
341
+ }
342
+
343
+ let configuredCount = 0;
344
+ for (const target of mcpTargets) {
345
+ const selected = opts.all || (hasExplicit ? explicitSet.has(target.id) : target.detected);
346
+ if (!selected && !(opts.uninstall && fs.existsSync(target.configPath))) continue;
347
+ const res = updateMcpConfig(target, opts.mode, opts.origin, runtimeRes.scriptPath, opts.dryRun, opts.uninstall);
348
+ if (res.status !== "skipped") configuredCount += 1;
349
+ console.log(` - ${target.id.padEnd(12)} [${res.status}] ${res.path}`);
350
+ }
351
+ if (configuredCount === 0 && !opts.uninstall) {
352
+ console.log(" - No existing agent MCP directory detected. Re-run with --all or --client antigravity,claude,cursor,windsurf.");
353
+ }
354
+ }
355
+
356
+ console.log("\nDone. Restart active AI IDE/CLI sessions to reload updated skills & MCP tools.\n");
357
+ }
358
+
359
+ function runMcpServer(argv) {
360
+ if (argv.includes("--http")) {
361
+ let port = 3333;
362
+ let host = "127.0.0.1";
363
+ for (let i = 0; i < argv.length; i += 1) {
364
+ if (argv[i] === "--port" && argv[i + 1]) port = Number(argv[++i]) || 3333;
365
+ else if (argv[i].startsWith("--port=")) port = Number(argv[i].slice(7)) || 3333;
366
+ else if (argv[i] === "--host" && argv[i + 1]) host = argv[++i];
367
+ else if (argv[i].startsWith("--host=")) host = argv[i].slice(7);
368
+ }
369
+ startHttpServer({ port, host });
370
+ return;
371
+ }
372
+ startStdioServer();
373
+ }
374
+
375
+ function emitToolOutput(result, asJson) {
376
+ const text = (result?.content || []).map((c) => c.text).join("\n");
377
+ if (result?.isError) {
378
+ console.error(asJson ? JSON.stringify(result, null, 2) : text);
379
+ process.exitCode = 1;
380
+ return;
381
+ }
382
+ if (!asJson) {
383
+ console.log(text);
384
+ return;
385
+ }
386
+ try {
387
+ console.log(JSON.stringify(JSON.parse(text), null, 2));
388
+ } catch {
389
+ console.log(JSON.stringify({ text }, null, 2));
390
+ }
391
+ }
392
+
393
+ function runMcpCliCommand(subcommand, argv) {
394
+ const asJson = argv.includes("--json");
395
+ const positional = [];
396
+ let onlyColors = false;
397
+ let onlyVariants = false;
398
+ let limit = 15;
399
+
400
+ for (let i = 0; i < argv.length; i += 1) {
401
+ const arg = argv[i];
402
+ if (arg === "--json") continue;
403
+ if (arg === "--colors") { onlyColors = true; continue; }
404
+ if (arg === "--variants") { onlyVariants = true; continue; }
405
+ if (arg === "--limit" && argv[i + 1]) { limit = Number(argv[++i]) || 15; continue; }
406
+ if (arg.startsWith("--limit=")) { limit = Number(arg.slice(8)) || 15; continue; }
407
+ positional.push(arg);
408
+ }
409
+
410
+ switch (subcommand) {
411
+ case "list": {
412
+ const res = callTool("min98_ui_list_components", {
413
+ category: positional[0] || "all",
414
+ onlyWithColors: onlyColors,
415
+ onlyWithVariants: onlyVariants,
416
+ });
417
+ if (asJson || res.isError) {
418
+ emitToolOutput(res, true);
419
+ return;
420
+ }
421
+ const parsed = JSON.parse(res.content[0].text);
422
+ console.log(`Found ${parsed.count} component(s):`);
423
+ for (const item of parsed.components) {
424
+ console.log(` - ${item.slug.padEnd(22)} [${item.category}] ${item.name} (${item.exports.join(", ")})`);
425
+ }
426
+ return;
427
+ }
428
+
429
+ case "get": {
430
+ emitToolOutput(callTool("min98_ui_get_component", { slug: positional[0] || "" }), asJson);
431
+ return;
432
+ }
433
+
434
+ case "search": {
435
+ const query = positional.join(" ");
436
+ const res = callTool("min98_ui_search_components", { query, limit });
437
+ if (asJson || res.isError) {
438
+ emitToolOutput(res, true);
439
+ return;
440
+ }
441
+ const parsed = JSON.parse(res.content[0].text);
442
+ console.log(`Search "${parsed.query}" (${parsed.count} match(es)):`);
443
+ for (const item of parsed.results) {
444
+ console.log(` - ${item.slug.padEnd(22)} [${item.category}] ${item.summary}`);
445
+ }
446
+ return;
447
+ }
448
+
449
+ case "guide": {
450
+ emitToolOutput(callTool("min98_ui_get_setup_guide", { topic: positional[0] || "all" }), asJson);
451
+ return;
452
+ }
453
+
454
+ case "skill": {
455
+ emitToolOutput(callTool("min98_ui_get_skill_markdown", {}), asJson);
456
+ return;
457
+ }
458
+
459
+ case "tool": {
460
+ const toolName = positional[0] || "";
461
+ let parsedArgs = {};
462
+ if (positional[1]) {
463
+ try {
464
+ parsedArgs = JSON.parse(positional.slice(1).join(" "));
465
+ } catch {
466
+ console.error("Invalid JSON arguments for `tool` command.");
467
+ process.exitCode = 1;
468
+ return;
469
+ }
470
+ }
471
+ emitToolOutput(callTool(toolName, parsedArgs), asJson);
472
+ return;
473
+ }
474
+ }
475
+ }
476
+
477
+ async function main() {
478
+ const argv = process.argv.slice(2);
479
+ const subcommand = argv[0];
480
+
481
+ if (!subcommand || subcommand === "-h" || subcommand === "--help" || subcommand === "help") {
482
+ printHelp();
483
+ return;
484
+ }
485
+ if (subcommand === "setup") {
486
+ await runSetup(argv.slice(1));
487
+ return;
488
+ }
489
+ if (subcommand === "mcp") {
490
+ runMcpServer(argv.slice(1));
491
+ return;
492
+ }
493
+ if (["list", "get", "search", "guide", "skill", "tool"].includes(subcommand)) {
494
+ runMcpCliCommand(subcommand, argv.slice(1));
495
+ return;
496
+ }
497
+
498
+ console.error(`Unknown command: ${subcommand}\n`);
499
+ printHelp();
500
+ process.exitCode = 1;
501
+ }
502
+
503
+ await main();