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.
Files changed (131) hide show
  1. package/app/SomaPageClient.tsx +28 -9
  2. package/app/soma/manifest/route.ts +3 -0
  3. package/bin/migrate.cjs +71 -1
  4. package/bin/soma-lsp.cjs +8 -1
  5. package/core/build/blocks/block-compile.ts +23 -5
  6. package/core/build/compiler/full-manifest-builder.ts +15 -0
  7. package/core/build/compiler/page-assets.ts +17 -1
  8. package/core/build/compiler/page-declaration-compiler.ts +67 -11
  9. package/core/build/compiler/precompiled-manifest-loader.ts +7 -0
  10. package/core/build/compiler/soma-manifest-webpack-plugin.js +7 -0
  11. package/core/build/compiler/soma-precompile.js +30 -6
  12. package/core/build/component/package-loader.ts +35 -4
  13. package/core/build/component-tree/artifact-codec.ts +192 -0
  14. package/core/build/component-tree/binding-bridge.ts +272 -0
  15. package/core/build/component-tree/collection-binding-lowerer.ts +65 -0
  16. package/core/build/component-tree/definition-preparation.ts +320 -0
  17. package/core/build/component-tree/migration-files.ts +214 -0
  18. package/core/build/component-tree/migration.ts +170 -0
  19. package/core/build/component-tree/parser.ts +362 -0
  20. package/core/build/component-tree/registry-snapshot.ts +317 -0
  21. package/core/build/component-tree/source-preflight.ts +132 -0
  22. package/core/build/component-tree/structure-topology.ts +63 -0
  23. package/core/build/component-tree/validator.ts +318 -0
  24. package/core/build/lsp/component-tree-service.ts +79 -0
  25. package/core/build/lsp/component-tree.cjs +42 -0
  26. package/core/build/lsp/cross-file-diagnostics.cjs +15 -3
  27. package/core/build/lsp/extra-completion.cjs +7 -0
  28. package/core/client/compiler/manifest-compiler.ts +2 -0
  29. package/core/client/component/ai-catalog.ts +41 -3
  30. package/core/client/component/catalog-examples.ts +60 -0
  31. package/core/client/component/component-definition.types.ts +9 -0
  32. package/core/client/component/component-expander.ts +21 -5
  33. package/core/client/component/component-manager.ts +103 -16
  34. package/core/client/component/component-registry.ts +10 -1
  35. package/core/client/component/scoped-adapter.ts +29 -2
  36. package/core/client/component/structure-adapter.ts +207 -0
  37. package/core/client/component/verify-pack.ts +21 -1
  38. package/core/client/engine/asset-resolver.ts +1 -1
  39. package/core/client/engine/dom-renderer.ts +283 -0
  40. package/core/client/engine/event-engine.ts +28 -9
  41. package/core/client/engine/render-engine.ts +2 -0
  42. package/core/client/engine/row-range.ts +62 -0
  43. package/core/client/engine/row-scope.ts +77 -0
  44. package/core/client/engine/runtime-builder.ts +2 -0
  45. package/core/client/engine/soma-bootstrap.ts +146 -1
  46. package/core/client/parser/blocks/page-parser.ts +9 -2
  47. package/core/client/parser/ui-config-parser.ts +38 -6
  48. package/core/client/registry/declaration-renderer.ts +32 -24
  49. package/core/client/registry/remote-page.ts +1 -1
  50. package/core/client/validation/contract-validator.ts +1 -1
  51. package/core/index.ts +3 -0
  52. package/core/server/host/page-markup-config.ts +42 -0
  53. package/core/server/host/published-page-artifact-cache.ts +36 -4
  54. package/core/server/host/published-page-assets.ts +13 -7
  55. package/core/server/host/resolve-host-tree-context.ts +43 -0
  56. package/core/server/host/server-page-assets.ts +23 -4
  57. package/core/server/host/soma-page-compile.ts +10 -0
  58. package/core/server/page-declaration.ts +7 -0
  59. package/core/server/registry/declaration-precompiler.ts +35 -3
  60. package/core/server/registry/page-registry-repository.ts +31 -3
  61. package/core/server/registry/page-registry-store.ts +64 -7
  62. package/core/server/registry/publish-asset-pin.ts +6 -1
  63. package/core/server/registry/services/pages/Get.ts +11 -6
  64. package/core/server/registry/validation/compile-gate.ts +10 -1
  65. package/core/shared/component-tree-artifact.ts +237 -0
  66. package/core/shared/component-tree-errors.ts +52 -0
  67. package/core/shared/types/component-contract.types.ts +51 -0
  68. package/core/shared/types/component-tree-artifact.types.ts +121 -0
  69. package/core/shared/types/component-tree.types.ts +170 -0
  70. package/core/shared/types/engine.types.ts +5 -0
  71. package/core/shared/types/manifest.types.ts +4 -0
  72. package/core/shared/types/ui-config.types.ts +8 -0
  73. package/dist/cli/soma.js +1 -1
  74. package/dist/core/index.cjs +1757 -511
  75. package/dist/lsp/component-tree.cjs +20807 -0
  76. package/dist/types/build/blocks/block-compile.d.ts +10 -1
  77. package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
  78. package/dist/types/build/compiler/page-assets.d.ts +6 -1
  79. package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
  80. package/dist/types/build/component/package-loader.d.ts +4 -1
  81. package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
  82. package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
  83. package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
  84. package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
  85. package/dist/types/build/component-tree/migration-files.d.ts +35 -0
  86. package/dist/types/build/component-tree/migration.d.ts +28 -0
  87. package/dist/types/build/component-tree/parser.d.ts +13 -0
  88. package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
  89. package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
  90. package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
  91. package/dist/types/build/component-tree/validator.d.ts +9 -0
  92. package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
  93. package/dist/types/client/component/ai-catalog.d.ts +18 -1
  94. package/dist/types/client/component/catalog-examples.d.ts +18 -0
  95. package/dist/types/client/component/component-definition.types.d.ts +9 -0
  96. package/dist/types/client/component/component-expander.d.ts +2 -1
  97. package/dist/types/client/component/component-manager.d.ts +11 -0
  98. package/dist/types/client/component/scoped-adapter.d.ts +1 -0
  99. package/dist/types/client/component/structure-adapter.d.ts +17 -0
  100. package/dist/types/client/engine/dom-renderer.d.ts +15 -0
  101. package/dist/types/client/engine/event-engine.d.ts +1 -0
  102. package/dist/types/client/engine/render-engine.d.ts +1 -0
  103. package/dist/types/client/engine/row-range.d.ts +13 -0
  104. package/dist/types/client/engine/row-scope.d.ts +20 -0
  105. package/dist/types/client/engine/runtime-builder.d.ts +1 -0
  106. package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
  107. package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
  108. package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
  109. package/dist/types/client/registry/remote-page.d.ts +1 -1
  110. package/dist/types/index.d.ts +3 -1
  111. package/dist/types/server/host/page-markup-config.d.ts +6 -0
  112. package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
  113. package/dist/types/server/host/published-page-assets.d.ts +5 -3
  114. package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
  115. package/dist/types/server/host/server-page-assets.d.ts +6 -0
  116. package/dist/types/server/host/soma-page-compile.d.ts +10 -1
  117. package/dist/types/server/page-declaration.d.ts +6 -0
  118. package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
  119. package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
  120. package/dist/types/server/registry/page-registry-store.d.ts +11 -1
  121. package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
  122. package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
  123. package/dist/types/shared/component-tree-artifact.d.ts +5 -0
  124. package/dist/types/shared/component-tree-errors.d.ts +22 -0
  125. package/dist/types/shared/types/component-contract.types.d.ts +42 -0
  126. package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
  127. package/dist/types/shared/types/component-tree.types.d.ts +149 -0
  128. package/dist/types/shared/types/engine.types.d.ts +5 -0
  129. package/dist/types/shared/types/manifest.types.d.ts +4 -0
  130. package/dist/types/shared/types/ui-config.types.d.ts +8 -0
  131. package/package.json +2 -1
