@finedesign/cli 0.8.0 → 0.9.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.
@@ -2,17 +2,15 @@
2
2
  "schemaVersion": 1,
3
3
  "version": "1.25.0",
4
4
  "sourceKind": "repository-snapshot",
5
- "sourceRevision": "c9d380a665f17001c406dbb081b1fcd91f6befa7",
5
+ "sourceRevision": "92a59ee18e00b27b76e666638c27534e2f3be53a",
6
6
  "sourceDirty": false,
7
- "contentHash": "b4069c8284ff843f8824b5685dad688e867eb13622832cedc36cfbe48da584a3",
8
- "catalogSha256": "63de4489e56aaf268d6363a65f35bd57cede27cd679afba7ae45bcc49ae16500",
7
+ "contentHash": "4bbd31b489ef7fbe290d88499038147053f7dd148a502ba5553e6bf1dce6b7f7",
8
+ "catalogSha256": "118ce4717d01727ee24291b62aa06ee1740cbd129bebb18734fbcaa4e1b045e3",
9
9
  "skillFiles": {
10
- "references/component-guide.md": "a91d47075e1c9fc90e8c4a5160e645a4d6ba7d12903688014cd1a22b0c5ef627",
10
+ "references/component-guide.md": "e48d32c664034bae5cf3aaf2d8c294f99e3374645e2b8482844e79e82b8548b6",
11
11
  "references/docs-slug-map.md": "440ce5cf137fd22eabfcc5b51c3f55b85174aa643773ef0cedd5df542e77bbc2",
12
- "references/imports-and-setup.md": "12278a80918a003a2285da510a77e77521a2771d47ae7bd0c8ea3f9a181d8398",
13
- "references/standalone-task-page.md": "97f05c06e1a4e7a9517d53ed6a358d9515d799e1b8c8731cbd50ccf060f3eaea",
14
- "references/task-list.js": "8e9f7daea7b8a003b0eb4cc1fc510b4a2d37f6812c846c882c01fa23be5adf19",
12
+ "references/imports-and-setup.md": "012baad54842ba16f4b770295f3f9beabcd090ecbcee78dade9c663e740edd3c",
15
13
  "references/theme-and-dark-mode.md": "2eccae4930ea993e7088eee03a4b4a0f1c839033079db5f21f8c60e0fe8168d1",
16
- "SKILL.md": "ad0bb8cf8a588b28e06a2a786483cb54124198a1e2bdf2e99a4c178147cd7968"
14
+ "SKILL.md": "e1024432c8b37d88057cfd851d40d3f1747b8b0354d12f9c4d510810757d62c8"
17
15
  }
18
16
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@finedesign/cli",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Versioned Fine Design docs, code checks and agent setup for coding agents",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -31,5 +31,4 @@ Use the project-local `npx fine-design` when installed, otherwise the global `fi
31
31
  | Condition | Reference |
32
32
  | --- | --- |
33
33
  | Version mismatch, installation failures, unavailable docs, imports, or standalone setup | [imports-and-setup.md](references/imports-and-setup.md) |
34
- | New standalone table with filters, pagination and draft editing, or offline runtime export | [standalone-task-page.md](references/standalone-task-page.md) |
35
34
  | Theme, dark mode, or scoped themes | [theme-and-dark-mode.md](references/theme-and-dark-mode.md) |
@@ -67,6 +67,6 @@ render: (_value, record) => {
67
67
  - Verify affected behavior: change a filter from a later page; cancel then confirm removal; submit an invalid draft; cancel an edit; save and reopen another row. Choose checks for the actual change rather than testing every example.
68
68
  - Check business wording against actual predicates (calendar week versus rolling days), ensure actions report real results, and verify keyboard access to filters, cards and actions. New multi-project records must select or inherit the intended project. CLI lint does not verify these business contracts.
69
69
 
70
- For standalone HTML, see the bundled [task page](standalone-task-page.md). Use shared semantic tokens for page surfaces/text instead of recoloring every component; select exact theme tokens through `token` when needed.
70
+ Use shared semantic tokens for page surfaces/text instead of recoloring every component; select exact theme tokens through `token` when needed.
71
71
 
72
72
  For full page patterns in this repository, consult `playground/product-list/index.tsx`. Outside it, reuse local project examples. These are references, not dependencies for single-file outputs.
@@ -56,7 +56,7 @@ Run `npx -y @finedesign/cli runtime list --format json` first and check its exit
56
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
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.
58
58
 
59
- 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`; it also includes a working [task page](standalone-task-page.md). 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.
59
+ 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
60
 
61
61
  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
