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
@@ -0,0 +1,317 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { SomaComponentDefinition } from '../../client/component/component-definition.types';
3
+ import type {
4
+ SomaComponentContract,
5
+ SomaStructureSemanticToken,
6
+ } from '../../shared/types/component-contract.types';
7
+ import type { TreeComponentSnapshot, TreeRegistrySnapshot } from '../../shared/types/component-tree.types';
8
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
9
+ import { inspectStructureTopology } from './structure-topology';
10
+ import type { SomaStructureAdapterDefinition } from '../../shared/types/component-tree-artifact.types';
11
+
12
+ export interface ComponentTreeRegistryEntry {
13
+ definition: SomaComponentDefinition;
14
+ packName?: string;
15
+ packVersion?: string;
16
+ }
17
+
18
+ export interface ComponentTreeRegistrySnapshotOptions {
19
+ sourceId?: string;
20
+ }
21
+
22
+ const CONTRACT_KEYS = [
23
+ 'name', 'layer', 'version', 'description', 'geometry', 'props', 'emits', 'slots',
24
+ 'structure', 'tokens', 'ai', 'overrides', 'uses', 'overlay', 'keyboard',
25
+ ] as const;
26
+ const STRUCTURE_KEYS = ['kind', 'rootless', 'tree_mount', 'semantics', 'slots'];
27
+ const SEMANTIC_TOKENS = new Set<SomaStructureSemanticToken>([
28
+ 'root', 'main', 'section', 'article', 'div', 'flow', 'aside', 'header', 'footer', 'nav',
29
+ 'navigation', 'complementary', 'contentinfo', 'region', 'none', 'unordered', 'ordered',
30
+ ]);
31
+ const NAME = /^[A-Z][A-Za-z0-9]*$/;
32
+ const IMPLEMENTATION_KEY = /^[A-Za-z_][A-Za-z0-9_-]*$/;
33
+ const LAYERS = new Set(['atom', 'composite', 'solution', 'template']);
34
+ const LANDMARK_TOKENS = new Set(['main', 'navigation', 'complementary', 'contentinfo', 'region', 'none']);
35
+ type Plain = Record<string, unknown>;
36
+ type Fail = (path: string, expected: string, actual: unknown, structure?: boolean) => never;
37
+
38
+ function plain(value: unknown): value is Plain {
39
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
40
+ && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
41
+ }
42
+
43
+ function summarize(value: unknown): string {
44
+ if (value === null) return 'null';
45
+ if (Array.isArray(value)) return `array(${value.length})`;
46
+ if (typeof value === 'object') return 'object';
47
+ if (typeof value === 'string') return `string(${value.length})`;
48
+ return typeof value;
49
+ }
50
+
51
+ /** Reads data descriptors only: snapshot construction must not execute definition getters. */
52
+ function own(object: Plain, key: string, path: string, fail: Fail): unknown {
53
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
54
+ if (!descriptor) return undefined;
55
+ if (!('value' in descriptor)) fail(path, 'a data property, not an accessor', 'accessor');
56
+ return descriptor.value;
57
+ }
58
+
59
+ function cloneData(value: unknown, path: string, fail: Fail, ancestors = new Set<object>()): unknown {
60
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
61
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
62
+ if (typeof value !== 'object' || value === null || (!Array.isArray(value) && !plain(value))) {
63
+ fail(path, 'finite JSON data without functions or class instances', value);
64
+ }
65
+ if (ancestors.has(value)) fail(path, 'acyclic contract data', 'cyclic reference');
66
+ ancestors.add(value);
67
+ let result: unknown;
68
+ if (Array.isArray(value)) {
69
+ result = Array.from({ length: value.length }, (_, index) => {
70
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
71
+ if (!descriptor || !('value' in descriptor)) fail(`${path}[${index}]`, 'a data array item', 'missing/accessor');
72
+ return cloneData(descriptor.value, `${path}[${index}]`, fail, ancestors);
73
+ });
74
+ } else {
75
+ const object: Plain = {};
76
+ for (const key of Object.keys(value).sort()) {
77
+ if (key === '__proto__' || key === 'prototype' || key === 'constructor') {
78
+ fail(`${path}.${key}`, 'a non-reserved data key', key);
79
+ }
80
+ const child = own(value as Plain, key, `${path}.${key}`, fail);
81
+ if (child !== undefined) object[key] = cloneData(child, `${path}.${key}`, fail, ancestors);
82
+ }
83
+ result = object;
84
+ }
85
+ ancestors.delete(value);
86
+ return result;
87
+ }
88
+
89
+ function assertKeys(value: Plain, allowed: readonly string[], path: string, fail: Fail): void {
90
+ for (const key of Object.keys(value)) {
91
+ if (!allowed.includes(key)) fail(`${path}.${key}`, `one of ${allowed.join(', ')}`, key, true);
92
+ }
93
+ }
94
+
95
+ function requirePlain(value: unknown, path: string, fail: Fail): Plain {
96
+ if (!plain(value)) fail(path, 'a plain object', value, true);
97
+ return value;
98
+ }
99
+
100
+ function validateStructure(contract: SomaComponentContract, definition: Plain, fail: Fail): void {
101
+ if (contract.structure === undefined) return;
102
+ const path = `registry.${contract.name}.structure`;
103
+ const structure = requirePlain(contract.structure, path, fail);
104
+ assertKeys(structure, STRUCTURE_KEYS, path, fail);
105
+ if (structure.kind !== 'element' && structure.kind !== 'fragment-macro') {
106
+ fail(`${path}.kind`, 'element or fragment-macro', structure.kind, true);
107
+ }
108
+ if (typeof structure.rootless !== 'boolean') fail(`${path}.rootless`, 'boolean', structure.rootless, true);
109
+ if (typeof structure.tree_mount !== 'string'
110
+ || !['legacy-host', 'controlled-host', 'single-host', 'erase'].includes(structure.tree_mount)) {
111
+ fail(`${path}.tree_mount`, 'legacy-host, controlled-host, single-host or erase', structure.tree_mount, true);
112
+ }
113
+ const macro = structure.kind === 'fragment-macro';
114
+ if (macro ? !structure.rootless || structure.tree_mount !== 'erase' : structure.rootless || structure.tree_mount === 'erase') {
115
+ fail(path, 'element with a host, or rootless fragment-macro with erase', structure, true);
116
+ }
117
+ if (macro) {
118
+ if (structure.semantics !== undefined) fail(`${path}.semantics`, 'no semantics on a fragment macro', structure.semantics, true);
119
+ for (const field of ['props', 'emits', 'tokens', 'keyboard', 'overlay'] as const) {
120
+ if (contract[field] !== undefined) fail(`registry.${contract.name}.${field}`, 'absent on a fragment macro', contract[field], true);
121
+ }
122
+ for (const field of ['controllerFactory', 'uiConfig', 'eventConfig', 'services', 'styleFeatures', 'styles', 'css']) {
123
+ const value = own(definition, field, `registry.${contract.name}.${field}`, fail);
124
+ if (value !== undefined) fail(`registry.${contract.name}.${field}`, 'absent on a fragment macro', value, true);
125
+ }
126
+ if (!contract.slots || Object.keys(contract.slots).length !== 1 || contract.slots.content?.required !== true) {
127
+ fail(`${path}.slots`, 'one required content slot for fragment-macro', contract.slots, true);
128
+ }
129
+ }
130
+ if (structure.semantics !== undefined) {
131
+ const semantics = requirePlain(structure.semantics, `${path}.semantics`, fail);
132
+ assertKeys(semantics, ['target', 'default', 'allowed', 'staticProp'], `${path}.semantics`, fail);
133
+ if (semantics.target !== 'host') fail(`${path}.semantics.target`, 'host', semantics.target, true);
134
+ if (!Array.isArray(semantics.allowed) || semantics.allowed.length === 0) {
135
+ fail(`${path}.semantics.allowed`, 'a nonempty array of Core semantic tokens', semantics.allowed, true);
136
+ }
137
+ const allowed = semantics.allowed as unknown[];
138
+ if (new Set(allowed).size !== allowed.length) fail(`${path}.semantics.allowed`, 'unique tokens', allowed, true);
139
+ for (const token of allowed) {
140
+ if (!SEMANTIC_TOKENS.has(token as SomaStructureSemanticToken)) fail(`${path}.semantics.allowed`, 'Core semantic tokens', token, true);
141
+ }
142
+ if (!allowed.includes(semantics.default)) fail(`${path}.semantics.default`, 'a token in allowed', semantics.default, true);
143
+ if (semantics.staticProp !== undefined) {
144
+ const propName = semantics.staticProp;
145
+ if (typeof propName !== 'string' || !['as', 'landmark', 'ordered'].includes(propName)) {
146
+ fail(`${path}.semantics.staticProp`, 'as, landmark or ordered with a Core mapping', propName, true);
147
+ }
148
+ const prop = contract.props?.[propName];
149
+ if (!prop) fail(`${path}.semantics.staticProp`, 'a declared component prop', propName, true);
150
+ const map = (value: unknown): unknown => propName === 'ordered'
151
+ ? typeof value === 'boolean' ? value ? 'ordered' : 'unordered' : undefined
152
+ : value;
153
+ if (propName === 'ordered' ? prop.type !== 'boolean' : prop.type !== 'enum' || !Array.isArray(prop.values) || prop.values.length === 0) {
154
+ fail(`${path}.semantics.staticProp`, propName === 'ordered' ? 'a boolean prop' : 'an enum prop with values', prop.type, true);
155
+ }
156
+ const values: unknown[] = propName === 'ordered' ? [false, true] : prop.values!;
157
+ if (propName === 'landmark' && values.some(value => typeof value !== 'string' || !LANDMARK_TOKENS.has(value))) {
158
+ fail(`${path}.semantics.staticProp`, 'the closed landmark token mapping', propName, true);
159
+ }
160
+ if (values.some(value => !allowed.includes(map(value)))) fail(`${path}.semantics.staticProp`, 'all prop values mapped into allowed', propName, true);
161
+ if (prop.default !== undefined && map(prop.default) !== semantics.default) {
162
+ fail(`${path}.semantics.default`, 'the same semantic as the prop default', prop.default, true);
163
+ }
164
+ }
165
+ }
166
+ if (structure.slots !== undefined) {
167
+ const slots = requirePlain(structure.slots, `${path}.slots`, fail);
168
+ for (const [name, value] of Object.entries(slots)) {
169
+ const slotPath = `${path}.slots.${name}`;
170
+ if (!IMPLEMENTATION_KEY.test(name) || !Object.hasOwn(contract.slots ?? {}, name)) fail(slotPath, 'a declared contract slot', name, true);
171
+ const slot = requirePlain(value, slotPath, fail);
172
+ assertKeys(slot, ['kind', 'layoutRoot', 'directChildren', 'rowContainer'], slotPath, fail);
173
+ if (slot.kind !== 'projection' && slot.kind !== 'collection') fail(`${slotPath}.kind`, 'projection or collection', slot.kind, true);
174
+ if (typeof slot.directChildren !== 'boolean') fail(`${slotPath}.directChildren`, 'boolean', slot.directChildren, true);
175
+ if (slot.layoutRoot !== undefined && (typeof slot.layoutRoot !== 'string' || !IMPLEMENTATION_KEY.test(slot.layoutRoot))) {
176
+ fail(`${slotPath}.layoutRoot`, 'an implementation key, not a selector', slot.layoutRoot, true);
177
+ }
178
+ if ((slot.kind === 'collection' || slot.directChildren) && slot.layoutRoot === undefined) {
179
+ fail(`${slotPath}.layoutRoot`, 'an explicit stable implementation root', undefined, true);
180
+ }
181
+ if (slot.kind === 'collection') {
182
+ if (macro) fail(slotPath, 'only projection slots on a fragment macro', slot.kind, true);
183
+ if (slot.rowContainer !== 'none' && slot.rowContainer !== 'list-item') fail(`${slotPath}.rowContainer`, 'none or list-item', slot.rowContainer, true);
184
+ } else if (slot.rowContainer !== undefined) {
185
+ fail(`${slotPath}.rowContainer`, 'absent on projection slots', slot.rowContainer, true);
186
+ }
187
+ }
188
+ }
189
+ }
190
+
191
+ function freezeDeep<T>(value: T): T {
192
+ if (value !== null && typeof value === 'object') {
193
+ for (const child of Object.values(value)) freezeDeep(child);
194
+ Object.freeze(value);
195
+ }
196
+ return value;
197
+ }
198
+
199
+ function digest(value: unknown): string {
200
+ // All data records were recursively key-sorted during cloning; snapshots are inserted by name.
201
+ return createHash('sha256').update(JSON.stringify(value), 'utf8').digest('hex');
202
+ }
203
+
204
+ /**
205
+ * Captures contract/schema preconditions without executing controllers or UI package code.
206
+ * Captures trusted implementation topology without retaining templates or executing controllers.
207
+ */
208
+ export function buildComponentTreeRegistrySnapshot(
209
+ entries: readonly ComponentTreeRegistryEntry[],
210
+ options: ComponentTreeRegistrySnapshotOptions = {},
211
+ ): TreeRegistrySnapshot {
212
+ const sourceId = options.sourceId ?? '<component-registry>';
213
+ const fail: Fail = (nodePath, expected, actual, structure = false) => {
214
+ throw new SomaComponentTreeError({
215
+ code: structure ? 'CT-STRUCTURE-MOUNT' : 'CT-REGISTRY-COMPONENT',
216
+ phase: 'registry', sourceId, nodePath, attribute: nodePath.split('.').at(-1),
217
+ expected, actualSummary: summarize(actual),
218
+ fixHint: 'Correct the composed component definition and rebuild its Registry snapshot.',
219
+ });
220
+ };
221
+ if (!Array.isArray(entries)) fail('registry', 'an array of composed component definitions', entries);
222
+ const captured = new Map<string, TreeComponentSnapshot>();
223
+ for (let index = 0; index < entries.length; index++) {
224
+ const entry = entries[index];
225
+ if (!plain(entry)) fail(`registry[${index}]`, 'a Registry entry', entry);
226
+ const definition = own(entry as unknown as Plain, 'definition', `registry[${index}].definition`, fail);
227
+ if (!plain(definition)) fail(`registry[${index}].definition`, 'a plain component definition', definition);
228
+ const rawContract = own(definition, 'contract', `registry[${index}].contract`, fail);
229
+ if (!plain(rawContract)) fail(`registry[${index}].contract`, 'a component contract', rawContract);
230
+ const selected: Plain = {};
231
+ for (const key of [...CONTRACT_KEYS].sort()) {
232
+ const value = own(rawContract, key, `registry[${index}].contract.${key}`, fail);
233
+ if (value !== undefined) selected[key] = cloneData(value, `registry[${index}].contract.${key}`, fail);
234
+ }
235
+ const contract = selected as unknown as SomaComponentContract;
236
+ if (typeof contract.name !== 'string' || !NAME.test(contract.name)) fail(`registry[${index}].name`, 'a PascalCase component name', contract.name);
237
+ const name = contract.name;
238
+ if (captured.has(name)) fail(`registry.${name}`, 'a unique already-composed component name', name);
239
+ if (!LAYERS.has(contract.layer)) fail(`registry.${name}.layer`, 'atom, composite, solution or template', contract.layer);
240
+ if (typeof contract.version !== 'string' || !contract.version.trim()) fail(`registry.${name}.version`, 'a nonempty contract version', contract.version);
241
+ if (typeof contract.description !== 'string') fail(`registry.${name}.description`, 'a contract description', contract.description);
242
+ for (const field of ['props', 'emits', 'slots'] as const) {
243
+ if (contract[field] !== undefined && !plain(contract[field])) fail(`registry.${name}.${field}`, 'a contract mapping', contract[field]);
244
+ }
245
+ for (const [slotName, slot] of Object.entries(contract.slots ?? {})) {
246
+ const slotPath = `registry.${name}.slots.${slotName}`;
247
+ if (!plain(slot)) fail(slotPath, 'a plain slot contract', slot);
248
+ if (slot.required !== undefined && typeof slot.required !== 'boolean') {
249
+ fail(`${slotPath}.required`, 'a boolean when provided', slot.required);
250
+ }
251
+ if (slot.desc !== undefined && typeof slot.desc !== 'string') {
252
+ fail(`${slotPath}.desc`, 'a string when provided', slot.desc);
253
+ }
254
+ }
255
+ if (contract.uses !== undefined) {
256
+ if (!Array.isArray(contract.uses) || contract.uses.some(dependency => typeof dependency !== 'string' || !NAME.test(dependency))) {
257
+ fail(`registry.${name}.uses`, 'an array of component names', contract.uses);
258
+ }
259
+ if (new Set(contract.uses).size !== contract.uses.length) fail(`registry.${name}.uses`, 'unique component dependencies', contract.uses);
260
+ contract.uses.sort();
261
+ }
262
+ validateStructure(contract, definition, fail);
263
+ const templateHtml = own(definition, 'templateHtml', `registry.${name}.templateHtml`, fail);
264
+ if (typeof templateHtml !== 'string') fail(`registry.${name}.templateHtml`, 'a template string', templateHtml);
265
+ if (contract.structure?.kind === 'fragment-macro' && templateHtml.trim() !== '') {
266
+ fail(`registry.${name}.templateHtml`, 'an empty template for a compile-time macro', 'nonempty template', true);
267
+ }
268
+ const adapterRaw = own(definition, 'structureAdapter', `registry.${name}.structureAdapter`, fail);
269
+ const structureAdapter = adapterRaw === undefined ? undefined
270
+ : cloneData(adapterRaw, `registry.${name}.structureAdapter`, fail) as SomaStructureAdapterDefinition;
271
+ if (structureAdapter) {
272
+ if (!plain(structureAdapter) || !plain(structureAdapter.layoutRoots)
273
+ || (structureAdapter.rootAnchor !== undefined && !IMPLEMENTATION_KEY.test(structureAdapter.rootAnchor))
274
+ || Object.entries(structureAdapter.layoutRoots).some(([key, value]) => !IMPLEMENTATION_KEY.test(key) || typeof value !== 'string' || !IMPLEMENTATION_KEY.test(value))) {
275
+ fail(`registry.${name}.structureAdapter`, 'safe implementation anchor keys and layoutRoots', structureAdapter, true);
276
+ }
277
+ }
278
+ const uiRaw = own(definition, 'uiConfig', `registry.${name}.uiConfig`, fail);
279
+ const uiConfig = uiRaw === undefined ? undefined : cloneData(uiRaw, `registry.${name}.uiConfig`, fail);
280
+ const collectionRaw = own(definition, 'collectionSources', `registry.${name}.collectionSources`, fail);
281
+ const collectionSources = collectionRaw === undefined ? undefined : cloneData(collectionRaw, `registry.${name}.collectionSources`, fail);
282
+ const plansRaw = own(definition, 'definitionRepeatPlans', `registry.${name}.definitionRepeatPlans`, fail);
283
+ const definitionRepeatPlans = plansRaw === undefined ? undefined : cloneData(plansRaw, `registry.${name}.definitionRepeatPlans`, fail);
284
+ const topology = inspectStructureTopology(contract, templateHtml, structureAdapter, uiConfig);
285
+ const packIdentity: { packName?: string; packVersion?: string } = {};
286
+ for (const key of ['packName', 'packVersion'] as const) {
287
+ const value = own(entry as unknown as Plain, key, `registry.${name}.${key}`, fail);
288
+ if (value !== undefined) {
289
+ if (typeof value !== 'string' || !value.trim()) fail(`registry.${name}.${key}`, 'a nonempty package identity', value);
290
+ packIdentity[key] = value;
291
+ }
292
+ }
293
+ captured.set(name, {
294
+ name, layer: contract.layer, version: contract.version, contract,
295
+ ...packIdentity, ...topology, ...(structureAdapter ? { structureAdapter } : {}),
296
+ contractDigest: digest(contract),
297
+ structureDigest: digest({ contract, templateHtml, structureAdapter, uiConfig, collectionSources, definitionRepeatPlans }),
298
+ });
299
+ }
300
+ const state = new Map<string, 'visiting' | 'done'>();
301
+ const visit = (name: string, stack: string[]): void => {
302
+ if (state.get(name) === 'done') return;
303
+ if (state.get(name) === 'visiting') fail(`registry.${name}.uses`, 'an acyclic dependency graph', [...stack, name].join(' -> '));
304
+ state.set(name, 'visiting');
305
+ for (const dependency of captured.get(name)!.contract.uses ?? []) {
306
+ if (!captured.has(dependency)) fail(`registry.${name}.uses`, 'a dependency in the composed Registry', dependency);
307
+ visit(dependency, [...stack, name]);
308
+ }
309
+ state.set(name, 'done');
310
+ };
311
+ const components: Record<string, TreeComponentSnapshot> = {};
312
+ for (const name of [...captured.keys()].sort()) {
313
+ visit(name, []);
314
+ components[name] = captured.get(name)!;
315
+ }
316
+ return freezeDeep({ components, digest: digest(components) });
317
+ }
@@ -0,0 +1,132 @@
1
+ import yaml from 'js-yaml';
2
+ import { parseFragment, type DefaultTreeAdapterMap } from 'parse5';
3
+ import { parseSomaBlockContainer } from '../blocks/block-container';
4
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
5
+ import type {
6
+ SomaPageMarkup, TreeCompileContext, TreeValidationResult,
7
+ } from '../../shared/types/component-tree.types';
8
+ import { DEFAULT_TREE_LIMITS } from '../../shared/types/component-tree.types';
9
+ import { parseComponentTree } from './parser';
10
+ import { validateComponentTree } from './validator';
11
+
12
+ export interface ComponentTreePreflightInput {
13
+ html: string;
14
+ uiYaml: string;
15
+ markup?: SomaPageMarkup;
16
+ grammarVersion?: number;
17
+ treeContext?: TreeCompileContext;
18
+ externalBlocks?: ReadonlyMap<string, string>;
19
+ }
20
+
21
+ /** Explicit format selection. Invalid metadata must never fall back to legacy HTML. */
22
+ export function resolvePageMarkup(input: Pick<ComponentTreePreflightInput, 'markup' | 'grammarVersion'>): SomaPageMarkup {
23
+ const markup = input.markup === undefined ? 'legacy-html' : input.markup;
24
+ if ((markup !== 'legacy-html' && markup !== 'component-tree')
25
+ || (markup === 'component-tree' && input.grammarVersion !== 1)
26
+ || (markup === 'legacy-html' && input.grammarVersion !== undefined)) {
27
+ throw new SomaComponentTreeError({
28
+ code: 'CT-ARTIFACT-VERSION', phase: 'input', sourceId: '<page>', nodePath: 'markup',
29
+ expected: 'legacy-html without grammarVersion, or component-tree with grammarVersion=1',
30
+ actualSummary: 'unsupported source format/version combination',
31
+ fixHint: '显式选择源格式;组件树必须声明 grammarVersion=1,不能自动回退到 HTML。',
32
+ });
33
+ }
34
+ return markup;
35
+ }
36
+
37
+ /**
38
+ * Build/server preflight only: grammar, identity, Registry and composition rules.
39
+ * It does not compile canonical props/events, emit HTML or produce a publishable artifact.
40
+ */
41
+ export function preflightComponentTree(input: ComponentTreePreflightInput): TreeValidationResult {
42
+ if (resolvePageMarkup(input) !== 'component-tree') {
43
+ throw new SomaComponentTreeError({
44
+ code: 'CT-ARTIFACT-VERSION', phase: 'input', sourceId: '<page>', nodePath: 'markup',
45
+ fixHint: '组件树预检只接收显式 component-tree 源。',
46
+ });
47
+ }
48
+ const sourceBytes = Buffer.byteLength(input.html, 'utf8') + Buffer.byteLength(input.uiYaml, 'utf8')
49
+ + [...(input.externalBlocks ?? [])].reduce((sum, [id, value]) => sum + Buffer.byteLength(id, 'utf8') + Buffer.byteLength(value, 'utf8'), 0);
50
+ if (sourceBytes > (input.treeContext?.limits?.maxSourceBytes ?? DEFAULT_TREE_LIMITS.maxSourceBytes)) {
51
+ throw new SomaComponentTreeError({ code: 'CT-LIMIT', phase: 'input', sourceId: '<page>', nodePath: 'source',
52
+ fixHint: '树与 canonical/外置块的总源字节数超过部署预算;减少静态内容。' });
53
+ }
54
+ const tree = parseComponentTree(input.html, { limits: input.treeContext?.limits });
55
+ if (!input.treeContext) {
56
+ throw new SomaComponentTreeError({
57
+ code: 'CT-REGISTRY-CONTEXT', phase: 'validate', sourceId: tree.sourceId, nodePath: 'treeContext',
58
+ fixHint: 'Host 必须提供实际 Registry 快照和页面准入策略。',
59
+ });
60
+ }
61
+ let doc: Record<string, unknown>;
62
+ try {
63
+ ({ doc } = parseSomaBlockContainer(input.uiYaml));
64
+ } catch {
65
+ // The legacy parser can include YAML source excerpts or block ids in its
66
+ // errors. Do not retain that error as a cause in the tree diagnostic.
67
+ throw new SomaComponentTreeError({
68
+ code: 'CT-BINDING-SCOPE', phase: 'bind', sourceId: tree.sourceId, nodePath: 'canonical',
69
+ fixHint: '内联 canonical 块无效;请检查 {{/}} 容器、YAML 映射和重复声明。',
70
+ });
71
+ }
72
+ const blocks = new Map(Object.entries(doc));
73
+ for (const [id, text] of input.externalBlocks ?? []) {
74
+ if (blocks.has(id)) {
75
+ throw new SomaComponentTreeError({
76
+ code: 'CT-BINDING-DUPLICATE', phase: 'bind', sourceId: tree.sourceId, nodePath: 'canonical',
77
+ fixHint: '内联与外置块不能重复声明同一个 id。',
78
+ });
79
+ }
80
+ let body: unknown;
81
+ try {
82
+ body = yaml.load(text);
83
+ } catch {
84
+ throw new SomaComponentTreeError({
85
+ code: 'CT-BINDING-SCOPE', phase: 'bind', sourceId: tree.sourceId, nodePath: 'canonical',
86
+ fixHint: '外置块 YAML 无效;请在原声明中检查映射和引号。',
87
+ });
88
+ }
89
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
90
+ throw new SomaComponentTreeError({
91
+ code: 'CT-BINDING-SCOPE', phase: 'bind', sourceId: tree.sourceId, nodePath: 'canonical',
92
+ fixHint: '外置块必须为单个声明映射。',
93
+ });
94
+ }
95
+ blocks.set(id, body);
96
+ }
97
+ const page = blocks.get('page');
98
+ const domain = page && typeof page === 'object' && !Array.isArray(page)
99
+ ? (page as Record<string, unknown>).domain : undefined;
100
+ if (typeof domain !== 'string') {
101
+ throw new SomaComponentTreeError({
102
+ code: 'CT-IDENTITY-HOST', phase: 'validate', sourceId: tree.sourceId, nodePath: 'page.domain',
103
+ fixHint: 'canonical page 块必须声明与 Host.name 相同的 domain。',
104
+ });
105
+ }
106
+ return validateComponentTree(tree, { domain, context: input.treeContext });
107
+ }
108
+
109
+ /**
110
+ * A syntax leak guard, not an HTML sanitizer. Use the HTML tree-builder's actual
111
+ * namespace/raw-text rules and visit inert template content as well as ordinary children.
112
+ * Existing Registry injection checks retain responsibility for unsafe native HTML.
113
+ */
114
+ export function assertNoComponentTreeSyntax(html: string): void {
115
+ const pending: DefaultTreeAdapterMap['node'][] = [parseFragment(html)];
116
+ while (pending.length > 0) {
117
+ const node = pending.pop()!;
118
+ if ('tagName' in node && node.tagName.toLowerCase().startsWith('soma-')) {
119
+ throw new SomaComponentTreeError({
120
+ code: 'CT-SYNTAX-LEAK', phase: 'input', sourceId: '<page>', nodePath: 'html',
121
+ actualSummary: 'uncompiled SOMA syntax element',
122
+ fixHint: 'HTML 中包含未编译的 SOMA 语法元素;不能作为 legacy 页面下发。',
123
+ });
124
+ }
125
+ if ('childNodes' in node) {
126
+ for (const child of node.childNodes) pending.push(child);
127
+ }
128
+ if ('tagName' in node && node.tagName === 'template' && 'content' in node) {
129
+ pending.push((node as DefaultTreeAdapterMap['template']).content);
130
+ }
131
+ }
132
+ }
@@ -0,0 +1,63 @@
1
+ import { parseFragment, type DefaultTreeAdapterMap } from 'parse5';
2
+ import type { SomaComponentContract } from '../../shared/types/component-contract.types';
3
+ import type { SomaStructureAdapterDefinition } from '../../shared/types/component-tree-artifact.types';
4
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
5
+
6
+ type Element = DefaultTreeAdapterMap['element'];
7
+
8
+ /** Proves the trusted implementation topology once, without a browser or controllers. */
9
+ export function inspectStructureTopology(
10
+ contract: SomaComponentContract, templateHtml: string, adapter?: SomaStructureAdapterDefinition,
11
+ uiConfig?: unknown,
12
+ ): { internalRootId?: string; templateRootTag?: string } {
13
+ const fail: (path: string) => never = path => { throw new SomaComponentTreeError({
14
+ code: 'CT-STRUCTURE-MOUNT', phase: 'registry', sourceId: '<component-registry>',
15
+ nodePath: `registry.${contract.name}.${path}`, expected: 'one stable trusted root/outlet with contract-matching topology',
16
+ fixHint: '修正组件实现的 structureAdapter、唯一根与长期存活的插槽父节点后重新构建组件包。',
17
+ }); };
18
+ const root = parseFragment(templateHtml);
19
+ const elements: Element[] = [];
20
+ const visit = (node: DefaultTreeAdapterMap['node']): void => {
21
+ if ('tagName' in node) elements.push(node);
22
+ if ('childNodes' in node) node.childNodes.forEach(visit);
23
+ // Internal row templates are different scopes, not layout roots of this instance.
24
+ };
25
+ root.childNodes.forEach(visit);
26
+ const attribute = (el: Element, name: string): string | undefined => el.attrs.find(attr => attr.name === name)?.value;
27
+ const roots = root.childNodes.filter((node): node is Element => 'tagName' in node);
28
+ const structure = contract.structure;
29
+ if (!structure || structure.kind === 'fragment-macro') return {};
30
+ if (!adapter && (structure.tree_mount === 'single-host' || structure.semantics || Object.keys(structure.slots ?? {}).length)) fail('structureAdapter');
31
+ const anchor = (id: string): Element => {
32
+ const matched = elements.filter(el => attribute(el, 'data-soma-id') === id);
33
+ if (matched.length !== 1) fail('structureAdapter.anchor');
34
+ return matched[0];
35
+ };
36
+ const implementationRoot = adapter?.rootAnchor ? anchor(adapter.rootAnchor) : undefined;
37
+ if (structure.semantics && !implementationRoot) fail('structureAdapter.rootAnchor');
38
+ if (structure.tree_mount === 'single-host' && (!implementationRoot || roots.length !== 1 || roots[0] !== implementationRoot
39
+ || root.childNodes.some(node => node.nodeName === '#text' && 'value' in node && node.value.trim()))) fail('templateHtml.root');
40
+ if (implementationRoot) {
41
+ if (implementationRoot.attrs.some(attr => attr.name === 'hidden' || attr.name === 'style' || attr.name.startsWith('on'))) fail('templateHtml.visibility');
42
+ const show = (uiConfig as { show?: Record<string, unknown> } | undefined)?.show ?? {};
43
+ const binding = show[adapter!.rootAnchor!];
44
+ if ((binding && typeof binding === 'object' && ('when' in binding || 'style' in binding))
45
+ || Object.keys(show).some(key => key === `${adapter!.rootAnchor}@hidden` || key === `${adapter!.rootAnchor}@style`)) fail('uiConfig.visibility');
46
+ }
47
+ for (const [name, slot] of Object.entries(structure.slots ?? {})) {
48
+ const outlets = elements.filter(el => attribute(el, 'data-soma-slot-outlet') === name);
49
+ if (outlets.length !== 1) fail(`structure.slots.${name}`);
50
+ if (slot.layoutRoot) {
51
+ const id = adapter?.layoutRoots[slot.layoutRoot];
52
+ if (!id) fail(`structureAdapter.layoutRoots.${slot.layoutRoot}`);
53
+ const parent = anchor(id);
54
+ if (attribute(parent, 'data-soma-slot-outlet') !== undefined) fail(`structure.slots.${name}.layoutRoot`);
55
+ if (slot.directChildren && outlets[0].parentNode !== parent) fail(`structure.slots.${name}.directChildren`);
56
+ if (slot.kind === 'collection' && slot.rowContainer === 'list-item' && !['ul', 'ol'].includes(parent.tagName)) fail(`structure.slots.${name}.rowContainer`);
57
+ }
58
+ }
59
+ return {
60
+ ...(adapter?.rootAnchor ? { internalRootId: adapter.rootAnchor } : {}),
61
+ ...(implementationRoot ? { templateRootTag: implementationRoot.tagName } : {}),
62
+ };
63
+ }