soma-core 1.3.2 → 1.3.4

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 (281) hide show
  1. package/README.md +43 -0
  2. package/app/SomaPageClient.tsx +22 -68
  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/bin/soma-lsp.cjs +1 -4
  13. package/core/build/compiler/full-manifest-builder.ts +19 -23
  14. package/core/build/compiler/html-include-expander.ts +56 -0
  15. package/core/build/compiler/page-assets.ts +26 -0
  16. package/core/build/compiler/page-declaration-compiler.ts +85 -0
  17. package/core/build/compiler/rollup-plugin-soma.ts +4 -13
  18. package/core/build/compiler/route-builder.ts +0 -2
  19. package/core/build/compiler/rspack-plugin-soma.js +1 -10
  20. package/core/build/compiler/soma-manifest-webpack-plugin.js +54 -9
  21. package/core/build/compiler/soma-precompile.js +3581 -2387
  22. package/core/build/compiler/soma-precompile.ts +44 -2
  23. package/core/build/compiler/soma-rspack-yaml-loader.js +5 -8
  24. package/core/build/compiler/soma-webpack-loader.js +6 -15
  25. package/core/build/compiler/vite-plugin-soma.ts +9 -21
  26. package/core/build/component/pack-from-dir.ts +58 -0
  27. package/core/build/component/package-loader.ts +281 -0
  28. package/core/build/eject/apply-eject.ts +133 -0
  29. package/core/build/eject/plan-eject.ts +133 -0
  30. package/core/build/lsp/cross-file-diagnostics.cjs +82 -113
  31. package/core/build/lsp/extra-completion.cjs +14 -8
  32. package/core/build/lsp/lsp-navigation.cjs +50 -43
  33. package/core/build/lsp/soma-declaration.cjs +85 -0
  34. package/core/build/lsp/ui-yaml-completion.cjs +98 -104
  35. package/core/build/v2/block-compile.ts +200 -0
  36. package/core/build/v2/block-loader.ts +33 -0
  37. package/core/build/v2/html-index.ts +120 -0
  38. package/core/build/v2/migrate-v1.ts +370 -0
  39. package/core/build/v2/soma-file-loader.ts +216 -0
  40. package/core/client/adaptive/flush-scheduler.ts +96 -0
  41. package/core/client/adaptive/hysteresis.ts +56 -0
  42. package/core/client/adaptive/index.ts +23 -0
  43. package/core/client/adaptive/observer-pool.ts +90 -0
  44. package/core/client/base/SomaPageRootBase.ts +50 -0
  45. package/core/client/compiler/adaptive-compile.ts +136 -0
  46. package/core/client/compiler/manifest-compiler.ts +155 -27
  47. package/core/client/component/ai-catalog.ts +277 -0
  48. package/core/client/component/component-definition.types.ts +65 -0
  49. package/core/client/component/component-expander.ts +119 -0
  50. package/core/client/component/component-manager.ts +933 -0
  51. package/core/client/component/component-pack.ts +445 -0
  52. package/core/client/component/component-registry.ts +71 -0
  53. package/core/client/component/contract-compat.ts +132 -0
  54. package/core/client/component/example-v2.ts +132 -0
  55. package/core/client/component/pack-styles.ts +94 -0
  56. package/core/client/component/scoped-adapter.ts +85 -0
  57. package/core/client/component/verify-pack.ts +247 -0
  58. package/core/client/container/MiniProgramContainerAdapter.ts +15 -1
  59. package/core/client/container/ReactNativeContainerAdapter.ts +15 -1
  60. package/core/client/container/SomaContainerAdapter.ts +186 -180
  61. package/core/client/data/data-object-resolver.ts +417 -0
  62. package/core/client/diagnostics/SomaDiagnostics.ts +187 -186
  63. package/core/client/diagnostics/boot-timings.ts +152 -0
  64. package/core/client/engine/asset-resolver.ts +12 -2
  65. package/core/client/engine/dom-renderer.ts +249 -24
  66. package/core/client/engine/emit-event.ts +21 -0
  67. package/core/client/engine/event-engine.ts +34 -4
  68. package/core/client/engine/on-change-engine.ts +1 -1
  69. package/core/client/engine/property-watcher.ts +1 -1
  70. package/core/client/engine/reactive-proxy.ts +11 -10
  71. package/core/client/engine/render-engine.ts +39 -4
  72. package/core/client/engine/runtime-builder.ts +23 -0
  73. package/core/client/engine/soma-bootstrap.ts +380 -7
  74. package/core/client/engine/style-binder.ts +47 -1
  75. package/core/client/observability/error-reporter.ts +173 -0
  76. package/core/client/parser/adaptive-parser.ts +264 -0
  77. package/core/client/parser/data-config-parser.ts +396 -0
  78. package/core/client/parser/pipeline-parser.ts +15 -3
  79. package/core/client/parser/style-config-parser.ts +65 -2
  80. package/core/client/parser/ui-config-parser.ts +52 -3
  81. package/core/client/parser/v2/namespace.ts +182 -0
  82. package/core/client/parser/v2/page-parser.ts +359 -0
  83. package/core/client/parser/v2/use-parser.ts +412 -0
  84. package/core/client/parser/value-lang.ts +340 -0
  85. package/core/client/pipes/pipe-registry.ts +249 -0
  86. package/core/client/quality/SomaQualityRegistry.ts +3 -0
  87. package/core/client/registry/declaration-renderer.ts +161 -0
  88. package/core/client/registry/index.ts +28 -0
  89. package/core/client/registry/page-lifecycle.ts +171 -0
  90. package/core/client/registry/remote-page.ts +139 -0
  91. package/core/client/runtime/SomaRuntimeServices.ts +24 -0
  92. package/core/client/security/attribute-presence.ts +70 -0
  93. package/core/client/security/html-sanitizer.ts +113 -0
  94. package/core/client/security/url-guard.ts +0 -0
  95. package/core/client/theme/harmony.ts +307 -0
  96. package/core/client/theme/scene-tokens.ts +134 -0
  97. package/core/client/theme/theme-axes.ts +228 -0
  98. package/core/client/theme/theme-engine.ts +1196 -0
  99. package/core/client/theme/tone-solver.ts +118 -0
  100. package/core/client/typography/typography-base.ts +34 -0
  101. package/core/client/validation/contract-validator.ts +48 -5
  102. package/core/index.ts +262 -2
  103. package/core/server/api/IService.ts +18 -6
  104. package/core/server/api/load-host-service.ts +3 -3
  105. package/core/server/host/content-security-policy.ts +190 -0
  106. package/core/server/host/csp-nonce-metadata.ts +75 -0
  107. package/core/server/host/resolve-host-request-hook.ts +5 -0
  108. package/core/server/host/server-page-assets.ts +34 -7
  109. package/core/server/host/soma-page-compile.ts +33 -0
  110. package/core/server/index.ts +45 -1
  111. package/core/server/infra/cache/ServerFileCache.ts +1 -1
  112. package/core/server/mock/node/cli.mjs +2 -2
  113. package/core/server/registry/api-registry-store.ts +518 -0
  114. package/core/server/registry/conditional-object-store.ts +29 -0
  115. package/core/server/registry/declaration-precompiler.ts +99 -0
  116. package/core/server/registry/in-memory-conditional-object-store.ts +43 -0
  117. package/core/server/registry/index.ts +142 -0
  118. package/core/server/registry/page-registry-repository.ts +373 -0
  119. package/core/server/registry/page-registry-store.ts +932 -0
  120. package/core/server/registry/registry-error.ts +17 -0
  121. package/core/server/registry/registry-file-lock.ts +173 -0
  122. package/core/server/registry/registry-response.ts +71 -0
  123. package/core/server/registry/registry-subjects.ts +194 -0
  124. package/core/server/registry/registry-write-pipeline.ts +240 -0
  125. package/core/server/registry/request-body-limit.ts +99 -0
  126. package/core/server/registry/services/apis/Get.ts +25 -0
  127. package/core/server/registry/services/apis/List.ts +41 -0
  128. package/core/server/registry/services/apis/Register.ts +39 -0
  129. package/core/server/registry/services/apis/Unregister.ts +24 -0
  130. package/core/server/registry/services/index.ts +40 -0
  131. package/core/server/registry/services/pages/Get.ts +96 -0
  132. package/core/server/registry/services/pages/List.ts +53 -0
  133. package/core/server/registry/services/pages/Register.ts +49 -0
  134. package/core/server/registry/services/pages/Rollback.ts +36 -0
  135. package/core/server/registry/services/pages/Unregister.ts +23 -0
  136. package/core/server/registry/services/service-utils.ts +21 -0
  137. package/core/server/registry/validation/compile-gate.ts +54 -0
  138. package/core/server/registry/validation/component-existence.ts +55 -0
  139. package/core/server/registry/validation/credential-ban.ts +86 -0
  140. package/core/server/registry/validation/cross-check.ts +67 -0
  141. package/core/server/registry/validation/declaration-safety-scan.ts +102 -0
  142. package/core/shared/types/adaptive.types.ts +109 -0
  143. package/core/shared/types/component-contract.types.ts +120 -0
  144. package/core/shared/types/data-config.types.ts +105 -0
  145. package/core/shared/types/domain.types.ts +6 -0
  146. package/core/shared/types/engine.types.ts +41 -35
  147. package/core/shared/types/manifest.types.ts +55 -32
  148. package/core/shared/types/scope-manifest.types.ts +96 -0
  149. package/core/shared/types/style-config.types.ts +9 -0
  150. package/core/shared/types/ui-config.types.ts +118 -98
  151. package/dist/cli/soma.js +20 -5
  152. package/dist/core/index.cjs +7811 -1380
  153. package/dist/types/build/compiler/full-manifest-builder.d.ts +6 -2
  154. package/dist/types/build/compiler/html-include-expander.d.ts +19 -0
  155. package/dist/types/build/compiler/page-assets.d.ts +3 -0
  156. package/dist/types/build/compiler/page-declaration-compiler.d.ts +33 -0
  157. package/dist/types/build/compiler/rollup-plugin-soma.d.ts +0 -2
  158. package/dist/types/build/compiler/route-builder.d.ts +0 -1
  159. package/dist/types/build/compiler/soma-precompile.d.ts +17 -0
  160. package/dist/types/build/compiler/vite-plugin-soma.d.ts +2 -7
  161. package/dist/types/build/component/pack-from-dir.d.ts +17 -0
  162. package/dist/types/build/component/package-loader.d.ts +40 -0
  163. package/dist/types/build/eject/apply-eject.d.ts +22 -0
  164. package/dist/types/build/eject/plan-eject.d.ts +32 -0
  165. package/dist/types/build/v2/block-compile.d.ts +28 -0
  166. package/dist/types/build/v2/block-loader.d.ts +9 -0
  167. package/dist/types/build/v2/html-index.d.ts +37 -0
  168. package/dist/types/build/v2/migrate-v1.d.ts +32 -0
  169. package/dist/types/build/v2/soma-file-loader.d.ts +45 -0
  170. package/dist/types/client/adaptive/flush-scheduler.d.ts +13 -0
  171. package/dist/types/client/adaptive/hysteresis.d.ts +16 -0
  172. package/dist/types/client/adaptive/index.d.ts +5 -0
  173. package/dist/types/client/adaptive/observer-pool.d.ts +15 -0
  174. package/dist/types/client/base/SomaPageRootBase.d.ts +33 -0
  175. package/dist/types/client/compiler/adaptive-compile.d.ts +26 -0
  176. package/dist/types/client/compiler/manifest-compiler.d.ts +13 -2
  177. package/dist/types/client/component/ai-catalog.d.ts +73 -0
  178. package/dist/types/client/component/component-definition.types.d.ts +54 -0
  179. package/dist/types/client/component/component-expander.d.ts +25 -0
  180. package/dist/types/client/component/component-manager.d.ts +160 -0
  181. package/dist/types/client/component/component-pack.d.ts +110 -0
  182. package/dist/types/client/component/component-registry.d.ts +12 -0
  183. package/dist/types/client/component/contract-compat.d.ts +16 -0
  184. package/dist/types/client/component/example-v2.d.ts +9 -0
  185. package/dist/types/client/component/pack-styles.d.ts +22 -0
  186. package/dist/types/client/component/scoped-adapter.d.ts +18 -0
  187. package/dist/types/client/component/verify-pack.d.ts +14 -0
  188. package/dist/types/client/data/data-object-resolver.d.ts +71 -0
  189. package/dist/types/client/diagnostics/SomaDiagnostics.d.ts +2 -1
  190. package/dist/types/client/diagnostics/boot-timings.d.ts +30 -0
  191. package/dist/types/client/engine/asset-resolver.d.ts +7 -1
  192. package/dist/types/client/engine/dom-renderer.d.ts +51 -1
  193. package/dist/types/client/engine/emit-event.d.ts +6 -0
  194. package/dist/types/client/engine/event-engine.d.ts +6 -0
  195. package/dist/types/client/engine/render-engine.d.ts +25 -1
  196. package/dist/types/client/engine/runtime-builder.d.ts +7 -0
  197. package/dist/types/client/engine/soma-bootstrap.d.ts +118 -0
  198. package/dist/types/client/observability/error-reporter.d.ts +51 -0
  199. package/dist/types/client/parser/adaptive-parser.d.ts +28 -0
  200. package/dist/types/client/parser/data-config-parser.d.ts +34 -0
  201. package/dist/types/client/parser/pipeline-parser.d.ts +2 -0
  202. package/dist/types/client/parser/style-config-parser.d.ts +5 -3
  203. package/dist/types/client/parser/ui-config-parser.d.ts +22 -1
  204. package/dist/types/client/parser/v2/namespace.d.ts +52 -0
  205. package/dist/types/client/parser/v2/page-parser.d.ts +21 -0
  206. package/dist/types/client/parser/v2/use-parser.d.ts +72 -0
  207. package/dist/types/client/parser/value-lang.d.ts +63 -0
  208. package/dist/types/client/pipes/pipe-registry.d.ts +38 -0
  209. package/dist/types/client/registry/declaration-renderer.d.ts +50 -0
  210. package/dist/types/client/registry/index.d.ts +10 -0
  211. package/dist/types/client/registry/page-lifecycle.d.ts +61 -0
  212. package/dist/types/client/registry/remote-page.d.ts +52 -0
  213. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +16 -0
  214. package/dist/types/client/security/attribute-presence.d.ts +7 -0
  215. package/dist/types/client/security/html-sanitizer.d.ts +37 -0
  216. package/dist/types/client/security/url-guard.d.ts +11 -0
  217. package/dist/types/client/theme/harmony.d.ts +77 -0
  218. package/dist/types/client/theme/scene-tokens.d.ts +25 -0
  219. package/dist/types/client/theme/theme-axes.d.ts +81 -0
  220. package/dist/types/client/theme/theme-engine.d.ts +77 -0
  221. package/dist/types/client/theme/tone-solver.d.ts +47 -0
  222. package/dist/types/client/typography/typography-base.d.ts +15 -0
  223. package/dist/types/client/validation/contract-validator.d.ts +2 -0
  224. package/dist/types/index.d.ts +47 -2
  225. package/dist/types/server/api/IService.d.ts +18 -6
  226. package/dist/types/server/host/content-security-policy.d.ts +53 -0
  227. package/dist/types/server/host/csp-nonce-metadata.d.ts +32 -0
  228. package/dist/types/server/host/resolve-host-request-hook.d.ts +5 -0
  229. package/dist/types/server/host/server-page-assets.d.ts +2 -0
  230. package/dist/types/server/host/soma-page-compile.d.ts +7 -0
  231. package/dist/types/server/index.d.ts +6 -1
  232. package/dist/types/server/registry/api-registry-store.d.ts +141 -0
  233. package/dist/types/server/registry/conditional-object-store.d.ts +27 -0
  234. package/dist/types/server/registry/declaration-precompiler.d.ts +30 -0
  235. package/dist/types/server/registry/in-memory-conditional-object-store.d.ts +8 -0
  236. package/dist/types/server/registry/index.d.ts +29 -0
  237. package/dist/types/server/registry/page-registry-repository.d.ts +58 -0
  238. package/dist/types/server/registry/page-registry-store.d.ts +259 -0
  239. package/dist/types/server/registry/registry-error.d.ts +12 -0
  240. package/dist/types/server/registry/registry-file-lock.d.ts +20 -0
  241. package/dist/types/server/registry/registry-response.d.ts +18 -0
  242. package/dist/types/server/registry/registry-subjects.d.ts +59 -0
  243. package/dist/types/server/registry/registry-write-pipeline.d.ts +48 -0
  244. package/dist/types/server/registry/request-body-limit.d.ts +31 -0
  245. package/dist/types/server/registry/services/apis/Get.d.ts +10 -0
  246. package/dist/types/server/registry/services/apis/List.d.ts +10 -0
  247. package/dist/types/server/registry/services/apis/Register.d.ts +13 -0
  248. package/dist/types/server/registry/services/apis/Unregister.d.ts +12 -0
  249. package/dist/types/server/registry/services/index.d.ts +3 -0
  250. package/dist/types/server/registry/services/pages/Get.d.ts +10 -0
  251. package/dist/types/server/registry/services/pages/List.d.ts +13 -0
  252. package/dist/types/server/registry/services/pages/Register.d.ts +11 -0
  253. package/dist/types/server/registry/services/pages/Rollback.d.ts +9 -0
  254. package/dist/types/server/registry/services/pages/Unregister.d.ts +9 -0
  255. package/dist/types/server/registry/services/service-utils.d.ts +10 -0
  256. package/dist/types/server/registry/validation/compile-gate.d.ts +12 -0
  257. package/dist/types/server/registry/validation/component-existence.d.ts +14 -0
  258. package/dist/types/server/registry/validation/credential-ban.d.ts +15 -0
  259. package/dist/types/server/registry/validation/cross-check.d.ts +16 -0
  260. package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +15 -0
  261. package/dist/types/shared/types/adaptive.types.d.ts +88 -0
  262. package/dist/types/shared/types/component-contract.types.d.ts +78 -0
  263. package/dist/types/shared/types/data-config.types.d.ts +81 -0
  264. package/dist/types/shared/types/domain.types.d.ts +6 -0
  265. package/dist/types/shared/types/engine.types.d.ts +6 -0
  266. package/dist/types/shared/types/manifest.types.d.ts +23 -0
  267. package/dist/types/shared/types/scope-manifest.types.d.ts +82 -0
  268. package/dist/types/shared/types/style-config.types.d.ts +8 -0
  269. package/dist/types/shared/types/ui-config.types.d.ts +20 -0
  270. package/editor/vscode/package.json +1 -24
  271. package/global.d.ts +5 -11
  272. package/next.config.js +85 -28
  273. package/package.json +33 -11
  274. package/proxy.ts +62 -0
  275. package/tailwind.config.ts +0 -1
  276. package/core/build/lsp/event-yaml-completion.cjs +0 -106
  277. package/core/client/engine/theme-variables.ts +0 -37
  278. package/dist/tsconfig.types.tsbuildinfo +0 -1
  279. package/dist/types/client/engine/theme-variables.d.ts +0 -3
  280. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +0 -30
  281. package/middleware.ts +0 -33
