soma-core 1.3.1 → 1.3.3

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 (233) hide show
  1. package/README.md +42 -0
  2. package/app/SomaPageClient.tsx +39 -2
  3. package/app/[...path]/page.tsx +7 -6
  4. package/app/api/[...path]/route.ts +3 -3
  5. package/app/api/soma-registry/[...path]/route.ts +67 -0
  6. package/app/components/SomaHostPage.tsx +3 -8
  7. package/app/components/SomaPageClientBoundary.tsx +13 -0
  8. package/app/layout.tsx +6 -1
  9. package/app/page.tsx +3 -3
  10. package/app/soma/manifest/route.ts +1 -0
  11. package/app/soma/page-object/route.ts +1 -1
  12. package/core/build/compiler/full-manifest-builder.ts +6 -1
  13. package/core/build/compiler/rollup-plugin-soma.ts +6 -0
  14. package/core/build/compiler/soma-manifest-webpack-plugin.js +4 -0
  15. package/core/build/compiler/soma-precompile.js +3507 -2387
  16. package/core/build/compiler/soma-precompile.ts +31 -2
  17. package/core/build/compiler/soma-rspack-yaml-loader.js +3 -0
  18. package/core/build/compiler/soma-webpack-loader.js +7 -1
  19. package/core/build/compiler/vite-plugin-soma.ts +11 -1
  20. package/core/build/component/package-loader.ts +135 -0
  21. package/core/build/eject/apply-eject.ts +133 -0
  22. package/core/build/eject/plan-eject.ts +139 -0
  23. package/core/client/adaptive/flush-scheduler.ts +96 -0
  24. package/core/client/adaptive/hysteresis.ts +56 -0
  25. package/core/client/adaptive/index.ts +23 -0
  26. package/core/client/adaptive/observer-pool.ts +90 -0
  27. package/core/client/base/SomaPageRootBase.ts +50 -0
  28. package/core/client/compiler/adaptive-compile.ts +136 -0
  29. package/core/client/compiler/manifest-compiler.ts +155 -27
  30. package/core/client/component/ai-catalog.ts +262 -0
  31. package/core/client/component/component-definition.types.ts +65 -0
  32. package/core/client/component/component-expander.ts +119 -0
  33. package/core/client/component/component-manager.ts +933 -0
  34. package/core/client/component/component-pack.ts +271 -0
  35. package/core/client/component/component-registry.ts +71 -0
  36. package/core/client/component/pack-styles.ts +94 -0
  37. package/core/client/component/scoped-adapter.ts +85 -0
  38. package/core/client/component/verify-pack.ts +247 -0
  39. package/core/client/container/MiniProgramContainerAdapter.ts +15 -1
  40. package/core/client/container/ReactNativeContainerAdapter.ts +15 -1
  41. package/core/client/container/SomaContainerAdapter.ts +186 -180
  42. package/core/client/data/data-object-resolver.ts +417 -0
  43. package/core/client/diagnostics/SomaDiagnostics.ts +187 -186
  44. package/core/client/diagnostics/boot-timings.ts +152 -0
  45. package/core/client/engine/asset-resolver.ts +12 -2
  46. package/core/client/engine/dom-renderer.ts +235 -16
  47. package/core/client/engine/emit-event.ts +21 -0
  48. package/core/client/engine/event-engine.ts +34 -4
  49. package/core/client/engine/on-change-engine.ts +1 -1
  50. package/core/client/engine/property-watcher.ts +1 -1
  51. package/core/client/engine/reactive-proxy.ts +3 -3
  52. package/core/client/engine/render-engine.ts +43 -4
  53. package/core/client/engine/runtime-builder.ts +23 -0
  54. package/core/client/engine/soma-bootstrap.ts +389 -5
  55. package/core/client/engine/style-binder.ts +47 -1
  56. package/core/client/host-bridge/empty-host/data/README.md +17 -0
  57. package/core/client/infra/http/SomaHttpService.ts +5 -0
  58. package/core/client/observability/error-reporter.ts +173 -0
  59. package/core/client/parser/adaptive-parser.ts +264 -0
  60. package/core/client/parser/data-config-parser.ts +396 -0
  61. package/core/client/parser/pipeline-parser.ts +15 -3
  62. package/core/client/parser/style-config-parser.ts +65 -2
  63. package/core/client/parser/ui-config-parser.ts +52 -3
  64. package/core/client/pipes/pipe-registry.ts +249 -0
  65. package/core/client/quality/SomaQualityRegistry.ts +3 -0
  66. package/core/client/registry/declaration-renderer.ts +159 -0
  67. package/core/client/registry/index.ts +28 -0
  68. package/core/client/registry/page-lifecycle.ts +171 -0
  69. package/core/client/registry/remote-page.ts +139 -0
  70. package/core/client/runtime/SomaRuntimeServices.ts +24 -0
  71. package/core/client/scheduler/SomaScheduler.ts +29 -1
  72. package/core/client/security/attribute-presence.ts +70 -0
  73. package/core/client/security/html-sanitizer.ts +113 -0
  74. package/core/client/security/url-guard.ts +0 -0
  75. package/core/client/theme/theme-engine.ts +936 -0
  76. package/core/client/typography/typography-base.ts +34 -0
  77. package/core/client/validation/contract-validator.ts +48 -5
  78. package/core/index.ts +190 -2
  79. package/core/server/api/IService.ts +18 -6
  80. package/core/server/api/load-host-service.ts +3 -3
  81. package/core/server/host/content-security-policy.ts +190 -0
  82. package/core/server/host/csp-nonce-metadata.ts +75 -0
  83. package/core/server/host/resolve-host-request-hook.ts +5 -0
  84. package/core/server/host/server-page-assets.ts +10 -0
  85. package/core/server/index.ts +30 -1
  86. package/core/server/infra/cache/ServerFileCache.ts +1 -1
  87. package/core/server/mock/node/cli.mjs +2 -2
  88. package/core/server/registry/api-registry-store.ts +518 -0
  89. package/core/server/registry/conditional-object-store.ts +29 -0
  90. package/core/server/registry/declaration-precompiler.ts +129 -0
  91. package/core/server/registry/in-memory-conditional-object-store.ts +43 -0
  92. package/core/server/registry/index.ts +142 -0
  93. package/core/server/registry/page-registry-repository.ts +373 -0
  94. package/core/server/registry/page-registry-store.ts +903 -0
  95. package/core/server/registry/registry-error.ts +17 -0
  96. package/core/server/registry/registry-file-lock.ts +173 -0
  97. package/core/server/registry/registry-response.ts +71 -0
  98. package/core/server/registry/registry-subjects.ts +194 -0
  99. package/core/server/registry/registry-write-pipeline.ts +240 -0
  100. package/core/server/registry/request-body-limit.ts +99 -0
  101. package/core/server/registry/services/apis/Get.ts +25 -0
  102. package/core/server/registry/services/apis/List.ts +41 -0
  103. package/core/server/registry/services/apis/Register.ts +39 -0
  104. package/core/server/registry/services/apis/Unregister.ts +24 -0
  105. package/core/server/registry/services/index.ts +40 -0
  106. package/core/server/registry/services/pages/Get.ts +86 -0
  107. package/core/server/registry/services/pages/List.ts +53 -0
  108. package/core/server/registry/services/pages/Register.ts +49 -0
  109. package/core/server/registry/services/pages/Rollback.ts +36 -0
  110. package/core/server/registry/services/pages/Unregister.ts +23 -0
  111. package/core/server/registry/services/service-utils.ts +21 -0
  112. package/core/server/registry/validation/compile-gate.ts +71 -0
  113. package/core/server/registry/validation/component-existence.ts +55 -0
  114. package/core/server/registry/validation/credential-ban.ts +86 -0
  115. package/core/server/registry/validation/cross-check.ts +77 -0
  116. package/core/server/registry/validation/declaration-safety-scan.ts +102 -0
  117. package/core/shared/types/adaptive.types.ts +109 -0
  118. package/core/shared/types/component-contract.types.ts +110 -0
  119. package/core/shared/types/data-config.types.ts +105 -0
  120. package/core/shared/types/domain.types.ts +6 -0
  121. package/core/shared/types/engine.types.ts +41 -35
  122. package/core/shared/types/manifest.types.ts +55 -32
  123. package/core/shared/types/scope-manifest.types.ts +96 -0
  124. package/core/shared/types/style-config.types.ts +9 -0
  125. package/core/shared/types/ui-config.types.ts +118 -98
  126. package/dist/cli/soma.js +20 -5
  127. package/dist/core/index.cjs +5388 -888
  128. package/dist/types/build/compiler/full-manifest-builder.d.ts +4 -0
  129. package/dist/types/build/compiler/rollup-plugin-soma.d.ts +1 -0
  130. package/dist/types/build/compiler/soma-precompile.d.ts +9 -0
  131. package/dist/types/build/compiler/vite-plugin-soma.d.ts +3 -0
  132. package/dist/types/build/component/package-loader.d.ts +9 -0
  133. package/dist/types/build/eject/apply-eject.d.ts +22 -0
  134. package/dist/types/build/eject/plan-eject.d.ts +32 -0
  135. package/dist/types/client/adaptive/flush-scheduler.d.ts +13 -0
  136. package/dist/types/client/adaptive/hysteresis.d.ts +16 -0
  137. package/dist/types/client/adaptive/index.d.ts +5 -0
  138. package/dist/types/client/adaptive/observer-pool.d.ts +15 -0
  139. package/dist/types/client/base/SomaPageRootBase.d.ts +33 -0
  140. package/dist/types/client/compiler/adaptive-compile.d.ts +26 -0
  141. package/dist/types/client/compiler/manifest-compiler.d.ts +13 -2
  142. package/dist/types/client/component/ai-catalog.d.ts +73 -0
  143. package/dist/types/client/component/component-definition.types.d.ts +54 -0
  144. package/dist/types/client/component/component-expander.d.ts +25 -0
  145. package/dist/types/client/component/component-manager.d.ts +160 -0
  146. package/dist/types/client/component/component-pack.d.ts +90 -0
  147. package/dist/types/client/component/component-registry.d.ts +12 -0
  148. package/dist/types/client/component/pack-styles.d.ts +22 -0
  149. package/dist/types/client/component/scoped-adapter.d.ts +18 -0
  150. package/dist/types/client/component/verify-pack.d.ts +14 -0
  151. package/dist/types/client/data/data-object-resolver.d.ts +71 -0
  152. package/dist/types/client/diagnostics/SomaDiagnostics.d.ts +2 -1
  153. package/dist/types/client/diagnostics/boot-timings.d.ts +30 -0
  154. package/dist/types/client/engine/asset-resolver.d.ts +7 -1
  155. package/dist/types/client/engine/dom-renderer.d.ts +49 -1
  156. package/dist/types/client/engine/emit-event.d.ts +6 -0
  157. package/dist/types/client/engine/event-engine.d.ts +6 -0
  158. package/dist/types/client/engine/render-engine.d.ts +26 -1
  159. package/dist/types/client/engine/runtime-builder.d.ts +7 -0
  160. package/dist/types/client/engine/soma-bootstrap.d.ts +122 -0
  161. package/dist/types/client/infra/http/SomaHttpService.d.ts +2 -0
  162. package/dist/types/client/observability/error-reporter.d.ts +51 -0
  163. package/dist/types/client/parser/adaptive-parser.d.ts +28 -0
  164. package/dist/types/client/parser/data-config-parser.d.ts +34 -0
  165. package/dist/types/client/parser/pipeline-parser.d.ts +2 -0
  166. package/dist/types/client/parser/style-config-parser.d.ts +5 -3
  167. package/dist/types/client/parser/ui-config-parser.d.ts +22 -1
  168. package/dist/types/client/pipes/pipe-registry.d.ts +38 -0
  169. package/dist/types/client/registry/declaration-renderer.d.ts +51 -0
  170. package/dist/types/client/registry/index.d.ts +10 -0
  171. package/dist/types/client/registry/page-lifecycle.d.ts +61 -0
  172. package/dist/types/client/registry/remote-page.d.ts +52 -0
  173. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +16 -0
  174. package/dist/types/client/scheduler/SomaScheduler.d.ts +8 -0
  175. package/dist/types/client/security/attribute-presence.d.ts +7 -0
  176. package/dist/types/client/security/html-sanitizer.d.ts +37 -0
  177. package/dist/types/client/security/url-guard.d.ts +11 -0
  178. package/dist/types/client/theme/theme-engine.d.ts +49 -0
  179. package/dist/types/client/typography/typography-base.d.ts +15 -0
  180. package/dist/types/client/validation/contract-validator.d.ts +2 -0
  181. package/dist/types/index.d.ts +36 -2
  182. package/dist/types/server/api/IService.d.ts +18 -6
  183. package/dist/types/server/host/content-security-policy.d.ts +53 -0
  184. package/dist/types/server/host/csp-nonce-metadata.d.ts +32 -0
  185. package/dist/types/server/host/resolve-host-request-hook.d.ts +5 -0
  186. package/dist/types/server/host/server-page-assets.d.ts +5 -0
  187. package/dist/types/server/index.d.ts +4 -1
  188. package/dist/types/server/registry/api-registry-store.d.ts +141 -0
  189. package/dist/types/server/registry/conditional-object-store.d.ts +27 -0
  190. package/dist/types/server/registry/declaration-precompiler.d.ts +30 -0
  191. package/dist/types/server/registry/in-memory-conditional-object-store.d.ts +8 -0
  192. package/dist/types/server/registry/index.d.ts +29 -0
  193. package/dist/types/server/registry/page-registry-repository.d.ts +58 -0
  194. package/dist/types/server/registry/page-registry-store.d.ts +259 -0
  195. package/dist/types/server/registry/registry-error.d.ts +12 -0
  196. package/dist/types/server/registry/registry-file-lock.d.ts +20 -0
  197. package/dist/types/server/registry/registry-response.d.ts +18 -0
  198. package/dist/types/server/registry/registry-subjects.d.ts +59 -0
  199. package/dist/types/server/registry/registry-write-pipeline.d.ts +48 -0
  200. package/dist/types/server/registry/request-body-limit.d.ts +31 -0
  201. package/dist/types/server/registry/services/apis/Get.d.ts +10 -0
  202. package/dist/types/server/registry/services/apis/List.d.ts +10 -0
  203. package/dist/types/server/registry/services/apis/Register.d.ts +13 -0
  204. package/dist/types/server/registry/services/apis/Unregister.d.ts +12 -0
  205. package/dist/types/server/registry/services/index.d.ts +3 -0
  206. package/dist/types/server/registry/services/pages/Get.d.ts +10 -0
  207. package/dist/types/server/registry/services/pages/List.d.ts +13 -0
  208. package/dist/types/server/registry/services/pages/Register.d.ts +11 -0
  209. package/dist/types/server/registry/services/pages/Rollback.d.ts +9 -0
  210. package/dist/types/server/registry/services/pages/Unregister.d.ts +9 -0
  211. package/dist/types/server/registry/services/service-utils.d.ts +10 -0
  212. package/dist/types/server/registry/validation/compile-gate.d.ts +10 -0
  213. package/dist/types/server/registry/validation/component-existence.d.ts +14 -0
  214. package/dist/types/server/registry/validation/credential-ban.d.ts +15 -0
  215. package/dist/types/server/registry/validation/cross-check.d.ts +16 -0
  216. package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +15 -0
  217. package/dist/types/shared/types/adaptive.types.d.ts +88 -0
  218. package/dist/types/shared/types/component-contract.types.d.ts +68 -0
  219. package/dist/types/shared/types/data-config.types.d.ts +81 -0
  220. package/dist/types/shared/types/domain.types.d.ts +6 -0
  221. package/dist/types/shared/types/engine.types.d.ts +6 -0
  222. package/dist/types/shared/types/manifest.types.d.ts +23 -0
  223. package/dist/types/shared/types/scope-manifest.types.d.ts +82 -0
  224. package/dist/types/shared/types/style-config.types.d.ts +8 -0
  225. package/dist/types/shared/types/ui-config.types.d.ts +20 -0
  226. package/global.d.ts +12 -0
  227. package/next.config.js +76 -1
  228. package/package.json +32 -11
  229. package/proxy.ts +62 -0
  230. package/core/client/engine/theme-variables.ts +0 -37
  231. package/dist/tsconfig.types.tsbuildinfo +0 -1
  232. package/dist/types/client/engine/theme-variables.d.ts +0 -3
  233. package/middleware.ts +0 -33
