soma-core 1.3.5 → 1.4.1

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 (169) hide show
  1. package/README.md +20 -7
  2. package/app/SomaPageClient.tsx +4 -4
  3. package/app/components/SomaHostPage.tsx +5 -5
  4. package/app/components/SomaHydrationShell.tsx +4 -7
  5. package/app/globals.css +126 -3
  6. package/core/build/{v2 → blocks}/block-compile.ts +47 -18
  7. package/core/build/{v2/soma-file-loader.ts → blocks/block-container.ts} +28 -37
  8. package/core/build/{v2 → blocks}/block-loader.ts +1 -1
  9. package/core/build/{v2 → blocks}/html-index.ts +1 -1
  10. package/core/build/{v2/migrate-v1.ts → blocks/migrate-flat.ts} +27 -27
  11. package/core/build/compiler/host-config-sync.cjs +2 -9
  12. package/core/build/compiler/page-declaration-compiler.ts +32 -4
  13. package/core/build/compiler/soma-manifest-webpack-plugin.js +1 -1
  14. package/core/build/compiler/soma-precompile.js +2057 -35
  15. package/core/build/compiler/soma-precompile.ts +2 -2
  16. package/core/build/component/component-graph.ts +208 -0
  17. package/core/build/eject/component-eject.ts +473 -0
  18. package/core/build/eject/component-upgrade.ts +359 -0
  19. package/core/build/layout/constraint-solver.ts +235 -0
  20. package/core/build/layout/css-emitter.ts +116 -0
  21. package/core/build/layout/page-layout.ts +85 -0
  22. package/core/build/pack/pack-init.ts +265 -0
  23. package/core/client/base/SomaPageRootBase.ts +61 -0
  24. package/core/client/component/ai-catalog.ts +83 -8
  25. package/core/client/component/component-defaults.ts +100 -0
  26. package/core/client/component/component-definition.types.ts +39 -0
  27. package/core/client/component/component-manager.ts +79 -4
  28. package/core/client/component/component-pack.ts +126 -2
  29. package/core/client/component/contract-compat.ts +32 -3
  30. package/core/client/component/{example-v2.ts → example-blocks.ts} +19 -19
  31. package/core/client/component/keyboard-matrix.ts +144 -0
  32. package/core/client/component/pack-styles.ts +59 -1
  33. package/core/client/component/style-features.ts +131 -0
  34. package/core/client/component/theme-component-tokens.ts +83 -0
  35. package/core/client/data/data-object-resolver.ts +407 -4
  36. package/core/client/data/reaction-engine.ts +176 -0
  37. package/core/client/data/window-engine.ts +477 -0
  38. package/core/client/engine/event-engine.ts +98 -0
  39. package/core/client/engine/soma-bootstrap.ts +286 -7
  40. package/core/client/engine/step-runner.ts +134 -0
  41. package/core/client/engine/style-binder.ts +1 -1
  42. package/core/client/infra/notify/DomNotifyService.ts +2 -1
  43. package/core/client/infra/notify/INotifyTheme.ts +1 -1
  44. package/core/client/parser/{v2 → blocks}/namespace.ts +1 -1
  45. package/core/client/parser/{v2 → blocks}/page-parser.ts +30 -16
  46. package/core/client/parser/{v2 → blocks}/use-parser.ts +24 -25
  47. package/core/client/parser/data-config-parser.ts +316 -8
  48. package/core/client/parser/duration.ts +16 -0
  49. package/core/client/parser/layout-parser.ts +157 -0
  50. package/core/client/parser/page-state-parser.ts +166 -0
  51. package/core/client/parser/pipeline-parser.ts +76 -1
  52. package/core/client/parser/reaction-parser.ts +459 -0
  53. package/core/client/parser/reaction-sugar.ts +47 -0
  54. package/core/client/parser/step-parser.ts +359 -0
  55. package/core/client/parser/style-config-parser.ts +7 -7
  56. package/core/client/parser/ui-config-parser.ts +59 -0
  57. package/core/client/parser/value-lang.ts +1 -1
  58. package/core/client/parser/window-parser.ts +294 -0
  59. package/core/client/registry/index.ts +8 -0
  60. package/core/client/theme/theme-engine.ts +144 -16
  61. package/core/client/typography/typography-base.ts +1 -1
  62. package/core/index.ts +188 -13
  63. package/core/server/host/csp-nonce-metadata.ts +1 -1
  64. package/core/server/host/published-page-assets.ts +3 -8
  65. package/core/server/host/soma-page-compile.ts +1 -1
  66. package/core/server/index.ts +2 -2
  67. package/core/shared/block-errors.ts +11 -0
  68. package/core/shared/calc/coerce.ts +29 -0
  69. package/core/shared/calc/errors.ts +43 -0
  70. package/core/shared/calc/evaluator.ts +101 -0
  71. package/core/shared/calc/index.ts +12 -0
  72. package/core/shared/calc/lexer.ts +194 -0
  73. package/core/shared/calc/parser.ts +204 -0
  74. package/core/shared/calc/typer.ts +184 -0
  75. package/core/shared/path-algebra.ts +169 -0
  76. package/core/shared/predicates/index.ts +527 -0
  77. package/core/shared/published-page-route.ts +61 -0
  78. package/core/shared/types/adaptive.types.ts +1 -1
  79. package/core/shared/types/component-contract.types.ts +128 -2
  80. package/core/shared/types/data-config.types.ts +149 -2
  81. package/core/shared/types/domain.types.ts +13 -0
  82. package/core/shared/types/event.types.ts +22 -2
  83. package/core/shared/types/layout-constraint.types.ts +73 -0
  84. package/core/shared/types/page-state.types.ts +60 -0
  85. package/core/shared/types/reaction.types.ts +144 -0
  86. package/core/shared/types/scope-manifest.types.ts +11 -15
  87. package/core/shared/types/step.types.ts +91 -0
  88. package/core/shared/types/style-config.types.ts +4 -4
  89. package/core/shared/types/ui-config.types.ts +18 -0
  90. package/core/shared/types/window.types.ts +177 -0
  91. package/dist/cli/soma.js +28 -3
  92. package/dist/core/index.cjs +4829 -405
  93. package/dist/types/build/{v2 → blocks}/block-compile.d.ts +7 -7
  94. package/dist/types/build/{v2/soma-file-loader.d.ts → blocks/block-container.d.ts} +6 -11
  95. package/dist/types/build/{v2/migrate-v1.d.ts → blocks/migrate-flat.d.ts} +6 -6
  96. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
  97. package/dist/types/build/component/component-graph.d.ts +85 -0
  98. package/dist/types/build/eject/component-eject.d.ts +121 -0
  99. package/dist/types/build/eject/component-upgrade.d.ts +43 -0
  100. package/dist/types/build/layout/constraint-solver.d.ts +36 -0
  101. package/dist/types/build/layout/css-emitter.d.ts +18 -0
  102. package/dist/types/build/layout/page-layout.d.ts +24 -0
  103. package/dist/types/build/pack/pack-init.d.ts +8 -0
  104. package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
  105. package/dist/types/client/component/ai-catalog.d.ts +24 -1
  106. package/dist/types/client/component/component-defaults.d.ts +15 -0
  107. package/dist/types/client/component/component-definition.types.d.ts +38 -0
  108. package/dist/types/client/component/component-manager.d.ts +36 -0
  109. package/dist/types/client/component/component-pack.d.ts +32 -2
  110. package/dist/types/client/component/contract-compat.d.ts +2 -2
  111. package/dist/types/client/component/example-blocks.d.ts +9 -0
  112. package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
  113. package/dist/types/client/component/pack-styles.d.ts +21 -0
  114. package/dist/types/client/component/style-features.d.ts +26 -0
  115. package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
  116. package/dist/types/client/data/data-object-resolver.d.ts +106 -1
  117. package/dist/types/client/data/reaction-engine.d.ts +21 -0
  118. package/dist/types/client/data/window-engine.d.ts +27 -0
  119. package/dist/types/client/engine/event-engine.d.ts +15 -0
  120. package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
  121. package/dist/types/client/engine/step-runner.d.ts +24 -0
  122. package/dist/types/client/infra/notify/DomNotifyService.d.ts +2 -1
  123. package/dist/types/client/infra/notify/INotifyTheme.d.ts +1 -1
  124. package/dist/types/client/parser/{v2 → blocks}/page-parser.d.ts +2 -2
  125. package/dist/types/client/parser/{v2 → blocks}/use-parser.d.ts +3 -3
  126. package/dist/types/client/parser/duration.d.ts +1 -0
  127. package/dist/types/client/parser/layout-parser.d.ts +9 -0
  128. package/dist/types/client/parser/page-state-parser.d.ts +32 -0
  129. package/dist/types/client/parser/reaction-parser.d.ts +16 -0
  130. package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
  131. package/dist/types/client/parser/step-parser.d.ts +23 -0
  132. package/dist/types/client/parser/style-config-parser.d.ts +1 -1
  133. package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
  134. package/dist/types/client/parser/window-parser.d.ts +25 -0
  135. package/dist/types/client/registry/index.d.ts +1 -0
  136. package/dist/types/client/theme/theme-engine.d.ts +37 -0
  137. package/dist/types/index.d.ts +40 -9
  138. package/dist/types/server/host/published-page-assets.d.ts +3 -2
  139. package/dist/types/server/index.d.ts +1 -1
  140. package/dist/types/shared/block-errors.d.ts +5 -0
  141. package/dist/types/shared/calc/coerce.d.ts +4 -0
  142. package/dist/types/shared/calc/errors.d.ts +14 -0
  143. package/dist/types/shared/calc/evaluator.d.ts +2 -0
  144. package/dist/types/shared/calc/index.d.ts +6 -0
  145. package/dist/types/shared/calc/lexer.d.ts +20 -0
  146. package/dist/types/shared/calc/parser.d.ts +49 -0
  147. package/dist/types/shared/calc/typer.d.ts +16 -0
  148. package/dist/types/shared/path-algebra.d.ts +56 -0
  149. package/dist/types/shared/predicates/index.d.ts +79 -0
  150. package/dist/types/shared/published-page-route.d.ts +21 -0
  151. package/dist/types/shared/types/component-contract.types.d.ts +112 -0
  152. package/dist/types/shared/types/data-config.types.d.ts +132 -2
  153. package/dist/types/shared/types/domain.types.d.ts +12 -0
  154. package/dist/types/shared/types/event.types.d.ts +8 -2
  155. package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
  156. package/dist/types/shared/types/page-state.types.d.ts +49 -0
  157. package/dist/types/shared/types/reaction.types.d.ts +115 -0
  158. package/dist/types/shared/types/scope-manifest.types.d.ts +11 -11
  159. package/dist/types/shared/types/step.types.d.ts +76 -0
  160. package/dist/types/shared/types/style-config.types.d.ts +4 -4
  161. package/dist/types/shared/types/ui-config.types.d.ts +18 -0
  162. package/dist/types/shared/types/window.types.d.ts +171 -0
  163. package/package.json +2 -6
  164. package/dist/types/client/component/example-v2.d.ts +0 -9
  165. package/postcss.config.js +0 -6
  166. package/tailwind.config.ts +0 -43
  167. /package/dist/types/build/{v2 → blocks}/block-loader.d.ts +0 -0
  168. /package/dist/types/build/{v2 → blocks}/html-index.d.ts +0 -0
  169. /package/dist/types/client/parser/{v2 → blocks}/namespace.d.ts +0 -0