@@ -0,0 +1,207 @@
1
+ import type { StructurePlan, RepeatPlan } from '../../shared/types/component-tree-artifact.types';
2
+ import type { SomaStructureSemanticToken } from '../../shared/types/component-contract.types';
3
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
4
+ import type { SomaComponentDefinition } from './component-definition.types';
5
+ import { SomaScopedContainerAdapter } from './scoped-adapter';
6
+
7
+ const preparedHosts = new WeakMap<HTMLElement, { definition: SomaComponentDefinition; scopeId: string; staticProps: Record<string, unknown> }>();
8
+ const semanticTags: Record<SomaStructureSemanticToken, string> = {
9
+ root: 'div', div: 'div', flow: 'div', none: 'div', main: 'main', section: 'section',
10
+ article: 'article', aside: 'aside', header: 'header', footer: 'footer', nav: 'nav',
11
+ navigation: 'nav', complementary: 'aside', contentinfo: 'footer', region: 'section',
12
+ unordered: 'ul', ordered: 'ol',
13
+ };
14
+
15
+ export interface PreparedStructureTemplate {
16
+ fragment: DocumentFragment;
17
+ root?: HTMLElement;
18
+ rootAlias?: string;
19
+ merge: boolean;
20
+ staticProps: Record<string, unknown>;
21
+ }
22
+
23
+ /** Validate off-DOM, before replacing the old host or activating any controller. */
24
+ export function prepareStructureTemplate(
25
+ host: HTMLElement, definition: SomaComponentDefinition, plan?: StructurePlan,
26
+ suppliedProps: Record<string, unknown> = {},
27
+ ): PreparedStructureTemplate {
28
+ const structure = definition.contract.structure;
29
+ if (structure?.kind === 'fragment-macro') fail('Fragment 宏不可在运行时挂载');
30
+ if (!plan && (host.hasAttribute('data-soma-tree-mount') || host.hasAttribute('data-soma-tree-as'))) {
31
+ fail('结构标记没有已验证的实例计划');
32
+ }
33
+ if (plan && (plan.componentName !== definition.contract.name
34
+ || plan.mountMode !== (structure?.tree_mount ?? 'legacy-host')
35
+ || plan.hostTag.toLowerCase() !== host.tagName.toLowerCase())) fail('结构计划与实际组件或宿主不一致');
36
+ const template = host.ownerDocument.createElement('template');
37
+ template.innerHTML = definition.templateHtml;
38
+ const result: PreparedStructureTemplate = { fragment: template.content, merge: plan?.mountMode === 'single-host', staticProps: {} };
39
+ if (!structure) return result;
40
+ const rootId = definition.structureAdapter?.rootAnchor;
41
+ let root: HTMLElement | undefined;
42
+ if (rootId) {
43
+ const matches = [...template.content.querySelectorAll<HTMLElement>('[data-soma-id]')].filter(el => el.getAttribute('data-soma-id') === rootId);
44
+ if (matches.length !== 1) fail('结构定义的内部根必须恰好匹配一次');
45
+ root = matches[0];
46
+ }
47
+ const semantics = structure.semantics;
48
+ if (semantics) {
49
+ let token = plan?.semanticToken;
50
+ const prop = semantics.staticProp;
51
+ if (prop) {
52
+ const raw = suppliedProps[prop] ?? plan?.staticProps?.[prop] ?? definition.contract.props?.[prop]?.default;
53
+ const derived = prop === 'ordered' ? typeof raw === 'boolean' ? raw ? 'ordered' : 'unordered' : undefined : raw;
54
+ if (derived !== undefined && (typeof derived !== 'string' || !semantics.allowed.includes(derived as SomaStructureSemanticToken))) {
55
+ fail('结构语义属性必须是受控静态字面量');
56
+ }
57
+ if (token && derived !== undefined && token !== derived) fail('结构计划与静态语义属性冲突');
58
+ token ??= derived as SomaStructureSemanticToken | undefined;
59
+ result.staticProps[prop] = prop === 'ordered' ? (token ?? semantics.default) === 'ordered' : token ?? semantics.default;
60
+ }
61
+ token ??= semantics.default;
62
+ if (!semantics.allowed.includes(token)) fail('结构语义不在组件允许词汇中');
63
+ const tag = semanticTags[token];
64
+ if (plan && plan.mountMode !== 'legacy-host' && plan.hostTag !== tag) fail('结构计划宿主标签不符合受控语义');
65
+ if (root && root.tagName.toLowerCase() !== tag) {
66
+ const replacement = host.ownerDocument.createElement(tag);
67
+ for (const attr of [...root.attributes]) replacement.setAttribute(attr.name, attr.value);
68
+ replacement.append(...Array.from(root.childNodes));
69
+ root.replaceWith(replacement);
70
+ root = replacement;
71
+ }
72
+ }
73
+ if (rootId && hasRootVisibility(definition.uiConfig?.show, rootId)) fail('结构原语内部不得接管共享宿主显隐');
74
+ if (root?.hasAttribute('hidden') || root?.hasAttribute('style')) fail('结构根不得写入 hidden/style 显隐后门');
75
+ assertStructureLabel(definition, { label: definition.contract.props?.label?.default, ...suppliedProps, ...result.staticProps });
76
+ if (result.merge) {
77
+ if (!root || root.parentNode !== template.content || template.content.children.length !== 1
78
+ || [...template.content.childNodes].some(node => node.nodeType === 3 && !!node.textContent?.trim())) {
79
+ fail('single-host 定义必须恰好有一个元素根');
80
+ }
81
+ if (plan?.internalRootId && plan.internalRootId !== rootId) fail('内部根别名与计划不符');
82
+ for (const attr of [...root.attributes]) {
83
+ if (attr.name === 'data-soma-id' || attr.name === 'class') continue;
84
+ if (attr.name === 'id' || attr.name.startsWith('data-soma-') || attr.name.startsWith('on')) fail('模板根不能覆盖外部身份属性');
85
+ if (host.hasAttribute(attr.name) && host.getAttribute(attr.name) !== attr.value) fail('模板根与外部宿主属性冲突');
86
+ }
87
+ result.rootAlias = rootId;
88
+ }
89
+ result.root = root;
90
+ return result;
91
+ }
92
+
93
+ export function commitStructureTemplate(host: HTMLElement, prepared: PreparedStructureTemplate): void {
94
+ if (!prepared.merge) {
95
+ host.replaceChildren(prepared.fragment);
96
+ return;
97
+ }
98
+ const root = prepared.root!;
99
+ for (const attr of [...root.attributes]) {
100
+ if (attr.name === 'data-soma-id') continue;
101
+ if (attr.name === 'class') {
102
+ for (const name of [...root.classList]) host.classList.add(name);
103
+ } else host.setAttribute(attr.name, attr.value);
104
+ }
105
+ host.replaceChildren(...Array.from(root.childNodes));
106
+ }
107
+
108
+ export function registerPreparedStructure(host: HTMLElement, definition: SomaComponentDefinition, scopeId: string, staticProps: Record<string, unknown>): void {
109
+ preparedHosts.set(host, { definition, scopeId, staticProps });
110
+ }
111
+
112
+ export function assertPreparedStructureProps(host: HTMLElement, props: Record<string, unknown>): void {
113
+ const prepared = preparedHosts.get(host);
114
+ const staticProps = prepared?.staticProps;
115
+ for (const [name, value] of Object.entries(staticProps ?? {})) {
116
+ if (props[name] !== value) fail('组件更新不能改变已冻结的结构语义属性');
117
+ }
118
+ if (prepared) {
119
+ assertStructureLabel(prepared.definition, props);
120
+ assertResolvedPrimitiveProps(prepared.definition, props);
121
+ }
122
+ }
123
+
124
+ /** The new closed primitive protocol only; legacy component validation is unchanged. */
125
+ function assertResolvedPrimitiveProps(definition: SomaComponentDefinition, props: Record<string, unknown>): void {
126
+ const contract = definition.contract;
127
+ if (contract.structure?.tree_mount !== 'single-host'
128
+ || !['Box', 'Region', 'Heading', 'Text', 'List'].includes(contract.name)) return;
129
+ const fields = contract.props ?? {};
130
+ for (const [name, value] of Object.entries(props)) {
131
+ const field = fields[name];
132
+ if (!field || (field.type === 'enum' ? !field.values?.some(option => option === value)
133
+ : field.type === 'array' ? !Array.isArray(value)
134
+ : field.type === 'object' ? value === null || typeof value !== 'object' || Array.isArray(value)
135
+ : typeof value !== field.type || (typeof value === 'number' && !Number.isFinite(value)))) {
136
+ fail('结构原语属性不符合契约类型或值域;拒绝本次挂载或属性更新');
137
+ }
138
+ }
139
+ for (const [name, field] of Object.entries(fields)) {
140
+ if (field.required && !Object.hasOwn(props, name)) fail('结构原语缺少必填属性');
141
+ }
142
+ if (contract.name === 'Box' && props.display === 'block' && props.gap !== 'none') {
143
+ fail('Box block 布局只允许 gap=none;拒绝本次挂载或属性更新');
144
+ }
145
+ if (contract.name === 'Text' && ((props.truncate === true && (props.wrap !== 'none' || props.line_clamp !== 0))
146
+ || (props.line_clamp !== 0 && (props.truncate === true || props.wrap === 'none')))) {
147
+ fail('Text truncate/wrap/line_clamp 组合互斥;拒绝本次挂载或属性更新');
148
+ }
149
+ }
150
+
151
+ function assertStructureLabel(definition: SomaComponentDefinition, props: Record<string, unknown>): void {
152
+ const semantics = definition.contract.structure?.semantics;
153
+ const token = semantics?.staticProp ? props[semantics.staticProp] : semantics?.default;
154
+ if (['nav', 'navigation', 'region'].includes(String(token))
155
+ && (typeof props.label !== 'string' || !props.label.trim())) fail('命名导航或区域必须保持非空 label;拒绝本次挂载或属性更新');
156
+ }
157
+
158
+ export function withPreparedStructureProps(host: HTMLElement, props: Record<string, unknown>, declared: Record<string, unknown>): Record<string, unknown> {
159
+ const result = { ...props };
160
+ for (const [name, value] of Object.entries(preparedHosts.get(host)?.staticProps ?? {})) {
161
+ if (!Object.prototype.hasOwnProperty.call(declared, name)) result[name] = value;
162
+ }
163
+ return result;
164
+ }
165
+
166
+ export function resolveCollectionOutlet(host: HTMLElement, plan: RepeatPlan): HTMLElement {
167
+ const prepared = preparedHosts.get(host);
168
+ if (!prepared || prepared.definition.contract.name !== plan.consumerOwner.componentName) fail('集合缺少已准备的消费组件');
169
+ const slot = prepared.definition.contract.structure?.slots?.[plan.consumerOwner.slotName];
170
+ if (slot?.kind !== 'collection' || slot.layoutRoot !== plan.consumerOwner.layoutRootKey
171
+ || slot.rowContainer !== plan.consumerOwner.rowContainer) fail('集合计划与消费组件出口契约不符');
172
+ const anchor = prepared.definition.structureAdapter?.layoutRoots[plan.consumerOwner.layoutRootKey];
173
+ if (!anchor) fail('集合出口缺少受信内部根映射');
174
+ const adapter = new SomaScopedContainerAdapter(prepared.scopeId);
175
+ const root = adapter.findAnchor(host, anchor);
176
+ if (!root) fail('集合出口内部根不存在');
177
+ return root;
178
+ }
179
+
180
+ export function publishCollectionState(host: HTMLElement, root: HTMLElement, phase: 'pending' | 'ready' | 'error', count: number, generation: number): void {
181
+ const prepared = preparedHosts.get(host);
182
+ if (!prepared) return;
183
+ root.setAttribute('aria-busy', String(phase === 'pending'));
184
+ root.setAttribute('data-soma-collection-phase', phase);
185
+ root.setAttribute('data-soma-collection-generation', String(generation));
186
+ const emptyAnchor = prepared.definition.structureAdapter?.layoutRoots.empty;
187
+ if (emptyAnchor) {
188
+ const empty = new SomaScopedContainerAdapter(prepared.scopeId).findAnchor(host, emptyAnchor);
189
+ if (empty) empty.hidden = phase !== 'ready' || count !== 0;
190
+ }
191
+ }
192
+
193
+ function hasRootVisibility(show: unknown, rootId: string): boolean {
194
+ if (!show || typeof show !== 'object') return false;
195
+ for (const [key, value] of Object.entries(show)) {
196
+ if (key === `${rootId}@hidden` || key === `${rootId}@style`) return true;
197
+ if (!value || typeof value !== 'object') continue;
198
+ const config = value as Record<string, unknown>;
199
+ if (key === rootId && config.when !== undefined) return true;
200
+ if (config.show && hasRootVisibility(config.show, rootId)) return true;
201
+ }
202
+ return false;
203
+ }
204
+
205
+ function fail(fixHint: string): never {
206
+ throw new SomaComponentTreeError({ code: 'CT-STRUCTURE-MOUNT', phase: 'runtime', sourceId: 'runtime', nodePath: 'component', fixHint });
207
+ }
@@ -19,6 +19,7 @@ import {
19
19
  type SomaContractField,
20
20
  } from '../../shared/types/component-contract.types';
