@finedesign/cli 0.6.1 → 0.8.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.
@@ -0,0 +1,138 @@
1
+ import fs from 'node:fs';
2
+ import { ToolError } from './errors.mjs';
3
+
4
+ const figmaData = JSON.parse(fs.readFileSync(new URL('./figma-data.json', import.meta.url), 'utf8'));
5
+
6
+ export function normalizeNodeId(nodeId) {
7
+ if (!nodeId || typeof nodeId !== 'string') return null;
8
+ const trimmed = nodeId.trim();
9
+ const match = trimmed.match(/^(\d+)[:-](\d+)$/);
10
+ return match ? `${match[1]}:${match[2]}` : null;
11
+ }
12
+
13
+ export function parseFigmaUrl(value) {
14
+ try {
15
+ const url = new URL(value);
16
+ if (!['http:', 'https:'].includes(url.protocol) || !['figma.com', 'www.figma.com'].includes(url.hostname)) return null;
17
+ const path = url.pathname.match(/^\/(?:design|file)\/([a-z\d]+)(?:\/branch\/([a-z\d]+))?(?:\/|$)/i);
18
+ if (!path) return null;
19
+ return { fileKey: path[2] || path[1], nodeId: normalizeNodeId(url.searchParams.get('node-id')) };
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ function matchedResult(match, query) {
26
+ return {
27
+ matched: true,
28
+ query,
29
+ component: match.component,
30
+ designName: match.designName,
31
+ nodeId: match.nodeId,
32
+ url: match.url,
33
+ fileKey: figmaData.fileKey,
34
+ codeConnect: {
35
+ templateId: match.templateId,
36
+ templateFile: match.file,
37
+ source: match.source,
38
+ imports: match.imports,
39
+ connectedComponent: match.connectedComponent,
40
+ wrapperSignature: match.wrapperSignature,
41
+ shortcut: match.shortcut,
42
+ businessInputs: match.businessInputs,
43
+ exampleSnippet: match.exampleSnippet,
44
+ exampleNodeId: match.exampleNodeId,
45
+ exampleImports: match.exampleImports
46
+ },
47
+ designProperties: match.properties,
48
+ recommendations: match.recommendations,
49
+ apiDocHint: `fine-design info ${match.component.split('.')[0]}`
50
+ };
51
+ }
52
+
53
+ export function resolveFigmaComponent(input = {}) {
54
+ const target = (input.target || input.url || input.nodeId || input.component || '').trim();
55
+ if (!target) {
56
+ throw new ToolError('INVALID_ARGUMENT', 'Target URL, node ID, or component name is required.', 2);
57
+ }
58
+
59
+ const isUrl = (!input.target && !!input.url) || /^[a-z][a-z\d+.-]*:\/\//i.test(target);
60
+ const url = isUrl ? parseFigmaUrl(target) : null;
61
+ if (isUrl && url?.fileKey !== figmaData.fileKey) {
62
+ return {
63
+ matched: false,
64
+ query: { input: target },
65
+ message: `Use a Figma design or file URL from the Fine Design library (${figmaData.fileKey}). For a project design, use Figma MCP to locate the library's main component first.`
66
+ };
67
+ }
68
+ const nodeId = isUrl ? url.nodeId : normalizeNodeId(target);
69
+ if (isUrl || nodeId || (!input.target && input.nodeId)) {
70
+ const query = { input: target, nodeId };
71
+ const match = figmaData.mappings.find((m) => m.nodeId === nodeId);
72
+ if (match) return matchedResult(match, query);
73
+ return {
74
+ matched: false,
75
+ query,
76
+ message: 'No mapped library node found. Use Figma MCP to locate the main component for a page, instance or variant, then query its URL or node ID.'
77
+ };
78
+ }
79
+
80
+ const searchName = target.toLowerCase().replace(/[-_\s]/g, '');
81
+ const canonicalName = (Object.hasOwn(figmaData.aliases, searchName) ? figmaData.aliases[searchName] : target).toLowerCase();
82
+
83
+ // Check known unmapped notes
84
+ for (const [unmappedName, note] of Object.entries(figmaData.unmappedNotes)) {
85
+ const unmappedLower = unmappedName.toLowerCase();
86
+ if (unmappedLower === searchName || unmappedLower === canonicalName) {
87
+ return {
88
+ matched: false,
89
+ unmapped: true,
90
+ component: unmappedName,
91
+ note,
92
+ fileKey: figmaData.fileKey,
93
+ apiDocHint: `fine-design info ${unmappedName}`
94
+ };
95
+ }
96
+ }
97
+
98
+ 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]
101
+ ?? figmaData.mappings.find((m) => m.component.toLowerCase().replace(/[-_\s.]/g, '') === searchName)
102
+ ?? (searchName && figmaData.mappings.find((m) => m.designName.toLowerCase().includes(searchName) || m.component.toLowerCase().includes(searchName)));
103
+ if (matchedEntry) {
104
+ return matchedResult(matchedEntry, { input: target, component: matchedEntry.component });
105
+ }
106
+
107
+ // Suggestions when not matched
108
+ const suggestions = figmaData.mappings
109
+ .filter((m) => searchName && m.component.toLowerCase().includes(searchName.slice(0, 3)))
110
+ .map((m) => `${m.component} (${m.designName})`)
111
+ .slice(0, 5);
112
+
113
+ return {
114
+ matched: false,
115
+ query: { input: target },
116
+ message: `No matching Fine Design component found for "${target}".`,
117
+ ...(suggestions.length ? { suggestions } : {})
118
+ };
119
+ }
120
+
121
+ export function listFigmaComponents() {
122
+ return {
123
+ total: figmaData.mappings.length,
124
+ fileKey: figmaData.fileKey,
125
+ indexNodeId: figmaData.indexNodeId,
126
+ components: figmaData.mappings.map((m) => ({
127
+ component: m.component,
128
+ designName: m.designName,
129
+ nodeId: m.nodeId,
130
+ url: m.url,
131
+ templateId: m.templateId,
132
+ templateFile: m.file,
133
+ imports: m.imports,
134
+ shortcut: m.shortcut,
135
+ businessInputs: m.businessInputs
136
+ }))
137
+ };
138
+ }
package/src/core/html.cjs CHANGED
@@ -1,4 +1,4 @@
1
- function exampleHTML(resources, prefix) {
1
+ function exampleHTML(resources, prefix, appScript) {
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,6 +8,14 @@ function exampleHTML(resources, prefix) {
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) }, '重置')));`;
11
19
  return `<!doctype html>