@@ -0,0 +1,271 @@
1
+ // 组件包:让 soma-ui 之外的业务组件库像 soma-ui 一样被使用。
2
+ //
3
+ // 今天一个第三方库其实已经能被 spread 进宿主的 components 表里,能跑——
4
+ // 但有四个**静默**的坑,每一个都不报错:
5
+ // 1. 重名:两个库都叫 Card,后 spread 的赢,页面用的是哪个只能靠顺序猜;
6
+ // 2. AI 不认识:组件目录只从 soma-ui 生成,第三方组件形同不存在;
7
+ // 3. 样式装配:按需注入是 soma-ui 私有的,第三方要么全量注入要么没样式;
8
+ // 4. 质量漂移:裸色值让换肤失效、物理方向属性让 RTL 错位——都不报错。
9
+ //
10
+ // 本模块把这四件事变成显式契约:包交出完整描述,平台负责合成、查重、
11
+ // 喂目录、登记样式,并给一套可自检的闸门(verifyComponentPack)。
12
+ //
13
+ // 一条刻意的默认值:**重名直接抛错**,不做"后者胜出"。静默覆盖的排查成本极高
14
+ // (页面渲染诡异,而所有测试都绿);要覆盖就显式写进 allowOverride——
15
+ // 写出来的覆盖是设计决定,猜出来的覆盖是事故。
16
+ //
17
+ // 接入指南见 soma-core/doc/soma 组件包接入指南.md。
18
+
19
+ import type { SomaComponentDefinition } from './component-definition.types';
20
+ import { generateAiCatalog, type SomaAiCatalog } from './ai-catalog';
21
+ import { attachPackStyles } from './pack-styles';
22
+
23
+ /** 包标识:小写字母/数字/连字符——冲突报错与来源登记都用它 */
24
+ export const PACK_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
25
+
26
+ export interface SomaComponentPackStyles {
27
+ /** 组件名 → 该组件独有的 CSS(首次实例化时按需注入) */
28
+ components?: Record<string, string>;
29
+ /** 共享分片名 → CSS(被多个组件依赖的资产;不要复制进组件分片) */
30
+ shared?: Record<string, string>;
31
+ /** 组件名 → 依赖的共享分片名列表 */
32
+ deps?: Record<string, string[]>;
33
+ /** 包级基座 CSS(恒定注入;克制使用——它是每个页面首屏都要付的钱) */
34
+ base?: string;
35
+ }
36
+
37
+ export interface SomaComponentPack {
38
+ /** 包标识(小写字母/数字/连字符) */
39
+ name: string;
40
+ version: string;
41
+ /** 组件名 → 运行时定义,与 createSomaUiComponents() 同构 */
42
+ components: Record<string, SomaComponentDefinition>;
43
+ /** 按需装配的样式资产(可选) */
44
+ styles?: SomaComponentPackStyles;
45
+ /** 并进组件目录的写作规范补充(可选) */
46
+ catalogConventions?: string;
47
+ meta?: {
48
+ description?: string;
49
+ homepage?: string;
50
+ license?: string;
51
+ };
52
+ }
53
+
54
+ export class ComponentPackError extends Error {
55
+ constructor(message: string) {
56
+ super(`[SomaComponentPack] ${message}`);
57
+ this.name = 'ComponentPackError';
58
+ }
59
+ }
60
+
61
+ export interface ComposePacksOptions {
62
+ /**
63
+ * 显式覆盖:组件名 → 胜出的包名。
64
+ * 不在这张表里的重名一律抛错——默认拒绝,而不是让 spread 顺序决定渲染结果。
65
+ */
66
+ allowOverride?: Record<string, string>;
67
+ /**
68
+ * 按需样式装配(缺省开)。开着时返回的组件定义已经包好——首次实例化才注入 CSS。
69
+ * 关掉只有一种正当理由:宿主自己接管样式注入。**不要因为"在 Node 里跑"而关它**——
70
+ * 包装只在实例化那一刻碰 document,合成本身是纯数据操作。
71
+ */
72
+ lazyStyles?: boolean;
73
+ /** CSP nonce,透传给注入的 <style> */
74
+ styleNonce?: string | null;
75
+ }
76
+
77
+ export interface ComposedComponentPacks {
78
+ /** 合成后的组件表,直接喂 bootstrap 的 components */
79
+ components: Record<string, SomaComponentDefinition>;
80
+ /** 组件名 → 来源包名。排障、目录展示、闸门报错都用它 */
81
+ provenance: Record<string, string>;
82
+ /** 合成后的按需装配样式(键已按包做过冲突检查) */
83
+ styles: Required<Omit<SomaComponentPackStyles, 'base'>> & { base: string[] };
84
+ /** 参与合成的包(顺序保留;目录生成用) */
85
+ packs: SomaComponentPack[];
86
+ /** 被显式覆盖的组件名 → { 胜出包, 被盖掉的包 } */
87
+ overrides: Record<string, { winner: string; shadowed: string[] }>;
88
+ }
89
+
90
+ function assertPack(pack: SomaComponentPack): void {
91
+ if (!pack || typeof pack !== 'object') {
92
+ throw new ComponentPackError('组件包必须是对象');
93
+ }
94
+ if (typeof pack.name !== 'string' || !PACK_NAME_PATTERN.test(pack.name)) {
95
+ throw new ComponentPackError(`包名 "${String(pack?.name)}" 必须匹配 [a-z][a-z0-9-]*`);
96
+ }
97
+ if (typeof pack.version !== 'string' || !pack.version.trim()) {
98
+ throw new ComponentPackError(`包 "${pack.name}" 缺少 version`);
99
+ }
100
+ if (!pack.components || typeof pack.components !== 'object' || Array.isArray(pack.components)) {
101
+ throw new ComponentPackError(`包 "${pack.name}" 的 components 必须是 { 组件名: 定义 } 对象`);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * 合成多个组件包。
107
+ *
108
+ * 重名默认抛错并点名到两个包;要覆盖就在 allowOverride 里写清楚谁赢。
109
+ * 样式分片同理:两个包提供同名共享分片时也拦下——那通常意味着有人复制了别人的资产。
110
+ */
111
+ export function composeComponentPacks(
112
+ packs: readonly SomaComponentPack[],
113
+ options: ComposePacksOptions = {},
114
+ ): ComposedComponentPacks {
115
+ if (!Array.isArray(packs) || packs.length === 0) {
116
+ throw new ComponentPackError('至少要给一个组件包');
117
+ }
118
+ const seenPackNames = new Set<string>();
119
+ for (const pack of packs) {
120
+ assertPack(pack);
121
+ if (seenPackNames.has(pack.name)) {
122
+ throw new ComponentPackError(`包名重复:${pack.name}(同一包不要合成两次)`);
123
+ }
124
+ seenPackNames.add(pack.name);
125
+ }
126
+
127
+ const components: Record<string, SomaComponentDefinition> = {};
128
+ const provenance: Record<string, string> = {};
129
+ const overrides: Record<string, { winner: string; shadowed: string[] }> = {};
130
+ const allowOverride = options.allowOverride ?? {};
131
+
132
+ for (const [name, winner] of Object.entries(allowOverride)) {
133
+ if (!seenPackNames.has(winner)) {
134
+ throw new ComponentPackError(
135
+ `allowOverride 指定 "${name}" 由包 "${winner}" 胜出,但该包不在本次合成里`,
136
+ );
137
+ }
138
+ }
139
+
140
+ for (const pack of packs) {
141
+ for (const [name, definition] of Object.entries(pack.components) as Array<[string, SomaComponentDefinition]>) {
142
+ const previous = provenance[name];
143
+ if (previous === undefined) {
144
+ components[name] = definition;
145
+ provenance[name] = pack.name;
146
+ continue;
147
+ }
148
+ const winner = allowOverride[name];
149
+ if (winner === undefined) {
150
+ throw new ComponentPackError(
151
+ `组件名冲突:"${name}" 同时来自包 "${previous}" 与 "${pack.name}"。`
152
+ + `\n 合成默认拒绝重名——静默覆盖会让"页面用的是哪个组件"只能靠顺序猜。`
153
+ + `\n 确实要覆盖就显式声明:composeComponentPacks(..., { allowOverride: { ${name}: '包名' } })`,
154
+ );
155
+ }
156
+ const record = overrides[name] ?? { winner, shadowed: [] };
157
+ // 胜出方的定义留下,其余记为被遮蔽
158
+ if (pack.name === winner) {
159
+ components[name] = definition;
160
+ if (!record.shadowed.includes(previous)) record.shadowed.push(previous);
161
+ } else {
162
+ if (!record.shadowed.includes(pack.name)) record.shadowed.push(pack.name);
163
+ }
164
+ provenance[name] = winner;
165
+ overrides[name] = record;
166
+ }
167
+ }
168
+
169
+ const composed: ComposedComponentPacks = {
170
+ components,
171
+ provenance,
172
+ styles: composeStyles(packs, provenance),
173
+ packs: [...packs],
174
+ overrides,
175
+ };
176
+ if (options.lazyStyles === false) return composed;
177
+ return {
178
+ ...composed,
179
+ components: attachPackStyles(composed, { nonce: options.styleNonce ?? null }),
180
+ };
181
+ }
182
+
183
+ /**
184
+ * 合成按需装配的样式资产。
185
+ *
186
+ * 两条检查:
187
+ * - 组件分片的键必须是**本包真的提供的组件**(写错组件名的下场是样式永远不注入,
188
+ * 而页面看起来"就是有点不对",没人能一眼看出来);
189
+ * - 共享分片重名拦下:两个包起了同名共享资产,多半是有人复制了别人的 CSS。
190
+ */
191
+ function composeStyles(
192
+ packs: readonly SomaComponentPack[],
193
+ provenance: Record<string, string>,
194
+ ): ComposedComponentPacks['styles'] {
195
+ const components: Record<string, string> = {};
196
+ const shared: Record<string, string> = {};
197
+ const deps: Record<string, string[]> = {};
198
+ const base: string[] = [];
199
+ const sharedOwner: Record<string, string> = {};
200
+
201
+ for (const pack of packs) {
202
+ const styles = pack.styles;
203
+ if (!styles) continue;
204
+
205
+ for (const [name, css] of Object.entries(styles.components ?? {})) {
206
+ if (!(name in pack.components)) {
207
+ throw new ComponentPackError(
208
+ `包 "${pack.name}" 为组件 "${name}" 登记了样式,但它没有提供这个组件`
209
+ + '(组件名写错时样式永远不会注入,而页面只是"看起来有点不对")',
210
+ );
211
+ }
212
+ // 组件已被别的包覆盖时,它的样式也不该生效
213
+ if (provenance[name] === pack.name) components[name] = css;
214
+ }
215
+ for (const [name, css] of Object.entries(styles.shared ?? {})) {
216
+ const owner = sharedOwner[name];
217
+ if (owner !== undefined && owner !== pack.name) {
218
+ throw new ComponentPackError(
219
+ `共享样式分片 "${name}" 同时来自包 "${owner}" 与 "${pack.name}"——`
220
+ + '同名共享资产通常意味着有人复制了别人的 CSS,请改名或复用',
221
+ );
222
+ }
223
+ sharedOwner[name] = pack.name;
224
+ shared[name] = css;
225
+ }
226
+ for (const [name, list] of Object.entries(styles.deps ?? {})) {
227
+ if (provenance[name] === pack.name) deps[name] = [...list];
228
+ }
229
+ if (styles.base?.trim()) base.push(styles.base);
230
+ }
231
+
232
+ return { components, shared, deps, base };
233
+ }
234
+
235
+ /**
236
+ * 生成带来源标注的组件目录。
237
+ *
238
+ * 复用 generateAiCatalog(单一事实源:目录条目怎么长、ai 段怎么校验只有一处实现),
239
+ * 在它之上补两件包相关的事:
240
+ * - 每个条目盖 `pack` 戳,让人和排障工具知道这个组件是谁提供的;
241
+ * - 把各包的 catalogConventions 并进规范章节——第三方包对自己的组件有话要说时,
242
+ * 那些话必须跟着组件一起进模型的上下文,否则等于没写。
243
+ *
244
+ * 参数是合成结果而不是散装组件表:目录必须与运行时注册的是同一批组件,
245
+ * 中间隔一次手工拼装就迟早漂移。
246
+ */
247
+ export function generatePackCatalog(
248
+ composed: ComposedComponentPacks,
249
+ options: { conventions?: string; strict?: boolean } = {},
250
+ ): SomaAiCatalog & { packOf: Record<string, string> } {
251
+ const conventions = [
252
+ options.conventions,
253
+ ...composed.packs
254
+ .filter((pack) => pack.catalogConventions?.trim())
255
+ .map((pack) => `### 来自组件包 ${pack.name}\n\n${pack.catalogConventions!.trim()}`),
256
+ ].filter(Boolean).join('\n\n');
257
+
258
+ const catalog = generateAiCatalog(composed.components, {
259
+ ...(conventions ? { conventions } : {}),
260
+ ...(options.strict === undefined ? {} : { strict: options.strict }),
261
+ });
262
+
263
+ return {
264
+ ...catalog,
265
+ entries: catalog.entries.map((entry) => ({
266
+ ...entry,
267
+ pack: composed.provenance[entry.name],
268
+ })) as typeof catalog.entries,
269
+ packOf: { ...composed.provenance },
270
+ };
271
+ }
@@ -0,0 +1,71 @@
1
+ // 组件注册表:组件名 → 运行时定义。
2
+ // Host 级单注册域;Host 本地组件覆盖同名包组件(覆盖告警由 LSP/诊断承担)。
3
+
4
+ import type { SomaComponentDefinition } from './component-definition.types';
5
+ import { SOMA_COMPONENT_CTRL_KEY } from './component-definition.types';
6
+ import { findNestedMutableContractDefault } from '../../shared/types/component-contract.types';
7
+
8
+ export class SomaComponentRegistryError extends Error {
9
+ constructor(message: string) {
10
+ super(`[SomaComponentRegistry] ${message}`);
11
+ this.name = 'SomaComponentRegistryError';
12
+ }
13
+ }
14
+
15
+ export class SomaComponentRegistry {
16
+ private readonly defs = new Map<string, SomaComponentDefinition>();
17
+
18
+ register(def: SomaComponentDefinition): void {
19
+ const { contract } = def;
20
+ if (!contract?.name) {
21
+ throw new SomaComponentRegistryError('契约缺少 name');
22
+ }
23
+ if (!def.templateHtml) {
24
+ throw new SomaComponentRegistryError(`组件 "${contract.name}" 缺少 templateHtml`);
25
+ }
26
+ if (contract.props && SOMA_COMPONENT_CTRL_KEY in contract.props) {
27
+ throw new SomaComponentRegistryError(
28
+ `组件 "${contract.name}" 的 prop 名 "${SOMA_COMPONENT_CTRL_KEY}" 是保留键`,
29
+ );
30
+ }
31
+ for (const [propName, prop] of Object.entries(contract.props ?? {})) {
32
+ if (!prop.required && prop.default === undefined) {
33
+ throw new SomaComponentRegistryError(
34
+ `组件 "${contract.name}" 的可选 prop "${propName}" 缺少 default(契约规则 C4)`,
35
+ );
36
+ }
37
+ const nestedMutablePath = findNestedMutableContractDefault(prop.default);
38
+ if (nestedMutablePath) {
39
+ throw new SomaComponentRegistryError(
40
+ `组件 "${contract.name}" 的 prop "${propName}" default.${nestedMutablePath} 是嵌套可变默认值;默认值只允许一层数组/普通对象(契约规则 C4a)`,
41
+ );
42
+ }
43
+ }
44
+ this.defs.set(contract.name, def);
45
+ }
46
+
47
+ registerAll(defs: Record<string, SomaComponentDefinition> | SomaComponentDefinition[]): void {
48
+ const list = Array.isArray(defs) ? defs : Object.values(defs);
49
+ for (const def of list) {
50
+ this.register(def);
51
+ }
52
+ }
53
+
54
+ get(name: string): SomaComponentDefinition {
55
+ const def = this.defs.get(name);
56
+ if (!def) {
57
+ throw new SomaComponentRegistryError(
58
+ `未注册的组件 "${name}"(已注册:${[...this.defs.keys()].join(', ') || '无'})`,
59
+ );
60
+ }
61
+ return def;
62
+ }
63
+
64
+ has(name: string): boolean {
65
+ return this.defs.has(name);
66
+ }
67
+
68
+ names(): string[] {
69
+ return [...this.defs.keys()];
70
+ }
71
+ }
@@ -0,0 +1,94 @@
1
+ // 组件包的按需样式装配。
2
+ //
3
+ // 机制与 soma-ui 一致(它的 withSomaUiLazyStyles 是同一个套路):把组件的
4
+ // controllerFactory 包一层,**首次实例化**时才注入这个组件的 CSS 分片。
5
+ // 页面付的是"我用到的那几个"的钱,包的规模不再是每个页面的首屏成本。
6
+ //
7
+ // 两个刻意的决定:
8
+ // 1. **默认就包上**(composeComponentPacks 直接返回包好的定义)。
9
+ // 要求第三方包作者记得再调一次注入函数,是个必然被忘记的接线——
10
+ // 忘记的表现是"组件渲染出来但没样式",而且不报错;
11
+ // 2. **注入发生在实例化那一刻**,不在合成时。合成是纯数据操作,要能在 Node 里
12
+ // 跑测试;真正碰 document 的时机永远在浏览器里。
13
+ //
14
+ // 幂等:每个分片只注入一次(注入过的键记在模块级 Set 里,并在 <style> 上盖 data 属性,
15
+ // 这样热更新重复执行也不会堆出十几张同样的 <style>)。
16
+
17
+ import type { SomaComponentDefinition } from './component-definition.types';
18
+ import type { ComposedComponentPacks } from './component-pack';
19
+
20
+ const injected = new Set<string>();
21
+
22
+ export interface PackStyleOptions {
23
+ /** CSP nonce;宿主启用严格 CSP 时必须给 */
24
+ nonce?: string | null;
25
+ }
26
+
27
+ /** 测试用:清空注入记录(jsdom 之间不共享 document,但模块级 Set 会跨用例残留) */
28
+ export function resetPackStyleInjection(): void {
29
+ injected.clear();
30
+ }
31
+
32
+ function injectOnce(key: string, css: string, options: PackStyleOptions): void {
33
+ if (!css.trim() || injected.has(key)) return;
34
+ if (typeof document === 'undefined') return;
35
+ injected.add(key);
36
+ const existing = document.querySelector(`style[data-soma-pack-style="${key}"]`);
37
+ if (existing) return;
38
+ const style = document.createElement('style');
39
+ style.setAttribute('data-soma-pack-style', key);
40
+ if (options.nonce) style.setAttribute('nonce', options.nonce);
41
+ style.textContent = css;
42
+ document.head.appendChild(style);
43
+ }
44
+
45
+ /**
46
+ * 给合成结果里的每个组件接上按需样式。
47
+ *
48
+ * 注入顺序是**先共享分片、再组件分片**:组件分片经常覆盖共享分片里的默认值,
49
+ * 反过来注入会让覆盖失效——而这种失效只在"共享分片恰好晚注入"时出现,
50
+ * 也就是取决于页面先实例化了哪个组件,是最难复现的一类样式 bug。
51
+ */
52
+ export function attachPackStyles(
53
+ composed: ComposedComponentPacks,
54
+ options: PackStyleOptions = {},
55
+ ): Record<string, SomaComponentDefinition> {
56
+ const { components, styles } = composed;
57
+ const result: Record<string, SomaComponentDefinition> = {};
58
+
59
+ for (const [name, definition] of Object.entries(components) as Array<[string, SomaComponentDefinition]>) {
60
+ const own = styles.components[name];
61
+ const deps = styles.deps[name] ?? [];
62
+ if (!own && deps.length === 0) {
63
+ result[name] = definition;
64
+ continue;
65
+ }
66
+ const inner = definition.controllerFactory;
67
+ result[name] = {
68
+ ...definition,
69
+ controllerFactory: (ctx) => {
70
+ for (const dep of deps) {
71
+ const shared = styles.shared[dep];
72
+ if (shared) injectOnce(`shared:${dep}`, shared, options);
73
+ }
74
+ if (own) injectOnce(`component:${name}`, own, options);
75
+ return inner ? inner(ctx) : {};
76
+ },
77
+ };
78
+ }
79
+ return result;
80
+ }
81
+
82
+ /**
83
+ * 注入包级基座 CSS(恒定注入,不等实例化)。
84
+ * 基座是每个页面首屏都要付的钱,所以接入指南里写着"克制使用";
85
+ * 这里按包分别盖戳,便于排查"这段全局样式是谁带来的"。
86
+ */
87
+ export function ensurePackBaseStyles(
88
+ composed: ComposedComponentPacks,
89
+ options: PackStyleOptions = {},
90
+ ): void {
91
+ composed.styles.base.forEach((css, index) => {
92
+ injectOnce(`base:${index}`, css, options);
93
+ });
94
+ }
@@ -0,0 +1,85 @@
1
+ // 组件实例作用域容器适配器。
2
+ //
3
+ // 实例内部锚点使用 data-soma-scoped-id(展开器改写产物),对页面引擎不可见;
4
+ // 实例引擎组(渲染/事件)经本适配器寻址,查询根为宿主元素,天然按实例隔离。
5
+ //
6
+ // 「查询根 = 宿主元素」这一条隔离在**父组件嵌子组件**时不够用:子组件展开后,
7
+ // 它的内部锚点也带 data-soma-scoped-id,且就住在父宿主的子树里——单看属性名
8
+ // 父子锚点无法区分。而插槽投影又要求父能看见"被搬进子组件出口里的那段内容"
9
+ // (那段是父模板写的,归父作用域)。所以隔离维度必须是**作用域归属**而不是"树位置":
10
+ // 展开器给每次展开分配一个 scopeId,本次展开所写下的每个锚点都打上 data-soma-scope,
11
+ // 适配器只认自己那个 scopeId。投影后内容搬了家,归属不变,父照样找得到;
12
+ // 子组件自己的锚点则永远不会被父吸进清单。
13
+ //
14
+ // scopeId 省略时退化为"认所有 scoped 锚点"(旧行为),仅用于不涉及嵌套的场景与测试。
15
+
16
+ import { SomaContainerAdapter } from '../container/SomaContainerAdapter';
17
+ import type { SomaAnchorStats } from '../container/IContainerAdapter';
18
+
19
+ export const SOMA_SCOPED_ID_ATTR = 'data-soma-scoped-id';
20
+ /** 锚点的作用域归属标记(展开器写入,值为该次展开的 scopeId) */
21
+ export const SOMA_SCOPE_ATTR = 'data-soma-scope';
22
+
23
+ export class SomaScopedContainerAdapter extends SomaContainerAdapter {
24
+ /** 本适配器认领的作用域;undefined = 认所有 scoped 锚点 */
25
+ private readonly scopeId?: string;
26
+ /** `[data-soma-scoped-id][data-soma-scope="X"]`,预拼避免每次查询字符串拼接 */
27
+ private readonly anyAnchorSelector: string;
28
+
29
+ constructor(scopeId?: string) {
30
+ super();
31
+ this.scopeId = scopeId;
32
+ this.anyAnchorSelector = scopeId
33
+ ? `[${SOMA_SCOPED_ID_ATTR}][${SOMA_SCOPE_ATTR}="${scopeId}"]`
34
+ : `[${SOMA_SCOPED_ID_ATTR}]`;
35
+ }
36
+
37
+ getScopeId(): string | undefined {
38
+ return this.scopeId;
39
+ }
40
+
41
+ private anchorSelector(somaId: string): string {
42
+ return this.scopeId
43
+ ? `[${SOMA_SCOPED_ID_ATTR}="${somaId}"][${SOMA_SCOPE_ATTR}="${this.scopeId}"]`
44
+ : `[${SOMA_SCOPED_ID_ATTR}="${somaId}"]`;
45
+ }
46
+
47
+ findAnchor(root: ParentNode, somaId: string): HTMLElement | null {
48
+ return root.querySelector<HTMLElement>(this.anchorSelector(somaId));
49
+ }
50
+
51
+ findClosestAnchor(target: EventTarget | null): HTMLElement | null {
52
+ if (!(target instanceof HTMLElement)) {
53
+ return null;
54
+ }
55
+ return target.closest<HTMLElement>(this.anyAnchorSelector);
56
+ }
57
+
58
+ getAnchorId(element: HTMLElement): string | null {
59
+ if (this.scopeId && element.getAttribute(SOMA_SCOPE_ATTR) !== this.scopeId) {
60
+ return null;
61
+ }
62
+ return element.getAttribute(SOMA_SCOPED_ID_ATTR);
63
+ }
64
+
65
+ collectAnchors(container: HTMLElement): SomaAnchorStats {
66
+ const anchors = new Set<string>();
67
+ const counts = new Map<string, number>();
68
+
69
+ container.querySelectorAll<HTMLElement>(this.anyAnchorSelector).forEach((element) => {
70
+ const somaId = element.getAttribute(SOMA_SCOPED_ID_ATTR);
71
+ if (!somaId) return;
72
+ anchors.add(somaId);
73
+ counts.set(somaId, (counts.get(somaId) ?? 0) + 1);
74
+ });
75
+
76
+ const duplicates = new Map<string, number>();
77
+ for (const [somaId, count] of counts.entries()) {
78
+ if (count > 1) {
79
+ duplicates.set(somaId, count);
80
+ }
81
+ }
82
+
83
+ return { anchors, duplicates };
84
+ }
85
+ }