soma-core 1.5.1 → 2.0.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 (173) 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 +212 -21
  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/eject/component-eject.ts +1 -0
  25. package/core/build/lsp/component-tree-service.ts +79 -0
  26. package/core/build/lsp/component-tree.cjs +42 -0
  27. package/core/build/lsp/cross-file-diagnostics.cjs +15 -3
  28. package/core/build/lsp/extra-completion.cjs +7 -0
  29. package/core/client/adaptive/observer-pool.ts +122 -8
  30. package/core/client/compiler/manifest-compiler.ts +48 -5
  31. package/core/client/component/ai-catalog.ts +41 -3
  32. package/core/client/component/catalog-examples.ts +60 -0
  33. package/core/client/component/component-defaults.ts +1 -1
  34. package/core/client/component/component-definition.types.ts +9 -0
  35. package/core/client/component/component-expander.ts +22 -6
  36. package/core/client/component/component-manager.ts +881 -45
  37. package/core/client/component/component-pack.ts +1 -1
  38. package/core/client/component/component-registry.ts +11 -2
  39. package/core/client/component/scoped-adapter.ts +29 -2
  40. package/core/client/component/structure-adapter.ts +207 -0
  41. package/core/client/component/verify-pack.ts +21 -1
  42. package/core/client/container/SomaContainerAdapter.ts +103 -2
  43. package/core/client/data/data-object-resolver.ts +45 -1
  44. package/core/client/engine/asset-resolver.ts +1 -1
  45. package/core/client/engine/dom-renderer.ts +712 -26
  46. package/core/client/engine/event-engine.ts +328 -21
  47. package/core/client/engine/property-watcher.ts +164 -18
  48. package/core/client/engine/reactive-proxy.ts +194 -23
  49. package/core/client/engine/render-engine.ts +120 -11
  50. package/core/client/engine/row-range.ts +62 -0
  51. package/core/client/engine/row-scope.ts +77 -0
  52. package/core/client/engine/runtime-builder.ts +2 -0
  53. package/core/client/engine/scope-resolver.ts +3 -3
  54. package/core/client/engine/soma-bootstrap.ts +176 -17
  55. package/core/client/parser/adaptive-parser.ts +1 -1
  56. package/core/client/parser/annotation-extractor.ts +1 -1
  57. package/core/client/parser/blocks/page-parser.ts +53 -3
  58. package/core/client/parser/blocks/use-parser.ts +21 -6
  59. package/core/client/parser/data-config-parser.ts +1 -1
  60. package/core/client/parser/pipeline-parser.ts +252 -15
  61. package/core/client/parser/style-config-parser.ts +1 -1
  62. package/core/client/parser/timer-parser.ts +1 -1
  63. package/core/client/parser/trigger-parser.ts +1 -1
  64. package/core/client/parser/ui-config-parser.ts +39 -7
  65. package/core/client/pipes/pipe-registry.ts +45 -4
  66. package/core/client/registry/declaration-renderer.ts +32 -24
  67. package/core/client/registry/remote-page.ts +1 -1
  68. package/core/client/runtime/SomaSnapshotStore.ts +1 -1
  69. package/core/client/scheduler/SomaScheduler.ts +1 -1
  70. package/core/client/security/attribute-presence.ts +3 -0
  71. package/core/client/theme/harmony.ts +135 -13
  72. package/core/client/theme/scene-tokens.ts +17 -2
  73. package/core/client/theme/theme-axes.ts +43 -6
  74. package/core/client/theme/theme-engine.ts +921 -126
  75. package/core/client/validation/contract-validator.ts +2 -2
  76. package/core/index.ts +3 -0
  77. package/core/server/host/page-markup-config.ts +42 -0
  78. package/core/server/host/published-page-artifact-cache.ts +36 -4
  79. package/core/server/host/published-page-assets.ts +13 -7
  80. package/core/server/host/resolve-host-tree-context.ts +43 -0
  81. package/core/server/host/server-page-assets.ts +23 -4
  82. package/core/server/host/soma-page-compile.ts +10 -0
  83. package/core/server/mock/node/cli.mjs +3 -3
  84. package/core/server/page-declaration.ts +7 -0
  85. package/core/server/registry/declaration-precompiler.ts +35 -3
  86. package/core/server/registry/page-registry-repository.ts +31 -3
  87. package/core/server/registry/page-registry-store.ts +64 -7
  88. package/core/server/registry/publish-asset-pin.ts +6 -1
  89. package/core/server/registry/services/pages/Get.ts +11 -6
  90. package/core/server/registry/validation/compile-gate.ts +10 -1
  91. package/core/shared/component-tree-artifact.ts +237 -0
  92. package/core/shared/component-tree-errors.ts +52 -0
  93. package/core/shared/path-algebra.ts +1 -1
  94. package/core/shared/types/component-contract.types.ts +51 -0
  95. package/core/shared/types/component-tree-artifact.types.ts +121 -0
  96. package/core/shared/types/component-tree.types.ts +170 -0
  97. package/core/shared/types/engine.types.ts +5 -0
  98. package/core/shared/types/event.types.ts +8 -4
  99. package/core/shared/types/manifest.types.ts +4 -0
  100. package/core/shared/types/ui-config.types.ts +8 -0
  101. package/dist/cli/soma.js +1 -1
  102. package/dist/core/index.cjs +14508 -11358
  103. package/dist/lsp/component-tree.cjs +20997 -0
  104. package/dist/types/build/blocks/block-compile.d.ts +10 -1
  105. package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
  106. package/dist/types/build/compiler/page-assets.d.ts +6 -1
  107. package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
  108. package/dist/types/build/component/package-loader.d.ts +4 -1
  109. package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
  110. package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
  111. package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
  112. package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
  113. package/dist/types/build/component-tree/migration-files.d.ts +35 -0
  114. package/dist/types/build/component-tree/migration.d.ts +28 -0
  115. package/dist/types/build/component-tree/parser.d.ts +13 -0
  116. package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
  117. package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
  118. package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
  119. package/dist/types/build/component-tree/validator.d.ts +9 -0
  120. package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
  121. package/dist/types/client/adaptive/observer-pool.d.ts +9 -2
  122. package/dist/types/client/compiler/manifest-compiler.d.ts +11 -2
  123. package/dist/types/client/component/ai-catalog.d.ts +18 -1
  124. package/dist/types/client/component/catalog-examples.d.ts +18 -0
  125. package/dist/types/client/component/component-definition.types.d.ts +9 -0
  126. package/dist/types/client/component/component-expander.d.ts +2 -1
  127. package/dist/types/client/component/component-manager.d.ts +97 -0
  128. package/dist/types/client/component/scoped-adapter.d.ts +1 -0
  129. package/dist/types/client/component/structure-adapter.d.ts +17 -0
  130. package/dist/types/client/container/SomaContainerAdapter.d.ts +8 -0
  131. package/dist/types/client/data/data-object-resolver.d.ts +19 -0
  132. package/dist/types/client/engine/dom-renderer.d.ts +125 -2
  133. package/dist/types/client/engine/event-engine.d.ts +62 -3
  134. package/dist/types/client/engine/property-watcher.d.ts +41 -1
  135. package/dist/types/client/engine/reactive-proxy.d.ts +42 -2
  136. package/dist/types/client/engine/render-engine.d.ts +55 -3
  137. package/dist/types/client/engine/row-range.d.ts +13 -0
  138. package/dist/types/client/engine/row-scope.d.ts +20 -0
  139. package/dist/types/client/engine/runtime-builder.d.ts +1 -0
  140. package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
  141. package/dist/types/client/parser/blocks/use-parser.d.ts +18 -0
  142. package/dist/types/client/parser/pipeline-parser.d.ts +12 -4
  143. package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
  144. package/dist/types/client/pipes/pipe-registry.d.ts +39 -1
  145. package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
  146. package/dist/types/client/registry/remote-page.d.ts +1 -1
  147. package/dist/types/client/theme/harmony.d.ts +44 -2
  148. package/dist/types/client/theme/scene-tokens.d.ts +11 -1
  149. package/dist/types/client/theme/theme-axes.d.ts +36 -6
  150. package/dist/types/index.d.ts +3 -1
  151. package/dist/types/server/host/page-markup-config.d.ts +6 -0
  152. package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
  153. package/dist/types/server/host/published-page-assets.d.ts +5 -3
  154. package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
  155. package/dist/types/server/host/server-page-assets.d.ts +6 -0
  156. package/dist/types/server/host/soma-page-compile.d.ts +10 -1
  157. package/dist/types/server/page-declaration.d.ts +6 -0
  158. package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
  159. package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
  160. package/dist/types/server/registry/page-registry-store.d.ts +11 -1
  161. package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
  162. package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
  163. package/dist/types/shared/component-tree-artifact.d.ts +5 -0
  164. package/dist/types/shared/component-tree-errors.d.ts +22 -0
  165. package/dist/types/shared/types/component-contract.types.d.ts +42 -0
  166. package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
  167. package/dist/types/shared/types/component-tree.types.d.ts +149 -0
  168. package/dist/types/shared/types/engine.types.d.ts +5 -0
  169. package/dist/types/shared/types/event.types.d.ts +8 -4
  170. package/dist/types/shared/types/manifest.types.d.ts +4 -0
  171. package/dist/types/shared/types/ui-config.types.d.ts +8 -0
  172. package/package.json +5 -4
  173. package/dist/preview-export.cjs +0 -3401