12
20
  <html lang="zh-CN">
13
21
  <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
@@ -88,7 +96,7 @@ function exampleHTML(resources, prefix) {
88
96
  </main>
89
97
  <footer><span>Fine Design ${escape(resources.fineDesign.version)} / React ${escape(resources.react.version)}</span><span>组件通过 window.FineDesign 提供</span></footer>
90
98
  </div>
91
- <script>
99
+ ${appScript ? `<script src="${escape(appScript)}"></script>\n` : ''}<script>
92
100
  (() => {
93
101
  const loaded = new Set();
94
102
  const status = document.getElementById('runtime-status');
@@ -108,19 +116,13 @@ function exampleHTML(resources, prefix) {
108
116
  if (!window.React || !window.FineDesign || !window.ReactDOM || typeof ReactDOM.createRoot !== 'function') throw new Error('Missing runtime');
109
117
  const h = React.createElement;
110
118
  function App() {
111
- const [count, setCount] = React.useState(0);
119
+ ${state}
112
120
  React.useEffect(() => {
113
121
  document.body.dataset.state = 'ready';
114
122
  document.getElementById('root').setAttribute('aria-busy', 'false');
115
123
  status.textContent = '运行时已就绪';
116
124
  }, []);
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) }, '重置')));
125
+ ${demo}
124
126
  }
125
127
  ReactDOM.createRoot(document.getElementById('root')).render(h(App));
126
128
  }
package/src/core/lint.mjs CHANGED
@@ -133,6 +133,10 @@ function collectScopes(program) {
133
133
  if (spec.type === 'ImportSpecifier') scope.bindings.set(spec.local.name, { component: spec.imported.name ?? spec.imported.value });
134
134
  else if (spec.type === 'ImportNamespaceSpecifier') scope.bindings.set(spec.local.name, { namespace: true });
135
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
+ }
136
140
  }