@@ -6,6 +6,9 @@ import { parseUiConfig } from '../../client/parser/ui-config-parser';
6
6
  import { parseEventConfig } from '../../client/parser/pipeline-parser';
7
7
  import { splitEventConfigRaw } from '../../client/parser/trigger-parser';
8
8
  import { parseStyleConfig } from '../../client/parser/style-config-parser';
9
+ import { parseDataConfig } from '../../client/parser/data-config-parser';
10
+ import { parseSomaV2Container } from '../v2/soma-file-loader';
11
+ import type { SomaDataConfig } from '../../shared/types/data-config.types';
9
12
  import type { UiConfig } from '../../shared/types/ui-config.types';
10
13
  import type { ParsedEvent } from '../../shared/types/event.types';
11
14
  import type { PropertyTrigger } from '../../shared/types/trigger.types';
@@ -20,15 +23,37 @@ export interface CompiledEventConfig {
20
23
  }
21
24
  import type { StyleConfig } from '../../shared/types/style-config.types';
22
25
 
26
+ /**
27
+ * 构建期解析选项。
28
+ *
29
+ * 词汇不作要求:预编译发生在宿主 bootstrap 加载之前,阶梯词汇表无处可取。
30
+ * `adaptive` 的结构校验(级数 / 单键 / pin 冲突 / profile)在此照常执行,
31
+ * 只有"级值是否在词汇表内"这一项推迟到运行期 `compileAdaptive`——
32
+ * 那一刻词汇必然在手,报错与指路口径完全相同。
33
+ */
34
+ const PRECOMPILE_PARSE_OPTIONS = { adaptiveVocabularyRequired: false } as const;
35
+
23
36
  /**
24
37
  * 预编译 UI YAML → JSON 字符串
25
38
  */