@@ -0,0 +1,473 @@
1
+ // `soma component eject <Name>` —— 把一个官方组件的源码交给宿主(REQ-009 EC-1)。
2
+ //
3
+ // 这是 shadcn 那套「你拥有它」在 SOMA 的合法形态。已有的 `soma eject` 只固化**页面**;
4
+ // 组件此前没有这条路,于是「官方组件 90% 合适、剩下 10% 要改行为」只能整包覆盖,
5
+ // 而整包覆盖要求宿主从零重写一个组件。
6
+ //
7
+ // 与 shadcn 的两个关键差别,都是 SOMA 已有纪律的延伸:
8
+ // ① **不复制共享资产**。导入被改写成 `soma-ui/shared/*` 公开子路径——
9
+ // 焦点作用域、键盘漫游、四态这些行为底座仍由官方维护并随 soma-ui 升级。
10
+ // shadcn 把一切都拷给你,于是每个项目的 Dialog 焦点逻辑各自漂移。
11
+ // ② **产物仍过闸门**。契约自动加 `overrides: 'soma-ui'`,装配时走契约兼容检查
12
+ // (props 超集 + emit 全保留),所以「弹出去改一改」不会静默破坏存量页面。
13
+ //
14
+ // provenance 头记下源版本与 sha256,`soma component diff` 据此告诉宿主上游改了什么。
15
+
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import crypto from 'node:crypto';
19
+
20
+ export class ComponentEjectError extends Error {
21
+ constructor(message: string) {
22
+ super(`[soma component eject] ${message}`);
23
+ this.name = 'ComponentEjectError';
24
+ }
25
+ }
26
+
27
+ export interface ComponentEjectFile {
28
+ /** 相对目标目录的路径 */
29
+ path: string;
30
+ content: string;
31
+ }
32
+
33
+ export interface ComponentProvenance {
34
+ /** 来源包名 */
35
+ from: string;
36
+ /** 来源包版本 */
37
+ version: string;
38
+ /** 来源文件(相对 soma-ui 包根) */
39
+ source: string;
40
+ /** 来源文件内容的 sha256(diff 的比对基准) */
41
+ sha256: string;
42
+ }
43
+
44
+ export interface ComponentEjectPlan {
45
+ componentName: string;
46
+ files: ComponentEjectFile[];
47
+ provenance: ComponentProvenance;
48
+ /** 被改写的导入:内部相对路径 → 公开子路径 */
49
+ rewrittenImports: Array<{ from: string; to: string }>;
50
+ /** 用到的 soma-ui 公开子路径(不复制,运行期从包里取) */
51
+ requiredShared: string[];
52
+ /**
53
+ * 契约声明的组件级依赖(REQ-010 F-46)。
54
+ *
55
+ * eject 只拉这一个组件的源码;依赖仍从 soma-ui 取。列出来是为了让作者知道
56
+ * **这份副本还牵着谁**——把 TreeSelect 拉走却不知道它要 Tree 的话,
57
+ * 页面上是一排无样式的折叠箭头,而且不报错。
58
+ */
59
+ requiredComponents: string[];
60
+ }
61
+
62
+ export interface ComponentEjectOptions {
63
+ /** 组件契约名(PascalCase) */
64
+ name: string;
65
+ /** 目标目录(宿主的组件包目录) */
66
+ to: string;
67
+ /** soma-ui 包根(含 package.json 与 src/) */
68
+ uiRoot: string;
69
+ }
70
+
71
+ /** PascalCase → kebab-case 文件名(DataTable → data-table) */
72
+ export function componentFileNameOf(name: string): string {
73
+ return name
74
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
75
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
76
+ .toLowerCase();
77
+ }
78
+
79
+ const PROVENANCE_MARK = '@soma-ejected-from';
80
+
81
+ /**
82
+ * 内部导入 → 公开子路径的改写表。
83
+ *
84
+ * 表之外的内部路径一律拒绝并点名,而不是「猜一个」——猜错的下场是宿主拿到一个
85
+ * 编译不过的文件,或者更糟:编译得过但绑到了另一份实现上。
86
+ */
87
+ const IMPORT_REWRITES: Array<{ test: RegExp; to: (match: RegExpMatchArray) => string }> = [
88
+ { test: /^\.\.\/shared\/(.+)$/, to: (m) => `soma-ui/shared/${m[1]}` },
89
+ { test: /^\.\.\/i18n$/, to: () => 'soma-ui' },
90
+ { test: /^\.\.\/adaptive\/(.+)$/, to: (m) => `soma-ui/adaptive/${m[1]}` },
91
+ { test: /^\.\.\/catalog\/(.+)$/, to: (m) => `soma-ui/catalog/${m[1]}` },
92
+ { test: /^\.\.\/(styles|style-base|theme-recipes|style-presets)$/, to: () => 'soma-ui' },
93
+ ];
94
+
95
+ /** 组件之间的相互导入:eject 一个就得连带 eject 它依赖的,这里明确拒绝而不是悄悄断链 */
96
+ const SIBLING_COMPONENT_IMPORT = /^\.\/(.+)$/;
97
+
98
+ function rewriteImport(specifier: string): { to: string } | { error: string } {
99
+ if (!specifier.startsWith('.')) return { to: specifier };
100
+ for (const rule of IMPORT_REWRITES) {
101
+ const match = specifier.match(rule.test);
102
+ if (match) return { to: rule.to(match) };
103
+ }
104
+ const sibling = specifier.match(SIBLING_COMPONENT_IMPORT);
105
+ if (sibling) {
106
+ return {
107
+ error: `它导入了同目录的另一个组件 "${sibling[1]}"——`
108
+ + '请连同那个组件一起 eject,或先把共用逻辑提到 shared 再重试',
109
+ };
110
+ }
111
+ return { error: `无法把内部导入 "${specifier}" 改写成公开子路径` };
112
+ }
113
+
114
+ function sha256Of(text: string): string {
115
+ return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
116
+ }
117
+
118
+ function readPackageVersion(uiRoot: string): string {
119
+ const manifestPath = path.join(uiRoot, 'package.json');
120
+ if (!fs.existsSync(manifestPath)) {
121
+ throw new ComponentEjectError(`在 "${uiRoot}" 下找不到 package.json,它不像 soma-ui 包根`);
122
+ }
123
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as { version?: string };
124
+ return manifest.version ?? '0.0.0';
125
+ }
126
+
127
+ /**
128
+ * 规划一次组件固化:读源、改写导入、盖 provenance、加 overrides 声明。
129
+ * 纯计算 + 只读文件,不落盘——落盘是 applyComponentEject 的事(与页面 eject 同形)。
130
+ */
131
+ export function planComponentEject(options: ComponentEjectOptions): ComponentEjectPlan {
132
+ const { name, uiRoot } = options;
133
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name)) {
134
+ throw new ComponentEjectError(`组件名 "${name}" 必须是 PascalCase 契约名`);
135
+ }
136
+
137
+ const fileName = componentFileNameOf(name);
138
+ const relativeSource = path.join('src', 'components', `${fileName}.ts`);
139
+ const sourcePath = path.join(uiRoot, relativeSource);
140
+ if (!fs.existsSync(sourcePath)) {
141
+ throw new ComponentEjectError(
142
+ `找不到组件源文件 ${relativeSource}。`
143
+ + `\n 组件名与文件名的映射是 PascalCase → kebab-case(DataTable → data-table.ts);`
144
+ + '\n 请确认组件名拼写,或该组件是否来自别的包',
145
+ );
146
+ }
147
+
148
+ const original = fs.readFileSync(sourcePath, 'utf8');
149
+ const version = readPackageVersion(uiRoot);
150
+
151
+ const rewrittenImports: Array<{ from: string; to: string }> = [];
152
+ const requiredShared = new Set<string>();
153
+ const problems: string[] = [];
154
+
155
+ // from '…' / import('…') 两种形态都要改;正则只认引号内的模块说明符,不动别的字符串
156
+ const rewritten = original.replace(
157
+ /(from\s+|import\s*\(\s*)(['"])([^'"]+)\2/g,
158
+ (whole, prefix: string, quote: string, specifier: string) => {
159
+ const result = rewriteImport(specifier);
160
+ if ('error' in result) {
161
+ problems.push(`${specifier}:${result.error}`);
162
+ return whole;
163
+ }
164
+ if (result.to !== specifier) {
165
+ rewrittenImports.push({ from: specifier, to: result.to });
166
+ if (result.to.startsWith('soma-ui/')) requiredShared.add(result.to);
167
+ }
168
+ return `${prefix}${quote}${result.to}${quote}`;
169
+ },
170
+ );
171
+
172
+ if (problems.length > 0) {
173
+ throw new ComponentEjectError(
174
+ `"${name}" 有 ${problems.length} 处导入无法改写成公开路径:`
175
+ + `\n${problems.map((item) => ` · ${item}`).join('\n')}`
176
+ + '\n eject 刻意不复制共享资产——那样每个项目的焦点/键盘实现都会各自漂移。',
177
+ );
178
+ }
179
+
180
+ const provenance: ComponentProvenance = {
181
+ from: 'soma-ui',
182
+ version,
183
+ source: relativeSource.split(path.sep).join('/'),
184
+ sha256: sha256Of(original),
185
+ };
186
+
187
+ const withOverrides = injectOverridesDeclaration(rewritten, name);
188
+ const content = `${renderProvenanceHeader(provenance)}\n${withOverrides}`;
189
+
190
+ return {
191
+ componentName: name,
192
+ files: [
193
+ { path: `${fileName}.ts`, content },
194
+ // 基线快照:eject 那一刻的上游**原文**,逐字节。
195
+ //
196
+ // 没有它,diff 只能拿 sha256 判定"上游动没动",却拿不出"动了哪几行"——
197
+ // 第一版正是这样:把空串当旧文本,输出是整文件全加,不是 diff。
198
+ // 有了它,diff 是真正的「上游旧 vs 上游新」;将来的升级合并也有了 base
199
+ // (base = 这份 / ours = 宿主当前 / theirs = 上游当前)——
200
+ // shadcn 的协议无版本无基线,做不到这一步;SOMA 只差存一份原文。
201
+ { path: `${BASE_DIR}/${fileName}.ts`, content: original },
202
+ ],
203
+ provenance,
204
+ rewrittenImports,
205
+ requiredShared: [...requiredShared].sort(),
206
+ requiredComponents: readContractUses(original),
207
+ };
208
+ }
209
+
210
+ /**
211
+ * 从源码里读契约的 `uses`(REQ-010 F-46)。
212
+ *
213
+ * 用正则而不是把文件 import 进来求值:eject 是构建期工具,它面对的可能是一份
214
+ * **改坏了的**源码(宿主正在编辑),import 会直接抛在一个与 eject 无关的地方。
215
+ * 正则读不出来就当没有依赖——比整条命令挂掉好:拉少了作者看得见(页面缺一块),
216
+ * 而命令挂掉他连拉都拉不成。
217
+ */
218
+ export function readContractUses(source: string): string[] {
219
+ const match = /\buses:\s*\[([^\]]*)\]/.exec(source);
220
+ if (!match) return [];
221
+ return [...match[1].matchAll(/['"]([A-Z][A-Za-z0-9]*)['"]/g)].map((item) => item[1]);
222
+ }
223
+
224
+ /** 基线快照目录(相对目标包目录):与产物同级、单独一层,不会被当成组件源码注册 */
225
+ export const BASE_DIR = '.soma-eject-base';
226
+
227
+ function renderProvenanceHeader(provenance: ComponentProvenance): string {
228
+ return [
229
+ '// 本文件由 `soma component eject` 生成——它现在归你维护。',
230
+ '//',
231
+ `// ${PROVENANCE_MARK} ${provenance.from}@${provenance.version} ${provenance.source}`,
232
+ `// @soma-ejected-sha256 ${provenance.sha256}`,
233
+ '//',
234
+ '// 上游改了什么:`soma component diff <组件名>`。',
235
+ '// 契约里的 overrides 声明让它在合成时替掉官方同名组件,并强制过契约兼容闸门',
236
+ '// (props 超集 + emit 全保留)——所以改归改,存量页面不会静默失守。',
237
+ ].join('\n');
238
+ }
239
+
240
+ /**
241
+ * 在契约里插入 `overrides: 'soma-ui'`。
242
+ *
243
+ * 找的是 `name: '<组件名>',` 那一行——契约的第一个字段,位置最稳定。
244
+ * 找不到就抛:静默产出一个不带 overrides 的组件,会在合成时以「组件名冲突」
245
+ * 报错,而那时的错误信息完全指不到这里。
246
+ */
247
+ function injectOverridesDeclaration(source: string, name: string): string {
248
+ if (/\boverrides\s*:\s*['"]/.test(source)) return source;
249
+ const anchor = new RegExp(`(\\n(\\s*)name:\\s*['"]${name}['"],)`);
250
+ const match = source.match(anchor);
251
+ if (!match) {
252
+ throw new ComponentEjectError(
253
+ `在源码里找不到契约的 name: '${name}' 行,无法插入 overrides 声明。`
254
+ + '\n 没有 overrides 的产物会在合成时以"组件名冲突"报错,且错误信息指不回这里,所以这里直接拒绝',
255
+ );
256
+ }
257
+ return source.replace(anchor, `$1\n$2overrides: 'soma-ui',`);
258
+ }
259
+
260
+ export interface ApplyComponentEjectOptions {
261
+ /** 目标目录(宿主组件包目录) */
262
+ to: string;
263
+ force?: boolean;
264
+ }
265
+
266
+ export interface ComponentEjectResult {
267
+ written: string[];
268
+ skipped: string[];
269
+ }
270
+
271
+ /** 落盘。默认撞名即中止——宿主目录里的东西是人写的(与页面 eject 同一条默认值)。 */
272
+ export function applyComponentEject(
273
+ plan: ComponentEjectPlan,
274
+ options: ApplyComponentEjectOptions,
275
+ ): ComponentEjectResult {
276
+ const written: string[] = [];
277
+
278
+ // 先查一遍再写:撞名要**在动手之前**中止。
279
+ //
280
+ // 原先是边查边写、最后拿 `written.length === 0` 当判据——那在一次 eject 只落一个文件时
281
+ // 恰好成立。加上基线快照(`.soma-eject-base/<name>.ts`)之后就不成立了:组件文件撞名被跳过,
282
+ // 基线文件照写,`written` 非空于是闸门不响。结果是宿主看着命令成功返回,
283
+ // 他手写的那个文件没被动(还好),但目录里多了一份与之不对应的基线——
284
+ // 下一次 `diff` 会拿这份错基线去比,报出一堆不存在的改动。
285
+ const collisions = plan.files
286
+ .map((file) => path.join(options.to, file.path))
287
+ .filter((target) => fs.existsSync(target));
288
+ if (collisions.length > 0 && !options.force) {
289
+ throw new ComponentEjectError(
290
+ `目标文件已存在:${collisions.join('、')}\n 要覆盖请加 --force(默认不动宿主目录里的东西)`,
291
+ );
292
+ }
293
+
294
+ for (const file of plan.files) {
295
+ const target = path.join(options.to, file.path);
296
+ fs.mkdirSync(path.dirname(target), { recursive: true });
297
+ fs.writeFileSync(target, file.content, 'utf8');
298
+ written.push(target);
299
+ }
300
+
301
+ return { written, skipped: [] };
302
+ }
303
+
304
+ // ─── diff(EC-2)────────────────────────────────────────────────────────────
305
+
306
+ export interface ComponentDiffResult {
307
+ componentName: string;
308
+ changed: boolean;
309
+ /** 记在产物里的来源版本 */
310
+ ejectedFrom: ComponentProvenance;
311
+ /** 上游当前版本 */
312
+ currentVersion: string;
313
+ /** 上游当前内容的 sha256 */
314
+ currentSha256: string;
315
+ /** 是否找到了 eject 时落盘的基线;没有基线就出不了 diff,只能报"变了" */
316
+ hasBaseline?: boolean;
317
+ /** 统一 diff(changed 且有基线时给出) */
318
+ unified?: string;
319
+ }
320
+
321
+ /** 从 eject 产物的头部读回 provenance;读不到说明它不是 eject 产物 */
322
+ /**
323
+ * 剥掉 eject 产物的 provenance 头,返回 `{ header, body }`。
324
+ *
325
+ * 三方合并要用它:产物带头、基线不带,不剥的话那几行会被当成"宿主的插入",
326
+ * 与上游在同一位置的任何改动撞成冲突——而那是一次凭空的冲突。
327
+ */
328
+ export function splitProvenanceHeader(content: string): { header: string; body: string } {
329
+ const lines = content.split('\n');
330
+ let end = 0;
331
+ while (end < lines.length && lines[end].startsWith('//')) end += 1;
332
+ // 头必须真的含 provenance 标记;否则这只是文件开头的普通注释,不该剥
333
+ const header = lines.slice(0, end).join('\n');
334
+ if (!header.includes(PROVENANCE_MARK)) return { header: '', body: content };
335
+ return { header, body: lines.slice(end).join('\n').replace(/^\n/, '') };
336
+ }
337
+
338
+ /**
339
+ * 把一份上游原文按 eject 的同一张表改写导入。
340
+ *
341
+ * 三方合并要把基线与上游都搬到"宿主坐标系"里:产物里的导入是改写过的,
342
+ * 而基线与上游是原始相对路径。不搬的话,每一条 import 都会被当成宿主的改动,
343
+ * 于是上游任何一次 import 调整都变成冲突。
344
+ */
345
+ export function rewriteImportsForHost(source: string): string {
346
+ return source.replace(
347
+ /(from\s+|import\s*\(\s*)(['"])([^'"]+)\2/g,
348
+ (whole, prefix: string, quote: string, specifier: string) => {
349
+ const result = rewriteImport(specifier);
350
+ return 'error' in result ? whole : `${prefix}${quote}${result.to}${quote}`;
351
+ },
352
+ );
353
+ }
354
+
355
+ export function readProvenance(content: string): ComponentProvenance | null {
356
+ const from = content.match(
357
+ new RegExp(`${PROVENANCE_MARK}\\s+([\\w-]+)@([^\\s]+)\\s+(\\S+)`),
358
+ );
359
+ const hash = content.match(/@soma-ejected-sha256\s+([0-9a-f]{64})/);
360
+ if (!from || !hash) return null;
361
+ return { from: from[1], version: from[2], source: from[3], sha256: hash[1] };
362
+ }
363
+
364
+ /**
365
+ * 对比 eject 产物与上游当前源码。
366
+ *
367
+ * 比的是**上游的旧版与新版**(用产物里记的 sha256 判定上游是否动过),
368
+ * 不是「产物 vs 上游」——产物本来就该被宿主改,拿它去比只会满屏都是宿主自己的改动。
369
+ */
370
+ export function diffEjectedComponent(ejectedFile: string, uiRoot: string): ComponentDiffResult {
371
+ if (!fs.existsSync(ejectedFile)) {
372
+ throw new ComponentEjectError(`找不到文件 ${ejectedFile}`);
373
+ }
374
+ const content = fs.readFileSync(ejectedFile, 'utf8');
375
+ const provenance = readProvenance(content);
376
+ if (!provenance) {
377
+ throw new ComponentEjectError(
378
+ `${ejectedFile} 里没有 provenance 头,它不是 \`soma component eject\` 的产物`,
379
+ );
380
+ }
381
+
382
+ const upstreamPath = path.join(uiRoot, provenance.source);
383
+ if (!fs.existsSync(upstreamPath)) {
384
+ throw new ComponentEjectError(
385
+ `上游文件 ${provenance.source} 已不存在——该组件可能已改名或被删除`,
386
+ );
387
+ }
388
+ const upstream = fs.readFileSync(upstreamPath, 'utf8');
389
+ const currentSha256 = sha256Of(upstream);
390
+ const componentName = path.basename(ejectedFile).replace(/\.ts$/, '');
391
+ const currentVersion = readPackageVersion(uiRoot);
392
+
393
+ if (currentSha256 === provenance.sha256) {
394
+ return { componentName, changed: false, ejectedFrom: provenance, currentVersion, currentSha256 };
395
+ }
396
+
397
+ // 基线:eject 时落盘的上游原文。找得到才有真 diff;找不到就如实说,不伪造。
398
+ const basePath = path.join(path.dirname(ejectedFile), BASE_DIR, path.basename(ejectedFile));
399
+ const base = fs.existsSync(basePath) ? fs.readFileSync(basePath, 'utf8') : null;
400
+ if (base !== null && sha256Of(base) !== provenance.sha256) {
401
+ throw new ComponentEjectError(
402
+ `基线文件 ${basePath} 与 provenance 记录的 sha256 不一致——它被改动过。`
403
+ + '\n 基线是 eject 那一刻的上游原文,不该被编辑;请从版本控制恢复它',
404
+ );
405
+ }
406
+
407
+ return {
408
+ componentName,
409
+ changed: true,
410
+ ejectedFrom: provenance,
411
+ currentVersion,
412
+ currentSha256,
413
+ hasBaseline: base !== null,
414
+ unified: base !== null
415
+ ? renderUnifiedDiff(provenance.source, `(soma-ui@${provenance.version})`, `(soma-ui@${currentVersion})`, base, upstream)
416
+ : undefined,
417
+ };
418
+ }
419
+
420
+ /**
421
+ * 极简统一 diff(LCS)。刻意不引第三方 diff 依赖:
422
+ * 供应链闸门要为每个新依赖负责,而这里要的只是「让人看见改了哪几行」。
423
+ */
424
+ export function renderUnifiedDiff(
425
+ label: string,
426
+ oldTag: string,
427
+ newTag: string,
428
+ oldText: string,
429
+ newText: string,
430
+ ): string {
431
+ const a = oldText.split('\n');
432
+ const b = newText.split('\n');
433
+ const lcs = longestCommonSubsequence(a, b);
434
+ const lines: string[] = [`--- ${label} ${oldTag}`, `+++ ${label} ${newTag}`];
435
+
436
+ let i = 0;
437
+ let j = 0;
438
+ for (const [ai, bj] of lcs) {
439
+ while (i < ai) lines.push(`-${a[i++]}`);
440
+ while (j < bj) lines.push(`+${b[j++]}`);
441
+ lines.push(` ${a[i]}`);
442
+ i += 1;
443
+ j += 1;
444
+ }
445
+ while (i < a.length) lines.push(`-${a[i++]}`);
446
+ while (j < b.length) lines.push(`+${b[j++]}`);
447
+ return lines.join('\n');
448
+ }
449
+
450
+ /** 返回配对索引序列 [[aIndex, bIndex], …] */
451
+ function longestCommonSubsequence(a: string[], b: string[]): Array<[number, number]> {
452
+ const rows = a.length;
453
+ const cols = b.length;
454
+ // 行数 × 列数在组件源码尺度(千行级)下完全可接受
455
+ const table: number[][] = Array.from({ length: rows + 1 }, () => new Array<number>(cols + 1).fill(0));
456
+ for (let i = rows - 1; i >= 0; i -= 1) {
457
+ for (let j = cols - 1; j >= 0; j -= 1) {
458
+ table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
459
+ }
460
+ }
461
+ const pairs: Array<[number, number]> = [];
462
+ let i = 0;
463
+ let j = 0;
464
+ while (i < rows && j < cols) {
465
+ if (a[i] === b[j]) {
466
+ pairs.push([i, j]);
467
+ i += 1;
468
+ j += 1;
469
+ } else if (table[i + 1][j] >= table[i][j + 1]) i += 1;
470
+ else j += 1;
471
+ }
472
+ return pairs;
473
+ }