137
141
  } else if (node.type === 'VariableDeclaration') {
138
142
  const targetScope = node.kind === 'var' ? scope.varScope : scope;
@@ -196,6 +200,7 @@ function componentName(node, scope) {
196
200
  function isReactCreateElement(node, scope) {
197
201
  if (node.type === 'Identifier') {
198
202
  const binding = findBinding(scope, node.name);
203
+ if (binding?.reactFactory) return true;
199
204
  node = binding?.initializer;
200
205
  scope = binding?.scope;
201
206
  }
@@ -204,9 +209,25 @@ function isReactCreateElement(node, scope) {
204
209
  if (node.object.type !== 'Identifier') return false;
205
210
  const binding = findBinding(scope, node.object.name);
206
211
  return (node.object.name === 'React' && binding === undefined) ||
212
+ binding?.reactNamespace ||
207
213
  isGlobalMember(binding?.initializer, binding?.scope, 'window', 'React');
208
214
  }
209
215
 
216
+ function staticProps(attributes) {
217
+ const props = new Map();
218
+ let unknown = false;
219
+ for (const attr of attributes) {
220
+ if (attr.type === 'SpreadElement' || attr.type === 'JSXSpreadAttribute' || attr.computed) {
221
+ unknown = true;
222
+ for (const prop of props.values()) prop.value = undefined;
223
+ } else {
224
+ const name = attr.type === 'JSXAttribute' ? attr.name.name : attr.key?.name ?? attr.key?.value;
225
+ if (typeof name === 'string') props.set(name, { node: attr, value: attr.value?.type === 'JSXExpressionContainer' ? attr.value.expression : attr.value });
226
+ }
227
+ }
228
+ return { props, unknown };
229
+ }
230
+
210
231
  export function lintFiles(catalog, targets = ['.']) {
211
232
  const files = [...new Set(targets.flatMap((t) => collectFiles(t)))];
212
233
  const validValueExports = new Set(EXTRA_VALUE_EXPORTS);
@@ -256,6 +277,57 @@ export function lintFiles(catalog, targets = ['.']) {
256
277
  report(node, 'unknown-export', 'error', `Unknown export "${name}" from @fx-ui/fine-design.`, suggestion);
257
278
  };
258
279
 
280
+ function checkProps(component, attributes) {
281
+ if (!component) return;
282
+ const { props, unknown } = staticProps(attributes);
283
+ if (component === 'Pagination' && props.has('sizeSet') && !props.has('showPageSize') && !unknown) {
284
+ report(props.get('sizeSet').node, 'pagination-missing-showpagesize', 'warning',
285
+ 'Pagination has "sizeSet" but lacks "showPageSize".',
286
+ 'Provide showPageSize: (size) => String(size) so the page size selector is displayed.');
287
+ }
288
+ for (const [name, { node, value }] of props) {
289
+ if (component === 'Button' && name === 'type') {
290
+ checkButtonType(node, value?.value);
291
+ } else if (component === 'NextTable' && name === 'columns') {
292
+ report(node, 'next-table-columns-prop', 'error', 'NextTable does not accept a "columns" prop.',
293
+ 'Declare NextTable.Column, NextTable.HeaderCell, and NextTable.Cell children instead.');
294
+ } else if (component === 'NextTable' && name === 'pagination' && value?.type === 'ObjectExpression') {
295
+ const pagination = staticProps(value.properties);
296
+ for (const [oldName, newName] of [['current', 'page'], ['pageSize', 'size']]) {
297
+ if (pagination.props.has(oldName)) report(pagination.props.get(oldName).node,
298
+ oldName === 'current' ? 'pagination-current-prop' : 'pagination-pagesize-prop', 'error',
299
+ `NextTable pagination object does not accept a "${oldName}" property.`, `Use "${newName}" instead of "${oldName}".`);
300
+ }
301
+ if (pagination.props.has('sizeSet') && !pagination.props.has('showPageSize') && !pagination.unknown) {
302
+ report(pagination.props.get('sizeSet').node, 'pagination-missing-showpagesize', 'warning',
303
+ 'NextTable pagination object has "sizeSet" but lacks "showPageSize".',
304
+ 'Provide showPageSize: (size) => String(size) so the page size selector is displayed.');
305
+ }
306
+ } else if (component === 'Select' && name === 'items') {
307
+ report(node, 'select-items-prop', 'error', 'Select does not accept an "items" prop.',
308
+ 'Use "options" ({ label, value }[]) for Select, or use Combo / Combo.Check if you intended a Combo dropdown with items.');
309
+ } else if ((component === 'Combo' || component === 'Combo.Check') && name === 'options') {
310
+ report(node, 'combo-options-prop', 'error', `${component} does not accept an "options" prop.`,
311
+ `Use "items" ({ text, value }[]) for ${component}.`);
312
+ } else if (component === 'PopConfirm' && name === 'onConfirm') {
313
+ report(node, 'popconfirm-onconfirm-prop', 'error', 'PopConfirm does not accept an "onConfirm" prop.',
314
+ 'Use "onOk" for confirmation callback in PopConfirm.');
315
+ } else if (component === 'Pagination' && (name === 'current' || name === 'pageSize')) {
316
+ report(node, name === 'current' ? 'pagination-current-prop' : 'pagination-pagesize-prop', 'error',
317
+ `Pagination does not accept a "${name}" prop.`, `Use "${name === 'current' ? 'page' : 'size'}" instead of "${name}".`);
318
+ } else if (component === 'Dialog' && name === 'onCloseBtnClick') {
319
+ report(node, 'dialog-deprecated-close-btn', 'warning', 'Dialog "onCloseBtnClick" is deprecated and fires alongside "onCancel" when clicking the close button.',
320
+ 'Handle close and cancel solely via "onCancel".');
321
+ } else if (component === 'Tag' && name === 'color') {
322
+ report(node, 'tag-color-prop', 'warning', 'Tag does not support a "color" prop.',
323
+ 'Use semantic type or custom style={{ color, backgroundColor }}.');
324
+ } else if (component === 'ConfigProvider' && name === 'prefixCls' && value?.value === 'fd') {
325
+ report(node, 'config-provider-dumi-prefix', 'warning', 'ConfigProvider has hardcoded prefixCls="fd" (used only by the Dumi doc site).',
326
+ 'Remove prefixCls="fd" so components match the default CSS class prefix in production and UMD builds.');
327
+ }
328
+ }
329
+ }
330
+
259
331
  function visit(node, scopes) {
260
332
  const scope = scopes.get(node);
261
333
  if (node.type === 'ImportDeclaration') {
@@ -281,85 +353,10 @@ export function lintFiles(catalog, targets = ['.']) {
281
353
  if (prop.type === 'ObjectProperty' && !prop.computed) checkExport(String(prop.key.name ?? prop.key.value), prop);
282
354
  }
283
355
  }
284
- } else if (node.type === 'CallExpression' && node.arguments[1]?.type === 'ObjectExpression' &&
285
- isReactCreateElement(node.callee, scope) && componentName(node.arguments[0], scope) === 'Button') {
286
- const type = node.arguments[1].properties.findLast((prop) =>
287
- prop.type === 'SpreadElement' || prop.computed || (prop.key.name ?? prop.key.value) === 'type');
288
- if (type?.type === 'ObjectProperty' && !type.computed) checkButtonType(type, type.value.value);
356
+ } else if (node.type === 'CallExpression' && node.arguments[1]?.type === 'ObjectExpression' && isReactCreateElement(node.callee, scope)) {
357
+ checkProps(componentName(node.arguments[0], scope), node.arguments[1].properties);
289
358
  } else if (node.type === 'JSXOpeningElement') {
290
- const component = componentName(node.name, scope);
291
- const jsxAttrs = node.attributes.filter((item) => item.type === 'JSXAttribute');
292
- const attrNames = new Set(jsxAttrs.map((item) => item.name?.name));
293
-
294
- if (component === 'Pagination' && attrNames.has('sizeSet') && !attrNames.has('showPageSize')) {
295
- const sizeSetAttr = jsxAttrs.find((item) => item.name?.name === 'sizeSet');
296
- report(sizeSetAttr, 'pagination-missing-showpagesize', 'warning',
297
- 'Pagination has "sizeSet" but lacks "showPageSize".',
298
- 'Provide showPageSize={(size) => String(size)} so the page size selector is displayed.');
299
- }
300
-
301
- for (const attr of jsxAttrs) {
302
- const name = attr.name.name;
303
- const value = (attr.value?.expression || attr.value)?.value;
304
- if (component === 'Button' && name === 'type') {
305
- checkButtonType(attr, value);
306
- } else if (component === 'NextTable' && name === 'columns') {
307
- report(attr, 'next-table-columns-prop', 'error', 'NextTable does not accept a "columns" prop.',
308
- 'Declare <NextTable.Column>, <NextTable.HeaderCell>, and <NextTable.Cell dataKey="..."> children instead.');
309
- } else if (component === 'NextTable' && name === 'pagination' && attr.value?.type === 'JSXExpressionContainer' && attr.value.expression?.type === 'ObjectExpression') {
310
- const props = attr.value.expression.properties;
311
- const propMap = new Map();
312
- for (const prop of props) {
313
- if (prop.type === 'ObjectProperty' && !prop.computed) {
314
- propMap.set(prop.key.name ?? prop.key.value, prop);
315
- }
316
- }
317
- if (propMap.has('current')) {
318
- report(propMap.get('current'), 'pagination-current-prop', 'error',
319
- 'NextTable pagination object does not accept a "current" property.',
320
- 'Use "page" instead of "current" to specify the active page.');
321
- }
322
- if (propMap.has('pageSize')) {
323
- report(propMap.get('pageSize'), 'pagination-pagesize-prop', 'error',
324
- 'NextTable pagination object does not accept a "pageSize" property.',
325
- 'Use "size" instead of "pageSize" to specify the page size.');
326
- }
327
- if (propMap.has('sizeSet') && !propMap.has('showPageSize')) {
328
- report(propMap.get('sizeSet'), 'pagination-missing-showpagesize', 'warning',
329
- 'NextTable pagination object has "sizeSet" but lacks "showPageSize".',
330
- 'Provide showPageSize: (size) => String(size) so the page size selector is displayed.');
331
- }
332
- } else if (component === 'Select' && name === 'items') {
333
- report(attr, 'select-items-prop', 'error',
334
- 'Select does not accept an "items" prop.',
335
- 'Use "options" ({ label, value }[]) for Select, or use Combo / Combo.Check if you intended a Combo dropdown with items.');
336
- } else if ((component === 'Combo' || component === 'Combo.Check') && name === 'options') {
337
- report(attr, 'combo-options-prop', 'error',
338
- `${component} does not accept an "options" prop.`,
339
- `Use "items" ({ text, value }[]) for ${component}.`);
340
- } else if (component === 'PopConfirm' && name === 'onConfirm') {
341
- report(attr, 'popconfirm-onconfirm-prop', 'error',
342
- 'PopConfirm does not accept an "onConfirm" prop.',
343
- 'Use "onOk" for confirmation callback in PopConfirm.');
344
- } else if (component === 'Pagination' && name === 'current') {
345
- report(attr, 'pagination-current-prop', 'error',
346
- 'Pagination does not accept a "current" prop.',
347
- 'Use "page" instead of "current" to specify the active page.');
348
- } else if (component === 'Pagination' && name === 'pageSize') {
349
- report(attr, 'pagination-pagesize-prop', 'error',
350
- 'Pagination does not accept a "pageSize" prop.',
351
- 'Use "size" instead of "pageSize" to specify the page size.');
352
- } else if (component === 'Dialog' && name === 'onCloseBtnClick') {
353
- report(attr, 'dialog-deprecated-close-btn', 'warning', 'Dialog "onCloseBtnClick" is deprecated and fires alongside "onCancel" when clicking the close button.',
354
- 'Handle close and cancel solely via "onCancel".');
355
- } else if (component === 'Tag' && name === 'color') {
356
- report(attr, 'tag-color-prop', 'warning', 'Tag does not support a "color" prop.',
357
- 'Use semantic type ("default" | "primary" | "success" | "warning" | "error") or custom style={{ color, backgroundColor }}.');
358
- } else if (component === 'ConfigProvider' && name === 'prefixCls' && value === 'fd') {
359
- report(attr, 'config-provider-dumi-prefix', 'warning', 'ConfigProvider has hardcoded prefixCls="fd" (used only by the Dumi doc site).',
360
- 'Remove prefixCls="fd" so components match the default "f-" CSS class prefix in production and UMD builds.');
361
- }
362
- }
359
+ checkProps(componentName(node.name, scope), node.attributes);
363
360
  }
364
361
  for (const child of Object.values(node)) {
365
362
  if (Array.isArray(child)) child.filter((item) => item?.type).forEach((item) => visit(item, scopes));
@@ -1,8 +1,12 @@
1
- import { exactVersion, readIndex } from './data.mjs';
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { exactVersion, readIndex, sha256 } from './data.mjs';
2
4
  import { ToolError } from './errors.mjs';
5
+ import html from './html.cjs';
3
6
 
4
7
  export const defaultRuntimeURL = 'https://fine-design-runtime.pages.dev/';
5
8
  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
+ const requiredResources = ['fineDesignCss', 'react', 'reactDOM', 'fineDesign'];
6
10
  const invalid = (message) => { throw new ToolError('RUNTIME_INVALID', message, 1); };
7
11
 
8
12
  export function validateRuntimeManifest(manifest) {
@@ -60,9 +64,62 @@ export async function resolveRuntime({ version, runtimeURL }) {
60
64
  const targetVersion = version || current.manifest.version;
61
65
  if (current.manifest.version !== targetVersion) throw new ToolError('RUNTIME_VERSION_NOT_FOUND', `Only Fine Design ${current.manifest.version} is currently hosted; ${targetVersion} is unavailable. Historical UMD files are not retained.`, 3, { availableVersions: [current.manifest.version] });
62
66
  const resources = Object.fromEntries(Object.entries(current.manifest.resources).map(([key, entry]) => [key, { ...entry, url: entry.url || new URL(entry.path, current.manifestURL).href }]));
63
- const tags = ['fineDesignCss', 'react', 'reactDOM', 'fineDesign'].map((key) => {
67
+ const tags = requiredResources.map((key) => {
64
68
  const entry = resources[key];
65
69
  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>`;
66
70
  }).join('\n');
67
71
  return { version: targetVersion, docsAvailable: Object.hasOwn(readIndex().versions, targetVersion), manifestURL: current.manifestURL, exampleURL: new URL('index.html', current.runtimeURL).href, resources, tags };
68
72
  }
73
+
74
+ export async function exportRuntime(runtime, output, dryRun = false) {
75
+ if (typeof output !== 'string' || !output.trim()) throw new ToolError('INVALID_ARGUMENT', '--output requires a directory.', 2);
76
+ const targetDir = path.resolve(output);
77
+ const checkConflict = () => {
78
+ if (fs.lstatSync(targetDir, { throwIfNoEntry: false })) throw new ToolError('FILE_EXISTS', `Directory already exists: ${targetDir}. Choose a new --output directory.`, 1);
79
+ };
80
+ checkConflict();
81
+ const resources = Object.fromEntries(requiredResources.map((name) => {
82
+ const entry = runtime.resources[name];
83
+ return [name, { ...entry, localPath: `vendor/${path.posix.basename(new URL(entry.url).pathname)}` }];
84
+ }));
85
+ const plannedFiles = ['index.html', 'task-list.html', 'task-list.js', 'runtime-lock.json', ...Object.values(resources).map((entry) => entry.localPath)];
86
+ const report = { version: runtime.version, targetDir, plannedFiles, writtenFiles: [], dryRun };
87
+ if (dryRun) return report;
88
+ const files = new Map();
89
+ for (const entry of Object.values(resources)) {
90
+ if (entry.size > 32 * 1024 * 1024) invalid(`Runtime resource exceeds 32 MB: ${entry.url}`);
91
+ try {
92
+ const response = await fetch(entry.url, { redirect: 'error', signal: AbortSignal.timeout(30000) });
93
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
94
+ const chunks = []; let size = 0;
95
+ for await (const chunk of response.body) {
96
+ size += chunk.length;
97
+ if (size > entry.size) invalid(`Runtime resource exceeds its declared size: ${entry.url}`);
98
+ chunks.push(chunk);
99
+ }
100
+ const bytes = Buffer.concat(chunks);
101
+ if (bytes.length !== entry.size || sha256(bytes) !== entry.sha256) invalid(`Runtime resource integrity mismatch: ${entry.url}`);
102
+ files.set(entry.localPath, bytes);
103
+ } catch (error) {
104
+ if (error instanceof ToolError) throw error;
105
+ throw new ToolError('RUNTIME_UNAVAILABLE', `Cannot download ${entry.url}: ${error.message}`, 1);
106
+ }
107
+ }
108
+ const localResources = Object.fromEntries(Object.entries(resources).map(([name, entry]) => [name, { ...entry, url: entry.localPath }]));
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
+ files.set('runtime-lock.json', JSON.stringify({ schemaVersion: 1, version: runtime.version, manifestURL: runtime.manifestURL, resources }, null, 2) + '\n');
113
+ const parent = path.dirname(targetDir);
114
+ fs.mkdirSync(parent, { recursive: true });
115
+ const staging = fs.mkdtempSync(path.join(parent, '.fine-design-runtime-'));
116
+ try {
117
+ for (const [name, bytes] of files) {
118
+ fs.mkdirSync(path.dirname(path.join(staging, name)), { recursive: true });
119
+ fs.writeFileSync(path.join(staging, name), bytes);
120
+ }
121
+ checkConflict();
122
+ fs.renameSync(staging, targetDir);
123
+ } finally { fs.rmSync(staging, { recursive: true, force: true }); }
124
+ return { ...report, writtenFiles: plannedFiles };
125
+ }
package/src/mcp.mjs CHANGED
@@ -29,7 +29,9 @@ export async function startMcp() {
29
29
  lint_files: 'Scan code for Fine Design API traps. Pass an exact version if it cannot be detected from the targets.',
30
30
  get_component_example: 'List example IDs and titles, or pass exampleId to read source, dependencies and asset metadata. Version is optional. Set includeAssets with exampleId to include large assets.',
31
31
  list_browser_runtimes: 'Read the one currently hosted UMD version from its online manifest. Requires network access.',
32
- get_browser_runtime: 'Resolve a component version to versioned current UMD URLs and SRI loading tags. Version is optional (defaults to hosted version). Requires network access; never falls back to another version.'
32
+ get_browser_runtime: 'Resolve a component version to versioned current UMD URLs and SRI loading tags. Version is optional (defaults to hosted version). Requires network access; never falls back to another version.',
33
+ resolve_figma_component: 'Look up a Fine Design library node URL, library node ID, or component name in the offline Code Connect snapshot. Use Figma MCP first for page, frame, or instance links.',
34
+ list_figma_components: 'List all Figma-connected Fine Design components, node IDs, and Code Connect template IDs.'
33
35
  };
34
36
  server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: Object.entries(schemas).map(([name, schema]) => ({
35
37
  name, description: descriptions[name], inputSchema: z.toJSONSchema(schema, { target: 'draft-07' }),
@@ -61,6 +63,12 @@ export async function startMcp() {
61
63
  const version = resolveLintVersion(args.version, targets);
62
64
  const { lintFiles } = await import('./core/lint.mjs');
63
65
  result = lintFiles(loadCatalog(version), targets);
66
+ } else if (toolName === 'resolve_figma_component') {
67
+ const { resolveFigmaComponent } = await import('./core/figma.mjs');
68
+ result = resolveFigmaComponent(args);
69
+ } else if (toolName === 'list_figma_components') {
70
+ const { listFigmaComponents } = await import('./core/figma.mjs');
71
+ result = listFigmaComponents();
64
72
  } else {
65
73
  const ver = resolveMcpVersion(args.version);
66
74
  result = queryCatalog(loadCatalog(ver), toolName, { ...args, version: ver });