@@ -75,7 +75,7 @@ export interface SomaComponentPack {
75
75
 
76
76
  export class ComponentPackError extends Error {
77
77
  constructor(message: string) {
78
- super(`[SomaComponentPack] ${message}`);
78
+ super(`[soma-core][组件] ${message}`);
79
79
  this.name = 'ComponentPackError';
80
80
  }
81
81
  }
@@ -7,7 +7,7 @@ import { findNestedMutableContractDefault } from '../../shared/types/component-c
7
7
 
8
8
  export class SomaComponentRegistryError extends Error {
9
9
  constructor(message: string) {
10
- super(`[SomaComponentRegistry] ${message}`);
10
+ super(`[soma-core][组件] ${message}`);
11
11
  this.name = 'SomaComponentRegistryError';
12
12
  }
13
13
  }
@@ -20,7 +20,16 @@ export class SomaComponentRegistry {
20
20
  if (!contract?.name) {
21
21
  throw new SomaComponentRegistryError('契约缺少 name');
22
22
  }
23
- if (!def.templateHtml) {
23
+ const macro = contract.structure?.kind === 'fragment-macro';
24
+ if (macro && (contract.structure?.tree_mount !== 'erase' || !contract.structure.rootless
25
+ || typeof def.templateHtml !== 'string' || def.templateHtml.trim() || def.controllerFactory || def.uiConfig || def.eventConfig?.length
26
+ || Object.keys(contract.props ?? {}).length || Object.keys(contract.emits ?? {}).length
27
+ || def.services?.length || def.definitionRepeatPlans?.length || Object.keys(def.styleFeatures ?? {}).length
28
+ || contract.keyboard || contract.overlay || contract.structure.semantics || contract.uses?.length
29
+ || !contract.slots?.content?.required || Object.keys(contract.slots).length !== 1)) {
30
+ throw new SomaComponentRegistryError(`组件 "${contract.name}" 的 fragment-macro 含运行时行为`);
31
+ }
32
+ if (!def.templateHtml && !macro) {
24
33
  throw new SomaComponentRegistryError(`组件 "${contract.name}" 缺少 templateHtml`);
25
34
  }
26
35
  if (contract.props && SOMA_COMPONENT_CTRL_KEY in contract.props) {
@@ -20,6 +20,21 @@ export const SOMA_SCOPED_ID_ATTR = 'data-soma-scoped-id';
20
20
  /** 锚点的作用域归属标记(展开器写入,值为该次展开的 scopeId) */
21
21
  export const SOMA_SCOPE_ATTR = 'data-soma-scope';
22
22
 
23
+ // A shared physical host keeps its parent/row DOM identity. Its own internal
24
+ // root is an instance-local alias, never a second set of DOM scope attributes.
25
+ const rootAliases = new WeakMap<HTMLElement, { scopeId: string; anchorId: string }>();
26
+
27
+ export function registerSomaRootAlias(host: HTMLElement, scopeId: string, anchorId: string): void {
28
+ rootAliases.set(host, { scopeId, anchorId });
29
+ }
30
+
31
+ /** Supports roots/events from a different window and server DOMs without global constructors. */
32
+ function isHtmlElement(value: unknown): value is HTMLElement {
33
+ const element = value as Element | null;
34
+ return element?.nodeType === 1 && element.namespaceURI === 'http://www.w3.org/1999/xhtml'
35
+ && typeof element.getAttribute === 'function';
36
+ }
37
+
23
38
  export class SomaScopedContainerAdapter extends SomaContainerAdapter {
24
39
  /** 本适配器认领的作用域;undefined = 认所有 scoped 锚点 */
25
40
  private readonly scopeId?: string;
@@ -45,17 +60,23 @@ export class SomaScopedContainerAdapter extends SomaContainerAdapter {
45
60
  }
46
61
 
47
62
  findAnchor(root: ParentNode, somaId: string): HTMLElement | null {
63
+ if (isHtmlElement(root) && this.getAnchorId(root) === somaId) return root;
48
64
  return root.querySelector<HTMLElement>(this.anchorSelector(somaId));
49
65
  }
50
66
 
51
67
  findClosestAnchor(target: EventTarget | null): HTMLElement | null {
52
- if (!(target instanceof HTMLElement)) {
68
+ if (!isHtmlElement(target)) {
53
69
  return null;
54
70
  }
55
- return target.closest<HTMLElement>(this.anyAnchorSelector);
71
+ for (let element: HTMLElement | null = target; element; element = element.parentElement) {
72
+ if (this.getAnchorId(element) !== null) return element;
73
+ }
74
+ return null;
56
75
  }
57
76
 
58
77
  getAnchorId(element: HTMLElement): string | null {
78
+ const alias = rootAliases.get(element);
79
+ if (alias && alias.scopeId === this.scopeId) return alias.anchorId;
59
80
  if (this.scopeId && element.getAttribute(SOMA_SCOPE_ATTR) !== this.scopeId) {
60
81
  return null;
61
82
  }
@@ -66,6 +87,12 @@ export class SomaScopedContainerAdapter extends SomaContainerAdapter {
66
87
  const anchors = new Set<string>();
67
88
  const counts = new Map<string, number>();
68
89
 
90
+ const rootId = this.getAnchorId(container);
91
+ if (rootId) {
92
+ anchors.add(rootId);
93
+ counts.set(rootId, 1);
94
+ }
95
+
69
96
  container.querySelectorAll<HTMLElement>(this.anyAnchorSelector).forEach((element) => {
70
97
  const somaId = element.getAttribute(SOMA_SCOPED_ID_ATTR);
71
98
  if (!somaId) return;
@@ -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}" 登记了组件样式,但包里没有这个组件——`
@@ -104,12 +104,19 @@ export class SomaContainerAdapter implements IContainerAdapter {
104
104
  if (safe === null) {
105
105
  return;
106
106
  }
107
+ const previous = element.getAttribute(attrName);
108
+ const inputValueBefore = readInputValue(element, attrName);
107
109
  // 空串在布尔/ARIA 状态属性上意味着「本行不该有这个属性」——删除而非写空串
108
110
  if (shouldRemoveAttribute(attrName, safe)) {
109
111
  element.removeAttribute(attrName);
110
- return;
112
+ } else {
113
+ element.setAttribute(attrName, safe);
114
+ }
115
+ // 特性没变 = 绑定值没变:不碰控件当前状态。重渲染(props 下行、行复用、无关字段变更)
116
+ // 每次都会走到这里,用户键入中尚未回写的内容、点掉的勾选都原样保留
117
+ if (element.getAttribute(attrName) !== previous) {
118
+ syncFormControlState(element, attrName, inputValueBefore);
111
119
  }
112
- element.setAttribute(attrName, safe);
113
120
  }
114
121
 
115
122
  setHtml(element: HTMLElement, value: string): void {
@@ -137,7 +144,20 @@ export class SomaContainerAdapter implements IContainerAdapter {
137
144
  element.classList.remove(...classes);
138
145
  }
139
146
 
147
+ /**
148
+ * 读写控件的 `.value`(文本值)。checkbox 的 `.value` 是提交值(缺省 "on"),不是勾选状态;
149
+ * checkbox / radio / select[multiple] 的模型值分别是布尔、组内选中值、数组,
150
+ * 渲染器的 model 读写按控件形态直接处理 `.checked` / `.selected`,不经过这两个方法。
151
+ * number / file 的取值规整(转数值、只许清空)也在渲染器里,到这里的一律是字符串。
152
+ * input / textarea 经 writeTextValue 写入:控件正聚焦时保住选区——model 回写被处理器改写过的值
153
+ * (大写化、去空格)与特性路径同一套写法,光标不跳到末尾。
154
+ */
140
155
  setValue(element: HTMLElement, value: string): void {
156
+ const tag = element.localName;
157
+ if (tag === 'input' || tag === 'textarea') {
158
+ writeTextValue(element as HTMLInputElement | HTMLTextAreaElement, value);
159
+ return;
160
+ }
141
161
  (element as HTMLInputElement).value = value;
142
162
  }
143
163
 
@@ -188,3 +208,84 @@ export class SomaContainerAdapter implements IContainerAdapter {
188
208
  }
189
209
  }
190
210
  }
211
+
212
+ /**
213
+ * 表单控件的特性只管初始值:value / checked / selected 特性对应的是 defaultValue / defaultChecked /
214
+ * defaultSelected。用户输入过、点选过,或脚本写过 property 之后控件就是 dirty 的,再改特性不会改变
215
+ * 显示——页面「重置」「清空」这类程序化改值会静默失效。故特性变化时把控件当前状态对齐到刚写下的特性:
216
+ * - input / textarea / select 的 value → `.value`(file 输入框除外);
217
+ * - checkbox / radio 的 checked → `.checked`(特性存在即为真,与布尔属性语义一致);
218
+ * - option 的 selected → `.selected`。
219
+ * property 已等于目标时不写:写 `.value` 会把光标移到末尾。
220
+ * `inputValueBefore` 是写特性前 input 的 `.value`(非 input 或非 value 特性时为 null)。
221
+ */
222
+ function syncFormControlState(element: HTMLElement, attrName: string, inputValueBefore: string | null): void {
223
+ const tag = element.localName;
224
+ switch (attrName.toLowerCase()) {
225
+ case 'value': {
226
+ const next = element.getAttribute('value') ?? '';
227
+ if (tag === 'select') {
228
+ const select = element as HTMLSelectElement;
229
+ if (select.value !== next) select.value = next;
230
+ return;
231
+ }
232
+ if (tag === 'textarea') {
233
+ writeTextValue(element as HTMLTextAreaElement, next);
234
+ return;
235
+ }
236
+ const input = element as HTMLInputElement;
237
+ // file 输入框的 value 只能由用户选文件改变,脚本写非空值会抛 InvalidStateError
238
+ if (tag !== 'input' || input.type === 'file') return;
239
+ // 值随特性变了 = 控件没被改过,原生语义已经生效(含取值规整,如 range 按 min/max 夹取)。
240
+ // 此时不写 property:写了控件就成了 dirty,之后 min/max 等特性再变,它不会再按特性重新规整
241
+ if (input.value !== inputValueBefore) return;
242
+ writeTextValue(input, next);
243
+ return;
244
+ }
245
+ case 'checked': {
246
+ const input = element as HTMLInputElement;
247
+ if (tag !== 'input' || (input.type !== 'checkbox' && input.type !== 'radio')) return;
248
+ const next = input.hasAttribute('checked');
249
+ if (input.checked !== next) input.checked = next;
250
+ return;
251
+ }
252
+ case 'selected': {
253
+ if (tag !== 'option') return;
254
+ const option = element as HTMLOptionElement;
255
+ const next = option.hasAttribute('selected');
256
+ if (option.selected !== next) option.selected = next;
257
+ return;
258
+ }
259
+ default:
260
+ return;
261
+ }
262
+ }
263
+
264
+ /** 写特性前 input 的当前值(只有 input 的 value 用得上:据此识别控件是否跟随了特性) */
265
+ function readInputValue(element: HTMLElement, attrName: string): string | null {
266
+ return element.localName === 'input' && attrName.toLowerCase() === 'value'
267
+ ? (element as HTMLInputElement).value
268
+ : null;
269
+ }
270
+
271
+ /**
272
+ * 写文本类控件的 `.value`。控件正聚焦时保住选区:转换类页面(大写化、去空格)每敲一个字
273
+ * 值就被改写一次,不保的话光标每次都跳到末尾。
274
+ */
275
+ function writeTextValue(control: HTMLInputElement | HTMLTextAreaElement, next: string): void {
276
+ if (control.value === next) return;
277
+ const root = control.getRootNode() as Document | ShadowRoot;
278
+ let selection: { start: number; end: number; direction: 'forward' | 'backward' | 'none' } | null = null;
279
+ if (root.activeElement === control) {
280
+ try {
281
+ const { selectionStart: start, selectionEnd: end, selectionDirection: direction } = control;
282
+ if (start !== null && end !== null) selection = { start, end, direction: direction ?? 'none' };
283
+ } catch { /* 类型不支持选区(如 number / email)时忽略 */ }
284
+ }
285
+ control.value = next;
286
+ if (!selection) return;
287
+ const length = control.value.length;
288
+ try {
289
+ control.setSelectionRange(Math.min(selection.start, length), Math.min(selection.end, length), selection.direction);
290
+ } catch { /* 类型不支持选区时忽略 */ }
291
+ }
@@ -698,6 +698,9 @@ export class SomaDataObjectResolver {
698
698
  /** 派生列 AST 缓存:对象名 → 字段名 → AST */
699
699
  private readonly derivedAsts = new Map<string, Map<string, CalcAst>>();
700
700
 
701
+ /** 已报过 transform 管道执行失败的位置(对象 + 字段 + 声明):同一处只报一次,随解析器生存 */
702
+ private readonly warnedTransformPipes = new Set<string>();
703
+
701
704
  /** 数据窗口:对象名 → 窗口实例(惰性建,reload 时销毁) */
702
705
  private readonly windows = new Map<string, SomaWindowHandle>();
703
706
 
@@ -719,6 +722,14 @@ export class SomaDataObjectResolver {
719
722
  return this.applyTransform(this.applyDerived(value, decl), decl);
720
723
  }
721
724
 
725
+ /**
726
+ * 展示管道(`transform:`)求值。
727
+ *
728
+ * 与页面绑定、行绑定、组件 props 同样走 tryApply 而不是 apply:apply 自己吞掉异常、
729
+ * 打一条不带出处的 `管道 "x" 执行失败` 就完了——一份 data.yaml 里十几个 transform 声明时
730
+ * 看不出是哪一个,而取数每重来一次(reload、窗口翻页)就再刷一遍。这里把失败接回来,
731
+ * 按「对象 + 字段 + 声明」点名并去重。降级值与 apply 完全一致:原值字符串,上屏内容一个字不变。
732
+ */
722
733
  private applyTransform(value: unknown, decl: SomaDataObjectConfig): unknown {
723
734
  if (!decl.transform) return value;
724
735
  if (!isPlainObject(value)) {
@@ -739,11 +750,44 @@ export class SomaDataObjectResolver {
739
750
  }
740
751
  const parsed = parsePipedValue(normalized, () => false);
741
752
  const base = readPath(value, parsed.basePath.split('.'));
742
- value[key] = this.pipes.apply(base, parsed.pipes, ctx);
753
+ const result = this.pipes.tryApply(base, parsed.pipes, ctx);
754
+ if (result.ok) {
755
+ value[key] = result.value;
756
+ continue;
757
+ }
758
+ this.warnTransformPipeFailure(decl.name, key, normalized, result.pipeName, result.error);
759
+ value[key] = String(base ?? '');
743
760
  }
744
761
  return value;
745
762
  }
746
763
 
764
+ /**
765
+ * transform 管道执行失败的告警:点名对象、派生字段、声明原文、出错的管道名与原因,
766
+ * 原始异常作为第二个实参(控制台可展开堆栈)。同一对象同一字段同一声明只报一次——
767
+ * 取数会重来(reload、窗口翻页),一个写错的管道不该每取一次就刷一遍控制台。
768
+ *
769
+ * 未注册的管道名不会走到这里:构造时的声明期白名单已经 fail fast(见 constructor)。
770
+ * 能到这里的只有管道函数自己抛错——多半是值的形状与管道不匹配(date 收到非日期串这类)。
771
+ */
772
+ private warnTransformPipeFailure(
773
+ objectName: string,
774
+ field: string,
775
+ decl: string,
776
+ pipeName: string,
777
+ error: unknown,
778
+ ): void {
779
+ const key = `${objectName}\u0000${field}\u0000${decl}`;
780
+ if (this.warnedTransformPipes.has(key)) return;
781
+ this.warnedTransformPipes.add(key);
782
+ // SomaPipeError 的消息自带 [soma-core][管道] 前缀,拼进本条告警前去掉,免得一行两个前缀
783
+ const reason = error instanceof Error ? error.message.replace(/^\[soma-core\]\[管道\]\s*/, '') : String(error);
784
+ console.warn(
785
+ `[soma-core][数据] 对象 "${objectName}" 的 transform.${field} 声明为 ${JSON.stringify(decl)},`
786
+ + `管道 "${pipeName}" 执行失败(${reason})。该字段降级为原值字符串照常上屏;同一对象同一字段只报这一次`,
787
+ error,
788
+ );
789
+ }
790
+
747
791
  /**
748
792
  * 派生列求值(REQ-010 F-10):把 `fields.<x>.calc` 算出来挂到值上。
749
793
  *
@@ -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;