21
21
  import { deriveContractSample, hasRenderableSample } from '../../shared/component/derive-sample';
22
+ import { copyCatalogExamples } from './catalog-examples';
22
23
 
23
24
  const LAYERS = new Set(['atom', 'composite', 'solution', 'template', 'page', 'token']);
24
25
 
@@ -154,10 +155,26 @@ function verifyDefinition(key: string, definition: SomaComponentDefinition): str
154
155
  if (ai.example === undefined || (typeof ai.example === 'string' && !ai.example.trim())) {
155
156
  issues.push(`[目录] ${label} 的 ai.example 为空——给一段能直接用的四件套片段`);
156
157
  }
158
+ if (ai.examples !== undefined) {
159
+ try { copyCatalogExamples(ai.examples as Parameters<typeof copyCatalogExamples>[0]); }
160
+ catch { issues.push(`[目录] ${label} 的 ai.examples 格式/语法版本/统一声明非法`); }
161
+ }
157
162
  }
158
163
 
159
164
  const template = definition.templateHtml;
160
- if (typeof template !== 'string' || !template.trim()) {
165
+ const macro = definition.contract.structure?.kind === 'fragment-macro';
166
+ if (macro) {
167
+ const structure = definition.contract.structure!;
168
+ const slots = definition.contract.slots;
169
+ const executableFields = ['controllerFactory', 'uiConfig', 'eventConfig', 'services', 'styleFeatures'] as const;
170
+ const runtimeContractFields = ['props', 'emits', 'tokens', 'keyboard', 'overlay'] as const;
171
+ if (template !== '' || !structure.rootless || structure.tree_mount !== 'erase'
172
+ || structure.semantics !== undefined || slots?.content?.required !== true || Object.keys(slots ?? {}).length !== 1
173
+ || executableFields.some((field) => definition[field] !== undefined)
174
+ || runtimeContractFields.some((field) => definition.contract[field] !== undefined)) {
175
+ issues.push(`[结构] ${label} 的 fragment-macro 必须是空模板、必填content与纯编译元数据,不得带运行时能力`);
176
+ }
177
+ } else if (typeof template !== 'string' || !template.trim()) {
161
178
  issues.push(`[模板] ${label} 的 templateHtml 为空`);
162
179
  } else {
163
180
  if (/data-soma-scoped-id=/.test(template)) {
@@ -291,6 +308,9 @@ function verifyStyleRegistration(pack: SomaComponentPack): string[] {
291
308
  const sharedNames = new Set(Object.keys(styles.shared ?? {}));
292
309
 
293
310
  for (const name of Object.keys(styles.components ?? {})) {
311
+ if (pack.components[name]?.contract.structure?.kind === 'fragment-macro') {
312
+ issues.push(`[结构] 编译宏 ${name} 不得登记运行时 CSS`);
313
+ }
294
314
  if (!componentNames.has(name)) {
295
315
  issues.push(
296
316
  `[样式] 为 "${name}" 登记了组件样式,但包里没有这个组件——`
@@ -67,7 +67,7 @@ export class SomaAssetResolver {
67
67
  };
68
68
  }
69
69
 
70
- const cacheKey = `${uiYaml}\0${eventYaml}\0${localeYaml}\0${assets.appConfigYaml ?? ''}\0${assets.styleYaml ?? ''}`;
70
+ const cacheKey = `${uiYaml}\0${eventYaml}\0${localeYaml}\0${assets.appConfigYaml ?? ''}\0${assets.styleYaml ?? ''}\0${assets.dataYaml ?? ''}\0${assets.sourceMarkup ?? 'legacy-html'}\0${assets.artifact?.artifactDigest ?? ''}`;
71
71
  const cached = this.cache.get(cacheKey);
72
72
  if (cached) {
73
73
  return cached;
@@ -17,6 +17,32 @@ import {
17
17
  type SomaPipeRegistry,
18
18
  } from '../pipes/pipe-registry';
19
19
  import type { SomaPipeCall } from '../../shared/types/scope-manifest.types';
20
+ import { SomaRowRange } from './row-range';
21
+ import { SomaRowScope, validateRowKeys, type SomaTypedRowKey } from './row-scope';
22
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
23
+ import type { RepeatPlan } from '../../shared/types/component-tree-artifact.types';
24
+ import { resolveCollectionOutlet, publishCollectionState } from '../component/structure-adapter';
25
+
26
+ interface ExplicitListState {
27
+ element: HTMLElement;
28
+ end: Comment;
29
+ rows: Map<SomaTypedRowKey, SomaRowRange>;
30
+ generation: number;
31
+ }
32
+
33
+ // Component-owned renderers and the page renderer share a physical-page budget.
34
+ // Weak roots/scopes never expose business identities or retain unmounted pages.
35
+ const pageRowBudgets = new WeakMap<HTMLElement, Map<SomaRowScope, HTMLElement>>();
36
+ const rowBudgetMembership = new WeakMap<SomaRowScope, Map<SomaRowScope, HTMLElement>>();
37
+
38
+ function pageRowBudget(element: HTMLElement): Map<SomaRowScope, HTMLElement> {
39
+ let root = element;
40
+ while (root.parentElement && root.parentElement !== root.ownerDocument.body
41
+ && root.parentElement !== root.ownerDocument.documentElement) root = root.parentElement;
42
+ let budget = pageRowBudgets.get(root);
43
+ if (!budget) { budget = new Map(); pageRowBudgets.set(root, budget); }
44
+ return budget;
45
+ }
20
46
 
21
47
  export type ModelWriteBack = (path: string, value: string) => void;
22
48
 
@@ -54,6 +80,16 @@ export class SomaDomRenderer {
54
80
  private componentHook: SomaRowComponentHook | null = null;
55
81
  private componentReleaseHook: SomaRowComponentReleaseHook | null = null;
56
82
  private pipeRegistry: SomaPipeRegistry = defaultPipeRegistry;
83
+ private explicitLists = new Map<HTMLElement, ExplicitListState>();
84
+ private repeatPlans = new Map<string, RepeatPlan>();
85
+
86
+ setRepeatPlans(plans: readonly RepeatPlan[]): void {
87
+ this.repeatPlans.clear();
88
+ for (const plan of plans) {
89
+ if (this.repeatPlans.has(plan.planId)) this.repeatArtifactError('集合计划 id 重复');
90
+ this.repeatPlans.set(plan.planId, plan);
91
+ }
92
+ }
57
93
 
58
94
  setComponentHook(hook: SomaRowComponentHook | null): void {
59
95
  this.componentHook = hook;
@@ -197,11 +233,15 @@ export class SomaDomRenderer {
197
233
  : undefined,
198
234
  childShowConfig: binding.childShowConfig,
199
235
  roleBy: binding.roleBy,
236
+ keyPath: binding.keyPath,
237
+ itemAlias: binding.itemAlias,
238
+ repeatPlanId: binding.repeatPlanId,
200
239
  attrName: binding.attrName,
201
240
  negate: binding.negate,
202
241
  classRules: binding.classRules,
203
242
  pipes: binding.pipes,
204
243
  };
244
+ if (binding.repeatPlanId) this.attachRepeatPlan(entry, binding.repeatPlanId);
205
245
 
206
246
  // 编译渲染函数:消除运行时 switch + 类型判断
207
247
  entry.compiledRender = this.compileRenderFn(entry);
@@ -301,6 +341,11 @@ export class SomaDomRenderer {
301
341
 
302
342
  case 'list':
303
343
  return (v) => {
344
+ if (entry.keyPath) {
345
+ if (!this.collectionReady(entry)) return;
346
+ this.renderExplicitList(entry, v);
347
+ return;
348
+ }
304
349
  if (Array.isArray(v)) this.renderList(entry, v);
305
350
  };
306
351
 
@@ -315,6 +360,7 @@ export class SomaDomRenderer {
315
360
  }
316
361
 
317
362
  destroy(): void {
363
+ for (const state of [...this.explicitLists.values()]) this.disposeExplicitList(state);
318
364
  this.modelAbort.abort();
319
365
  this.modelAbort = new AbortController();
320
366
  this.modelListeners = new WeakSet<HTMLElement>();
@@ -442,6 +488,216 @@ export class SomaDomRenderer {
442
488
  }
443
489
  }
444
490
 
491
+ /** All explicit-key sources share this range reconciler; legacy guessing stays separate. */
492
+ private renderExplicitList(entry: BindingEntry, value: unknown, parentScope?: SomaRowScope): void {
493
+ const alias = entry.itemAlias!;
494
+ const keys = validateRowKeys(value, entry.keyPath!, alias, entry.repeatPlan?.limits);
495
+ const rows = value as unknown[];
496
+ const depth = this.rowDepth(parentScope) + 1;
497
+ if (depth > (entry.repeatPlan?.limits.maxDepth ?? 4)) this.repeatLimit('集合嵌套超过受信深度预算');
498
+ const nextSubtreeSize = this.validateNestedRows(rows, keys, alias, entry.childShowConfig, parentScope, depth, entry.repeatPlan?.limits);
499
+ if (!entry.templateCache) throw new SomaComponentTreeError({
500
+ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat',
501
+ fixHint: '显式键集合缺少完整行模板',
502
+ });
503
+ let state = this.explicitLists.get(entry.element);
504
+ const budget = pageRowBudget(entry.element);
505
+ const replacedRoots = [...(state?.rows.values() ?? [])].flatMap(range => [...range.roots]);
506
+ const replacedScopes = new Set([...(state?.rows.values() ?? [])].map(range => range.scope));
507
+ let replaced = 0;
508
+ for (const [scope, owner] of budget) {
509
+ if (replacedScopes.has(scope) || replacedRoots.some(root => root === owner || root.contains(owner))) replaced++;
510
+ }
511
+ if (budget.size - replaced + nextSubtreeSize > (entry.repeatPlan?.limits.maxPageRows ?? 5000)) this.repeatLimit('页面活跃行数超过受信预算');
512
+ const next = new Map<SomaTypedRowKey, SomaRowRange>();
513
+ const preparedRanges = new Set<SomaRowRange>();
514
+ for (let index = 0; index < rows.length; index++) {
515
+ const key = keys[index];
516
+ const picked = this.pickRowTemplate(entry, rows[index]);
517
+ const existing = state?.rows.get(key);
518
+ if (existing && existing.variant === picked.variant) {
519
+ next.set(key, existing);
520
+ } else {
521
+ if (!picked.template) throw new SomaComponentTreeError({
522
+ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat',
523
+ fixHint: '集合行类型没有可用模板',
524
+ });
525
+ const fragment = picked.template.cloneNode(true) as DocumentFragment;
526
+ if (entry.repeatPlan?.consumerOwner.rowContainer === 'list-item') {
527
+ const row = entry.element.ownerDocument.createElement('li');
528
+ row.append(...Array.from(fragment.childNodes));
529
+ fragment.append(row);
530
+ }
531
+ const scope = new SomaRowScope(alias, key, rows[index], parentScope);
532
+ const range = new SomaRowRange(fragment, scope, picked.variant);
533
+ next.set(key, range);
534
+ preparedRanges.add(range);
535
+ }
536
+ }
537
+ if (!state) {
538
+ const end = entry.element.ownerDocument.createComment('/soma-repeat');
539
+ entry.element.appendChild(end);
540
+ state = { element: entry.element, end, rows: new Map(), generation: 0 };
541
+ this.explicitLists.set(entry.element, state);
542
+ }
543
+ // No DOM mutation happened before all keys, templates and row budgets passed.
544
+ let before: Node = state.end;
545
+ for (const range of [...next.values()].reverse()) {
546
+ range.moveBefore(entry.element, before);
547
+ before = range.start;
548
+ }
549
+ for (const [key, range] of state.rows) {
550
+ if (next.get(key) !== range) this.releaseExplicitRange(range);
551
+ }
552
+ state.rows = next;
553
+ state.generation++;
554
+ let applying: SomaRowRange | undefined;
555
+ try { rows.forEach((data, index) => {
556
+ const range = next.get(keys[index])!;
557
+ applying = range;
558
+ budget.set(range.scope, entry.element);
559
+ rowBudgetMembership.set(range.scope, budget);
560
+ range.scope.update(data);
561
+ for (const root of range.roots) {
562
+ this.scopeTracker?.set(root, range.scope);
563
+ if (range.variant) root.setAttribute('data-soma-variant', range.variant);
564
+ if (entry.childShowConfig) this.applyShowConfig(root, range.scope, entry.childShowConfig);
565
+ this.activateDefaultRowComponents(root, range.scope, entry.childShowConfig);
566
+ }
567
+ }); } catch (error) {
568
+ // A controller may fail after DOM commit. Release every uncommitted/new
569
+ // row and the affected reused row through the same lifecycle hooks.
570
+ if (applying) preparedRanges.add(applying);
571
+ for (const [key, range] of next) {
572
+ if (!preparedRanges.has(range)) continue;
573
+ this.releaseExplicitRange(range);
574
+ next.delete(key);
575
+ }
576
+ if (entry.collectionOwner) publishCollectionState(entry.collectionOwner, entry.element, 'error', next.size, state.generation);
577
+ throw error;
578
+ }
579
+ if (entry.collectionOwner) publishCollectionState(entry.collectionOwner, entry.element, 'ready', next.size, state.generation);
580
+ }
581
+
582
+ private attachRepeatPlan(entry: BindingEntry, planId: string): void {
583
+ const plan = this.repeatPlans.get(planId);
584
+ if (!plan) this.repeatArtifactError('集合绑定引用未知计划');
585
+ if (entry.itemAlias !== plan.itemAlias
586
+ || this.resolver?.resolvePath(plan.sourcePath) !== this.resolver?.resolvePath(entry.dataPath)) {
587
+ this.repeatArtifactError('集合绑定与计划的数据源或行变量不一致');
588
+ }
589
+ const host = entry.element;
590
+ const symbol = host.getAttribute('data-soma-id') ?? host.getAttribute('data-soma-scoped-id');
591
+ if (symbol !== plan.consumerOwner.instanceSymbol) this.repeatArtifactError('集合消费宿主与计划符号不一致');
592
+ const outlet = resolveCollectionOutlet(host, plan);
593
+ const templates = [...outlet.querySelectorAll<HTMLTemplateElement>('template[data-soma-role="item"]')]
594
+ .filter(template => template.getAttribute('data-soma-repeat-template') === plan.rowTemplateId);
595
+ if (templates.length !== 1) this.repeatArtifactError('集合计划没有唯一的完整行模板');
596
+ entry.collectionOwner = host;
597
+ entry.element = outlet;
598
+ entry.templateCache = templates[0].content;
599
+ entry.templatesByRole = undefined;
600
+ entry.repeatPlan = plan;
601
+ entry.keyPath = plan.keyPath;
602
+ entry.type = 'list';
603
+ if (plan.statusPlan.kind === 'async') {
604
+ entry.watchPaths = [...new Set([...(entry.watchPaths ?? []), this.resolver!.resolvePath(plan.statusPlan.statePath)])];
605
+ }
606
+ }
607
+
608
+ private collectionReady(entry: BindingEntry, scope?: SomaRowScope): boolean {
609
+ const plan = entry.repeatPlan;
610
+ if (!plan || plan.statusPlan.kind === 'sync') return true;
611
+ const phase = scope ? this.resolveShowValue(plan.statusPlan.statePath, scope)
612
+ : this.resolver?.readFromRoot(this.resolver.resolvePath(plan.statusPlan.statePath));
613
+ if (!['pending', 'ready', 'error'].includes(phase)) this.repeatArtifactError('异步集合状态必须是 pending/ready/error');
614
+ if (phase === 'ready') return true;
615
+ const state = this.explicitLists.get(entry.element);
616
+ if (entry.collectionOwner) publishCollectionState(entry.collectionOwner, entry.element, phase, state?.rows.size ?? 0, state?.generation ?? 0);
617
+ return false;
618
+ }
619
+
620
+ private repeatArtifactError(fixHint: string): never {
621
+ throw new SomaComponentTreeError({ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat', fixHint });
622
+ }
623
+
624
+ private activateDefaultRowComponents(root: HTMLElement, scope: SomaRowScope, show?: ShowMapping): void {
625
+ if (!this.componentHook || !this.adapter) return;
626
+ const hosts = [root, ...Array.from(root.querySelectorAll<HTMLElement>('[data-soma-component]'))];
627
+ for (const host of hosts) {
628
+ if (!host.hasAttribute('data-soma-component')) continue;
629
+ let foreignRow = false;
630
+ for (let current: HTMLElement | null = host; current; current = current.parentElement) {
631
+ const owner = this.scopeTracker?.get(current);
632
+ if (owner instanceof SomaRowScope) { foreignRow = owner !== scope; break; }
633
+ if (current === root) break;
634
+ }
635
+ if (foreignRow) continue;
636
+ const id = this.adapter.getAnchorId(host);
637
+ if (!id) continue;
638
+ const config = show?.[id];
639
+ if (config && typeof config === 'object' && config.props) continue;
640
+ this.componentHook(host, {}, scope);
641
+ }
642
+ }
643
+
644
+ private validateNestedRows(
645
+ rows: unknown[], keys: SomaTypedRowKey[], alias: string, show: ShowMapping | undefined,
646
+ parent: SomaRowScope | undefined, depth: number, limits?: RepeatPlan['limits'],
647
+ ): number {
648
+ let count = rows.length;
649
+ const visit = (mapping: ShowMapping, scope: SomaRowScope): void => {
650
+ for (const config of Object.values(mapping)) {
651
+ if (!config || typeof config !== 'object') continue;
652
+ if (this.isNestedShowMapping(config) && (config.bind.key || config.bind.repeatPlanId)) {
653
+ const plan = config.bind.repeatPlanId ? this.repeatPlans.get(config.bind.repeatPlanId) : undefined;
654
+ if (config.bind.repeatPlanId && !plan) this.repeatArtifactError('嵌套集合引用未知计划');
655
+ if (plan?.statusPlan.kind === 'async') {
656
+ const phase = this.resolveShowValue(plan.statusPlan.statePath, scope);
657
+ if (!['pending', 'ready', 'error'].includes(phase)) this.repeatArtifactError('异步集合状态无效');
658
+ if (phase !== 'ready') continue;
659
+ }
660
+ if (depth >= (plan?.limits.maxDepth ?? limits?.maxDepth ?? 4)) this.repeatLimit('集合嵌套超过受信深度预算');
661
+ const values = this.resolveShowValue(config.bind.obj, scope);
662
+ const childKeys = validateRowKeys(values, plan?.keyPath ?? config.bind.key!, config.bind.var, plan?.limits);
663
+ count += this.validateNestedRows(values, childKeys, config.bind.var, config.show, scope, depth + 1, plan?.limits ?? limits);
664
+ } else if (!this.isNestedShowMapping(config) && config.show) visit(config.show, scope);
665
+ }
666
+ };
667
+ if (show) rows.forEach((row, index) => visit(show, new SomaRowScope(alias, keys[index], row, parent)));
668
+ if (count > (limits?.maxPageRows ?? 5000)) this.repeatLimit('页面活跃行数超过受信预算');
669
+ return count;
670
+ }
671
+
672
+ private rowDepth(scope?: SomaRowScope): number {
673
+ let depth = 0;
674
+ for (let current = scope; current; current = current.parent) depth++;
675
+ return depth;
676
+ }
677
+
678
+ private repeatLimit(fixHint: string): never {
679
+ throw new SomaComponentTreeError({ code: 'CT-LIMIT', phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat', fixHint });
680
+ }
681
+
682
+ private releaseExplicitRange(range: SomaRowRange): void {
683
+ rowBudgetMembership.get(range.scope)?.delete(range.scope);
684
+ rowBudgetMembership.delete(range.scope);
685
+ range.release(root => {
686
+ for (const state of [...this.explicitLists.values()]) {
687
+ if (root === state.element || root.contains(state.element)) this.disposeExplicitList(state);
688
+ }
689
+ this.componentReleaseHook?.(root);
690
+ this.scopeTracker?.delete(root);
691
+ });
692
+ }
693
+
694
+ private disposeExplicitList(state: ExplicitListState): void {
695
+ if (!this.explicitLists.delete(state.element)) return;
696
+ for (const range of state.rows.values()) this.releaseExplicitRange(range);
697
+ state.rows.clear();
698
+ state.end.remove();
699
+ }
700
+
445
701
  private appendListItem(entry: BindingEntry, itemData: any): void {
446
702
  if (!this.adapter) return;
447
703
  const { template, variant } = this.pickRowTemplate(entry, itemData);
@@ -542,6 +798,7 @@ export class SomaDomRenderer {
542
798
  if (!element) {
543
799
  return;
544
800
  }
801
+ if (this.componentHook && element.hasAttribute('data-soma-component')) this.componentHook(element, config.props ?? {}, data);
545
802
  // 行内嵌套列表的整块显隐(与行内 when 走同一套解析与可见性写入)
546
803
  if (typeof config.when === 'string') {
547
804
  const { path, negate } = this.parseConditionalPath(config.when);
@@ -554,6 +811,20 @@ export class SomaDomRenderer {
554
811
  const nestedData = this.resolveShowValue(config.bind.obj, data);
555
812
  const role = this.adapter.readRole(element);
556
813
  const templateCache = this.adapter.cloneTemplate(element);
814
+ if (config.bind.repeatPlanId) {
815
+ // RuntimeBuilder performs the first page render before Manager.activate
816
+ // installs row hooks. Nested consumer templates become available on the
817
+ // activation render; never infer their outlet from the authored source.
818
+ if (!this.componentHook && !element.hasAttribute('data-soma-component-ready')) return;
819
+ const entry: BindingEntry = {
820
+ element, type: 'list', dataPath: config.bind.obj,
821
+ itemAlias: config.bind.var, childShowConfig: config.show,
822
+ };
823
+ this.attachRepeatPlan(entry, config.bind.repeatPlanId);
824
+ const parentScope = data instanceof SomaRowScope ? data : undefined;
825
+ if (this.collectionReady(entry, parentScope)) this.renderExplicitList(entry, nestedData, parentScope);
826
+ return;
827
+ }
557
828
  if (!templateCache) {
558
829
  return;
559
830
  }
@@ -561,6 +832,15 @@ export class SomaDomRenderer {
561
832
  const templatesByRole = this.collectRoleTemplates(element);
562
833
  const roleBy = config.bind.role_by;
563
834
 
835
+ if (config.bind.key) {
836
+ this.renderExplicitList({
837
+ element, type: 'list', dataPath: config.bind.obj, templateCache,
838
+ templatesByRole, roleBy, childShowConfig: config.show,
839
+ keyPath: config.bind.key, itemAlias: config.bind.var,
840
+ }, nestedData, data instanceof SomaRowScope ? data : undefined);
841
+ return;
842
+ }
843
+
564
844
  // 行内嵌套列表**每次行重渲都整体重建**,是比顶层列表更快的泄漏路径
565
845
  this.clearRendered(element);
566
846
 
@@ -693,6 +973,9 @@ export class SomaDomRenderer {
693
973
  }
694
974
 
695
975
  private resolveShowValue(valuePath: string, itemData: any): any {
976
+ if (itemData instanceof SomaRowScope) {
977
+ return itemData.read(valuePath, path => this.resolver?.readFromRoot(this.resolver.resolvePath(path)));
978
+ }
696
979
  const segments = valuePath.split('.');
697
980
  const firstSeg = segments[0];
698
981