@finedesign/cli 0.8.1 → 0.10.0
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/CHANGELOG.md +14 -0
- package/README.md +4 -4
- package/data/1.25.1/catalog.json +1 -0
- package/data/1.25.1/manifest.json +16 -0
- package/data/index.json +5 -1
- package/package.json +1 -1
- package/skills/fine-design/references/imports-and-setup.md +4 -7
- package/src/cli.mjs +62 -5
- package/src/core/contracts.mjs +4 -1
- package/src/core/figma.mjs +93 -2
- package/src/core/lint.mjs +7 -179
- package/src/core/runtime.mjs +21 -10
- package/src/core/source-code.mjs +204 -0
- package/src/mcp.mjs +9 -2
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"version": "1.25.1",
|
|
4
|
+
"sourceKind": "repository-snapshot",
|
|
5
|
+
"sourceRevision": "508ca187dd94fd821eb164f4ae045c9a38b805ca",
|
|
6
|
+
"sourceDirty": false,
|
|
7
|
+
"contentHash": "79b401f3998a2d49cae141df1f7e2627df41fe341cf53f155ef687e16377b12c",
|
|
8
|
+
"catalogSha256": "3845f98ba76866a89b609284ae8c0171d6f8ff3621e4ce7d9d82584350c894de",
|
|
9
|
+
"skillFiles": {
|
|
10
|
+
"references/component-guide.md": "e48d32c664034bae5cf3aaf2d8c294f99e3374645e2b8482844e79e82b8548b6",
|
|
11
|
+
"references/docs-slug-map.md": "440ce5cf137fd22eabfcc5b51c3f55b85174aa643773ef0cedd5df542e77bbc2",
|
|
12
|
+
"references/imports-and-setup.md": "cd9c8452d62bebecf2fb6a2ffd74772c673e41c3290f424d96674c3ad327bc74",
|
|
13
|
+
"references/theme-and-dark-mode.md": "2eccae4930ea993e7088eee03a4b4a0f1c839033079db5f21f8c60e0fe8168d1",
|
|
14
|
+
"SKILL.md": "e1024432c8b37d88057cfd851d40d3f1747b8b0354d12f9c4d510810757d62c8"
|
|
15
|
+
}
|
|
16
|
+
}
|
package/data/index.json
CHANGED
|
@@ -8,7 +8,11 @@
|
|
|
8
8
|
"1.25.0": {
|
|
9
9
|
"catalog": "1.25.0/catalog.json",
|
|
10
10
|
"manifest": "1.25.0/manifest.json"
|
|
11
|
+
},
|
|
12
|
+
"1.25.1": {
|
|
13
|
+
"catalog": "1.25.1/catalog.json",
|
|
14
|
+
"manifest": "1.25.1/manifest.json"
|
|
11
15
|
}
|
|
12
16
|
},
|
|
13
|
-
"skillVersion": "1.25.
|
|
17
|
+
"skillVersion": "1.25.1"
|
|
14
18
|
}
|
package/package.json
CHANGED
|
@@ -49,18 +49,15 @@ Use browser/CDN mode for standalone pages, embedded pages and previews without a
|
|
|
49
49
|
|
|
50
50
|
### Select Resources
|
|
51
51
|
|
|
52
|
-
Run `npx -y @finedesign/cli runtime list --format json` first and check its exit code. Use a version from its `versions` result with `npx -y @finedesign/cli runtime --fd-version <exact-version> --format html > demo.html` for a standalone starting page, or `--format json` for resources (MCP: `list_browser_runtimes` / `get_browser_runtime`). Use `--runtime-url` only for an explicitly selected preview.
|
|
52
|
+
Run `npx -y @finedesign/cli runtime list --format json` first and check its exit code. Use a version from its `versions` result with `npx -y @finedesign/cli runtime --fd-version <exact-version> --format html > demo.html` for a standalone starting page, or `--format json` for resources (MCP: `list_browser_runtimes` / `get_browser_runtime`). Use `--runtime-url` only for an explicitly selected preview.
|
|
53
53
|
|
|
54
|
-
|
|
55
|
-
2. Resolve resource `path` relative to that manifest; `url` is used exactly. Hosted paths include the precise package version, such as `fine-design/1.25.0/fine-design.min.js`. There is no hash directory or releaseId. Resource SHA-256 and SRI still verify the exact bytes.
|
|
56
|
-
3. The host retains only the current release files. Old URLs may disappear on upgrade; save matching resources yourself for long-lived standalone pages. Do not claim historical runtime availability from the CLI's offline catalog.
|
|
57
|
-
4. If the manifest cannot be retrieved, report the failure and use an explicitly selected verified host or previously saved matching resources. The old unversioned website resources have been removed; do not fall back to them or substitute another component version.
|
|
54
|
+
The public npm package `@finedesign/runtime` contains the UMD script, stylesheet and manifest. Discovery reads the latest manifest. For a known published version use `https://cdn.jsdelivr.net/npm/@finedesign/runtime@<exact-version>/manifest.json`. Resolve resource paths relative to that exact manifest and preserve the supplied URLs, hashes and SRI. If a requested version is unavailable, report the error or use matching previously saved resources.
|
|
58
55
|
|
|
59
56
|
For offline or CSP-restricted previews, use `fine-design runtime --fd-version <exact-version> --output ./demo` with a new destination directory. `--dry-run --format json` previews file paths. The export verifies sizes/SHA-256 before writing local resources, preserves SRI and records their remote provenance in `runtime-lock.json`. Initial export needs network access; subsequent pages reference only local resources. The host must still permit page scripts/styles. Existing destinations are rejected rather than overwritten.
|
|
60
57
|
|
|
61
58
|
Load `fineDesignCss`, then `react`, `reactDOM`, `fineDesign`. Pin exact URLs and integrity in generated HTML and use `crossorigin="anonymous"`; the host must provide CORS. Do not drop SRI from a selected versioned runtime to hide an error. Avoid async scripts and conflicting second React instances. If an embedding host lacks compatible React globals, use a separate document/iframe.
|
|
62
59
|
|
|
63
|
-
Use `--runtime-url <verified-base-url>`
|
|
60
|
+
Use `--runtime-url <verified-base-url>` for an explicitly selected alternative host. Use the VanChart skill for chart resources.
|
|
64
61
|
|
|
65
62
|
### Mount And Verify
|
|
66
63
|
|
|
@@ -76,4 +73,4 @@ ReactDOM.createRoot(document.getElementById('root')).render(
|
|
|
76
73
|
);
|
|
77
74
|
```
|
|
78
75
|
|
|
79
|
-
|
|
76
|
+
Run `npm run build:public-assets` to build the production npm runtime tarball. See `tools/fine-design/README.md` for publishing and verification.
|
package/src/cli.mjs
CHANGED
|
@@ -25,7 +25,7 @@ Commands:
|
|
|
25
25
|
diff [fromVer] [toVer] Compare component changes and migrations between versions
|
|
26
26
|
doctor Inspect detected version, available catalogs and bundled Skill
|
|
27
27
|
runtime [list] Resolve a versioned online UMD runtime or list published versions
|
|
28
|
-
figma <resolve|list> [target] Look up Fine Design library nodes
|
|
28
|
+
figma <resolve|list|scan> [target] Look up Fine Design library nodes, list Code Connect mappings, or scan code for Figma components
|
|
29
29
|
mcp Start the stdio MCP server
|
|
30
30
|
|
|
31
31
|
Options:
|
|
@@ -36,7 +36,7 @@ Options:
|
|
|
36
36
|
--output <directory> Destination for an example or offline runtime (add and runtime)
|
|
37
37
|
--force Update managed files or overwrite examples (init and add)
|
|
38
38
|
--dry-run Preview changes without writing (init, add and runtime --output)
|
|
39
|
-
--runtime-url <url> Runtime hosting base URL (runtime command only)
|
|
39
|
+
--runtime-url <url> Runtime hosting base URL or npm (runtime command only)
|
|
40
40
|
--format <text|json|markdown|html> Output format (markdown: doc/info/token/figma; html: runtime)
|
|
41
41
|
--section <heading> Doc section heading (exact or case-insensitive)
|
|
42
42
|
--toc, --summary Show only doc metadata, section headings and example IDs
|
|
@@ -329,12 +329,69 @@ export async function main(argv) {
|
|
|
329
329
|
if (format === 'html' && (command !== 'runtime' || args.length)) throw new ToolError('INVALID_ARGUMENT', 'HTML output format is only supported for runtime resolution.', 2);
|
|
330
330
|
if (command === 'figma') {
|
|
331
331
|
const sub = args[0];
|
|
332
|
-
if (!['resolve', 'list'].includes(sub)) {
|
|
333
|
-
throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design figma <resolve|list> [target] [--format text|json|markdown]', 2);
|
|
332
|
+
if (!['resolve', 'list', 'scan'].includes(sub)) {
|
|
333
|
+
throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design figma <resolve|list|scan> [target] [--format text|json|markdown]', 2);
|
|
334
334
|
}
|
|
335
335
|
if (values.version || values.section !== undefined || summaryFlag || values.offset !== undefined || values.limit !== undefined || values['include-assets'] !== undefined || values['fd-version'] !== undefined) {
|
|
336
336
|
throw new ToolError('INVALID_ARGUMENT', 'Invalid options for figma command. Use --help for usage.', 2);
|
|
337
337
|
}
|
|
338
|
+
if (sub === 'scan') {
|
|
339
|
+
if (args.length !== 2) {
|
|
340
|
+
throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design figma scan <file-or-dir> [--format text|json|markdown]', 2);
|
|
341
|
+
}
|
|
342
|
+
const targetPath = args[1];
|
|
343
|
+
const { scanFigmaComponents } = await import('./core/figma.mjs');
|
|
344
|
+
const result = scanFigmaComponents(targetPath);
|
|
345
|
+
if (format === 'json') {
|
|
346
|
+
console.log(JSON.stringify(result));
|
|
347
|
+
} else if (format === 'markdown') {
|
|
348
|
+
const rows = result.matched.map((c) => `| \`${c.component}\` | \`${c.designName}\` | \`${c.nodeId}\` | \`${c.templateId}\` | ${c.businessInputs ? c.businessInputs.replace(/\|/g, '\\|') : '-'} |`);
|
|
349
|
+
const unmappedRows = result.unmapped.map((u) => `- **${u.component}**: ${u.note}`);
|
|
350
|
+
console.log([
|
|
351
|
+
`# Fine Design 页面物料清单 (Figma BOM)`,
|
|
352
|
+
`- **目标路径**: \`${result.target}\``,
|
|
353
|
+
`- **官方设计库**: \`${result.fileKey}\``,
|
|
354
|
+
`- **扫描文件数**: ${result.scannedFiles}`,
|
|
355
|
+
`- **检测到组件总数**: ${result.totalDetected}`,
|
|
356
|
+
'',
|
|
357
|
+
`## 已连接设计组件 (${result.matched.length})`,
|
|
358
|
+
'| 代码组件 | 设计名称 | Node ID | Code Connect 模板 | 业务入参要求 |',
|
|
359
|
+
'| --- | --- | --- | --- | --- |',
|
|
360
|
+
...rows,
|
|
361
|
+
...(result.unmapped.length ? [
|
|
362
|
+
'',
|
|
363
|
+
`## 未连接设计组件 (${result.unmapped.length})`,
|
|
364
|
+
...unmappedRows
|
|
365
|
+
] : []),
|
|
366
|
+
...(!result.passed ? [
|
|
367
|
+
'',
|
|
368
|
+
'## 解析失败,清单不完整',
|
|
369
|
+
...result.diagnostics.map(({ file, line, column, message }) => `- \`${file}:${line}:${column}\` ${message}`)
|
|
370
|
+
] : [])
|
|
371
|
+
].join('\n'));
|
|
372
|
+
} else {
|
|
373
|
+
const lines = result.matched.map((c) => ` ${c.component.padEnd(18)} ${c.nodeId.padEnd(16)} ${c.templateId.padEnd(24)} ${c.designName}`);
|
|
374
|
+
console.log([
|
|
375
|
+
`Fine Design Page Component Manifest (${result.matched.length} mapped / ${result.totalDetected} total):`,
|
|
376
|
+
`Target: ${result.target} (File Key: ${result.fileKey})`,
|
|
377
|
+
'',
|
|
378
|
+
'Mapped Library Components:',
|
|
379
|
+
...lines,
|
|
380
|
+
...(result.unmapped.length ? [
|
|
381
|
+
'',
|
|
382
|
+
'Unmapped Components:',
|
|
383
|
+
...result.unmapped.map((u) => ` * ${u.component.padEnd(16)} - ${u.note}`)
|
|
384
|
+
] : []),
|
|
385
|
+
...(!result.passed ? [
|
|
386
|
+
'',
|
|
387
|
+
'Parse errors (manifest is incomplete):',
|
|
388
|
+
...result.diagnostics.map(({ file, line, column, message }) => ` ${file}:${line}:${column} ${message}`)
|
|
389
|
+
] : [])
|
|
390
|
+
].join('\n'));
|
|
391
|
+
}
|
|
392
|
+
if (!result.passed) process.exitCode = 1;
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
338
395
|
if (sub === 'list') {
|
|
339
396
|
if (args.length > 1) {
|
|
340
397
|
throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design figma list [--format text|json|markdown]', 2);
|
|
@@ -462,7 +519,7 @@ export async function main(argv) {
|
|
|
462
519
|
console.log(format === 'json' ? JSON.stringify(report) : `${report.dryRun ? 'Preview' : 'Exported'} Fine Design ${report.version} to ${report.targetDir}:\n${report.plannedFiles.map((name) => ` ${name}`).join('\n')}`);
|
|
463
520
|
return;
|
|
464
521
|
}
|
|
465
|
-
console.log(format === 'html' ? html.exampleHTML(result.resources, './').trimEnd() : format === 'json' ? JSON.stringify(result) : list ? result.versions.join('\n') : `Fine Design ${result.version} (offline docs: ${result.docsAvailable ? 'available' : 'not bundled'})\n${result.tags}
|
|
522
|
+
console.log(format === 'html' ? html.exampleHTML(result.resources, './').trimEnd() : format === 'json' ? JSON.stringify(result) : list ? result.versions.join('\n') : `Fine Design ${result.version} (offline docs: ${result.docsAvailable ? 'available' : 'not bundled'})\n${result.tags}${result.exampleURL ? `\nExample: ${result.exampleURL}` : ''}`);
|
|
466
523
|
return;
|
|
467
524
|
}
|
|
468
525
|
if (command === 'doctor') {
|
package/src/core/contracts.mjs
CHANGED
|
@@ -56,7 +56,10 @@ export const schemas = {
|
|
|
56
56
|
}).strict().refine((data) => data.target || data.url || data.nodeId || data.component, {
|
|
57
57
|
message: 'Provide at least one of target, url, nodeId, or component.'
|
|
58
58
|
}),
|
|
59
|
-
list_figma_components: z.object({}).strict()
|
|
59
|
+
list_figma_components: z.object({}).strict(),
|
|
60
|
+
scan_figma_components: z.object({
|
|
61
|
+
path: z.string().min(1).max(2048).describe('Source file or directory to scan for Fine Design components, e.g. "src/App.tsx".')
|
|
62
|
+
}).strict()
|
|
60
63
|
};
|
|
61
64
|
|
|
62
65
|
export function validateInput(tool, input) {
|
package/src/core/figma.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
2
3
|
import { ToolError } from './errors.mjs';
|
|
4
|
+
import { componentName, isCodeFile, isReactCreateElement, listCodeFiles, visitCode } from './source-code.mjs';
|
|
3
5
|
|
|
4
6
|
const figmaData = JSON.parse(fs.readFileSync(new URL('./figma-data.json', import.meta.url), 'utf8'));
|
|
5
7
|
|
|
@@ -50,6 +52,18 @@ function matchedResult(match, query) {
|
|
|
50
52
|
};
|
|
51
53
|
}
|
|
52
54
|
|
|
55
|
+
function primaryMapping(matches) {
|
|
56
|
+
const nodeId = figmaData.primaryLinks[matches[0]?.component];
|
|
57
|
+
return matches.find((match) => match.nodeId === nodeId) ?? matches[0];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function exactComponentMapping(name) {
|
|
61
|
+
const exact = primaryMapping(figmaData.mappings.filter((match) => match.component === name));
|
|
62
|
+
const alias = name.toLowerCase();
|
|
63
|
+
if (exact || !Object.hasOwn(figmaData.aliases, alias)) return exact;
|
|
64
|
+
return primaryMapping(figmaData.mappings.filter((match) => match.component === figmaData.aliases[alias]));
|
|
65
|
+
}
|
|
66
|
+
|
|
53
67
|
export function resolveFigmaComponent(input = {}) {
|
|
54
68
|
const target = (input.target || input.url || input.nodeId || input.component || '').trim();
|
|
55
69
|
if (!target) {
|
|
@@ -68,6 +82,17 @@ export function resolveFigmaComponent(input = {}) {
|
|
|
68
82
|
const nodeId = isUrl ? url.nodeId : normalizeNodeId(target);
|
|
69
83
|
if (isUrl || nodeId || (!input.target && input.nodeId)) {
|
|
70
84
|
const query = { input: target, nodeId };
|
|
85
|
+
if (nodeId === figmaData.indexNodeId) {
|
|
86
|
+
return {
|
|
87
|
+
matched: false,
|
|
88
|
+
isIndex: true,
|
|
89
|
+
query,
|
|
90
|
+
fileKey: figmaData.fileKey,
|
|
91
|
+
indexNodeId: figmaData.indexNodeId,
|
|
92
|
+
url: `https://www.figma.com/design/${figmaData.fileKey}/FineDesign-System?node-id=${figmaData.indexNodeId.replace(':', '-')}`,
|
|
93
|
+
message: 'Target is the FineDesign System component index page (9874:1042). No mapped library node found for the index frame. Use Figma MCP to locate the main component for a page, instance or variant, or use "fine-design figma list" to view all 70 mapped components.'
|
|
94
|
+
};
|
|
95
|
+
}
|
|
71
96
|
const match = figmaData.mappings.find((m) => m.nodeId === nodeId);
|
|
72
97
|
if (match) return matchedResult(match, query);
|
|
73
98
|
return {
|
|
@@ -96,8 +121,7 @@ export function resolveFigmaComponent(input = {}) {
|
|
|
96
121
|
}
|
|
97
122
|
|
|
98
123
|
const exact = figmaData.mappings.filter((m) => m.component.toLowerCase() === canonicalName);
|
|
99
|
-
const
|
|
100
|
-
const matchedEntry = exact.find((m) => m.nodeId === primaryNodeId) ?? exact[0]
|
|
124
|
+
const matchedEntry = primaryMapping(exact)
|
|
101
125
|
?? figmaData.mappings.find((m) => m.component.toLowerCase().replace(/[-_\s.]/g, '') === searchName)
|
|
102
126
|
?? (searchName && figmaData.mappings.find((m) => m.designName.toLowerCase().includes(searchName) || m.component.toLowerCase().includes(searchName)));
|
|
103
127
|
if (matchedEntry) {
|
|
@@ -136,3 +160,70 @@ export function listFigmaComponents() {
|
|
|
136
160
|
}))
|
|
137
161
|
};
|
|
138
162
|
}
|
|
163
|
+
|
|
164
|
+
export function scanFigmaComponents(targetPath) {
|
|
165
|
+
const resolved = path.resolve(targetPath);
|
|
166
|
+
if (!fs.existsSync(resolved)) {
|
|
167
|
+
throw new ToolError('INVALID_ARGUMENT', `Target does not exist: ${targetPath}`, 2);
|
|
168
|
+
}
|
|
169
|
+
if (fs.statSync(resolved).isFile() && !isCodeFile(resolved)) {
|
|
170
|
+
throw new ToolError('INVALID_ARGUMENT', `Unsupported file type: ${targetPath}. Use a JavaScript, TypeScript, or HTML file.`, 2);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const files = listCodeFiles(resolved);
|
|
174
|
+
const names = new Set();
|
|
175
|
+
const diagnostics = [];
|
|
176
|
+
for (const file of files) {
|
|
177
|
+
visitCode(file, fs.readFileSync(file, 'utf8'), (node, scope) => {
|
|
178
|
+
let component;
|
|
179
|
+
if (node.type === 'JSXOpeningElement' &&
|
|
180
|
+
(node.name.type !== 'JSXIdentifier' || !/^[a-z]/.test(node.name.name))) {
|
|
181
|
+
component = componentName(node.name, scope);
|
|
182
|
+
} else if (node.type === 'CallExpression' && isReactCreateElement(node.callee, scope)) {
|
|
183
|
+
component = componentName(node.arguments[0], scope);
|
|
184
|
+
}
|
|
185
|
+
if (component) names.add(component);
|
|
186
|
+
}, (error) => diagnostics.push({
|
|
187
|
+
file, line: error.loc.line, column: error.loc.column + 1, message: error.message
|
|
188
|
+
}));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const matched = new Map();
|
|
192
|
+
const unmapped = new Map();
|
|
193
|
+
for (const name of names) {
|
|
194
|
+
const root = name.split('.')[0];
|
|
195
|
+
const match = exactComponentMapping(name) ?? (root !== name ? exactComponentMapping(root) : undefined);
|
|
196
|
+
if (match) {
|
|
197
|
+
matched.set(match.component, {
|
|
198
|
+
component: match.component,
|
|
199
|
+
designName: match.designName,
|
|
200
|
+
nodeId: match.nodeId,
|
|
201
|
+
url: match.url,
|
|
202
|
+
templateId: match.templateId,
|
|
203
|
+
templateFile: match.file,
|
|
204
|
+
businessInputs: match.businessInputs,
|
|
205
|
+
recommendations: match.recommendations
|
|
206
|
+
});
|
|
207
|
+
} else {
|
|
208
|
+
const component = [name, root].find((candidate) => Object.hasOwn(figmaData.unmappedNotes, candidate)) ?? name;
|
|
209
|
+
unmapped.set(component, {
|
|
210
|
+
component,
|
|
211
|
+
note: Object.hasOwn(figmaData.unmappedNotes, component)
|
|
212
|
+
? figmaData.unmappedNotes[component]
|
|
213
|
+
: 'No Figma library mapping is available for this component.'
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const byComponent = (a, b) => a.component.localeCompare(b.component);
|
|
219
|
+
return {
|
|
220
|
+
target: targetPath,
|
|
221
|
+
fileKey: figmaData.fileKey,
|
|
222
|
+
scannedFiles: files.length,
|
|
223
|
+
passed: diagnostics.length === 0,
|
|
224
|
+
totalDetected: matched.size + unmapped.size,
|
|
225
|
+
matched: [...matched.values()].sort(byComponent),
|
|
226
|
+
unmapped: [...unmapped.values()].sort(byComponent),
|
|
227
|
+
diagnostics
|
|
228
|
+
};
|
|
229
|
+
}
|
package/src/core/lint.mjs
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { parse } from '@babel/parser';
|
|
4
3
|
import { ToolError } from './errors.mjs';
|
|
5
4
|
import { suggestSimilarComponents } from './catalog.mjs';
|
|
5
|
+
import { componentName, isFineDesignNamespace, isReactCreateElement, isTypeScriptFile, listCodeFiles, visitCode } from './source-code.mjs';
|
|
6
6
|
|
|
7
|
-
const CODE_FILE_PATTERN = /\.(?:[cm]?[jt]sx?|html?)$/i;
|
|
8
|
-
const IGNORED_DIRS = new Set(['node_modules', '.git', 'dist', 'lib', 'es', '.dumi', 'coverage', 'artifacts']);
|
|
9
7
|
const BUTTON_TYPES = new Set(['primary', 'secondary', 'normal', 'negative', 'link', 'text', 'text-normal', 'bare']);
|
|
10
8
|
|
|
11
9
|
const KNOWN_TYPE_EXPORTS = new Set([
|
|
@@ -60,157 +58,7 @@ function collectFiles(targetPath) {
|
|
|
60
58
|
if (!fs.existsSync(resolved)) {
|
|
61
59
|
throw new ToolError('INVALID_ARGUMENT', `Lint target does not exist: ${targetPath}`, 2);
|
|
62
60
|
}
|
|
63
|
-
|
|
64
|
-
function walk(current) {
|
|
65
|
-
const stat = fs.statSync(current);
|
|
66
|
-
if (stat.isFile()) {
|
|
67
|
-
if (CODE_FILE_PATTERN.test(current)) results.push(current);
|
|
68
|
-
return;
|
|
69
|
-
}
|
|
70
|
-
if (!stat.isDirectory()) return;
|
|
71
|
-
for (const entry of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
72
|
-
if (entry.isDirectory()) {
|
|
73
|
-
if (!IGNORED_DIRS.has(entry.name) && !entry.name.startsWith('.')) {
|
|
74
|
-
walk(path.join(current, entry.name));
|
|
75
|
-
}
|
|
76
|
-
} else if (entry.isFile() && CODE_FILE_PATTERN.test(entry.name)) {
|
|
77
|
-
results.push(path.join(current, entry.name));
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
walk(resolved);
|
|
82
|
-
return results;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function lineOfIndex(content, index) {
|
|
86
|
-
let line = 1;
|
|
87
|
-
for (let i = 0; i < index; i++) {
|
|
88
|
-
if (content.charCodeAt(i) === 10) line++;
|
|
89
|
-
}
|
|
90
|
-
return line;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
function codeSources(file, content) {
|
|
94
|
-
if (!/\.html?$/i.test(file)) return [{ content, startLine: 1 }];
|
|
95
|
-
return [...content.matchAll(/<!--[\s\S]*?-->|<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)]
|
|
96
|
-
.filter((match) => {
|
|
97
|
-
if (match[1] === undefined) return false;
|
|
98
|
-
const type = match[1].match(/\btype\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
|
|
99
|
-
return !type || /^(?:module|(?:text|application)\/(?:javascript|ecmascript|babel|typescript))$/i.test(type[1] ?? type[2] ?? type[3]);
|
|
100
|
-
})
|
|
101
|
-
.map((match) => ({ content: match[2], startLine: lineOfIndex(content, match.index + match[0].indexOf('>') + 1) }));
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function bindPattern(pattern, scope) {
|
|
105
|
-
if (!pattern) return;
|
|
106
|
-
if (pattern.type === 'Identifier') scope.bindings.set(pattern.name, null);
|
|
107
|
-
else if (pattern.type === 'ObjectPattern') {
|
|
108
|
-
for (const prop of pattern.properties) bindPattern(prop.type === 'RestElement' ? prop.argument : prop.value, scope);
|
|
109
|
-
} else if (pattern.type === 'ArrayPattern') {
|
|
110
|
-
for (const element of pattern.elements) bindPattern(element, scope);
|
|
111
|
-
} else if (pattern.type === 'AssignmentPattern') bindPattern(pattern.left, scope);
|
|
112
|
-
else if (pattern.type === 'RestElement') bindPattern(pattern.argument, scope);
|
|
113
|
-
else if (pattern.type === 'TSParameterProperty') bindPattern(pattern.parameter, scope);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function collectScopes(program) {
|
|
117
|
-
const scopes = new WeakMap();
|
|
118
|
-
function collect(node, scope) {
|
|
119
|
-
if (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') bindPattern(node.id, scope);
|
|
120
|
-
const isFunction = /Function(?:Declaration|Expression)$|Method$/.test(node.type);
|
|
121
|
-
if (isFunction || ['Program', 'BlockStatement', 'CatchClause', 'ForStatement', 'ForInStatement', 'ForOfStatement', 'SwitchStatement', 'StaticBlock', 'ClassDeclaration', 'ClassExpression'].includes(node.type)) {
|
|
122
|
-
scope = { parent: scope, bindings: new Map(), varScope: isFunction || node.type === 'Program' || node.type === 'StaticBlock' ? null : scope.varScope };
|
|
123
|
-
scope.varScope ||= scope;
|
|
124
|
-
if (isFunction || node.type === 'ClassExpression') bindPattern(node.id, scope);
|
|
125
|
-
for (const param of node.params || []) bindPattern(param, scope);
|
|
126
|
-
if (node.type === 'CatchClause') bindPattern(node.param, scope);
|
|
127
|
-
}
|
|
128
|
-
scopes.set(node, scope);
|
|
129
|
-
if (node.type === 'ImportDeclaration') {
|
|
130
|
-
for (const spec of node.specifiers) {
|
|
131
|
-
bindPattern(spec.local, scope);
|
|
132
|
-
if (node.source.value === '@fx-ui/fine-design' && node.importKind !== 'type' && spec.importKind !== 'type') {
|
|
133
|
-
if (spec.type === 'ImportSpecifier') scope.bindings.set(spec.local.name, { component: spec.imported.name ?? spec.imported.value });
|
|
134
|
-
else if (spec.type === 'ImportNamespaceSpecifier') scope.bindings.set(spec.local.name, { namespace: true });
|
|
135
|
-
}
|
|
136
|
-
if (node.source.value === 'react' && node.importKind !== 'type' && spec.importKind !== 'type') {
|
|
137
|
-
if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportNamespaceSpecifier') scope.bindings.set(spec.local.name, { reactNamespace: true });
|
|
138
|
-
else if ((spec.imported.name ?? spec.imported.value) === 'createElement') scope.bindings.set(spec.local.name, { reactFactory: true });
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
} else if (node.type === 'VariableDeclaration') {
|
|
142
|
-
const targetScope = node.kind === 'var' ? scope.varScope : scope;
|
|
143
|
-
for (const declaration of node.declarations) {
|
|
144
|
-
bindPattern(declaration.id, targetScope);
|
|
145
|
-
if (declaration.id.type === 'Identifier' && declaration.init) {
|
|
146
|
-
targetScope.bindings.set(declaration.id.name, { initializer: declaration.init, scope });
|
|
147
|
-
}
|
|
148
|
-
if (declaration.id.type !== 'ObjectPattern') continue;
|
|
149
|
-
for (const prop of declaration.id.properties) {
|
|
150
|
-
if (prop.type !== 'ObjectProperty' || prop.computed) continue;
|
|
151
|
-
const local = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value;
|
|
152
|
-
if (local.type === 'Identifier') targetScope.bindings.set(local.name, { component: String(prop.key.name ?? prop.key.value), source: declaration.init, scope });
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
for (const child of Object.values(node)) {
|
|
157
|
-
if (Array.isArray(child)) child.filter((item) => item?.type).forEach((item) => collect(item, scope));
|
|
158
|
-
else if (child?.type) collect(child, scope);
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
collect(program);
|
|
162
|
-
return scopes;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
function findBinding(scope, name) {
|
|
166
|
-
for (; scope; scope = scope.parent) {
|
|
167
|
-
if (scope.bindings.has(name)) return scope.bindings.get(name);
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
function isGlobalMember(node, scope, object, property) {
|
|
172
|
-
return ['MemberExpression', 'JSXMemberExpression'].includes(node?.type) && !node.computed &&
|
|
173
|
-
node.object.name === object && node.property.name === property && findBinding(scope, object) === undefined;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
function isFineDesignNamespace(node, scope) {
|
|
177
|
-
if (node?.type === 'Identifier' || node?.type === 'JSXIdentifier') {
|
|
178
|
-
const binding = findBinding(scope, node.name);
|
|
179
|
-
return Boolean(binding?.namespace || (node.name === 'FineDesign' && binding === undefined) ||
|
|
180
|
-
isGlobalMember(binding?.initializer, binding?.scope, 'window', 'FineDesign'));
|
|
181
|
-
}
|
|
182
|
-
return isGlobalMember(node, scope, 'window', 'FineDesign');
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// shortcut: resolve imports and direct initializers in the same script, add data-flow analysis if reassigned or cross-script aliases need checking.
|
|
186
|
-
function componentName(node, scope) {
|
|
187
|
-
if (node?.type === 'JSXIdentifier' || node?.type === 'Identifier') {
|
|
188
|
-
const binding = findBinding(scope, node.name);
|
|
189
|
-
if (binding?.component && (!Object.hasOwn(binding, 'source') || isFineDesignNamespace(binding.source, binding.scope))) return binding.component;
|
|
190
|
-
node = binding?.initializer;
|
|
191
|
-
scope = binding?.scope;
|
|
192
|
-
}
|
|
193
|
-
if (['MemberExpression', 'JSXMemberExpression'].includes(node?.type) && !node.computed) {
|
|
194
|
-
if (isFineDesignNamespace(node.object, scope)) return node.property.name;
|
|
195
|
-
const parent = componentName(node.object, scope);
|
|
196
|
-
if (parent) return `${parent}.${node.property.name}`;
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
function isReactCreateElement(node, scope) {
|
|
201
|
-
if (node.type === 'Identifier') {
|
|
202
|
-
const binding = findBinding(scope, node.name);
|
|
203
|
-
if (binding?.reactFactory) return true;
|
|
204
|
-
node = binding?.initializer;
|
|
205
|
-
scope = binding?.scope;
|
|
206
|
-
}
|
|
207
|
-
if (node?.type !== 'MemberExpression' || node.computed || node.property.name !== 'createElement') return false;
|
|
208
|
-
if (isGlobalMember(node.object, scope, 'window', 'React')) return true;
|
|
209
|
-
if (node.object.type !== 'Identifier') return false;
|
|
210
|
-
const binding = findBinding(scope, node.object.name);
|
|
211
|
-
return (node.object.name === 'React' && binding === undefined) ||
|
|
212
|
-
binding?.reactNamespace ||
|
|
213
|
-
isGlobalMember(binding?.initializer, binding?.scope, 'window', 'React');
|
|
61
|
+
return listCodeFiles(resolved);
|
|
214
62
|
}
|
|
215
63
|
|
|
216
64
|
function staticProps(attributes) {
|
|
@@ -249,7 +97,7 @@ export function lintFiles(catalog, targets = ['.']) {
|
|
|
249
97
|
|
|
250
98
|
for (const file of files) {
|
|
251
99
|
const content = fs.readFileSync(file, 'utf8');
|
|
252
|
-
const typescript =
|
|
100
|
+
const typescript = isTypeScriptFile(file);
|
|
253
101
|
const report = (node, rule, severity, message, suggestion) => diagnostics.push({
|
|
254
102
|
file, line: node.loc.start.line, rule, severity, message, suggestion
|
|
255
103
|
});
|
|
@@ -328,8 +176,7 @@ export function lintFiles(catalog, targets = ['.']) {
|
|
|
328
176
|
}
|
|
329
177
|
}
|
|
330
178
|
|
|
331
|
-
function visit(node,
|
|
332
|
-
const scope = scopes.get(node);
|
|
179
|
+
function visit(node, scope) {
|
|
333
180
|
if (node.type === 'ImportDeclaration') {
|
|
334
181
|
const source = node.source.value;
|
|
335
182
|
if (/^(?:@fx-ui\/fine-design\/(?:es|lib)\/icons|@ant-design\/icons)$/.test(source)) {
|
|
@@ -358,30 +205,11 @@ export function lintFiles(catalog, targets = ['.']) {
|
|
|
358
205
|
} else if (node.type === 'JSXOpeningElement') {
|
|
359
206
|
checkProps(componentName(node.name, scope), node.attributes);
|
|
360
207
|
}
|
|
361
|
-
for (const child of Object.values(node)) {
|
|
362
|
-
if (Array.isArray(child)) child.filter((item) => item?.type).forEach((item) => visit(item, scopes));
|
|
363
|
-
else if (child?.type) visit(child, scopes);
|
|
364
|
-
}
|
|
365
208
|
}
|
|
366
209
|
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
ast = parse(source.content, {
|
|
371
|
-
sourceType: 'unambiguous', startLine: source.startLine, attachComment: false,
|
|
372
|
-
plugins: [
|
|
373
|
-
'decorators-legacy',
|
|
374
|
-
...(typescript ? [['typescript', { dts: /\.d\.[cm]?ts$/i.test(file) }]] : []),
|
|
375
|
-
...(!typescript || /tsx$/i.test(file) ? ['jsx'] : [])
|
|
376
|
-
]
|
|
377
|
-
});
|
|
378
|
-
} catch (error) {
|
|
379
|
-
if (!(error instanceof SyntaxError)) throw error;
|
|
380
|
-
report({ loc: { start: error.loc } }, 'parse-error', 'error', error.message, 'Fix the syntax error before checking Fine Design APIs.');
|
|
381
|
-
continue;
|
|
382
|
-
}
|
|
383
|
-
visit(ast.program, collectScopes(ast.program));
|
|
384
|
-
}
|
|
210
|
+
visitCode(file, content, visit, (error) => {
|
|
211
|
+
report({ loc: { start: error.loc } }, 'parse-error', 'error', error.message, 'Fix the syntax error before checking Fine Design APIs.');
|
|
212
|
+
});
|
|
385
213
|
}
|
|
386
214
|
|
|
387
215
|
const errorCount = diagnostics.filter((d) => d.severity === 'error').length;
|
package/src/core/runtime.mjs
CHANGED
|
@@ -4,31 +4,35 @@ import { exactVersion, readIndex, sha256 } from './data.mjs';
|
|
|
4
4
|
import { ToolError } from './errors.mjs';
|
|
5
5
|
import html from './html.cjs';
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
const defaultRuntimeURL = 'npm';
|
|
8
|
+
const npmRuntime = '@finedesign/runtime';
|
|
8
9
|
const hosted = { fineDesign: ['@fx-ui/fine-design', 'fine-design', 'fine-design.min.js'], fineDesignCss: ['@fx-ui/fine-design', 'fine-design', 'fine-design.min.css'], vanAnalysis: ['@van/analysis', 'van-analysis', 'van-analysis.min.js'], vanAnalysisCss: ['@van/analysis', 'van-analysis', 'van-analysis.min.css'] };
|
|
9
10
|
const requiredResources = ['fineDesignCss', 'react', 'reactDOM', 'fineDesign'];
|
|
10
11
|
const invalid = (message) => { throw new ToolError('RUNTIME_INVALID', message, 1); };
|
|
11
12
|
|
|
12
13
|
export function validateRuntimeManifest(manifest) {
|
|
13
|
-
|
|
14
|
+
const packaged = manifest?.package === npmRuntime;
|
|
15
|
+
const expected = packaged ? [...requiredResources] : ['react', 'reactDOM', ...Object.keys(hosted)];
|
|
16
|
+
if (manifest?.schemaVersion !== 1 || !exactVersion.test(manifest.version) || !manifest.resources || Object.keys(manifest.resources).sort().join(',') !== expected.sort().join(',')) invalid('Invalid current runtime manifest.');
|
|
14
17
|
for (const [key, entry] of Object.entries(manifest.resources)) {
|
|
15
18
|
if (!entry || !exactVersion.test(entry.version) || !/^[a-f0-9]{64}$/.test(entry.sha256) || entry.integrity !== `sha256-${Buffer.from(entry.sha256, 'hex').toString('base64')}` || !Number.isSafeInteger(entry.size) || entry.size <= 0 || entry.type !== (key.endsWith('Css') ? 'style' : 'script')) invalid(`Invalid runtime resource: ${key}`);
|
|
16
19
|
if (hosted[key]) {
|
|
17
20
|
const [pkg, directory, filename] = hosted[key];
|
|
18
|
-
|
|
21
|
+
const expectedPath = packaged ? filename : `${directory}/${entry.version}/${filename}`;
|
|
22
|
+
if (entry.package !== pkg || entry.path !== expectedPath || entry.url) invalid(`Unexpected versioned resource path: ${key}`);
|
|
19
23
|
} else {
|
|
20
24
|
const pkg = key === 'react' ? 'react' : 'react-dom';
|
|
21
25
|
if (entry.package !== pkg || entry.path || entry.url !== `https://cdn.jsdelivr.net/npm/${pkg}@${entry.version}/umd/${pkg}.production.min.js`) invalid(`Unexpected React runtime: ${key}`);
|
|
22
26
|
}
|
|
23
27
|
}
|
|
24
28
|
const r = manifest.resources;
|
|
25
|
-
if (r.fineDesign.version !== manifest.version || r.fineDesignCss.version !== manifest.version || r.react.version !== r.reactDOM.version || r.vanAnalysis.version !== r.vanAnalysisCss.version) invalid('Runtime package versions do not match.');
|
|
29
|
+
if (r.fineDesign.version !== manifest.version || r.fineDesignCss.version !== manifest.version || r.react.version !== r.reactDOM.version || (!packaged && r.vanAnalysis.version !== r.vanAnalysisCss.version)) invalid('Runtime package versions do not match.');
|
|
26
30
|
return manifest;
|
|
27
31
|
}
|
|
28
32
|
|
|
29
|
-
async function readRuntime(value = defaultRuntimeURL) {
|
|
33
|
+
async function readRuntime(value = defaultRuntimeURL, version) {
|
|
30
34
|
let base;
|
|
31
|
-
try { base = new URL(value); } catch { invalid('Invalid runtime URL.'); }
|
|
35
|
+
try { base = new URL(value === 'npm' ? `https://cdn.jsdelivr.net/npm/${npmRuntime}@${version || 'latest'}/` : value); } catch { invalid('Invalid runtime URL.'); }
|
|
32
36
|
if ((base.protocol !== 'https:' && !(base.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname))) || base.username || base.password || base.search || base.hash) invalid('Use an HTTPS runtime URL without credentials, query or fragment; HTTP is allowed on loopback.');
|
|
33
37
|
if (!base.pathname.endsWith('/')) base.pathname += '/';
|
|
34
38
|
const manifestURL = new URL('manifest.json', base);
|
|
@@ -50,7 +54,9 @@ async function readRuntime(value = defaultRuntimeURL) {
|
|
|
50
54
|
suggestions: ['Check access to the manifest from this environment or pass --runtime-url with a verified host.']
|
|
51
55
|
});
|
|
52
56
|
}
|
|
53
|
-
|
|
57
|
+
validateRuntimeManifest(manifest);
|
|
58
|
+
if (value === 'npm' && manifest.package !== npmRuntime) invalid('Expected the public npm runtime manifest.');
|
|
59
|
+
return { runtimeURL: base.href, manifestURL: manifestURL.href, manifest };
|
|
54
60
|
}
|
|
55
61
|
|
|
56
62
|
export async function listRuntimes(runtimeURL) {
|
|
@@ -60,15 +66,20 @@ export async function listRuntimes(runtimeURL) {
|
|
|
60
66
|
|
|
61
67
|
export async function resolveRuntime({ version, runtimeURL }) {
|
|
62
68
|
if (version !== undefined && !exactVersion.test(version)) throw new ToolError('INVALID_ARGUMENT', 'Specify an exact component version.', 2);
|
|
63
|
-
|
|
69
|
+
if (!version && (runtimeURL ?? defaultRuntimeURL) === 'npm') {
|
|
70
|
+
const { versions } = await listRuntimes('npm');
|
|
71
|
+
version = versions[0];
|
|
72
|
+
}
|
|
73
|
+
const current = await readRuntime(runtimeURL, version);
|
|
64
74
|
const targetVersion = version || current.manifest.version;
|
|
65
|
-
if (current.manifest.version !== targetVersion) throw new ToolError('RUNTIME_VERSION_NOT_FOUND', `
|
|
75
|
+
if (current.manifest.version !== targetVersion) throw new ToolError('RUNTIME_VERSION_NOT_FOUND', `The runtime manifest contains Fine Design ${current.manifest.version}; requested ${targetVersion}.`, 3, { availableVersions: [current.manifest.version] });
|
|
66
76
|
const resources = Object.fromEntries(Object.entries(current.manifest.resources).map(([key, entry]) => [key, { ...entry, url: entry.url || new URL(entry.path, current.manifestURL).href }]));
|
|
67
77
|
const tags = requiredResources.map((key) => {
|
|
68
78
|
const entry = resources[key];
|
|
69
79
|
return entry.type === 'style' ? `<link rel="stylesheet" href="${entry.url}" integrity="${entry.integrity}" crossorigin="anonymous">` : `<script src="${entry.url}" integrity="${entry.integrity}" crossorigin="anonymous"></script>`;
|
|
70
80
|
}).join('\n');
|
|
71
|
-
|
|
81
|
+
const example = current.manifest.package === npmRuntime ? {} : { exampleURL: new URL('index.html', current.runtimeURL).href };
|
|
82
|
+
return { version: targetVersion, docsAvailable: Object.hasOwn(readIndex().versions, targetVersion), manifestURL: current.manifestURL, ...example, resources, tags };
|
|
72
83
|
}
|
|
73
84
|
|
|
74
85
|
export async function exportRuntime(runtime, output, dryRun = false) {
|