26
39
  export function precompileUiYaml(yamlStr: string): string {
27
40
  const raw = yaml.load(yamlStr);
28
- const uiConfig = parseUiConfig(raw);
41
+ const uiConfig = parseUiConfig(raw, PRECOMPILE_PARSE_OPTIONS);
29
42
  return JSON.stringify(uiConfig);
30
43
  }
31
44
 
45
+ /**
46
+ * 单文件 bundler 的 UI 模块产物。
47
+ *
48
+ * SOMA DSL 必须拿同页 HTML 做页面级编译,单文件 loader 无权猜锚点上下文;因此
49
+ * 导出 null,让宿主转入 manifest/page-assets 路径。回退前仍完整校验 v2 容器,避免
50
+ * 旧页面形状、未闭合开关或坏 YAML 被伪装成“没有预编译产物”。
51
+ */
52
+ export function precompileUiModule(yamlStr: string): string {
53
+ parseSomaV2Container(yamlStr);
54
+ return 'null';
55
+ }
56
+
32
57
  /**
33
58
  * 预编译 Event YAML → JSON 字符串(含 events + triggers)
34
59
  */
@@ -54,7 +79,7 @@ export function precompileStyleYaml(yamlStr: string): string {
54
79
  * 预编译 UI YAML → UiConfig 对象
55
80
  */
56
81
  export function compileUiConfig(yamlStr: string): UiConfig {
57
- return parseUiConfig(yaml.load(yamlStr));
82
+ return parseUiConfig(yaml.load(yamlStr), PRECOMPILE_PARSE_OPTIONS);
58
83
  }
59
84
 
60
85
  /**
@@ -85,6 +110,23 @@ export function compileStyleConfig(yamlStr: string): StyleConfig | undefined {
85
110
  return parseStyleConfig(raw);
86
111
  }
87
112
 
113
+ /**
114
+ * 预编译 Data YAML(数据对象层声明)→ SomaDataConfig 对象
115
+ */
116
+ export function compileDataConfig(yamlStr: string): SomaDataConfig {
117
+ if (!yamlStr.trim()) {
118
+ return { objects: {} };
119
+ }
120
+ return parseDataConfig(yaml.load(yamlStr));
121
+ }
122
+
123
+ /**
124
+ * 预编译 Data YAML(数据对象层声明)→ JSON 字符串
125
+ */
126
+ export function precompileDataYaml(yamlStr: string): string {
127
+ return JSON.stringify(compileDataConfig(yamlStr));
128
+ }
129
+
88
130
  /**
89
131
  * 预编译任意 YAML → JSON 字符串(locale、app.config 等纯数据配置)
90
132
  */
@@ -1,21 +1,18 @@
1
1
  const {
2
- precompileUiYaml,
3
- precompileEventYaml,
4
- precompileStyleYaml,
2
+ precompileUiModule,
5
3
  precompileYaml,
6
4
  } = require('./soma-precompile');
7
5
 
8
6
  module.exports = function somaRspackYamlLoader(source) {
9
7
  const options = this.getOptions?.() ?? {};
10
8
  const uiSuffix = options.uiSuffix ?? '_ui.yaml';
11
- const eventSuffix = options.eventSuffix ?? '_event.yaml';
12
- const styleSuffix = options.styleSuffix ?? '_style.yaml';
13
9
  const resourcePath = this.resourcePath ?? '';
14
10
 
15
11
  let compiled;
16
- if (resourcePath.endsWith(uiSuffix)) compiled = precompileUiYaml(source);
17
- else if (resourcePath.endsWith(eventSuffix)) compiled = precompileEventYaml(source);
18
- else if (resourcePath.endsWith(styleSuffix)) compiled = precompileStyleYaml(source);
12
+ if (resourcePath.endsWith(uiSuffix)) compiled = precompileUiModule(source);
13
+ else if (/_((event)|(style)|(data))\.ya?ml$/.test(resourcePath)) {
14
+ throw new Error('页面侧车已退役;事件、样式状态与数据对象必须并入同一份 SOMA DSL 声明');
15
+ }
19
16
  else compiled = precompileYaml(source);
20
17
 
21
18
  return `export default ${compiled};`;
@@ -7,24 +7,16 @@ module.exports = function somaWebpackLoader(source) {
7
7
  const resourcePath = this.resourcePath;
8
8
 
9
9
  try {
10
- const { precompileUiYaml, precompileEventYaml, precompileStyleYaml, precompileYaml } = require('./soma-precompile');
10
+ const { precompileUiModule, precompileYaml } = require('./soma-precompile');
11
11
 
12
- // SOMA UI 配置
12
+ // SOMA DSL 源声明只做容器校验,页面级编译交给 manifest/page-assets。
13
13
  if (resourcePath.endsWith('_ui.yaml')) {
14
- const compiled = precompileUiYaml(source);
14
+ const compiled = precompileUiModule(source);
15
15
  return `export default ${compiled};`;
16
16
  }
17
17
 
18
- // SOMA Event 配置
19
- if (resourcePath.endsWith('_event.yaml')) {
20
- const compiled = precompileEventYaml(source);
21
- return `export default ${compiled};`;
22
- }
23
-
24
- // SOMA Style 配置
25
- if (resourcePath.endsWith('_style.yaml')) {
26
- const compiled = precompileStyleYaml(source);
27
- return `export default ${compiled};`;
18
+ if (/_((event)|(style)|(data))\.ya?ml$/.test(resourcePath)) {
19
+ throw new Error('页面侧车已退役;事件、样式状态与数据对象必须并入同一份 SOMA DSL 声明');
28
20
  }
29
21
 
30
22
  // 通用 YAML(locale、app.config 等)
@@ -35,7 +27,6 @@ module.exports = function somaWebpackLoader(source) {
35
27
 
36
28
  return source;
37
29
  } catch (e) {
38
- this.emitError(new Error(`[soma-webpack-loader] 预编译失败 (${resourcePath}): ${e.message}`));
39
- return source;
30
+ throw new Error(`[soma-webpack-loader] 预编译失败 (${resourcePath}): ${e.message}`);
40
31
  }
41
32
  };
@@ -2,15 +2,11 @@
2
2
  // Vite 预编译插件:在构建阶段将所有声明式 YAML 配置编译为 JS 模块
3
3
 
4
4
  import type { Plugin } from 'vite';
5
- import { precompileUiYaml, precompileEventYaml, precompileStyleYaml, precompileYaml } from './soma-precompile';
5
+ import { precompileUiModule, precompileYaml } from './soma-precompile';
6
6
 
7
7
  export interface SomaPluginOptions {
8
8
  /** UI 配置文件后缀,默认 _ui.yaml */
9
9
  uiSuffix?: string;
10
- /** 事件配置文件后缀,默认 _event.yaml */
11
- eventSuffix?: string;
12
- /** 样式配置文件后缀,默认 _style.yaml */
13
- styleSuffix?: string;
14
10
  }
15
11
 
16
12
  /**
@@ -20,9 +16,8 @@ export interface SomaPluginOptions {
20
16
  * 移到构建时完成。运行时直接 import 得到已解析的对象。
21
17
  *
22
18
  * 覆盖范围:
23
- * - `_ui.yaml` → UiConfig 对象(parseUiConfig 预编译)
24
- * - `_event.yaml` → ParsedEvent[] 数组(parseEventConfig 预编译)
25
- * - `_style.yaml` → StyleConfig 对象(parseStyleConfig 预编译)
19
+ * - `_ui.yaml` → 校验统一声明容器并导出 null(页面级 manifest 结合 HTML 编译)
20
+ * - 页面事件、样式、数据侧车 → 明确拒绝
26
21
  * - `locale.yaml` → Record<string, unknown>
27
22
  * - `*.config.yaml` → 任意配置对象
28
23
  * - 其他 `.yaml` → 通用 YAML → JS 对象
@@ -39,8 +34,6 @@ export interface SomaPluginOptions {
39
34
  */
40
35
  export function somaPlugin(options: SomaPluginOptions = {}): Plugin {
41
36
  const uiSuffix = options.uiSuffix ?? '_ui.yaml';
42
- const eventSuffix = options.eventSuffix ?? '_event.yaml';
43
- const styleSuffix = options.styleSuffix ?? '_style.yaml';
44
37
 
45
38
  return {
46
39
  name: 'vite-plugin-soma',
@@ -54,20 +47,15 @@ export function somaPlugin(options: SomaPluginOptions = {}): Plugin {
54
47
  try {
55
48
  // SOMA UI 配置
56
49
  if (id.endsWith(uiSuffix)) {
57
- const compiled = precompileUiYaml(code);
50
+ const compiled = precompileUiModule(code);
58
51
  return { code: `export default ${compiled};`, map: null };
59
52
  }
60
53
 
61
- // SOMA Event 配置
62
- if (id.endsWith(eventSuffix)) {
63
- const compiled = precompileEventYaml(code);
64
- return { code: `export default ${compiled};`, map: null };
65
- }
66
-
67
- // SOMA Style 配置
68
- if (id.endsWith(styleSuffix)) {
69
- const compiled = precompileStyleYaml(code);
70
- return { code: `export default ${compiled};`, map: null };
54
+ if (/_((event)|(style)|(data))\.ya?ml$/.test(id)) {
55
+ this.error(
56
+ `[vite-plugin-soma] 页面侧车已退役 (${id}):`
57
+ + '事件、样式状态与数据对象必须并入同一份 SOMA DSL 声明',
58
+ );
71
59
  }
72
60
 
73
61
  // 通用 YAML(locale、app.config 等)
@@ -0,0 +1,58 @@
1
+ // 固定目录 → 完整组件包(一步到位的接入路径)。
2
+ //
3
+ // loadComponentPackages 只给 { 组件名: 定义 },样式还要宿主自己接线——
4
+ // 而"装了库还要手动接 CSS"正是组件包体系要消灭的老路。本模块把扫描出来的
5
+ // style.css 一并装进 pack.styles.components,交出的东西可以直接喂
6
+ // composeComponentPacks,宿主接线是一行。
7
+ //
8
+ // 顺带闭合一条质量链路:CSS 落在 pack.styles 上之后,verifyComponentPack 的
9
+ // 颜色纪律与逻辑属性检查自动覆盖它——文件态组件与 TS 组件受同一把尺子。
10
+ //
11
+ // 运行环境:本模块用 node:fs,只能在构建期/服务端跑。宿主 bootstrap 会被打进
12
+ // 客户端 bundle,不要在那里直接调用;见接入指南"自动扫描"一节的构建期产物写法。
13
+
14
+ import type { SomaComponentPack } from '../../client/component/component-pack';
15
+ import {
16
+ scanComponentPackages,
17
+ type LoadPackagesOptions,
18
+ } from './package-loader';
19
+
20
+ export interface LoadPackFromDirOptions extends LoadPackagesOptions {
21
+ /** 包标识:小写字母/数字/连字符 */
22
+ name: string;
23
+ version: string;
24
+ meta?: SomaComponentPack['meta'];
25
+ /** 并进组件目录的写作规范补充(可选) */
26
+ catalogConventions?: string;
27
+ }
28
+
29
+ /**
30
+ * 扫描固定目录,产出可直接参与合成的组件包。
31
+ *
32
+ * 文件态只产组件私有分片(styles.components)——共享分片与包基座需要跨组件的
33
+ * 设计决策,仍属 TS 形态组件包的能力,不在目录约定里猜。
34
+ */
35
+ export function loadComponentPackFromDir(
36
+ rootDir: string,
37
+ options: LoadPackFromDirOptions,
38
+ ): SomaComponentPack {
39
+ const { name, version, meta, catalogConventions, ...scanOptions } = options;
40
+ const entries = scanComponentPackages(rootDir, scanOptions);
41
+
42
+ const components: SomaComponentPack['components'] = {};
43
+ const componentStyles: Record<string, string> = {};
44
+
45
+ for (const entry of entries) {
46
+ const componentName = entry.definition.contract.name;
47
+ components[componentName] = entry.definition;
48
+ if (entry.css) componentStyles[componentName] = entry.css;
49
+ }
50
+
51
+ const pack: SomaComponentPack = { name, version, components };
52
+ if (Object.keys(componentStyles).length > 0) {
53
+ pack.styles = { components: componentStyles };
54
+ }
55
+ if (catalogConventions) pack.catalogConventions = catalogConventions;
56
+ if (meta) pack.meta = meta;
57
+ return pack;
58
+ }
@@ -0,0 +1,281 @@
1
+ // 组件包文件态加载器(P1 尾款,契约规范第 1/12 章):
2
+ //
3
+ // components/qty-stepper/
4
+ // contract.yaml 必需(唯一事实源)
5
+ // template.html 必需
6
+ // ui.yaml 可选(内部绑定,作用域根 p/ctrl)
7
+ // event.yaml 可选(内部事件 Pipeline)
8
+ // style.css 可选(按需装配:首次实例化才注入)
9
+ //
10
+ // 装载为 SomaComponentDefinition,供 Host bootstrap 注册。声明式组件(无控制器)
11
+ // 可全文件态交付——这是"AI 自产组件落盘即用"生长层的文件通道;
12
+ // 需要控制器逻辑的组件仍用 TS 形态(controllerFactory)。
13
+ //
14
+ // 一条与合成层同源的默认值:**同一次扫描里组件名撞车直接抛错**并点名两个目录。
15
+ // 后者静默胜出会让"页面用的是哪个组件"只能靠 readdir 顺序猜——那正是
16
+ // composeComponentPacks 拒绝的东西,扫描层没有理由更宽松。
17
+
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import yaml from 'js-yaml';
21
+ import { parseUiConfig } from '../../client/parser/ui-config-parser';
22
+ import { parseEventConfig } from '../../client/parser/pipeline-parser';
23
+ import {
24
+ findNestedMutableContractDefault,
25
+ type SomaComponentContract,
26
+ } from '../../shared/types/component-contract.types';
27
+ import type { SomaComponentDefinition } from '../../client/component/component-definition.types';
28
+
29
+ export class SomaComponentPackageError extends Error {
30
+ constructor(message: string, readonly packageDir: string) {
31
+ super(`[SomaComponentPackage] ${message}(组件包: ${packageDir})`);
32
+ this.name = 'SomaComponentPackageError';
33
+ }
34
+ }
35
+
36
+ const LAYERS = new Set(['atom', 'composite', 'solution', 'template']);
37
+ const LAYER_LIST = 'atom|composite|solution|template';
38
+ /** 包名/覆盖目标包名:与合成层 PACK_NAME_PATTERN 同一把尺子(此处不 import,避免 build 层依赖 client 层导出) */
39
+ const PACK_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
40
+
41
+ /** 扫描期的软问题:不阻断装载,但必须让人看见(都是"不报错但坏掉"的前兆) */
42
+ export interface PackScanWarning {
43
+ kind: 'page-style-filename' | 'dir-name-mismatch';
44
+ packageDir: string;
45
+ message: string;
46
+ }
47
+
48
+ export interface LoadPackagesOptions {
49
+ /**
50
+ * 警告汇总回调(缺省时汇总为单块 console.warn)。
51
+ * 刻意做成"扫描结束一次性给全部"而不是逐条打印:dev 服务器的滚动输出里,
52
+ * 逐条 warn 与"没打印"的实际效果差不多。
53
+ */
54
+ onWarning?: (warnings: PackScanWarning[]) => void;
55
+ }
56
+
57
+ /** 单目录装载的完整产物(内部形态:definition 之外还带样式与警告) */
58
+ interface PackageEntry {
59
+ definition: SomaComponentDefinition;
60
+ /** style.css 内容;无文件或空文件为 null */
61
+ css: string | null;
62
+ warnings: PackScanWarning[];
63
+ packageDir: string;
64
+ }
65
+
66
+ /** 装载单个组件包目录 → 运行时定义(结构校验 fail fast) */
67
+ export function loadComponentPackage(packageDir: string): SomaComponentDefinition {
68
+ return loadComponentPackageEntry(packageDir).definition;
69
+ }
70
+
71
+ /** 装载单个组件包目录 → 定义 + 样式 + 警告(供整包装载复用) */
72
+ export function loadComponentPackageEntry(packageDir: string): PackageEntry {
73
+ const contractPath = path.join(packageDir, 'contract.yaml');
74
+ const templatePath = path.join(packageDir, 'template.html');
75
+
76
+ if (!fs.existsSync(contractPath)) {
77
+ throw new SomaComponentPackageError('缺少 contract.yaml', packageDir);
78
+ }
79
+ if (!fs.existsSync(templatePath)) {
80
+ throw new SomaComponentPackageError('缺少 template.html', packageDir);
81
+ }
82
+
83
+ const rawContract = yaml.load(fs.readFileSync(contractPath, 'utf-8'));
84
+ const contract = validateContract(rawContract, packageDir);
85
+
86
+ const templateHtml = fs.readFileSync(templatePath, 'utf-8').trim();
87
+ if (!templateHtml) {
88
+ throw new SomaComponentPackageError('template.html 为空', packageDir);
89
+ }
90
+
91
+ const definition: SomaComponentDefinition = { contract, templateHtml };
92
+
93
+ const uiPath = path.join(packageDir, 'ui.yaml');
94
+ if (fs.existsSync(uiPath)) {
95
+ try {
96
+ definition.uiConfig = parseUiConfig(yaml.load(fs.readFileSync(uiPath, 'utf-8')));
97
+ } catch (error) {
98
+ throw new SomaComponentPackageError(`ui.yaml 非法: ${(error as Error).message}`, packageDir);
99
+ }
100
+ }
101
+
102
+ const eventPath = path.join(packageDir, 'event.yaml');
103
+ if (fs.existsSync(eventPath)) {
104
+ try {
105
+ const rawEvents = yaml.load(fs.readFileSync(eventPath, 'utf-8'));
106
+ definition.eventConfig = parseEventConfig((rawEvents ?? {}) as Record<string, never>);
107
+ } catch (error) {
108
+ throw new SomaComponentPackageError(`event.yaml 非法: ${(error as Error).message}`, packageDir);
109
+ }
110
+ }
111
+
112
+ const servicesRaw = (rawContract as { autonomous?: { services?: unknown } })?.autonomous?.services;
113
+ if (Array.isArray(servicesRaw)) {
114
+ definition.services = servicesRaw.map(String);
115
+ }
116
+
117
+ const stylePath = path.join(packageDir, 'style.css');
118
+ let css: string | null = null;
119
+ if (fs.existsSync(stylePath)) {
120
+ const raw = fs.readFileSync(stylePath, 'utf-8').trim();
121
+ css = raw ? raw : null;
122
+ }
123
+
124
+ return { definition, css, warnings: collectWarnings(packageDir, contract), packageDir };
125
+ }
126
+
127
+ /**
128
+ * 扫描根目录下的全部组件包(含 contract.yaml 的一级子目录)。
129
+ *
130
+ * 组件名撞车抛错并点名两个目录——扫描层与合成层同一条纪律。
131
+ */
132
+ export function loadComponentPackages(
133
+ rootDir: string,
134
+ options: LoadPackagesOptions = {},
135
+ ): Record<string, SomaComponentDefinition> {
136
+ const entries = scanComponentPackages(rootDir, options);
137
+ const result: Record<string, SomaComponentDefinition> = {};
138
+ for (const entry of entries) {
139
+ result[entry.definition.contract.name] = entry.definition;
140
+ }
141
+ return result;
142
+ }
143
+
144
+ /** 扫描并返回完整条目(定义 + 样式 + 目录),整包装载与按需样式装配的共同入口 */
145
+ export function scanComponentPackages(
146
+ rootDir: string,
147
+ options: LoadPackagesOptions = {},
148
+ ): PackageEntry[] {
149
+ if (!fs.existsSync(rootDir)) {
150
+ return [];
151
+ }
152
+ const entries: PackageEntry[] = [];
153
+ const seenDirs: Record<string, string> = {};
154
+ const warnings: PackScanWarning[] = [];
155
+
156
+ for (const dirent of fs.readdirSync(rootDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
157
+ if (!dirent.isDirectory()) continue;
158
+ const dir = path.join(rootDir, dirent.name);
159
+ if (!fs.existsSync(path.join(dir, 'contract.yaml'))) continue;
160
+
161
+ const entry = loadComponentPackageEntry(dir);
162
+ const name = entry.definition.contract.name;
163
+ const firstDir = seenDirs[name];
164
+ if (firstDir !== undefined) {
165
+ throw new SomaComponentPackageError(
166
+ `组件名冲突:"${name}" 同时来自 "${firstDir}" 与 "${dir}"。`
167
+ + '\n 同一目录下的两个组件包不存在合理的胜者——请改掉其中一个的契约 name。'
168
+ + '\n (跨包覆盖是另一回事:在契约上写 overrides: <被覆盖的包名>)',
169
+ dir,
170
+ );
171
+ }
172
+ seenDirs[name] = dir;
173
+ warnings.push(...entry.warnings);
174
+ entries.push(entry);
175
+ }
176
+
177
+ reportWarnings(rootDir, entries.length, warnings, options.onWarning);
178
+ return entries;
179
+ }
180
+
181
+ /** 一次性汇总输出:逐条 warn 会淹没在 dev 服务器的滚动输出里 */
182
+ function reportWarnings(
183
+ rootDir: string,
184
+ packageCount: number,
185
+ warnings: PackScanWarning[],
186
+ onWarning?: (warnings: PackScanWarning[]) => void,
187
+ ): void {
188
+ if (onWarning) {
189
+ onWarning(warnings);
190
+ return;
191
+ }
192
+ if (warnings.length === 0) return;
193
+ const lines = warnings.map((warning) => ` · ${warning.message}`);
194
+ // 构建期/终端面向的日志,前缀按命令名走(与 core/build 下 `[soma db]` 同款约定)
195
+ // eslint-disable-next-line no-console
196
+ console.warn(
197
+ `[soma 组件扫描] ${rootDir}:${packageCount} 个组件,${warnings.length} 条警告\n${lines.join('\n')}`,
198
+ );
199
+ }
200
+
201
+ /** 目录级软问题:文件名写成页面四件套、目录名与组件名对不上 */
202
+ function collectWarnings(packageDir: string, contract: SomaComponentContract): PackScanWarning[] {
203
+ const warnings: PackScanWarning[] = [];
204
+
205
+ for (const [pageStyle, expected] of [['_ui.yaml', 'ui.yaml'], ['_event.yaml', 'event.yaml']] as const) {
206
+ if (fs.existsSync(path.join(packageDir, pageStyle))) {
207
+ warnings.push({
208
+ kind: 'page-style-filename',
209
+ packageDir,
210
+ message: `${packageDir} 里有 ${pageStyle}——组件内部声明的文件名是 ${expected}(不带下划线),`
211
+ + '当前这份不会被装载',
212
+ });
213
+ }
214
+ }
215
+
216
+ const dirName = path.basename(packageDir);
217
+ if (dirName && toKebabCase(contract.name) !== dirName) {
218
+ warnings.push({
219
+ kind: 'dir-name-mismatch',
220
+ packageDir,
221
+ message: `${packageDir} 的目录名与契约 name "${contract.name}" 对不上`
222
+ + `(建议目录名 ${toKebabCase(contract.name)})——不一致时按名字找组件只能靠 grep`,
223
+ });
224
+ }
225
+ return warnings;
226
+ }
227
+
228
+ function toKebabCase(name: string): string {
229
+ return name
230
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
231
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
232
+ .toLowerCase();
233
+ }
234
+
235
+ function validateContract(raw: unknown, packageDir: string): SomaComponentContract {
236
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
237
+ throw new SomaComponentPackageError('contract.yaml 必须是对象', packageDir);
238
+ }
239
+ const contract = raw as Record<string, unknown>;
240
+
241
+ for (const field of ['name', 'layer', 'version', 'description'] as const) {
242
+ if (typeof contract[field] !== 'string' || !contract[field]) {
243
+ throw new SomaComponentPackageError(`契约缺少必填字段 ${field}`, packageDir);
244
+ }
245
+ }
246
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(String(contract.name))) {
247
+ throw new SomaComponentPackageError(`契约 name "${contract.name}" 必须是 PascalCase`, packageDir);
248
+ }
249
+ if (!LAYERS.has(String(contract.layer))) {
250
+ throw new SomaComponentPackageError(`契约 layer "${contract.layer}" 非法(${LAYER_LIST})`, packageDir);
251
+ }
252
+ if (contract.overrides !== undefined) {
253
+ if (typeof contract.overrides !== 'string' || !PACK_NAME_PATTERN.test(contract.overrides)) {
254
+ throw new SomaComponentPackageError(
255
+ `契约 overrides "${String(contract.overrides)}" 必须是包名([a-z][a-z0-9-]*),`
256
+ + '值写被覆盖组件的来源包名,如 soma-ui',
257
+ packageDir,
258
+ );
259
+ }
260
+ }
261
+
262
+ // C1/C4:props 需 desc;可选 prop 必须有 default
263
+ for (const [propName, propRaw] of Object.entries((contract.props as Record<string, unknown>) ?? {})) {
264
+ const prop = propRaw as Record<string, unknown> | null;
265
+ if (!prop || typeof prop !== 'object' || typeof prop.type !== 'string') {
266
+ throw new SomaComponentPackageError(`prop "${propName}" 缺少 type`, packageDir);
267
+ }
268
+ if (prop.required !== true && prop.default === undefined) {
269
+ throw new SomaComponentPackageError(`可选 prop "${propName}" 缺少 default(契约规则 C4)`, packageDir);
270
+ }
271
+ const nestedMutablePath = findNestedMutableContractDefault(prop.default);
272
+ if (nestedMutablePath) {
273
+ throw new SomaComponentPackageError(
274
+ `prop "${propName}" default.${nestedMutablePath} 是嵌套可变默认值(契约规则 C4a)`,
275
+ packageDir,
276
+ );
277
+ }
278
+ }
279
+
280
+ return contract as unknown as SomaComponentContract;
281
+ }
@@ -0,0 +1,133 @@
1
+ // 固化的落盘与回滚。
2
+ //
3
+ // 固化最危险的失败不是"没写成",而是**写了一半**:三个文件写进去、第四个撞了名字,
4
+ // 宿主目录从此半新半旧,而 git status 里躺着一堆看不出来历的文件。
5
+ // 所以这里的顺序是死的:
6
+ // 1. 全部目标路径先查一遍冲突(默认撞名即整体中止,不写任何一个字节);
7
+ // 2. 一次性写完;
8
+ // 3. 调用方跑校验(测试/构建),不过就调 rollback —— 把这次写的**全部**删掉,
9
+ // 连中途建出来的空目录也一并清理。
10
+ //
11
+ // 回滚只删这次新建的东西:覆盖模式下被改写的既有文件会先备份、回滚时按原样还回去。
12
+ // 换句话说,固化失败之后,宿主目录应当与固化之前一字不差。
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import type { EjectFile, EjectPlan } from './plan-eject';
17
+
18
+ export class EjectApplyError extends Error {}
19
+
20
+ export interface ApplyEjectOptions {
21
+ /** 宿主根目录 */
22
+ hostDir: string;
23
+ /** 覆盖既有文件(默认 false:撞名即整体中止) */
24
+ force?: boolean;
25
+ }
26
+
27
+ export interface EjectApplyResult {
28
+ /** 实际写入的文件(相对宿主根) */
29
+ written: string[];
30
+ /** 被覆盖的既有文件(force 模式下才可能非空) */
31
+ overwritten: string[];
32
+ /** 撤销这次固化:新建的删掉、覆盖的还原、空目录清理 */
33
+ rollback(): void;
34
+ }
35
+
36
+ interface Backup {
37
+ absolute: string;
38
+ /** 既有内容;新建文件为 null */
39
+ previous: string | null;
40
+ /** 为写这个文件而新建的目录(从深到浅),回滚时逐个尝试删除 */
41
+ createdDirs: string[];
42
+ }
43
+
44
+ function conflictsOf(plan: EjectPlan, hostDir: string): string[] {
45
+ return plan.files
46
+ .filter((file) => fs.existsSync(path.join(hostDir, file.path)))
47
+ .map((file) => file.path);
48
+ }
49
+
50
+ /** 建目录并记下"这次新建了哪些层",供回滚清理 */
51
+ function ensureDir(dir: string): string[] {
52
+ const created: string[] = [];
53
+ let current = dir;
54
+ const missing: string[] = [];
55
+ while (!fs.existsSync(current)) {
56
+ missing.push(current);
57
+ const parent = path.dirname(current);
58
+ if (parent === current) break;
59
+ current = parent;
60
+ }
61
+ for (const target of [...missing].reverse()) {
62
+ fs.mkdirSync(target);
63
+ created.push(target);
64
+ }
65
+ return created.reverse();
66
+ }
67
+
68
+ /**
69
+ * 落盘一个固化计划。返回句柄带 rollback——校验不过时调它,
70
+ * 宿主目录回到固化之前的样子。
71
+ */
72
+ export function applyEject(plan: EjectPlan, options: ApplyEjectOptions): EjectApplyResult {
73
+ const hostDir = path.resolve(options.hostDir);
74
+ if (!fs.existsSync(hostDir)) {
75
+ throw new EjectApplyError(`宿主目录不存在:${hostDir}`);
76
+ }
77
+ const conflicts = conflictsOf(plan, hostDir);
78
+ if (conflicts.length > 0 && !options.force) {
79
+ throw new EjectApplyError(
80
+ `以下文件已存在,拒绝固化(不覆盖是默认行为,确认要盖再加 --force):\n ${conflicts.join('\n ')}`,
81
+ );
82
+ }
83
+
84
+ const backups: Backup[] = [];
85
+ const written: string[] = [];
86
+ const overwritten: string[] = [];
87
+
88
+ const undo = (): void => {
89
+ // 逆序还原:先写的后撤,目录清理才不会被后写的文件挡住
90
+ for (const backup of [...backups].reverse()) {
91
+ try {
92
+ if (backup.previous === null) {
93
+ fs.rmSync(backup.absolute, { force: true });
94
+ } else {
95
+ fs.writeFileSync(backup.absolute, backup.previous, 'utf8');
96
+ }
97
+ for (const dir of backup.createdDirs) {
98
+ try {
99
+ fs.rmdirSync(dir);
100
+ } catch {
101
+ // 目录非空(别的东西也在用)就留着——回滚只撤自己造的
102
+ }
103
+ }
104
+ } catch {
105
+ // 单个文件撤不掉不该让整个回滚停下;剩下的继续撤
106
+ }
107
+ }
108
+ };
109
+
110
+ try {
111
+ for (const file of plan.files as EjectFile[]) {
112
+ const absolute = path.join(hostDir, file.path);
113
+ const createdDirs = ensureDir(path.dirname(absolute));
114
+ const existed = fs.existsSync(absolute);
115
+ backups.push({
116
+ absolute,
117
+ previous: existed ? fs.readFileSync(absolute, 'utf8') : null,
118
+ createdDirs,
119
+ });
120
+ fs.writeFileSync(absolute, file.contents, 'utf8');
121
+ written.push(file.path);
122
+ if (existed) overwritten.push(file.path);
123
+ }
124
+ } catch (error) {
125
+ // 写到一半炸了:立刻撤干净再抛。半新半旧的宿主目录比失败本身更难收拾。
126
+ undo();
127
+ throw error instanceof Error
128
+ ? new EjectApplyError(`固化写入失败,已回滚:${error.message}`)
129
+ : new EjectApplyError('固化写入失败,已回滚');
130
+ }
131
+
132
+ return { written, overwritten, rollback: undo };
133
+ }