62
 
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 or list Code Connect mappings
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:
@@ -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);
@@ -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) {
@@ -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 primaryNodeId = figmaData.primaryLinks[exact[0]?.component];
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/html.cjs CHANGED
@@ -1,4 +1,4 @@
1
- function exampleHTML(resources, prefix, appScript) {
1
+ function exampleHTML(resources, prefix) {
2
2
  const url = (entry) => entry.url || `${prefix}${entry.path}`;
3
3
  const escape = (value) => String(value).replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
4
4
  const css = resources.fineDesignCss;
@@ -8,14 +8,6 @@ function exampleHTML(resources, prefix, appScript) {
8
8
  const entry = resources[name];
9
9
  return `<script defer src="${escape(url(entry))}" integrity="${escape(entry.integrity)}" crossorigin="anonymous" ${events(name)}></script>`;
10
10
  }).join('\n');
11
- const state = appScript ? '' : 'const [count, setCount] = React.useState(0);';
12
- const demo = appScript ? 'return h(window.FineDesignTaskList);' : `return h('div', { className: 'demo' },
13
- h('p', null, '每一次交互,都由真实组件驱动'),
14
- h('output', { className: 'demo-count', 'aria-live': 'polite' }, String(count).padStart(2, '0')),
15
- h('p', null, '试着点击按钮,开始你的第一次交互。'),
16
- h('div', { className: 'demo-actions' },
17
- h(FineDesign.Button, { type: 'primary', onClick: () => setCount(count + 1) }, '已点击 ' + count + ' 次'),
18
- h(FineDesign.Button, { type: 'normal', onClick: () => setCount(0) }, '重置')));`;
19
11
  return `<!doctype html>
20
12
  <html lang="zh-CN">
21
13
  <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
@@ -96,7 +88,7 @@ function exampleHTML(resources, prefix, appScript) {
96
88
  </main>
97
89
  <footer><span>Fine Design ${escape(resources.fineDesign.version)} / React ${escape(resources.react.version)}</span><span>组件通过 window.FineDesign 提供</span></footer>
98
90
  </div>
99
- ${appScript ? `<script src="${escape(appScript)}"></script>\n` : ''}<script>
91
+ <script>
100
92
  (() => {
101
93
  const loaded = new Set();
102
94
  const status = document.getElementById('runtime-status');
@@ -116,13 +108,19 @@ ${appScript ? `<script src="${escape(appScript)}"></script>\n` : ''}<script>
116
108
  if (!window.React || !window.FineDesign || !window.ReactDOM || typeof ReactDOM.createRoot !== 'function') throw new Error('Missing runtime');
117
109
  const h = React.createElement;
118
110
  function App() {
119
- ${state}
111
+ const [count, setCount] = React.useState(0);
120
112
  React.useEffect(() => {
121
113
  document.body.dataset.state = 'ready';
122
114
  document.getElementById('root').setAttribute('aria-busy', 'false');
123
115
  status.textContent = '运行时已就绪';
124
116
  }, []);
125
- ${demo}
117
+ return h('div', { className: 'demo' },
118
+ h('p', null, '每一次交互,都由真实组件驱动'),
119
+ h('output', { className: 'demo-count', 'aria-live': 'polite' }, String(count).padStart(2, '0')),
120
+ h('p', null, '试着点击按钮,开始你的第一次交互。'),
121
+ h('div', { className: 'demo-actions' },
122
+ h(FineDesign.Button, { type: 'primary', onClick: () => setCount(count + 1) }, '已点击 ' + count + ' 次'),
123
+ h(FineDesign.Button, { type: 'normal', onClick: () => setCount(0) }, '重置')));
126
124
  }
127
125
  ReactDOM.createRoot(document.getElementById('root')).render(h(App));
128
126
  }
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
- const results = [];
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 = /\.[cm]?tsx?$/i.test(file);
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, scopes) {
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
- for (const source of codeSources(file, content)) {
368
- let ast;
369
- try {
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;
@@ -82,7 +82,7 @@ export async function exportRuntime(runtime, output, dryRun = false) {
82
82
  const entry = runtime.resources[name];
83
83
  return [name, { ...entry, localPath: `vendor/${path.posix.basename(new URL(entry.url).pathname)}` }];
84
84
  }));
85
- const plannedFiles = ['index.html', 'task-list.html', 'task-list.js', 'runtime-lock.json', ...Object.values(resources).map((entry) => entry.localPath)];
85
+ const plannedFiles = ['index.html', 'runtime-lock.json', ...Object.values(resources).map((entry) => entry.localPath)];
86
86
  const report = { version: runtime.version, targetDir, plannedFiles, writtenFiles: [], dryRun };
87
87
  if (dryRun) return report;
88
88
  const files = new Map();
@@ -107,8 +107,6 @@ export async function exportRuntime(runtime, output, dryRun = false) {
107
107
  }
108
108
  const localResources = Object.fromEntries(Object.entries(resources).map(([name, entry]) => [name, { ...entry, url: entry.localPath }]));
109
109
  files.set('index.html', html.exampleHTML(localResources, './'));
110
- files.set('task-list.html', html.exampleHTML(localResources, './', 'task-list.js'));
111
- files.set('task-list.js', fs.readFileSync(new URL('../../skills/fine-design/references/task-list.js', import.meta.url)));
112
110
  files.set('runtime-lock.json', JSON.stringify({ schemaVersion: 1, version: runtime.version, manifestURL: runtime.manifestURL, resources }, null, 2) + '\n');
113
111
  const parent = path.dirname(targetDir);
114
112
  fs.mkdirSync(parent, { recursive: true });