soma-core 1.5.1 → 1.6.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/app/SomaPageClient.tsx +28 -9
- package/app/soma/manifest/route.ts +3 -0
- package/bin/migrate.cjs +71 -1
- package/bin/soma-lsp.cjs +8 -1
- package/core/build/blocks/block-compile.ts +23 -5
- package/core/build/compiler/full-manifest-builder.ts +15 -0
- package/core/build/compiler/page-assets.ts +17 -1
- package/core/build/compiler/page-declaration-compiler.ts +67 -11
- package/core/build/compiler/precompiled-manifest-loader.ts +7 -0
- package/core/build/compiler/soma-manifest-webpack-plugin.js +7 -0
- package/core/build/compiler/soma-precompile.js +30 -6
- package/core/build/component/package-loader.ts +35 -4
- package/core/build/component-tree/artifact-codec.ts +192 -0
- package/core/build/component-tree/binding-bridge.ts +272 -0
- package/core/build/component-tree/collection-binding-lowerer.ts +65 -0
- package/core/build/component-tree/definition-preparation.ts +320 -0
- package/core/build/component-tree/migration-files.ts +214 -0
- package/core/build/component-tree/migration.ts +170 -0
- package/core/build/component-tree/parser.ts +362 -0
- package/core/build/component-tree/registry-snapshot.ts +317 -0
- package/core/build/component-tree/source-preflight.ts +132 -0
- package/core/build/component-tree/structure-topology.ts +63 -0
- package/core/build/component-tree/validator.ts +318 -0
- package/core/build/lsp/component-tree-service.ts +79 -0
- package/core/build/lsp/component-tree.cjs +42 -0
- package/core/build/lsp/cross-file-diagnostics.cjs +15 -3
- package/core/build/lsp/extra-completion.cjs +7 -0
- package/core/client/compiler/manifest-compiler.ts +2 -0
- package/core/client/component/ai-catalog.ts +41 -3
- package/core/client/component/catalog-examples.ts +60 -0
- package/core/client/component/component-definition.types.ts +9 -0
- package/core/client/component/component-expander.ts +21 -5
- package/core/client/component/component-manager.ts +103 -16
- package/core/client/component/component-registry.ts +10 -1
- package/core/client/component/scoped-adapter.ts +29 -2
- package/core/client/component/structure-adapter.ts +207 -0
- package/core/client/component/verify-pack.ts +21 -1
- package/core/client/engine/asset-resolver.ts +1 -1
- package/core/client/engine/dom-renderer.ts +283 -0
- package/core/client/engine/event-engine.ts +28 -9
- package/core/client/engine/render-engine.ts +2 -0
- package/core/client/engine/row-range.ts +62 -0
- package/core/client/engine/row-scope.ts +77 -0
- package/core/client/engine/runtime-builder.ts +2 -0
- package/core/client/engine/soma-bootstrap.ts +146 -1
- package/core/client/parser/blocks/page-parser.ts +9 -2
- package/core/client/parser/ui-config-parser.ts +38 -6
- package/core/client/registry/declaration-renderer.ts +32 -24
- package/core/client/registry/remote-page.ts +1 -1
- package/core/client/validation/contract-validator.ts +1 -1
- package/core/index.ts +3 -0
- package/core/server/host/page-markup-config.ts +42 -0
- package/core/server/host/published-page-artifact-cache.ts +36 -4
- package/core/server/host/published-page-assets.ts +13 -7
- package/core/server/host/resolve-host-tree-context.ts +43 -0
- package/core/server/host/server-page-assets.ts +23 -4
- package/core/server/host/soma-page-compile.ts +10 -0
- package/core/server/page-declaration.ts +7 -0
- package/core/server/registry/declaration-precompiler.ts +35 -3
- package/core/server/registry/page-registry-repository.ts +31 -3
- package/core/server/registry/page-registry-store.ts +64 -7
- package/core/server/registry/publish-asset-pin.ts +6 -1
- package/core/server/registry/services/pages/Get.ts +11 -6
- package/core/server/registry/validation/compile-gate.ts +10 -1
- package/core/shared/component-tree-artifact.ts +237 -0
- package/core/shared/component-tree-errors.ts +52 -0
- package/core/shared/types/component-contract.types.ts +51 -0
- package/core/shared/types/component-tree-artifact.types.ts +121 -0
- package/core/shared/types/component-tree.types.ts +170 -0
- package/core/shared/types/engine.types.ts +5 -0
- package/core/shared/types/manifest.types.ts +4 -0
- package/core/shared/types/ui-config.types.ts +8 -0
- package/dist/cli/soma.js +1 -1
- package/dist/core/index.cjs +1757 -511
- package/dist/lsp/component-tree.cjs +20807 -0
- package/dist/types/build/blocks/block-compile.d.ts +10 -1
- package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
- package/dist/types/build/compiler/page-assets.d.ts +6 -1
- package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
- package/dist/types/build/component/package-loader.d.ts +4 -1
- package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
- package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
- package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
- package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
- package/dist/types/build/component-tree/migration-files.d.ts +35 -0
- package/dist/types/build/component-tree/migration.d.ts +28 -0
- package/dist/types/build/component-tree/parser.d.ts +13 -0
- package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
- package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
- package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
- package/dist/types/build/component-tree/validator.d.ts +9 -0
- package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
- package/dist/types/client/component/ai-catalog.d.ts +18 -1
- package/dist/types/client/component/catalog-examples.d.ts +18 -0
- package/dist/types/client/component/component-definition.types.d.ts +9 -0
- package/dist/types/client/component/component-expander.d.ts +2 -1
- package/dist/types/client/component/component-manager.d.ts +11 -0
- package/dist/types/client/component/scoped-adapter.d.ts +1 -0
- package/dist/types/client/component/structure-adapter.d.ts +17 -0
- package/dist/types/client/engine/dom-renderer.d.ts +15 -0
- package/dist/types/client/engine/event-engine.d.ts +1 -0
- package/dist/types/client/engine/render-engine.d.ts +1 -0
- package/dist/types/client/engine/row-range.d.ts +13 -0
- package/dist/types/client/engine/row-scope.d.ts +20 -0
- package/dist/types/client/engine/runtime-builder.d.ts +1 -0
- package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
- package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
- package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
- package/dist/types/client/registry/remote-page.d.ts +1 -1
- package/dist/types/index.d.ts +3 -1
- package/dist/types/server/host/page-markup-config.d.ts +6 -0
- package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
- package/dist/types/server/host/published-page-assets.d.ts +5 -3
- package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
- package/dist/types/server/host/server-page-assets.d.ts +6 -0
- package/dist/types/server/host/soma-page-compile.d.ts +10 -1
- package/dist/types/server/page-declaration.d.ts +6 -0
- package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
- package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
- package/dist/types/server/registry/page-registry-store.d.ts +11 -1
- package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
- package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
- package/dist/types/shared/component-tree-artifact.d.ts +5 -0
- package/dist/types/shared/component-tree-errors.d.ts +22 -0
- package/dist/types/shared/types/component-contract.types.d.ts +42 -0
- package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
- package/dist/types/shared/types/component-tree.types.d.ts +149 -0
- package/dist/types/shared/types/engine.types.d.ts +5 -0
- package/dist/types/shared/types/manifest.types.d.ts +4 -0
- package/dist/types/shared/types/ui-config.types.d.ts +8 -0
- package/package.json +2 -1
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
// REQ-016 build-only preflight. No DOM, component execution or runtime plans.
|
|
2
|
+
import { SomaComponentTreeError, type ComponentTreeErrorCode } from '../../shared/component-tree-errors';
|
|
3
|
+
import type { SomaContractField } from '../../shared/types/component-contract.types';
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_TREE_LIMITS,
|
|
6
|
+
type ComponentNode,
|
|
7
|
+
type NodeMeta,
|
|
8
|
+
type RepeatNode,
|
|
9
|
+
type SomaComponentTree,
|
|
10
|
+
type TreeCollectionSource,
|
|
11
|
+
type TreeCompileContext,
|
|
12
|
+
type TreeComponentSnapshot,
|
|
13
|
+
type TreeNode,
|
|
14
|
+
type TreeSlotPolicy,
|
|
15
|
+
type TreeValidationResult,
|
|
16
|
+
} from '../../shared/types/component-tree.types';
|
|
17
|
+
|
|
18
|
+
const ID = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
19
|
+
const VARIABLE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
20
|
+
const PATH = /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/;
|
|
21
|
+
const RESERVED = new Set(['page', 'p', 'ctrl', 'data', '__proto__', 'prototype', 'constructor']);
|
|
22
|
+
const UNSAFE_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
23
|
+
const HOST_SEMANTICS = new Set(['root', 'main', 'section', 'article', 'div']);
|
|
24
|
+
|
|
25
|
+
interface Scope {
|
|
26
|
+
ids: Map<string, NodeMeta>;
|
|
27
|
+
aliases: ReadonlyMap<string, SomaContractField>;
|
|
28
|
+
repeatDepth: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface Position {
|
|
32
|
+
root: boolean;
|
|
33
|
+
restrictions: readonly TreeSlotPolicy[];
|
|
34
|
+
repeatAllowed: boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function own<T>(record: Readonly<Record<string, T>> | undefined, key: string): T | undefined {
|
|
38
|
+
return record && Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isPath(value: string): boolean {
|
|
42
|
+
return typeof value === 'string' && PATH.test(value)
|
|
43
|
+
&& !value.split('.').some(segment => UNSAFE_SEGMENTS.has(segment));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function fieldAt(root: SomaContractField, segments: readonly string[]): SomaContractField | undefined {
|
|
47
|
+
let field: SomaContractField | undefined = root;
|
|
48
|
+
for (const segment of segments) {
|
|
49
|
+
if (field?.type !== 'object') return undefined;
|
|
50
|
+
field = own(field.fields, segment);
|
|
51
|
+
}
|
|
52
|
+
return field;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Validate only source/context facts. The return value is not an executable asset;
|
|
57
|
+
* binding lowering, effective-parent proof and full artifact delivery are separate.
|
|
58
|
+
*/
|
|
59
|
+
export function validateComponentTree(
|
|
60
|
+
tree: SomaComponentTree,
|
|
61
|
+
input: { domain: string; context: TreeCompileContext },
|
|
62
|
+
): TreeValidationResult {
|
|
63
|
+
function fail(
|
|
64
|
+
code: ComponentTreeErrorCode,
|
|
65
|
+
node: { meta: NodeMeta } | undefined,
|
|
66
|
+
fixHint: string,
|
|
67
|
+
attribute?: string,
|
|
68
|
+
related?: NodeMeta,
|
|
69
|
+
): never {
|
|
70
|
+
throw new SomaComponentTreeError({
|
|
71
|
+
code,
|
|
72
|
+
phase: 'validate',
|
|
73
|
+
sourceId: tree?.sourceId ?? '<component-tree>',
|
|
74
|
+
nodePath: node?.meta?.nodePath ?? '/',
|
|
75
|
+
...(node?.meta?.span ? { span: node.meta.span } : {}),
|
|
76
|
+
...(related ? { relatedSpans: [related.span] } : {}),
|
|
77
|
+
...(attribute ? { attribute } : {}),
|
|
78
|
+
fixHint,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (!tree || tree.grammarVersion !== 1 || tree.host?.kind !== 'host') {
|
|
83
|
+
fail('CT-SYNTAX-ROOT', tree?.host, '提供 grammarVersion=1 且只有一个 Host 根的解析树。');
|
|
84
|
+
}
|
|
85
|
+
const context = input?.context;
|
|
86
|
+
const registry = context?.registrySnapshot;
|
|
87
|
+
const policy = context?.compositionPolicy;
|
|
88
|
+
if (!registry?.digest || !registry.components || !policy?.policyId || !policy.version
|
|
89
|
+
|| !Array.isArray(policy.roots) || policy.roots.length === 0) {
|
|
90
|
+
fail('CT-REGISTRY-CONTEXT', tree.host, '由受信 Host 提供完整 Registry 快照与页面准入策略。');
|
|
91
|
+
}
|
|
92
|
+
const limits = { ...DEFAULT_TREE_LIMITS, ...context.limits };
|
|
93
|
+
for (const value of Object.values(limits)) {
|
|
94
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
95
|
+
fail('CT-LIMIT', tree.host, '部署限额必须是正安全整数。');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (!input.domain || tree.host.name !== input.domain) {
|
|
99
|
+
fail('CT-IDENTITY-HOST', tree.host, 'Host.name 必须与 canonical page.domain 一致。', 'name');
|
|
100
|
+
}
|
|
101
|
+
if (!HOST_SEMANTICS.has(tree.host.as)) {
|
|
102
|
+
fail('CT-STRUCTURE-MOUNT', tree.host, 'Host.as 必须使用 root/main/section/article/div。', 'as');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Bound traversal before recursive flattening or semantic checks, including
|
|
106
|
+
// hand-built editor ASTs that did not pass through the source parser.
|
|
107
|
+
let count = 0;
|
|
108
|
+
const inspectShape = (node: TreeNode, depth: number): void => {
|
|
109
|
+
if (++count > limits.maxNodes || depth > limits.maxDepth) {
|
|
110
|
+
fail('CT-LIMIT', node, '减少静态节点数或嵌套深度。');
|
|
111
|
+
}
|
|
112
|
+
if (!node || !['host', 'component', 'slot', 'fragment', 'repeat'].includes(node.kind)) {
|
|
113
|
+
fail('CT-SYNTAX-ELEMENT', node, '解析树只能包含已声明的五种节点。');
|
|
114
|
+
}
|
|
115
|
+
if (node.kind === 'repeat') {
|
|
116
|
+
if (!node.child || !['component', 'fragment'].includes(node.child.kind)) {
|
|
117
|
+
fail('CT-SYNTAX-ELEMENT', node, 'repeat 必须包含一个组件或非空 Fragment。');
|
|
118
|
+
}
|
|
119
|
+
inspectShape(node.child, depth + 1);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const children = node.kind === 'component' ? node.slots : node.children;
|
|
123
|
+
if (!Array.isArray(children)) {
|
|
124
|
+
fail('CT-SYNTAX-ELEMENT', node, '节点必须提供结构化的子节点列表。');
|
|
125
|
+
}
|
|
126
|
+
for (const child of children) inspectShape(child, depth + 1);
|
|
127
|
+
};
|
|
128
|
+
inspectShape(tree.host, 1);
|
|
129
|
+
|
|
130
|
+
const slotPolicies = new Map<string, TreeSlotPolicy>();
|
|
131
|
+
for (const rule of policy.slotRules ?? []) {
|
|
132
|
+
const key = `${rule.component}\0${rule.slot}`;
|
|
133
|
+
if (slotPolicies.has(key)) {
|
|
134
|
+
fail('CT-REGISTRY-CONTEXT', tree.host, '同一组件和 slot 只能配置一条准入规则。');
|
|
135
|
+
}
|
|
136
|
+
slotPolicies.set(key, rule);
|
|
137
|
+
}
|
|
138
|
+
const sources = new Map<string, TreeCollectionSource>();
|
|
139
|
+
for (const descriptor of context.collectionSources ?? []) {
|
|
140
|
+
if (!isPath(descriptor.path) || !descriptor.item || sources.has(descriptor.path)
|
|
141
|
+
|| !descriptor.statusPlan || !['sync', 'async'].includes(descriptor.statusPlan.kind)
|
|
142
|
+
|| (descriptor.statusPlan.kind === 'async' && !isPath(descriptor.statusPlan.statePath))) {
|
|
143
|
+
fail('CT-REPEAT-SOURCE', tree.host, '集合描述必须有唯一安全路径、元素类型和完整 sync/async 状态描述。');
|
|
144
|
+
}
|
|
145
|
+
sources.set(descriptor.path, descriptor);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const componentNames = new Set<string>();
|
|
149
|
+
const snapshotFor = (node: ComponentNode): TreeComponentSnapshot => {
|
|
150
|
+
const snapshot = own(registry.components, node.component);
|
|
151
|
+
if (!snapshot || snapshot.name !== node.component || snapshot.contract.name !== node.component) {
|
|
152
|
+
fail('CT-REGISTRY-COMPONENT', node, '组件必须存在于当前 Host 的有效 Registry 快照。', 'component');
|
|
153
|
+
}
|
|
154
|
+
return snapshot;
|
|
155
|
+
};
|
|
156
|
+
const isMacro = (node: TreeNode): node is ComponentNode => node.kind === 'component'
|
|
157
|
+
&& own(registry.components, node.component)?.contract.structure?.kind === 'fragment-macro';
|
|
158
|
+
|
|
159
|
+
const expanded = (nodes: readonly TreeNode[]): TreeNode[] => nodes.flatMap(node => {
|
|
160
|
+
if (node.kind === 'fragment') return expanded(node.children);
|
|
161
|
+
if (isMacro(node)) return expanded(node.slots.flatMap(slot => slot.children));
|
|
162
|
+
return [node];
|
|
163
|
+
});
|
|
164
|
+
const rememberId = (node: ComponentNode | SomaComponentTree['host'], scope: Scope): void => {
|
|
165
|
+
if (node.id === undefined && node.kind === 'host') return;
|
|
166
|
+
if (typeof node.id !== 'string' || !ID.test(node.id) || node.id.startsWith('__soma_tree_')) {
|
|
167
|
+
fail('CT-IDENTITY-ID', node, 'id 必须是 1–64 位安全标识符,不能使用内部保留前缀。', 'id');
|
|
168
|
+
}
|
|
169
|
+
const previous = scope.ids.get(node.id);
|
|
170
|
+
if (previous) {
|
|
171
|
+
fail('CT-IDENTITY-ID', node, '同一页面或行模板作用域内的 id 必须唯一。', 'id', previous);
|
|
172
|
+
}
|
|
173
|
+
scope.ids.set(node.id, node.meta);
|
|
174
|
+
};
|
|
175
|
+
const allowedBy = (
|
|
176
|
+
rule: Pick<TreeSlotPolicy, 'allowedComponents' | 'allowedLayers'>,
|
|
177
|
+
component: TreeComponentSnapshot,
|
|
178
|
+
): boolean => Boolean(rule.allowedComponents?.includes(component.name)
|
|
179
|
+
|| rule.allowedLayers?.includes(component.layer));
|
|
180
|
+
|
|
181
|
+
const validateMount = (node: ComponentNode, snapshot: TreeComponentSnapshot): void => {
|
|
182
|
+
const structure = snapshot.contract.structure;
|
|
183
|
+
if (structure?.kind === 'fragment-macro') {
|
|
184
|
+
if (node.mount !== 'fragment' || node.as !== undefined || !structure.rootless
|
|
185
|
+
|| structure.tree_mount !== 'erase') {
|
|
186
|
+
fail('CT-STRUCTURE-MOUNT', node, 'Fragment 宏必须 rootless/erase 且 mount=fragment,不能声明 as。', 'mount');
|
|
187
|
+
}
|
|
188
|
+
} else if (node.mount !== 'host' || structure?.rootless || structure?.tree_mount === 'erase') {
|
|
189
|
+
fail('CT-STRUCTURE-MOUNT', node, '普通组件必须保留 HTMLElement host,不能使用 fragment mount。', 'mount');
|
|
190
|
+
}
|
|
191
|
+
if (node.as !== undefined && (!structure?.semantics
|
|
192
|
+
|| !structure.semantics.allowed.some(token => token === node.as))) {
|
|
193
|
+
fail('CT-STRUCTURE-MOUNT', node, 'as 必须属于组件契约声明的封闭语义集合。', 'as');
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const rowItemSchema = (node: RepeatNode, scope: Scope): SomaContractField => {
|
|
198
|
+
if (!isPath(node.source)) {
|
|
199
|
+
fail('CT-REPEAT-SOURCE', node, 'source 只允许已声明集合的安全点分路径。', 'source');
|
|
200
|
+
}
|
|
201
|
+
const [root, ...segments] = node.source.split('.');
|
|
202
|
+
const parentItem = scope.aliases.get(root);
|
|
203
|
+
if (parentItem) {
|
|
204
|
+
const field = fieldAt(parentItem, segments);
|
|
205
|
+
if (field?.type !== 'array' || !field.items) {
|
|
206
|
+
fail('CT-REPEAT-SOURCE', node, '祖先行中的 source 必须是有 items 类型的 array 字段。', 'source');
|
|
207
|
+
}
|
|
208
|
+
return field.items;
|
|
209
|
+
}
|
|
210
|
+
const descriptor = sources.get(node.source);
|
|
211
|
+
if (!descriptor) {
|
|
212
|
+
fail('CT-REPEAT-SOURCE', node, '由 Host/canonical 类型声明提供该数组源,不能按运行数据猜测。', 'source');
|
|
213
|
+
}
|
|
214
|
+
return descriptor.item;
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const visit = (node: TreeNode, scope: Scope, position: Position): void => {
|
|
218
|
+
if (node.kind === 'host' || node.kind === 'slot') {
|
|
219
|
+
fail('CT-SYNTAX-ELEMENT', node, 'Host 只可作为根,slot 只可直接归属组件。');
|
|
220
|
+
}
|
|
221
|
+
if (node.kind === 'fragment') {
|
|
222
|
+
for (const child of node.children) visit(child, scope, position);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (node.kind === 'repeat') {
|
|
226
|
+
if (!position.repeatAllowed) {
|
|
227
|
+
fail('CT-SLOT-CONTRACT', node, 'repeat 只能作为已登记 collection.item 槽的唯一内容。');
|
|
228
|
+
}
|
|
229
|
+
if (scope.repeatDepth + 1 > limits.maxRepeatDepth) {
|
|
230
|
+
fail('CT-LIMIT', node, '减少嵌套集合层数。');
|
|
231
|
+
}
|
|
232
|
+
if (!VARIABLE.test(node.item) || RESERVED.has(node.item) || scope.aliases.has(node.item)) {
|
|
233
|
+
fail('CT-BINDING-SCOPE', node, '行变量不能遮蔽 page/p/ctrl/data 或祖先行变量。', 'item');
|
|
234
|
+
}
|
|
235
|
+
const item = rowItemSchema(node, scope);
|
|
236
|
+
if (!isPath(node.key) || !node.key.startsWith(`${node.item}.`)) {
|
|
237
|
+
fail('CT-REPEAT-KEY', node, 'key 必须是当前行变量起始的稳定字段路径。', 'key');
|
|
238
|
+
}
|
|
239
|
+
const keyField = fieldAt(item, node.key.split('.').slice(1));
|
|
240
|
+
if (!keyField || !['string', 'number', 'enum'].includes(keyField.type)
|
|
241
|
+
|| (keyField.type === 'enum' && (!keyField.values?.length
|
|
242
|
+
|| keyField.values.some(value => typeof value !== 'string'
|
|
243
|
+
&& (typeof value !== 'number' || !Number.isFinite(value)))))) {
|
|
244
|
+
fail('CT-REPEAT-KEY', node, 'key 字段必须有可验证的字符串或有限数字类型。', 'key');
|
|
245
|
+
}
|
|
246
|
+
if (expanded([node.child]).length === 0) {
|
|
247
|
+
fail('CT-SLOT-CONTRACT', node, 'repeat 的行模板必须至少有一个组件。');
|
|
248
|
+
}
|
|
249
|
+
const aliases = new Map(scope.aliases);
|
|
250
|
+
aliases.set(node.item, item);
|
|
251
|
+
visit(node.child, { ids: new Map(), aliases, repeatDepth: scope.repeatDepth + 1 }, {
|
|
252
|
+
...position, root: false, repeatAllowed: false,
|
|
253
|
+
});
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const snapshot = snapshotFor(node);
|
|
258
|
+
componentNames.add(snapshot.name);
|
|
259
|
+
rememberId(node, scope);
|
|
260
|
+
validateMount(node, snapshot);
|
|
261
|
+
const macro = snapshot.contract.structure?.kind === 'fragment-macro';
|
|
262
|
+
if (!macro) {
|
|
263
|
+
const permitted = position.root
|
|
264
|
+
? policy.roots.includes(snapshot.name)
|
|
265
|
+
: position.restrictions.length > 0
|
|
266
|
+
? position.restrictions.every(rule => allowedBy(rule, snapshot))
|
|
267
|
+
: allowedBy(policy, snapshot);
|
|
268
|
+
if (!permitted) {
|
|
269
|
+
fail('CT-POLICY-COMPONENT', node, '组件不符合当前根或继承的 slot 准入规则。', 'component');
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const seenSlots = new Map<string, NodeMeta>();
|
|
274
|
+
for (const slot of node.slots) {
|
|
275
|
+
if (slot.kind !== 'slot' || !own(snapshot.contract.slots, slot.name)) {
|
|
276
|
+
fail('CT-SLOT-CONTRACT', slot, '仅可投影组件契约已声明的 slot。', 'name');
|
|
277
|
+
}
|
|
278
|
+
const previous = seenSlots.get(slot.name);
|
|
279
|
+
if (previous) fail('CT-SLOT-CONTRACT', slot, '同一组件不能重复提供同名 slot。', 'name', previous);
|
|
280
|
+
seenSlots.set(slot.name, slot.meta);
|
|
281
|
+
if (slotPolicies.get(`${node.component}\0${slot.name}`)?.forbidden) {
|
|
282
|
+
fail('CT-POLICY-COMPONENT', slot, '当前 Host 未开放该 slot,包括显式空投影。', 'name');
|
|
283
|
+
}
|
|
284
|
+
if (own(snapshot.contract.slots, slot.name)?.required && expanded(slot.children).length === 0) {
|
|
285
|
+
fail('CT-SLOT-CONTRACT', slot, '必填 slot 不能只提供空 Fragment。', 'name');
|
|
286
|
+
}
|
|
287
|
+
const collection = own(snapshot.contract.structure?.slots, slot.name)?.kind === 'collection';
|
|
288
|
+
if (collection) {
|
|
289
|
+
const content = expanded(slot.children);
|
|
290
|
+
if (slot.name !== 'item' || content.length !== 1 || content[0].kind !== 'repeat') {
|
|
291
|
+
fail('CT-SLOT-CONTRACT', slot, 'collection.item 槽必须且只能提供一个 repeat。', 'name');
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const rule = macro ? undefined : slotPolicies.get(`${node.component}\0${slot.name}`);
|
|
295
|
+
const inherited = macro ? position.restrictions : position.restrictions.map(parent =>
|
|
296
|
+
parent.descendantAllowedComponents !== undefined || parent.descendantAllowedLayers !== undefined
|
|
297
|
+
? { ...parent, allowedComponents: parent.descendantAllowedComponents, allowedLayers: parent.descendantAllowedLayers }
|
|
298
|
+
: parent);
|
|
299
|
+
const restrictions = rule ? [...inherited, rule] : inherited;
|
|
300
|
+
const childPosition = macro ? position : { root: false, restrictions, repeatAllowed: collection };
|
|
301
|
+
for (const child of slot.children) visit(child, scope, childPosition);
|
|
302
|
+
}
|
|
303
|
+
for (const [name, slot] of Object.entries(snapshot.contract.slots ?? {})) {
|
|
304
|
+
if (slot.required && !seenSlots.has(name)) {
|
|
305
|
+
fail('CT-SLOT-CONTRACT', node, '组件缺少契约要求的必填 slot。', 'name');
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
const pageScope: Scope = { ids: new Map(), aliases: new Map(), repeatDepth: 0 };
|
|
311
|
+
rememberId(tree.host, pageScope);
|
|
312
|
+
const rootPosition: Position = { root: true, restrictions: [], repeatAllowed: false };
|
|
313
|
+
if (expanded(tree.host.children).length === 0) {
|
|
314
|
+
fail('CT-SYNTAX-ROOT', tree.host, 'Host 必须包含至少一个有效根组件。');
|
|
315
|
+
}
|
|
316
|
+
for (const child of tree.host.children) visit(child, pageScope, rootPosition);
|
|
317
|
+
return { tree, componentNames: Object.freeze([...componentNames].sort()) };
|
|
318
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { COMPONENT_TREE_ATTRIBUTES, parseComponentTree } from '../component-tree/parser';
|
|
2
|
+
import { compilePageDeclaration } from '../compiler/page-declaration-compiler';
|
|
3
|
+
import { SomaComponentTreeError } from '../../shared/component-tree-errors';
|
|
4
|
+
import type { SourceSpan, TreeCompileContext, TreeRegistrySnapshot } from '../../shared/types/component-tree.types';
|
|
5
|
+
export { loadPageMarkupConfig } from '../../server/host/page-markup-config';
|
|
6
|
+
|
|
7
|
+
export interface TreeEditorPosition { line: number; character: number }
|
|
8
|
+
export interface TreeEditorDiagnostic {
|
|
9
|
+
uri: string; code: string; severity: number; source: string; message: string;
|
|
10
|
+
range: { start: TreeEditorPosition; end: TreeEditorPosition };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Same parser/compiler as publishing. LSP supplies only trusted Host context, never source metadata. */
|
|
14
|
+
export function diagnoseComponentTree(input: {
|
|
15
|
+
html: string; uiYaml: string; htmlUri: string; uiUri: string;
|
|
16
|
+
markup?: 'legacy-html' | 'component-tree'; grammarVersion?: number; treeContext?: TreeCompileContext;
|
|
17
|
+
}): TreeEditorDiagnostic[] {
|
|
18
|
+
try {
|
|
19
|
+
if (input.markup === 'component-tree') parseComponentTree(input.html, { sourceId: input.htmlUri, limits: input.treeContext?.limits });
|
|
20
|
+
compilePageDeclaration(input);
|
|
21
|
+
return [];
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (!(error instanceof SomaComponentTreeError)) return [{
|
|
24
|
+
uri: input.uiUri, code: 'CT-BINDING-SCOPE', severity: 1, source: 'soma-component-tree',
|
|
25
|
+
message: 'canonical 声明未通过正式解析,请检查声明容器和字段。', range: diagnosticRange(),
|
|
26
|
+
}];
|
|
27
|
+
const diagnostic = error.diagnostic;
|
|
28
|
+
const canonical = diagnostic.phase === 'bind' || diagnostic.nodePath === 'page.domain';
|
|
29
|
+
return [{
|
|
30
|
+
uri: canonical && !diagnostic.span ? input.uiUri : input.htmlUri,
|
|
31
|
+
code: error.code, severity: error.code === 'CT-REGISTRY-CONTEXT' ? 2 : 1,
|
|
32
|
+
source: 'soma-component-tree',
|
|
33
|
+
message: diagnostic.fixHint ?? '组件树未通过正式编译验证。',
|
|
34
|
+
range: diagnosticRange(diagnostic.span),
|
|
35
|
+
}];
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function diagnosticRange(span?: SourceSpan): TreeEditorDiagnostic['range'] {
|
|
40
|
+
return span ? {
|
|
41
|
+
start: { line: span.startLine - 1, character: span.startColumn - 1 },
|
|
42
|
+
end: { line: span.endLine - 1, character: span.endColumn - 1 },
|
|
43
|
+
} : { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Tolerant cursor context is only for suggestions; it never claims a partial document is valid. */
|
|
47
|
+
export function completeComponentTree(text: string, position: TreeEditorPosition, registry?: TreeRegistrySnapshot) {
|
|
48
|
+
const lines = text.split('\n');
|
|
49
|
+
const prefix = [...lines.slice(0, position.line), (lines[position.line] ?? '').slice(0, position.character)].join('\n');
|
|
50
|
+
const open = prefix.match(/<([a-z-]*)([^<>]*)$/);
|
|
51
|
+
if (!open) return [];
|
|
52
|
+
const [, tag, rest] = open;
|
|
53
|
+
const item = (label: string, detail: string, kind = 12) => ({ label, insertText: label, detail, kind });
|
|
54
|
+
if (!rest && !Object.hasOwn(COMPONENT_TREE_ATTRIBUTES, tag)) return Object.keys(COMPONENT_TREE_ATTRIBUTES)
|
|
55
|
+
.filter((name) => name.startsWith(tag)).map((name) => item(name, 'component-tree:1 语法元素'));
|
|
56
|
+
const attributes = COMPONENT_TREE_ATTRIBUTES[tag as keyof typeof COMPONENT_TREE_ATTRIBUTES];
|
|
57
|
+
if (!attributes) return [];
|
|
58
|
+
const value = rest.match(/([a-z]+)\s*=\s*["']([^"']*)$/);
|
|
59
|
+
if (value) {
|
|
60
|
+
const [, attribute, partial] = value;
|
|
61
|
+
let values: readonly string[] = [];
|
|
62
|
+
if (tag === 'soma-component' && attribute === 'component') values = Object.keys(registry?.components ?? {}).sort();
|
|
63
|
+
if (tag === 'soma-component' && attribute === 'as') {
|
|
64
|
+
const name = rest.match(/\bcomponent\s*=\s*["']([^"']+)["']/)?.[1];
|
|
65
|
+
values = name ? registry?.components[name]?.contract.structure?.semantics?.allowed ?? [] : [];
|
|
66
|
+
}
|
|
67
|
+
if (tag === 'soma-slot' && attribute === 'name') {
|
|
68
|
+
const stack: string[] = [];
|
|
69
|
+
for (const token of prefix.slice(0, open.index).matchAll(/<\/?soma-component\b[^>]*>/g)) {
|
|
70
|
+
if (token[0].startsWith('</')) stack.pop();
|
|
71
|
+
else stack.push(token[0].match(/\bcomponent\s*=\s*["']([^"']+)["']/)?.[1] ?? '');
|
|
72
|
+
}
|
|
73
|
+
values = Object.keys(registry?.components[stack.at(-1) ?? '']?.contract.slots ?? {});
|
|
74
|
+
}
|
|
75
|
+
return values.filter((name) => name.startsWith(partial)).map((name) => item(name, '实际 Registry 契约', 12));
|
|
76
|
+
}
|
|
77
|
+
const used = new Set([...rest.matchAll(/([a-z]+)\s*=/g)].map((match) => match[1]));
|
|
78
|
+
return attributes.filter((name) => !used.has(name)).map((name) => item(`${name}=""`, 'component-tree:1 属性', 10));
|
|
79
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// CJS transport adapter. Grammar/diagnostics live in the real TS compiler service.
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const { pathToFileURL } = require('node:url');
|
|
5
|
+
let service;
|
|
6
|
+
let hostResolver;
|
|
7
|
+
function getService() {
|
|
8
|
+
if (!service) {
|
|
9
|
+
const compiled = path.resolve(__dirname, '../../../dist/lsp/component-tree.cjs');
|
|
10
|
+
service = fs.existsSync(compiled) ? require(compiled)
|
|
11
|
+
: require('jiti')(__filename, { interopDefault: false })(path.join(__dirname, 'component-tree-service.ts'));
|
|
12
|
+
}
|
|
13
|
+
return service;
|
|
14
|
+
}
|
|
15
|
+
function resolveContext(hostDir, pageBase) {
|
|
16
|
+
if (!hostResolver) hostResolver = require('jiti')(__filename, { interopDefault: false })(
|
|
17
|
+
path.resolve(__dirname, '../../server/host/resolve-host-tree-context.ts'),
|
|
18
|
+
).resolveHostTreeCompileContext;
|
|
19
|
+
return hostResolver(hostDir, { pageBase });
|
|
20
|
+
}
|
|
21
|
+
function treePageMode(hostDir, base) {
|
|
22
|
+
return getService().loadPageMarkupConfig(path.join(hostDir, 'config'), base);
|
|
23
|
+
}
|
|
24
|
+
function treeDiagnostics(hostDir, base, html, uiYaml) {
|
|
25
|
+
const htmlUri = pathToFileURL(path.join(hostDir, 'html', `${base}.html`)).href;
|
|
26
|
+
const uiUri = pathToFileURL(path.join(hostDir, 'ui', `${base}_ui.yaml`)).href;
|
|
27
|
+
try {
|
|
28
|
+
const mode = treePageMode(hostDir, base);
|
|
29
|
+
const treeContext = mode.markup === 'component-tree' ? resolveContext(hostDir, base) : undefined;
|
|
30
|
+
return getService().diagnoseComponentTree({ html, uiYaml, htmlUri, uiUri, ...mode, treeContext });
|
|
31
|
+
} catch {
|
|
32
|
+
return [{ uri: htmlUri, code: 'CT-REGISTRY-CONTEXT', source: 'soma-component-tree', severity: 2,
|
|
33
|
+
message: '缺少有效的受信页面格式或 Registry 上下文,尚未完成组件树验证。',
|
|
34
|
+
range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } } }];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function treeCompletions(hostDir, base, text, position) {
|
|
38
|
+
let registry;
|
|
39
|
+
try { registry = resolveContext(hostDir, base)?.registrySnapshot; } catch { /* syntax suggestions remain available */ }
|
|
40
|
+
return getService().completeComponentTree(text, position, registry);
|
|
41
|
+
}
|
|
42
|
+
module.exports = { treePageMode, treeDiagnostics, treeCompletions };
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
const fs = require('node:fs');
|
|
3
3
|
const path = require('node:path');
|
|
4
4
|
const { declarationFacts } = require('./soma-declaration.cjs');
|
|
5
|
+
const { pathToFileURL } = require('node:url');
|
|
6
|
+
const { treePageMode, treeDiagnostics } = require('./component-tree.cjs');
|
|
5
7
|
|
|
6
8
|
function extractSomaIdsFromHtml(html) {
|
|
7
9
|
const ids = new Set();
|
|
@@ -60,13 +62,14 @@ function retiredSidecarPaths(hostDir, base) {
|
|
|
60
62
|
];
|
|
61
63
|
}
|
|
62
64
|
|
|
63
|
-
function lintAnchorConsistency(hostDir) {
|
|
65
|
+
function lintAnchorConsistency(hostDir, openDocs = new Map()) {
|
|
64
66
|
const htmlDir = path.join(hostDir, 'html');
|
|
65
67
|
const diagnostics = [];
|
|
68
|
+
const readSource = (file) => openDocs.get(pathToFileURL(file).href) ?? openDocs.get(`file://${file}`) ?? fs.readFileSync(file, 'utf8');
|
|
66
69
|
for (const base of collectHtmlPages(htmlDir)) {
|
|
67
70
|
const htmlPath = path.join(htmlDir, `${base}.html`);
|
|
68
71
|
const declarationPath = path.join(hostDir, 'ui', `${base}_ui.yaml`);
|
|
69
|
-
const html =
|
|
72
|
+
const html = readSource(htmlPath);
|
|
70
73
|
const htmlIds = extractSomaIdsFromHtml(html);
|
|
71
74
|
|
|
72
75
|
for (const sidecar of retiredSidecarPaths(hostDir, base).filter(fs.existsSync)) {
|
|
@@ -88,7 +91,16 @@ function lintAnchorConsistency(hostDir) {
|
|
|
88
91
|
continue;
|
|
89
92
|
}
|
|
90
93
|
|
|
91
|
-
const source =
|
|
94
|
+
const source = readSource(declarationPath);
|
|
95
|
+
let treeMode = false;
|
|
96
|
+
if (fs.existsSync(path.join(hostDir, 'config', 'page-markup.config.yaml'))) {
|
|
97
|
+
try { treeMode = treePageMode(hostDir, base).markup === 'component-tree'; }
|
|
98
|
+
catch { treeMode = true; }
|
|
99
|
+
}
|
|
100
|
+
if (treeMode || /<\/?soma-(?:host|component|slot|fragment|repeat)\b/i.test(html)) {
|
|
101
|
+
diagnostics.push(...treeDiagnostics(hostDir, base, html, source));
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
92
104
|
let facts;
|
|
93
105
|
try {
|
|
94
106
|
facts = declarationFacts(source);
|
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
*/
|
|
4
4
|
const fs = require('node:fs');
|
|
5
5
|
const path = require('node:path');
|
|
6
|
+
const yaml = require('js-yaml');
|
|
6
7
|
const { declarationFacts } = require('./soma-declaration.cjs');
|
|
8
|
+
const { treePageMode, treeCompletions } = require('./component-tree.cjs');
|
|
7
9
|
|
|
8
10
|
const ANCHOR_PREFIXES = ['btn_', 'input_', 'txt_', 'list_', 'section_', 'nav_', 'link_', 'hero_'];
|
|
9
11
|
|
|
@@ -33,6 +35,11 @@ function getHtmlAnchorCompletions(hostDir, uri, text, position) {
|
|
|
33
35
|
const pageBase = !rel.startsWith('..') && rel.endsWith('.html')
|
|
34
36
|
? rel.replace(/\\/g, '/').replace(/\.html$/, '')
|
|
35
37
|
: path.basename(filePath, '.html');
|
|
38
|
+
let treeMode = /<\/?soma-(?:host|component|slot|fragment|repeat)\b/.test(text);
|
|
39
|
+
if (!treeMode && fs.existsSync(path.join(hostDir, 'config', 'page-markup.config.yaml'))) {
|
|
40
|
+
try { treeMode = treePageMode(hostDir, pageBase).markup === 'component-tree'; } catch { treeMode = true; }
|
|
41
|
+
}
|
|
42
|
+
if (treeMode) return treeCompletions(hostDir, pageBase, text, position);
|
|
36
43
|
const uiPath = path.join(hostDir, 'ui', `${pageBase}_ui.yaml`);
|
|
37
44
|
const existing = new Set();
|
|
38
45
|
for (const m of text.matchAll(/data-soma-id=["']([^"']+)["']/g)) existing.add(m[1]);
|
|
@@ -149,6 +149,8 @@ export class SomaManifestCompiler {
|
|
|
149
149
|
watchPaths: dataPath ? [dataPath] : [],
|
|
150
150
|
childShowConfig: showValue.show,
|
|
151
151
|
roleBy: showValue.bind.role_by,
|
|
152
|
+
...(showValue.bind.key ? { keyPath: showValue.bind.key, itemAlias: showValue.bind.var } : {}),
|
|
153
|
+
...(showValue.bind.repeatPlanId ? { repeatPlanId: showValue.bind.repeatPlanId, itemAlias: showValue.bind.var } : {}),
|
|
152
154
|
});
|
|
153
155
|
// 嵌套绑定同样支持整块显隐:再补一条 when 绑定(同一锚点,互不干扰)
|
|
154
156
|
if (typeof showValue.when === 'string') {
|
|
@@ -10,6 +10,7 @@ import { deriveBlockExample } from './example-blocks';
|
|
|
10
10
|
import { renderFieldLines } from '../../shared/component/field-lines';
|
|
11
11
|
import { deriveContractSample, hasRenderableSample } from '../../shared/component/derive-sample';
|
|
12
12
|
import { renderKeyboardMatrixLine } from './keyboard-matrix';
|
|
13
|
+
import { copyCatalogExamples, formatSomaCatalogExample, selectSomaCatalogExample, type CatalogExampleCapabilities } from './catalog-examples';
|
|
13
14
|
import {
|
|
14
15
|
componentTokenVar,
|
|
15
16
|
type SomaComponentContract,
|
|
@@ -17,6 +18,8 @@ import {
|
|
|
17
18
|
type SomaContractOverlay,
|
|
18
19
|
type SomaGeometryFamily,
|
|
19
20
|
type SomaContractProp,
|
|
21
|
+
type SomaContractExample,
|
|
22
|
+
type SomaContractStructure,
|
|
20
23
|
} from '../../shared/types/component-contract.types';
|
|
21
24
|
import type { SomaComponentDefinition } from './component-definition.types';
|
|
22
25
|
|
|
@@ -54,6 +57,14 @@ export interface SomaAiCatalogEntry {
|
|
|
54
57
|
keyboard?: { contract: SomaContractKeyboard };
|
|
55
58
|
/** 浮层行为契约(声明了才有) */
|
|
56
59
|
overlay?: SomaContractOverlay;
|
|
60
|
+
/** Public structural summary; implementation anchor names/selectors never enter the catalog. */
|
|
61
|
+
structure?: {
|
|
62
|
+
kind: SomaContractStructure['kind'];
|
|
63
|
+
rootless: boolean;
|
|
64
|
+
treeMount: SomaContractStructure['tree_mount'];
|
|
65
|
+
semantics?: SomaContractStructure['semantics'];
|
|
66
|
+
slots: Array<{ name: string; kind: 'projection' | 'collection'; directChildren: boolean; rowContainer?: 'none' | 'list-item' }>;
|
|
67
|
+
};
|
|
57
68
|
/** 契约级依赖(F-46):装这个还要装什么 */
|
|
58
69
|
uses?: string[];
|
|
59
70
|
/** 组件级令牌(M-1):这个组件开放的可调旋钮及其 CSS 变量名 */
|
|
@@ -62,6 +73,7 @@ export interface SomaAiCatalogEntry {
|
|
|
62
73
|
whenToUse: string;
|
|
63
74
|
whenNotToUse?: string;
|
|
64
75
|
example: string;
|
|
76
|
+
examples?: readonly SomaContractExample[];
|
|
65
77
|
antiPatterns?: string[];
|
|
66
78
|
};
|
|
67
79
|
/**
|
|
@@ -155,6 +167,14 @@ export function buildCatalogEntry(contract: SomaComponentContract): SomaAiCatalo
|
|
|
155
167
|
? { keyboard: { contract: contract.keyboard } }
|
|
156
168
|
: {}),
|
|
157
169
|
...(contract.overlay ? { overlay: contract.overlay } : {}),
|
|
170
|
+
...(contract.structure ? { structure: {
|
|
171
|
+
kind: contract.structure.kind, rootless: contract.structure.rootless, treeMount: contract.structure.tree_mount,
|
|
172
|
+
...(contract.structure.semantics ? { semantics: { ...contract.structure.semantics, allowed: [...contract.structure.semantics.allowed] } } : {}),
|
|
173
|
+
slots: Object.entries(contract.structure.slots ?? {}).map(([name, slot]) => ({
|
|
174
|
+
name, kind: slot.kind, directChildren: slot.directChildren,
|
|
175
|
+
...(slot.rowContainer ? { rowContainer: slot.rowContainer } : {}),
|
|
176
|
+
})),
|
|
177
|
+
} } : {}),
|
|
158
178
|
...(contract.uses && contract.uses.length > 0 ? { uses: [...contract.uses] } : {}),
|
|
159
179
|
...(contract.tokens && Object.keys(contract.tokens).length > 0
|
|
160
180
|
? {
|
|
@@ -171,6 +191,7 @@ export function buildCatalogEntry(contract: SomaComponentContract): SomaAiCatalo
|
|
|
171
191
|
whenToUse: contract.ai.when_to_use,
|
|
172
192
|
whenNotToUse: contract.ai.when_not_to_use,
|
|
173
193
|
example: contract.ai.example,
|
|
194
|
+
...(contract.ai.examples ? { examples: copyCatalogExamples(contract.ai.examples) } : {}),
|
|
174
195
|
antiPatterns: contract.ai.anti_patterns,
|
|
175
196
|
}
|
|
176
197
|
: undefined,
|
|
@@ -196,6 +217,8 @@ export interface GenerateAiCatalogOptions {
|
|
|
196
217
|
* 不传则目录产物与历史完全一致。
|
|
197
218
|
*/
|
|
198
219
|
conventions?: string;
|
|
220
|
+
/** Human/tool consumers may opt in; AI/native-page consumers remain legacy-only by default. */
|
|
221
|
+
exampleCapabilities?: CatalogExampleCapabilities;
|
|
199
222
|
}
|
|
200
223
|
|
|
201
224
|
/**
|
|
@@ -223,7 +246,7 @@ export function generateAiCatalog(
|
|
|
223
246
|
return {
|
|
224
247
|
generatedFrom: entries.map((entry) => `${entry.name}@${entry.version}`),
|
|
225
248
|
entries,
|
|
226
|
-
markdown: renderMarkdown(entries, options?.conventions),
|
|
249
|
+
markdown: renderMarkdown(entries, options?.conventions, options?.exampleCapabilities),
|
|
227
250
|
};
|
|
228
251
|
}
|
|
229
252
|
|
|
@@ -256,7 +279,7 @@ function propTypeLabel(prop: SomaContractProp): string {
|
|
|
256
279
|
/** 设计规范章节标题:固定文案,供调用方与测试稳定断言 */
|
|
257
280
|
const CONVENTIONS_HEADING = '## 版式与视觉规范(生成页面时必须遵守)';
|
|
258
281
|
|
|
259
|
-
function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string): string {
|
|
282
|
+
function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string, exampleCapabilities?: CatalogExampleCapabilities): string {
|
|
260
283
|
const lines: string[] = [
|
|
261
284
|
'# SOMA 组件目录(AI 查表用,契约自动生成 — 禁止手改)',
|
|
262
285
|
'',
|
|
@@ -336,6 +359,13 @@ function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string): st
|
|
|
336
359
|
`插槽:${entry.slots.map((s) => `\`${s.name}\`${s.required ? '(必填)' : ''} ${s.desc}`).join(';')}`,
|
|
337
360
|
);
|
|
338
361
|
}
|
|
362
|
+
if (entry.structure) {
|
|
363
|
+
lines.push('', `结构:${entry.structure.kind};挂载 ${entry.structure.treeMount};${entry.structure.rootless ? '编译消隐,无运行时实例' : '有稳定运行时宿主'}`);
|
|
364
|
+
if (entry.structure.semantics) lines.push(`语义:${entry.structure.semantics.allowed.join(' / ')}(默认 ${entry.structure.semantics.default})`);
|
|
365
|
+
for (const slot of entry.structure.slots) {
|
|
366
|
+
lines.push(`结构槽 ${slot.name}:${slot.kind}${slot.directChildren ? ',保持直接子项' : ''}${slot.rowContainer ? `,行容器 ${slot.rowContainer}` : ''}`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
339
369
|
|
|
340
370
|
// 键盘表 / 浮层语义 / 依赖 / 令牌(REQ-011):各一行,声明了才出现。
|
|
341
371
|
// 它们让"这个组件按键怎么走、Esc 关不关、还要装什么、能调什么"不必读源码——
|
|
@@ -357,10 +387,18 @@ function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string): st
|
|
|
357
387
|
lines.push(`组件令牌:${entry.tokens.map((token) => `\`${token.cssVar}\`(默认 ${token.default})${token.desc}`).join(';')}`);
|
|
358
388
|
}
|
|
359
389
|
|
|
360
|
-
|
|
390
|
+
const selectedExample = selectSomaCatalogExample(entry, exampleCapabilities);
|
|
391
|
+
if (selectedExample) {
|
|
392
|
+
lines.push('', `完整用法(${selectedExample.format},按消费能力选择):`, '```', formatSomaCatalogExample(selectedExample), '```');
|
|
393
|
+
} else if (entry.ai?.example) {
|
|
361
394
|
lines.push('');
|
|
362
395
|
lines.push('用法:');
|
|
363
396
|
lines.push('```');
|
|
397
|
+
// The compatibility string is never a side channel for tree source into
|
|
398
|
+
// legacy-only/AI catalog readers.
|
|
399
|
+
if (/<\/?soma-(?:host|component|slot|fragment|repeat)\b/i.test(entry.ai.example)) {
|
|
400
|
+
throw new TypeError(`[catalog] ${entry.name}: tree source belongs in format-labelled ai.examples`);
|
|
401
|
+
}
|
|
364
402
|
lines.push(entry.ai.example.trimEnd());
|
|
365
403
|
lines.push('```');
|
|
366
404
|
|