@finedesign/cli 0.6.1 → 0.7.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 +10 -0
- package/README.md +19 -13
- package/data/1.25.0/catalog.json +1 -1
- package/data/1.25.0/manifest.json +8 -6
- package/package.json +1 -1
- package/skills/fine-design/SKILL.md +5 -4
- package/skills/fine-design/references/component-guide.md +4 -0
- package/skills/fine-design/references/imports-and-setup.md +2 -0
- package/skills/fine-design/references/standalone-task-page.md +30 -0
- package/skills/fine-design/references/task-list.js +82 -0
- package/src/cli.mjs +15 -9
- package/src/core/html.cjs +12 -10
- package/src/core/lint.mjs +75 -78
- package/src/core/runtime.mjs +59 -2
|
@@ -2,15 +2,17 @@
|
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"version": "1.25.0",
|
|
4
4
|
"sourceKind": "repository-snapshot",
|
|
5
|
-
"sourceRevision": "
|
|
5
|
+
"sourceRevision": "1c7c921d638a7db72b10c53b264eb2b0a0c3ec9c",
|
|
6
6
|
"sourceDirty": false,
|
|
7
|
-
"contentHash": "
|
|
8
|
-
"catalogSha256": "
|
|
7
|
+
"contentHash": "556790f5c8bb8d702b3db8b5fe8925560bcdad642eb4f28de32d74b8e800401a",
|
|
8
|
+
"catalogSha256": "66c94445015341755aebe2a51e2947a4c3a76f796718f337f0eb1a5a81c56fbc",
|
|
9
9
|
"skillFiles": {
|
|
10
|
-
"references/component-guide.md": "
|
|
10
|
+
"references/component-guide.md": "a91d47075e1c9fc90e8c4a5160e645a4d6ba7d12903688014cd1a22b0c5ef627",
|
|
11
11
|
"references/docs-slug-map.md": "440ce5cf137fd22eabfcc5b51c3f55b85174aa643773ef0cedd5df542e77bbc2",
|
|
12
|
-
"references/imports-and-setup.md": "
|
|
12
|
+
"references/imports-and-setup.md": "12278a80918a003a2285da510a77e77521a2771d47ae7bd0c8ea3f9a181d8398",
|
|
13
|
+
"references/standalone-task-page.md": "97f05c06e1a4e7a9517d53ed6a358d9515d799e1b8c8731cbd50ccf060f3eaea",
|
|
14
|
+
"references/task-list.js": "8e9f7daea7b8a003b0eb4cc1fc510b4a2d37f6812c846c882c01fa23be5adf19",
|
|
13
15
|
"references/theme-and-dark-mode.md": "2eccae4930ea993e7088eee03a4b4a0f1c839033079db5f21f8c60e0fe8168d1",
|
|
14
|
-
"SKILL.md": "
|
|
16
|
+
"SKILL.md": "ad0bb8cf8a588b28e06a2a786483cb54124198a1e2bdf2e99a4c178147cd7968"
|
|
15
17
|
}
|
|
16
18
|
}
|
package/package.json
CHANGED
|
@@ -7,17 +7,17 @@ user-invocable: true
|
|
|
7
7
|
|
|
8
8
|
# Fine Design
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
Apply this skill proactively when the task asks for Fine Design pages or touches `@fx-ui/fine-design` / `window.FineDesign` components, including fixes and reviews. Do not wait for a `/fine-design` invocation. Unrelated tasks do not trigger CLI calls. This folder guides AI; generated code must run without resolving skill files.
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
Use the project-local `npx fine-design` when installed, otherwise the global `fine-design`; fall back to `npx -y @finedesign/cli` when neither is available. On the first Fine Design task in a workspace, run `doctor --format json` unless its result is already available in this session. This Skill is already loaded; do not read it again through `bundledSkillPath`. Reuse discovery and API results while the workspace, CLI and component versions remain unchanged. The public CLI is separate from the private component package; a failed private-package lookup does not prove the CLI is unavailable. Report the actual command and error if it fails.
|
|
13
13
|
|
|
14
14
|
## Workflow
|
|
15
15
|
|
|
16
16
|
1. Identify the deliverable and runtime: existing package-based project, standalone browser page, fix, or read-only review. Standalone HTML and embedded pages may use the public CDN runtime without npm or private-registry credentials. Preserve compatible existing components and explicit user choices; follow [imports-and-setup.md](references/imports-and-setup.md) for runtime selection.
|
|
17
17
|
2. In a package-based project, resolve Fine Design and React versions from installed packages or the lockfile; in this repository use the checked-out package and sources. In browser mode, use the selected runtime manifest and its compatibility evidence rather than requiring an installed package. State unknown versions instead of inventing them or upgrading dependencies to fit examples.
|
|
18
|
-
3.
|
|
18
|
+
3. Before implementation or review conclusions, verify only the relevant components at the exact target version; reuse matching results already read in this session. Prefer connected Fine Design MCP tools when matching-version data is available, or use the CLI with `--format json`. Start with `info <component>`; it includes example IDs, so fetch `example <component> <id>` source only when needed. Use `search` for unknown component names, `doc --toc` / `doc --section` for missing details, and `token` for theming. Do not default to full catalogs, full docs or `--help`. If the version is unknown or unsupported, consult matching local declarations/docs or verify browser exports and behavior. Resolve website pages through [docs-slug-map.md](references/docs-slug-map.md).
|
|
19
19
|
4. Use the relevant sections of [component-guide.md](references/component-guide.md) for component selection and API traps. Consult other references only for the conditions below.
|
|
20
|
-
5.
|
|
20
|
+
5. After code changes, run the existing build/type check (plus `fine-design lint <file>` when available) and verify the affected interaction with local test data. Check that filter wording matches its date/value semantics, primary actions produce their stated results, and filters/actions can be reached by keyboard. Report actual commands and results, distinguishing API lint, DOM tests, independent browser checks, target preview checks and unverified steps. A passing lint is not a business or visual acceptance result. Reviews remain read-only.
|
|
21
21
|
|
|
22
22
|
## Core Contracts
|
|
23
23
|
|
|
@@ -31,4 +31,5 @@ Run `npx -y @finedesign/cli doctor --format json` in the target project and read
|
|
|
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) |
|
|
34
35
|
| Theme, dark mode, or scoped themes | [theme-and-dark-mode.md](references/theme-and-dark-mode.md) |
|
|
@@ -36,6 +36,7 @@ Use the sections relevant to the task. Selection choices are defaults for new wo
|
|
|
36
36
|
| `Dialog` | Save via `onOk`; handle close/cancel via `onCancel` (clicking the close button triggers `onCancel`, so do not bind the same handler to both `onCancel` and deprecated `onCloseBtnClick`) |
|
|
37
37
|
| `Tag` | Use semantic `type` or `style`; do not assume a `color` prop |
|
|
38
38
|
| `Avatar` | Character fallback uses `name` |
|
|
39
|
+
| `Radio.Group` | Set `tabFocus: true` for keyboard-reachable filters/view switches; its default is false |
|
|
39
40
|
| `SvgIcon`, built-in icons | Import built-in icons from `@fx-ui/fine-design` (56 icons such as `SearchOutlined`, `PlusOutlined`, `EditOutlined`, `DeleteOutlined`, `SyncOutlined`, `RotateOutlined`, `EllipsisOutlined`); verify names via declarations or CLI `search`/`doc` instead of inventing `@ant-design/icons` names like `SettingOutlined` or `ReloadOutlined` |
|
|
40
41
|
|
|
41
42
|
The table declaration differs from common `columns` APIs:
|
|
@@ -64,5 +65,8 @@ render: (_value, record) => {
|
|
|
64
65
|
- Reset page to `1` when filters or page size change, including `AutoComplete.onSearch` and `onChange`. Use the filtered total, and clamp the page after filtering or deletion reduces available pages.
|
|
65
66
|
- Edit a draft separate from saved data. Validation/save failure preserves the draft and leaves the dialog open; cancel/close must not persist the edit. Expose pending/error feedback for asynchronous saves.
|
|
66
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
|
+
- 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
|
+
|
|
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.
|
|
67
71
|
|
|
68
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,6 +56,8 @@ 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.
|
|
60
|
+
|
|
59
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.
|
|
60
62
|
|
|
61
63
|
Use `--runtime-url <verified-base-url>` only for a clearly selected host. The default public host is `https://fine-design-runtime.pages.dev/`, verified after production deployment; local testing alone does not prove a host is live. Optional chart resources are loaded only for chart requests.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Standalone Task Page
|
|
2
|
+
|
|
3
|
+
Use this reference for a new standalone table with filters, pagination and draft editing. Preserve existing project components instead of replacing them with this sample.
|
|
4
|
+
|
|
5
|
+
After discovering the hosted version, run:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
fine-design runtime --fd-version <exact-version> --output ./task-demo
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The destination must not exist. `--dry-run --format json` previews paths without downloading assets or writing files. Export downloads the four required resources once, checks their declared sizes and SHA-256, then installs the directory. Download, integrity or conflict failures leave the destination untouched. The current browser starter uses React 18's `createRoot`; verify compatibility when targeting a different React major.
|
|
12
|
+
|
|
13
|
+
- `index.html`: existing button/runtime smoke example.
|
|
14
|
+
- `task-list.html` and `task-list.js`: working local task example. No JSX transformer or extra dependency.
|
|
15
|
+
- `vendor/`: pinned React, ReactDOM, Fine Design JavaScript and stylesheet.
|
|
16
|
+
- `runtime-lock.json`: source manifest URL, exact resource metadata and local paths. This is an archive record, not a hosting manifest.
|
|
17
|
+
|
|
18
|
+
Use the target host's normal local preview. Resource URLs are local and SRI is retained; the host must still permit the page's scripts and styles. No CDN fallback is needed for an exported directory. Keep the whole directory together when copying it.
|
|
19
|
+
|
|
20
|
+
The complete [task-list.js](task-list.js) is also bundled with this Skill. It is a reference, not a runtime dependency: copy it into the deliverable before linking it. Its component is `window.FineDesignTaskList`; mount it after the runtime is loaded. The example stores status codes consistently, enables Radio keyboard focus, labels text inputs, keeps edits in a separate draft, and binds deletion to `PopConfirm.onOk`.
|
|
21
|
+
|
|
22
|
+
## Verify The Business Contract
|
|
23
|
+
|
|
24
|
+
1. From a later page, filter by keyword/status and reset; verify the matching rows and page number.
|
|
25
|
+
2. Create a task, reject an empty name, save a valid task, edit it, cancel an edit, then reopen it.
|
|
26
|
+
3. Cancel deletion, then confirm deletion; remove the last row on a later page and verify pagination clamps.
|
|
27
|
+
4. Use Tab and the component's supported keys to reach filters and actions; check focus and the actual accessible names in the target preview.
|
|
28
|
+
5. For extensions, define calendar-week versus rolling-date semantics explicitly. An export action must create a file or report a real result; mark intentionally unfinished actions. If tasks belong to multiple projects, new tasks must select or inherit the intended project.
|
|
29
|
+
|
|
30
|
+
CLI lint checks API usage, not business correctness, accessibility compliance or visual layout. Report syntax/API tests, DOM behavior tests and actual browser/host checks separately. DOM-only checks cannot verify clipping, colors or responsive layout.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/* 独立页面组合参考:运行时加载后用 React.createElement(window.FineDesignTaskList) 渲染。 */
|
|
2
|
+
window.FineDesignTaskList = function FineDesignTaskList() {
|
|
3
|
+
const React = window.React;
|
|
4
|
+
const h = React.createElement;
|
|
5
|
+
const { Button, Input, Select, Radio, NextTable, Pagination, Drawer, PopConfirm, Tag } = window.FineDesign;
|
|
6
|
+
const [rows, setRows] = React.useState([
|
|
7
|
+
{ id: 1, name: '整理需求', status: 'todo' },
|
|
8
|
+
{ id: 2, name: '接口联调', status: 'doing' },
|
|
9
|
+
{ id: 3, name: '组件验收', status: 'done' },
|
|
10
|
+
{ id: 4, name: '补充用例', status: 'todo' },
|
|
11
|
+
{ id: 5, name: '检查交付', status: 'doing' }
|
|
12
|
+
]);
|
|
13
|
+
const [keyword, setKeyword] = React.useState('');
|
|
14
|
+
const [status, setStatus] = React.useState('all');
|
|
15
|
+
const [page, setPage] = React.useState(1);
|
|
16
|
+
const [size, setSize] = React.useState(2);
|
|
17
|
+
const [draft, setDraft] = React.useState(null);
|
|
18
|
+
const [error, setError] = React.useState('');
|
|
19
|
+
const statuses = [{ label: '待规划', value: 'todo' }, { label: '进行中', value: 'doing' }, { label: '已完成', value: 'done' }];
|
|
20
|
+
const filtered = rows.filter(row => (status === 'all' || row.status === status) && row.name.includes(keyword.trim()));
|
|
21
|
+
const maxPage = Math.max(1, Math.ceil(filtered.length / size));
|
|
22
|
+
React.useEffect(() => { if (page > maxPage) setPage(maxPage); }, [page, maxPage]);
|
|
23
|
+
|
|
24
|
+
function edit(row) { setDraft({ ...row }); setError(''); }
|
|
25
|
+
function close() { setDraft(null); setError(''); }
|
|
26
|
+
function save() {
|
|
27
|
+
const name = draft.name.trim();
|
|
28
|
+
if (!name) { setError('请填写任务名称'); return; }
|
|
29
|
+
const saved = { ...draft, name, id: draft.id ?? Math.max(0, ...rows.map(row => row.id)) + 1 };
|
|
30
|
+
setRows(draft.id == null ? [saved, ...rows] : rows.map(row => row.id === saved.id ? saved : row));
|
|
31
|
+
if (draft.id == null) setPage(1);
|
|
32
|
+
close();
|
|
33
|
+
}
|
|
34
|
+
function column(title, width, render) {
|
|
35
|
+
return h(NextTable.Column, { width }, h(NextTable.HeaderCell, null, title),
|
|
36
|
+
h(NextTable.Cell, null, row => row?.id != null ? render(row) : null));
|
|
37
|
+
}
|
|
38
|
+
const fieldStyle = { display: 'grid', gap: 8 };
|
|
39
|
+
return h('div', { style: { display: 'grid', gap: 16, padding: 20, color: 'var(--fd-color-text)' } },
|
|
40
|
+
h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 12 } },
|
|
41
|
+
h('strong', { 'aria-live': 'polite' }, '任务清单 · ' + filtered.length + ' 项'),
|
|
42
|
+
h(Button, { type: 'primary', onClick: () => edit({ id: null, name: '', status: 'todo' }) }, '新建任务')),
|
|
43
|
+
h('label', { style: fieldStyle }, '任务关键词', h(Input, {
|
|
44
|
+
value: keyword, placeholder: '输入任务名称', allowClear: true,
|
|
45
|
+
onChange: value => { setKeyword(value); setPage(1); }
|
|
46
|
+
})),
|
|
47
|
+
h(Radio.Group, { value: status, tabFocus: true, direction: 'horizontal', optionType: 'button', block: false,
|
|
48
|
+
onChange: value => { setStatus(value); setPage(1); }
|
|
49
|
+
}, [{ label: '全部任务', value: 'all' }, ...statuses].map(item => h(Radio, { key: item.value, value: item.value }, item.label))),
|
|
50
|
+
h(Button, { onClick: () => { setKeyword(''); setStatus('all'); setPage(1); } }, '重置筛选'),
|
|
51
|
+
h('div', { style: { overflowX: 'auto', minWidth: 0 } }, h(NextTable, {
|
|
52
|
+
data: filtered.slice((page - 1) * size, page * size), rowKey: 'id', width: 780, autoHeight: true, fillHeight: false,
|
|
53
|
+
renderEmpty: () => h('p', null, '暂无符合条件的任务')
|
|
54
|
+
},
|
|
55
|
+
column('编号', 100, row => String(row.id)),
|
|
56
|
+
column('名称', 340, row => row.name),
|
|
57
|
+
column('状态', 140, row => h(Tag, { type: row.status === 'done' ? 'success' : 'info' }, statuses.find(item => item.value === row.status).label)),
|
|
58
|
+
column('操作', 200, row => h('div', { style: { display: 'flex', gap: 8 } },
|
|
59
|
+
h(Button, { type: 'text', onClick: () => edit(row) }, '编辑'),
|
|
60
|
+
h(PopConfirm, { content: '确认删除“' + row.name + '”?', text4Ok: '确认删除', text4Cancel: '取消',
|
|
61
|
+
onOk: () => setRows(rows.filter(item => item.id !== row.id))
|
|
62
|
+
}, h(Button, { type: 'text', danger: true }, '删除'))))
|
|
63
|
+
)),
|
|
64
|
+
h(Pagination, { page, size, sizeSet: [2, 5], count: filtered.length, showPageSize: value => value + ' 条/页',
|
|
65
|
+
showTotal: count => '共 ' + count + ' 项', onPageChange: setPage,
|
|
66
|
+
onSizeChange: value => { setSize(value); setPage(1); }
|
|
67
|
+
}),
|
|
68
|
+
draft && h(Drawer, { visible: true, placement: 'right', edge: { width: 'min(520px, 100vw)', top: 0 },
|
|
69
|
+
title: draft.id == null ? '新建任务' : '编辑任务', onClose: close,
|
|
70
|
+
footer: h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8 } },
|
|
71
|
+
h(Button, { onClick: close }, '取消'), h(Button, { type: 'primary', onClick: save }, '保存'))
|
|
72
|
+
}, h('div', { style: { display: 'grid', gap: 16 } },
|
|
73
|
+
h('label', { style: fieldStyle }, '任务名称(必填)', h(Input, { value: draft.name,
|
|
74
|
+
inputState: error ? 'error' : 'normal', onChange: value => { setDraft({ ...draft, name: value }); setError(''); }
|
|
75
|
+
})),
|
|
76
|
+
error && h('p', { role: 'alert' }, error),
|
|
77
|
+
h('div', { style: fieldStyle }, h('span', null, '任务状态'), h(Select, { value: draft.status, options: statuses, 'aria-label': '任务状态',
|
|
78
|
+
onChange: value => setDraft({ ...draft, status: value })
|
|
79
|
+
})))
|
|
80
|
+
)
|
|
81
|
+
);
|
|
82
|
+
};
|
package/src/cli.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { validateInput } from './core/contracts.mjs';
|
|
|
7
7
|
import { loadCatalog, readIndex } from './core/data.mjs';
|
|
8
8
|
import { resolveLintVersion, resolveVersion } from './core/version.mjs';
|
|
9
9
|
import { ToolError, errorResult } from './core/errors.mjs';
|
|
10
|
-
import { listRuntimes, resolveRuntime } from './core/runtime.mjs';
|
|
10
|
+
import { listRuntimes, resolveRuntime, exportRuntime } from './core/runtime.mjs';
|
|
11
11
|
import html from './core/html.cjs';
|
|
12
12
|
|
|
13
13
|
const help = `Usage: fine-design <command> [arguments] [options]
|
|
@@ -32,9 +32,9 @@ Options:
|
|
|
32
32
|
--project <directory> Project used to detect the installed version
|
|
33
33
|
--component <name> Compare only this component (diff command only)
|
|
34
34
|
--agent <cursor|claude|codex|all> Target agent configuration (init command only)
|
|
35
|
-
--output <directory> Destination
|
|
35
|
+
--output <directory> Destination for an example or offline runtime (add and runtime)
|
|
36
36
|
--force Update managed files or overwrite examples (init and add)
|
|
37
|
-
--dry-run Preview changes without writing (init and
|
|
37
|
+
--dry-run Preview changes without writing (init, add and runtime --output)
|
|
38
38
|
--runtime-url <url> Runtime hosting base URL (runtime command only)
|
|
39
39
|
--format <text|json|markdown|html> Output format (markdown: doc/info/token; html: runtime)
|
|
40
40
|
--section <heading> Doc section heading (exact or case-insensitive)
|
|
@@ -115,12 +115,12 @@ function runInit(values) {
|
|
|
115
115
|
|
|
116
116
|
const agentInstructions = `# Fine Design Rules
|
|
117
117
|
|
|
118
|
-
开发或修改 Fine Design
|
|
118
|
+
开发或修改 Fine Design 页面时,以及调试或评审涉及 \`@fx-ui/fine-design\` / \`window.FineDesign\` 的代码时,主动调用 CLI 核对组件 API,无需用户提醒。无关任务不触发。在目标工作目录运行:项目内已安装 CLI 时用 \`npx fine-design\`,否则使用全局 \`fine-design\`;两者均不可用时用 \`npx -y @finedesign/cli\`。
|
|
119
119
|
|
|
120
|
-
1.
|
|
120
|
+
1. 首次处理当前工作目录的 Fine Design 任务时,运行 \`doctor --format json\`,读取 \`bundledSkillPath\` 指向的 Skill;当前会话已加载则复用,不重复读取。同一工作目录、CLI 和组件版本未变化时复用诊断结果。先确定交付形式;接入现有 React 工程时沿用项目组件版本、壳层和同类页面。
|
|
121
121
|
2. 交付独立 HTML 或无构建预览时,先单独运行 \`runtime list --format json\`,根据退出码判断清单是否可用。用 \`versions\` 返回的版本解析 UMD 资源,再查组件 API。
|
|
122
|
-
3.
|
|
123
|
-
4.
|
|
122
|
+
3. 实现或给出评审结论前,按目标版本用 \`info <组件> --format json\` 核对本次涉及的 API。同一版本已查资料可复用;组件不明确时才 \`search\`,需要示例时从 \`info\` 返回的 ID 读取源码,不默认运行全量 \`list\` 或读取全部文档。
|
|
123
|
+
4. 有代码改动时,对改动文件运行 \`lint\` 并执行项目已有检查,验证受影响交互。分别记录实际执行的命令、检查结果和未验证项;只读评审不修改代码。
|
|
124
124
|
5. CLI 与私有组件包是独立的;本地命令缺失或私有包查询失败不能证明公开 CLI 不存在。失败时记录实际命令、退出码和错误。真实组件不可用时,原生页面只能标为替代实现,不能声称通过官方 lint;若必须使用真实组件则报告阻碍。
|
|
125
125
|
`;
|
|
126
126
|
|
|
@@ -319,9 +319,9 @@ export async function main(argv) {
|
|
|
319
319
|
if (command !== 'runtime' && (values['runtime-url'] !== undefined)) throw new ToolError('INVALID_ARGUMENT', 'Runtime options are only supported for runtime.', 2);
|
|
320
320
|
if (command !== 'diff' && values.component !== undefined) throw new ToolError('INVALID_ARGUMENT', '--component is only supported for diff.', 2);
|
|
321
321
|
if (command !== 'init' && values.agent !== undefined) throw new ToolError('INVALID_ARGUMENT', '--agent is only supported for init.', 2);
|
|
322
|
-
if (
|
|
322
|
+
if (!['add', 'runtime'].includes(command) && values.output !== undefined) throw new ToolError('INVALID_ARGUMENT', '--output is only supported for add and runtime.', 2);
|
|
323
323
|
if (!['init', 'add'].includes(command) && values.force !== undefined) throw new ToolError('INVALID_ARGUMENT', '--force is only supported for init and add.', 2);
|
|
324
|
-
if (!['init', 'add'].includes(command) && values['dry-run'] !== undefined) throw new ToolError('INVALID_ARGUMENT', '--dry-run is only supported for init and
|
|
324
|
+
if (!['init', 'add', 'runtime'].includes(command) && values['dry-run'] !== undefined) throw new ToolError('INVALID_ARGUMENT', '--dry-run is only supported for init, add and runtime --output.', 2);
|
|
325
325
|
if (format === 'markdown' && !['doc', 'info', 'token'].includes(command)) {
|
|
326
326
|
throw new ToolError('INVALID_ARGUMENT', 'Markdown output format is only supported for the doc, info and token commands.', 2);
|
|
327
327
|
}
|
|
@@ -329,7 +329,13 @@ export async function main(argv) {
|
|
|
329
329
|
if (command === 'runtime') {
|
|
330
330
|
const list = args.length === 1 && args[0] === 'list';
|
|
331
331
|
if ((!list && args.length) || values.version || values.section !== undefined || summaryFlag || values.offset !== undefined || values.limit !== undefined || values['include-assets'] !== undefined || (list && (values['fd-version'] !== undefined || values.project !== undefined))) throw new ToolError('INVALID_ARGUMENT', 'Use runtime [list] with --fd-version and --runtime-url as applicable.', 2);
|
|
332
|
+
if ((list && (values.output !== undefined || values['dry-run'] !== undefined)) || (values['dry-run'] !== undefined && values.output === undefined) || (values.output !== undefined && (!values.output.trim() || !['text', 'json'].includes(format)))) throw new ToolError('INVALID_ARGUMENT', 'Use runtime --output <new-directory> [--dry-run] [--format text|json].', 2);
|
|
332
333
|
const result = list ? await listRuntimes(values['runtime-url']) : await resolveRuntime({ version: resolveVersion(values['fd-version'], values.project), runtimeURL: values['runtime-url'] });
|
|
334
|
+
if (values.output !== undefined) {
|
|
335
|
+
const report = await exportRuntime(result, path.resolve(values.project || process.cwd(), values.output), Boolean(values['dry-run']));
|
|
336
|
+
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')}`);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
333
339
|
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}\nExample: ${result.exampleURL}`);
|
|
334
340
|
return;
|
|
335
341
|
}
|
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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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));
|
package/src/core/runtime.mjs
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
|
-
import
|
|
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 =
|
|
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
|
+
}
|