soma-core 1.0.0 → 1.0.2

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 (228) hide show
  1. package/app/SomaPageClient.tsx +336 -0
  2. package/app/api/[...path]/route.ts +77 -0
  3. package/app/api/page/route.ts +18 -16
  4. package/app/api/soma-manifest/route.ts +39 -0
  5. package/app/components/SomaHydrationShell.tsx +23 -0
  6. package/app/layout.tsx +2 -2
  7. package/app/loading.tsx +5 -0
  8. package/app/page.tsx +19 -128
  9. package/bin/soma-lsp.cjs +195 -0
  10. package/bin/soma-sync.cjs +3 -0
  11. package/bin/soma.cjs +13 -1
  12. package/core/api/IService.ts +29 -0
  13. package/core/api/load-host-service.ts +72 -0
  14. package/core/api/service-path.ts +39 -0
  15. package/core/base/SomaEntity.ts +3 -10
  16. package/core/base/SomaLocaleOnlyPageRoot.ts +3 -4
  17. package/core/base/SomaPageRootBase.ts +20 -3
  18. package/core/base/decorators/Event.ts +23 -0
  19. package/core/base/decorators/Locale.ts +35 -0
  20. package/core/base/decorators/Page.ts +16 -0
  21. package/core/base/decorators/Show.ts +20 -0
  22. package/core/base/decorators/ShowList.ts +34 -0
  23. package/core/base/decorators/index.ts +5 -0
  24. package/core/base/index.ts +2 -0
  25. package/core/base/runAsync.ts +32 -0
  26. package/core/compiler/full-manifest-builder.ts +33 -7
  27. package/core/compiler/host-config-sync.cjs +38 -0
  28. package/core/compiler/manifest-compiler.ts +3 -2
  29. package/core/compiler/page-base-resolver.ts +23 -0
  30. package/core/compiler/precompiled-manifest-loader.ts +34 -0
  31. package/core/compiler/rollup-plugin-soma.ts +45 -0
  32. package/core/compiler/rspack-plugin-soma.js +33 -0
  33. package/core/compiler/soma-manifest-webpack-plugin.js +72 -0
  34. package/core/compiler/soma-precompile.js +3513 -0
  35. package/core/compiler/soma-precompile.ts +52 -6
  36. package/core/compiler/soma-rspack-yaml-loader.js +22 -0
  37. package/core/compiler/soma-webpack-loader.js +7 -1
  38. package/core/compiler/vite-plugin-soma.ts +11 -1
  39. package/core/container/IContainerAdapter.ts +36 -0
  40. package/core/container/MiniProgramContainerAdapter.ts +190 -0
  41. package/core/container/ReactNativeContainerAdapter.ts +189 -0
  42. package/core/container/SomaContainerAdapter.ts +17 -6
  43. package/core/diagnostics/SomaDiagnostics.ts +1 -1
  44. package/core/diagnostics/SomaTelemetry.ts +100 -0
  45. package/core/diagnostics/telemetry-context.ts +15 -0
  46. package/core/engine/asset-resolver.ts +39 -4
  47. package/core/engine/dom-renderer.ts +9 -11
  48. package/core/engine/event-engine.ts +110 -41
  49. package/core/engine/on-change-engine.ts +71 -0
  50. package/core/engine/property-watcher.ts +117 -0
  51. package/core/engine/reactive-proxy.ts +11 -5
  52. package/core/engine/render-engine.ts +97 -11
  53. package/core/engine/runtime-builder.ts +88 -11
  54. package/core/engine/scope-resolver.ts +65 -9
  55. package/core/engine/soma-bootstrap.ts +448 -244
  56. package/core/engine/style-binder.ts +423 -0
  57. package/core/engine/theme-variables.ts +37 -0
  58. package/core/engine/timer-engine.ts +92 -0
  59. package/core/engine/trigger-engine.ts +55 -0
  60. package/core/host/resolve-host-bootstrap.ts +28 -0
  61. package/core/host/soma-bootstrap-host.stub.ts +4 -0
  62. package/core/index.ts +40 -6
  63. package/core/infra/auth/TokenAuthService.ts +17 -3
  64. package/core/infra/http/IHttpClient.ts +11 -1
  65. package/core/infra/http/SomaHttpService.ts +89 -31
  66. package/core/infra/i18n/DefaultI18n.ts +6 -18
  67. package/core/infra/i18n/II18n.ts +2 -3
  68. package/core/infra/notify/DomNotifyService.ts +98 -0
  69. package/core/infra/notify/INotifyTheme.ts +22 -0
  70. package/core/infra/realtime/IRealtimeService.ts +23 -0
  71. package/core/infra/realtime/IRealtimeTransport.ts +9 -0
  72. package/core/infra/realtime/SomaRealtimeService.ts +95 -0
  73. package/core/infra/realtime/SseRealtimeTransport.ts +36 -0
  74. package/core/infra/realtime/WebSocketRealtimeTransport.ts +102 -0
  75. package/core/infra/router/router-path.ts +28 -0
  76. package/core/infra/storage/SessionStorageService.ts +59 -0
  77. package/core/lsp/cross-file-diagnostics.cjs +160 -0
  78. package/core/lsp/event-yaml-completion.cjs +106 -0
  79. package/core/lsp/extra-completion.cjs +64 -0
  80. package/core/lsp/lsp-navigation.cjs +191 -0
  81. package/core/lsp/ui-yaml-completion.cjs +170 -0
  82. package/core/manifest/manifest-contract.ts +12 -0
  83. package/core/middleware/createPermissionMiddleware.ts +37 -0
  84. package/core/parser/annotation-extractor.ts +113 -0
  85. package/core/parser/pipeline-parser.ts +344 -276
  86. package/core/parser/style-config-parser.ts +340 -0
  87. package/core/parser/timer-parser.ts +70 -0
  88. package/core/parser/trigger-parser.ts +90 -0
  89. package/core/parser/ui-config-parser.ts +73 -1
  90. package/core/quality/SomaQualityRegistry.ts +68 -0
  91. package/core/runtime/SomaRuntimeServices.ts +100 -0
  92. package/core/runtime/SomaSnapshotStore.ts +5 -3
  93. package/core/types/domain.types.ts +5 -2
  94. package/core/types/event.types.ts +82 -57
  95. package/core/types/manifest.types.ts +2 -0
  96. package/core/types/style-config.types.ts +76 -0
  97. package/core/types/timer.types.ts +23 -0
  98. package/core/types/trigger.types.ts +14 -0
  99. package/core/types/ui-config.types.ts +9 -0
  100. package/core/types/watcher.types.ts +29 -0
  101. package/core/validation/contract-validator.ts +465 -465
  102. package/dist/cli/soma.js +23 -23
  103. package/dist/core/index.cjs +8968 -0
  104. package/dist/diagnostics/telemetry.cjs +105 -0
  105. package/dist/preview-export.cjs +3401 -0
  106. package/dist/tsconfig.types.tsbuildinfo +1 -0
  107. package/dist/types/api/IService.d.ts +28 -0
  108. package/dist/types/api/load-host-service.d.ts +5 -0
  109. package/dist/types/api/service-path.d.ts +13 -0
  110. package/dist/types/base/SomaApi.d.ts +5 -0
  111. package/dist/types/base/SomaDict.d.ts +89 -0
  112. package/dist/types/base/SomaEntity.d.ts +15 -0
  113. package/dist/types/base/SomaHttpClient.d.ts +66 -0
  114. package/dist/types/base/SomaLocaleOnlyPageRoot.d.ts +3 -0
  115. package/dist/types/base/SomaPageRootBase.d.ts +49 -0
  116. package/dist/types/base/SomaValidator.d.ts +55 -0
  117. package/dist/types/base/decorators/Event.d.ts +10 -0
  118. package/dist/types/base/decorators/Locale.d.ts +9 -0
  119. package/dist/types/base/decorators/Page.d.ts +4 -0
  120. package/dist/types/base/decorators/Show.d.ts +7 -0
  121. package/dist/types/base/decorators/ShowList.d.ts +12 -0
  122. package/dist/types/base/decorators/index.d.ts +5 -0
  123. package/dist/types/base/index.d.ts +9 -0
  124. package/dist/types/base/runAsync.d.ts +12 -0
  125. package/dist/types/compiler/full-manifest-builder.d.ts +35 -0
  126. package/dist/types/compiler/manifest-compiler.d.ts +29 -0
  127. package/dist/types/compiler/page-base-resolver.d.ts +6 -0
  128. package/dist/types/compiler/precompiled-manifest-loader.d.ts +5 -0
  129. package/dist/types/compiler/rollup-plugin-soma.d.ts +14 -0
  130. package/dist/types/compiler/route-builder.d.ts +12 -0
  131. package/dist/types/compiler/soma-precompile.d.ts +40 -0
  132. package/dist/types/compiler/vite-plugin-soma.d.ts +34 -0
  133. package/dist/types/container/IContainerAdapter.d.ts +30 -0
  134. package/dist/types/container/MiniProgramContainerAdapter.d.ts +52 -0
  135. package/dist/types/container/ReactNativeContainerAdapter.d.ts +47 -0
  136. package/dist/types/container/SomaContainerAdapter.d.ts +30 -0
  137. package/dist/types/diagnostics/SomaDiagnostics.d.ts +64 -0
  138. package/dist/types/diagnostics/SomaTelemetry.d.ts +32 -0
  139. package/dist/types/diagnostics/telemetry-context.d.ts +4 -0
  140. package/dist/types/engine/asset-resolver.d.ts +17 -0
  141. package/dist/types/engine/dom-renderer.d.ts +35 -0
  142. package/dist/types/engine/event-engine.d.ts +64 -0
  143. package/dist/types/engine/lis.d.ts +10 -0
  144. package/dist/types/engine/on-change-engine.d.ts +16 -0
  145. package/dist/types/engine/property-watcher.d.ts +18 -0
  146. package/dist/types/engine/reactive-proxy.d.ts +58 -0
  147. package/dist/types/engine/render-engine.d.ts +73 -0
  148. package/dist/types/engine/runtime-builder.d.ts +58 -0
  149. package/dist/types/engine/scope-resolver.d.ts +90 -0
  150. package/dist/types/engine/soma-bootstrap.d.ts +112 -0
  151. package/dist/types/engine/style-binder.d.ts +81 -0
  152. package/dist/types/engine/theme-variables.d.ts +3 -0
  153. package/dist/types/engine/timer-engine.d.ts +19 -0
  154. package/dist/types/engine/trigger-engine.d.ts +16 -0
  155. package/dist/types/host/resolve-host-bootstrap.d.ts +11 -0
  156. package/dist/types/host/soma-bootstrap-host.stub.d.ts +3 -0
  157. package/dist/types/index.d.ts +35 -0
  158. package/dist/types/infra/auth/IAuthService.d.ts +12 -0
  159. package/dist/types/infra/auth/TokenAuthService.d.ts +26 -0
  160. package/dist/types/infra/cache/ICache.d.ts +12 -0
  161. package/dist/types/infra/cache/MemoryCache.d.ts +14 -0
  162. package/dist/types/infra/cache/ServerFileCache.d.ts +37 -0
  163. package/dist/types/infra/config/IConfig.d.ts +9 -0
  164. package/dist/types/infra/config/SomaConfig.d.ts +21 -0
  165. package/dist/types/infra/event-bus/IEventBus.d.ts +8 -0
  166. package/dist/types/infra/event-bus/SomaEventBus.d.ts +9 -0
  167. package/dist/types/infra/http/IHttpClient.d.ts +28 -0
  168. package/dist/types/infra/http/SomaHttpService.d.ts +27 -0
  169. package/dist/types/infra/i18n/DefaultI18n.d.ts +7 -0
  170. package/dist/types/infra/i18n/II18n.d.ts +6 -0
  171. package/dist/types/infra/logger/ConsoleLogger.d.ts +14 -0
  172. package/dist/types/infra/logger/ILogger.d.ts +17 -0
  173. package/dist/types/infra/notify/DefaultNotifyService.d.ts +16 -0
  174. package/dist/types/infra/notify/DomNotifyService.d.ts +16 -0
  175. package/dist/types/infra/notify/INotifyService.d.ts +12 -0
  176. package/dist/types/infra/notify/INotifyTheme.d.ts +12 -0
  177. package/dist/types/infra/permission/IPermission.d.ts +10 -0
  178. package/dist/types/infra/permission/SomaPermission.d.ts +19 -0
  179. package/dist/types/infra/realtime/IRealtimeService.d.ts +13 -0
  180. package/dist/types/infra/realtime/IRealtimeTransport.d.ts +8 -0
  181. package/dist/types/infra/realtime/SomaRealtimeService.d.ts +20 -0
  182. package/dist/types/infra/realtime/SseRealtimeTransport.d.ts +11 -0
  183. package/dist/types/infra/realtime/WebSocketRealtimeTransport.d.ts +30 -0
  184. package/dist/types/infra/router/IRouter.d.ts +16 -0
  185. package/dist/types/infra/router/SomaRouter.d.ts +18 -0
  186. package/dist/types/infra/router/router-path.d.ts +6 -0
  187. package/dist/types/infra/storage/IStorageService.d.ts +7 -0
  188. package/dist/types/infra/storage/MemoryStorageService.d.ts +15 -0
  189. package/dist/types/infra/storage/SessionStorageService.d.ts +14 -0
  190. package/dist/types/infra/timer/ITimer.d.ts +13 -0
  191. package/dist/types/infra/timer/SomaTimer.d.ts +21 -0
  192. package/dist/types/manifest/manifest-contract.d.ts +4 -0
  193. package/dist/types/middleware/SomaMiddlewareChain.d.ts +6 -0
  194. package/dist/types/middleware/createPermissionMiddleware.d.ts +14 -0
  195. package/dist/types/parser/annotation-extractor.d.ts +12 -0
  196. package/dist/types/parser/pipeline-parser.d.ts +62 -0
  197. package/dist/types/parser/style-config-parser.d.ts +20 -0
  198. package/dist/types/parser/timer-parser.d.ts +6 -0
  199. package/dist/types/parser/trigger-parser.d.ts +13 -0
  200. package/dist/types/parser/ui-config-parser.d.ts +34 -0
  201. package/dist/types/parser/yaml-loader.d.ts +21 -0
  202. package/dist/types/quality/SomaQualityRegistry.d.ts +31 -0
  203. package/dist/types/runtime/SomaRuntimeServices.d.ts +35 -0
  204. package/dist/types/runtime/SomaSnapshotStore.d.ts +13 -0
  205. package/dist/types/scheduler/SomaScheduler.d.ts +25 -0
  206. package/dist/types/types/domain.types.d.ts +82 -0
  207. package/dist/types/types/engine.types.d.ts +22 -0
  208. package/dist/types/types/event.types.d.ts +61 -0
  209. package/dist/types/types/keyboard.types.d.ts +4 -0
  210. package/dist/types/types/manifest.types.d.ts +29 -0
  211. package/dist/types/types/scheduler.types.d.ts +8 -0
  212. package/dist/types/types/style-config.types.d.ts +62 -0
  213. package/dist/types/types/timer.types.d.ts +19 -0
  214. package/dist/types/types/trigger.types.d.ts +12 -0
  215. package/dist/types/types/ui-config.types.d.ts +85 -0
  216. package/dist/types/types/watcher.types.d.ts +24 -0
  217. package/dist/types/validation/contract-validator.d.ts +40 -0
  218. package/editor/vscode/extension.js +39 -0
  219. package/editor/vscode/language-configuration.json +17 -0
  220. package/editor/vscode/package.json +98 -0
  221. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +30 -0
  222. package/editor/vscode/syntaxes/soma-ui-yaml.tmLanguage.json +42 -0
  223. package/global.d.ts +19 -0
  224. package/next.config.js +9 -4
  225. package/package.json +53 -16
  226. package/tailwind.config.ts +26 -7
  227. package/tsconfig.json +6 -2
  228. package/core/router/RouteHandler.ts +0 -93
@@ -0,0 +1,100 @@
1
+ /** CSS / 编译 Telemetry 度量 — 聚合诊断与编译指标 */
2
+ export interface TelemetryMetric {
3
+ name: string;
4
+ value: number;
5
+ unit: string;
6
+ timestamp: number;
7
+ }
8
+
9
+ export interface TelemetryExportOptions {
10
+ /** 导出为 OpenTelemetry 兼容 JSON 结构 */
11
+ format?: 'json' | 'otlp';
12
+ serviceName?: string;
13
+ }
14
+
15
+ export class SomaTelemetry {
16
+ private metrics: TelemetryMetric[] = [];
17
+ private readonly maxEntries: number;
18
+
19
+ constructor(maxEntries = 500) {
20
+ this.maxEntries = maxEntries;
21
+ }
22
+
23
+ record(name: string, value: number, unit = 'ms'): void {
24
+ this.metrics.push({ name, value, unit, timestamp: Date.now() });
25
+ if (this.metrics.length > this.maxEntries) {
26
+ this.metrics.shift();
27
+ }
28
+ }
29
+
30
+ getMetrics(name?: string): TelemetryMetric[] {
31
+ return name ? this.metrics.filter((m) => m.name === name) : [...this.metrics];
32
+ }
33
+
34
+ aggregate(name: string): { count: number; avg: number; max: number; min: number } {
35
+ const items = this.getMetrics(name);
36
+ if (items.length === 0) return { count: 0, avg: 0, max: 0, min: 0 };
37
+ const values = items.map((m) => m.value);
38
+ return {
39
+ count: values.length,
40
+ avg: values.reduce((a, b) => a + b, 0) / values.length,
41
+ max: Math.max(...values),
42
+ min: Math.min(...values),
43
+ };
44
+ }
45
+
46
+ snapshot(): Record<string, ReturnType<SomaTelemetry['aggregate']>> {
47
+ const names = [...new Set(this.metrics.map((m) => m.name))];
48
+ const result: Record<string, ReturnType<SomaTelemetry['aggregate']>> = {};
49
+ for (const n of names) result[n] = this.aggregate(n);
50
+ return result;
51
+ }
52
+
53
+ /** 导出原始指标 JSON */
54
+ exportJson(): string {
55
+ return JSON.stringify(
56
+ {
57
+ exportedAt: new Date().toISOString(),
58
+ metrics: this.metrics,
59
+ aggregates: this.snapshot(),
60
+ },
61
+ null,
62
+ 2,
63
+ );
64
+ }
65
+
66
+ /** 导出 OpenTelemetry 兼容 metrics 结构(简化版) */
67
+ exportOpenTelemetry(options: TelemetryExportOptions = {}): string {
68
+ const serviceName = options.serviceName ?? 'soma-runtime';
69
+ const resourceMetrics = {
70
+ resource: { attributes: [{ key: 'service.name', value: { stringValue: serviceName } }] },
71
+ scopeMetrics: [{
72
+ scope: { name: 'soma.telemetry' },
73
+ metrics: Object.entries(this.snapshot()).map(([name, stats]) => ({
74
+ name,
75
+ unit: 'ms',
76
+ summary: {
77
+ count: stats.count,
78
+ sum: stats.avg * stats.count,
79
+ quantileValues: [
80
+ { quantile: 0.5, value: stats.avg },
81
+ { quantile: 1, value: stats.max },
82
+ ],
83
+ },
84
+ })),
85
+ }],
86
+ };
87
+
88
+ return JSON.stringify({ resourceMetrics: [resourceMetrics] }, null, 2);
89
+ }
90
+
91
+ /** POST 到自定义 endpoint(浏览器 / Node fetch) */
92
+ async report(endpoint: string, format: 'json' | 'otlp' = 'json'): Promise<void> {
93
+ const body = format === 'otlp' ? this.exportOpenTelemetry() : this.exportJson();
94
+ await fetch(endpoint, {
95
+ method: 'POST',
96
+ headers: { 'Content-Type': 'application/json' },
97
+ body,
98
+ });
99
+ }
100
+ }
@@ -0,0 +1,15 @@
1
+ import type { SomaTelemetry } from './SomaTelemetry';
2
+
3
+ let active: SomaTelemetry | null = null;
4
+
5
+ export function setActiveTelemetry(telemetry: SomaTelemetry | null): void {
6
+ active = telemetry;
7
+ }
8
+
9
+ export function getActiveTelemetry(): SomaTelemetry | null {
10
+ return active;
11
+ }
12
+
13
+ export function recordMetric(name: string, value: number, unit = 'ms'): void {
14
+ active?.record(name, value, unit);
15
+ }
@@ -5,7 +5,12 @@ import yaml from 'js-yaml';
5
5
  import type { ICache } from '../infra/cache/ICache';
6
6
  import { MemoryCache } from '../infra/cache/MemoryCache';
7
7
  import { parseEventConfig } from '../parser/pipeline-parser';
8
+ import { splitEventConfigRaw } from '../parser/trigger-parser';
9
+ import { parseStyleConfig } from '../parser/style-config-parser';
8
10
  import { parseUiConfig } from '../parser/ui-config-parser';
11
+ import type { PropertyTrigger } from '../types/trigger.types';
12
+ import { extractConfigFromDomainClass } from '../parser/annotation-extractor';
13
+ import { hasPageMetadata } from '../base/decorators/Page';
9
14
  import type { SomaPageAssets, ParsedRuntimeAssets } from './soma-bootstrap';
10
15
 
11
16
  /**
@@ -28,25 +33,48 @@ export class SomaAssetResolver {
28
33
  return {
29
34
  uiConfig: assets.uiConfig,
30
35
  eventConfig: assets.eventConfig,
36
+ triggers: assets.triggerConfig ?? [],
37
+ timers: assets.timerConfig ?? [],
38
+ styleConfig: assets.styleConfig ?? this.parseStyleConfig(assets.styleYaml),
31
39
  locale: assets.locale ?? this.parseLocale(assets.localeYaml),
32
40
  appConfig: assets.appConfig ?? this.parseAppConfig(assets.appConfigYaml),
33
41
  };
34
42
  }
35
43
 
36
44
  // 字符串模式:运行时解析,带缓存
37
- const uiYaml = assets.uiYaml!;
38
- const eventYaml = assets.eventYaml!;
45
+ const uiYaml = assets.uiYaml ?? '';
46
+ const eventYaml = assets.eventYaml ?? '';
39
47
  const localeYaml = assets.localeYaml ?? '';
40
48
 
41
- const cacheKey = `${uiYaml}\0${eventYaml}\0${localeYaml}\0${assets.appConfigYaml ?? ''}`;
49
+ // 注解模式:无 YAML 时从 Domain Class 装饰器提取配置
50
+ if (!uiYaml.trim() && assets.DomainClass && hasPageMetadata(assets.DomainClass)) {
51
+ const extracted = extractConfigFromDomainClass(assets.DomainClass);
52
+ return {
53
+ uiConfig: extracted.uiConfig,
54
+ eventConfig: extracted.eventConfig,
55
+ triggers: assets.triggerConfig ?? [],
56
+ timers: assets.timerConfig ?? [],
57
+ styleConfig: this.parseStyleConfig(assets.styleYaml),
58
+ locale: localeYaml ? (yaml.load(localeYaml) as Record<string, unknown>) || {} : {},
59
+ appConfig: this.parseAppConfig(assets.appConfigYaml),
60
+ };
61
+ }
62
+
63
+ const cacheKey = `${uiYaml}\0${eventYaml}\0${localeYaml}\0${assets.appConfigYaml ?? ''}\0${assets.styleYaml ?? ''}`;
42
64
  const cached = this.cache.get(cacheKey);
43
65
  if (cached) {
44
66
  return cached;
45
67
  }
46
68
 
69
+ const eventRaw = eventYaml.trim() ? yaml.load(eventYaml) : {};
70
+ const { eventsRaw, triggers, timers } = splitEventConfigRaw(eventRaw);
71
+
47
72
  const result: ParsedRuntimeAssets = {
48
73
  uiConfig: parseUiConfig(yaml.load(uiYaml)),
49
- eventConfig: parseEventConfig(yaml.load(eventYaml) as any),
74
+ eventConfig: parseEventConfig(eventsRaw as any),
75
+ triggers,
76
+ timers,
77
+ styleConfig: this.parseStyleConfig(assets.styleYaml),
50
78
  locale: localeYaml ? (yaml.load(localeYaml) as Record<string, unknown>) || {} : {},
51
79
  appConfig: this.parseAppConfig(assets.appConfigYaml),
52
80
  };
@@ -64,4 +92,11 @@ export class SomaAssetResolver {
64
92
  if (!appConfigYaml) return null;
65
93
  return yaml.load(appConfigYaml);
66
94
  }
95
+
96
+ private parseStyleConfig(styleYaml?: string): import('../types/style-config.types').StyleConfig | undefined {
97
+ if (!styleYaml) return undefined;
98
+ const raw = yaml.load(styleYaml);
99
+ if (!raw) return undefined;
100
+ return parseStyleConfig(raw);
101
+ }
67
102
  }
@@ -1,4 +1,4 @@
1
- import type { SomaContainerAdapter } from '../container/SomaContainerAdapter';
1
+ import type { IContainerAdapter } from '../container/IContainerAdapter';
2
2
  import type { SomaCompiledBinding } from '../types/manifest.types';
3
3
  import type { BindingEntry } from '../types/engine.types';
4
4
  import type { ShowMapping } from '../types/ui-config.types';
@@ -8,7 +8,7 @@ import { longestIncreasingSubsequence } from './lis';
8
8
  export type ModelWriteBack = (path: string, value: string) => void;
9
9
 
10
10
  export class SomaDomRenderer {
11
- private adapter: SomaContainerAdapter | null = null;
11
+ private adapter: IContainerAdapter | null = null;
12
12
  private resolver: SomaScopeResolver | null = null;
13
13
  private scopeTracker: WeakMap<HTMLElement, any> | null = null;
14
14
  private modelWriteBack: ModelWriteBack | null = null;
@@ -16,7 +16,7 @@ export class SomaDomRenderer {
16
16
  private modelAbort = new AbortController();
17
17
 
18
18
  init(
19
- adapter: SomaContainerAdapter,
19
+ adapter: IContainerAdapter,
20
20
  resolver: SomaScopeResolver,
21
21
  scopeTracker: WeakMap<HTMLElement, any>,
22
22
  ): void {
@@ -111,14 +111,12 @@ export class SomaDomRenderer {
111
111
  }
112
112
  if (modelWriteBack && !modelListeners.has(modelEl)) {
113
113
  modelListeners.add(modelEl);
114
- modelAdapter.listen(
115
- modelEl,
116
- 'input',
117
- () => {
118
- modelWriteBack(dataPath, self.adapter!.getValue(modelEl));
119
- },
120
- modelAbort.signal,
121
- );
114
+ const writeModel = () => {
115
+ modelWriteBack(dataPath, modelAdapter.getValue(modelEl));
116
+ };
117
+ for (const eventType of ['input', 'change', 'blur']) {
118
+ modelAdapter.listen(modelEl, eventType, writeModel, modelAbort.signal);
119
+ }
122
120
  }
123
121
  };
124
122
  }
@@ -1,10 +1,11 @@
1
- import type { SomaContainerAdapter } from '../container/SomaContainerAdapter';
1
+ import { recordMetric } from '../diagnostics/telemetry-context';
2
+ import type { IContainerAdapter } from '../container/IContainerAdapter';
2
3
  import { SOMA_KEY_MODIFIERS } from '../types/keyboard.types';
3
4
  import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
4
5
  import { SomaMiddlewareChain } from '../middleware/SomaMiddlewareChain';
5
6
  import { SomaScheduler } from '../scheduler/SomaScheduler';
6
7
  import type { SomaCompiledEvent, SomaRuntimeManifest } from '../types/manifest.types';
7
- import type { InteractAction } from '../types/event.types';
8
+ import type { InteractAction, EventHandlerResult } from '../types/event.types';
8
9
  import type { SomaScopeResolver } from './scope-resolver';
9
10
 
10
11
  export interface SomaEventMiddlewareContext {
@@ -19,12 +20,18 @@ export interface SomaEventMiddlewareContext {
19
20
  export interface SomaEventEngineOptions<TContext extends Record<string, unknown> = Record<string, never>> {
20
21
  manifest: SomaRuntimeManifest;
21
22
  container: HTMLElement;
22
- adapter: SomaContainerAdapter;
23
+ adapter: IContainerAdapter;
23
24
  resolver: SomaScopeResolver;
24
25
  scopeTracker: WeakMap<HTMLElement, any>;
25
26
  callbacks: {
26
27
  onRefresh: () => void | Promise<void>;
27
- onFlush: () => void | Promise<void>;
28
+ /** @deprecated 使用 onCommit */
29
+ onFlush?: () => void | Promise<void>;
30
+ onCommit?: () => void | Promise<void>;
31
+ onBeginTransaction?: () => void;
32
+ onEndTransaction?: () => void;
33
+ onDiscardPending?: () => void;
34
+ onSyncModels?: () => void;
28
35
  };
29
36
  diagnostics?: SomaDiagnostics;
30
37
  scheduler?: SomaScheduler;
@@ -39,12 +46,16 @@ export interface SomaEventEngineOptions<TContext extends Record<string, unknown>
39
46
  export class SomaEventEngine<TContext extends Record<string, unknown> = Record<string, never>> {
40
47
  private readonly manifest: SomaRuntimeManifest;
41
48
  private readonly container: HTMLElement;
42
- private readonly adapter: SomaContainerAdapter;
49
+ private readonly adapter: IContainerAdapter;
43
50
  private readonly resolver: SomaScopeResolver;
44
51
  private readonly scopeTracker: WeakMap<HTMLElement, any>;
45
52
  private readonly callbacks: {
46
53
  onRefresh: () => void | Promise<void>;
47
- onFlush: () => void | Promise<void>;
54
+ onCommit: () => void | Promise<void>;
55
+ onBeginTransaction?: () => void;
56
+ onEndTransaction?: () => void;
57
+ onDiscardPending?: () => void;
58
+ onSyncModels?: () => void;
48
59
  };
49
60
  private readonly diagnostics: SomaDiagnostics | null;
50
61
  private readonly scheduler: SomaScheduler;
@@ -63,7 +74,17 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
63
74
  this.adapter = options.adapter;
64
75
  this.resolver = options.resolver;
65
76
  this.scopeTracker = options.scopeTracker;
66
- this.callbacks = options.callbacks;
77
+ this.callbacks = {
78
+ onRefresh: options.callbacks.onRefresh,
79
+ onCommit:
80
+ options.callbacks.onCommit ??
81
+ options.callbacks.onFlush ??
82
+ (() => Promise.resolve()),
83
+ onBeginTransaction: options.callbacks.onBeginTransaction,
84
+ onEndTransaction: options.callbacks.onEndTransaction,
85
+ onDiscardPending: options.callbacks.onDiscardPending,
86
+ onSyncModels: options.callbacks.onSyncModels,
87
+ };
67
88
  this.diagnostics = options.diagnostics ?? null;
68
89
  this.scheduler = options.scheduler ?? new SomaScheduler();
69
90
  this.middleware = options.middleware ?? null;
@@ -81,26 +102,39 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
81
102
  this.container,
82
103
  eventType,
83
104
  (event) => {
84
- const target = this.adapter.findClosestAnchor(event.target);
85
- if (!target) {
86
- return;
87
- }
88
-
89
- const somaId = this.adapter.getAnchorId(target);
90
- if (!somaId) {
105
+ const resolved = this.resolveEventBinding(eventType, event.target);
106
+ if (!resolved) {
91
107
  return;
92
108
  }
93
-
94
- const config = this.manifest.eventIndex.get(`${eventType}:${somaId}`);
95
- if (config) {
96
- void this.execute(config, target, event);
97
- }
109
+ void this.execute(resolved.config, resolved.element, event);
98
110
  },
99
111
  this.abortController.signal,
100
112
  );
101
113
  }
102
114
  }
103
115
 
116
+ /**
117
+ * 从内层锚点向上查找第一个已注册事件的 data-soma-id。
118
+ * 避免点击 product_name 等子节点时,closest 停在无事件的子 id 上。
119
+ */
120
+ private resolveEventBinding(
121
+ eventType: string,
122
+ start: EventTarget | null,
123
+ ): { element: HTMLElement; config: SomaCompiledEvent } | null {
124
+ let el: HTMLElement | null = start instanceof HTMLElement ? start : null;
125
+ while (el && el !== this.container) {
126
+ const somaId = this.adapter.getAnchorId(el);
127
+ if (somaId) {
128
+ const config = this.manifest.eventIndex.get(`${eventType}:${somaId}`);
129
+ if (config) {
130
+ return { element: el, config };
131
+ }
132
+ }
133
+ el = el.parentElement;
134
+ }
135
+ return null;
136
+ }
137
+
104
138
  execute(config: SomaCompiledEvent, element: HTMLElement, originalEvent: Event): Promise<void> {
105
139
  return this.scheduler.schedule(
106
140
  () => this.executeNow(config, element, originalEvent),
@@ -148,27 +182,61 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
148
182
  }
149
183
  }
150
184
 
151
- let result = true;
152
- if (config.funcPath && config.type !== 'NAV_STATIC') {
153
- try {
154
- this.pendingSet.add(config.somaId);
155
- const fn = this.resolveFunction(config.funcPath, currentVar);
156
- result = await fn(currentVar, originalEvent);
157
- } catch (error) {
158
- runtime.status = 'error';
159
- runtime.message = error instanceof Error ? error.message : String(error);
160
- result = false;
161
- } finally {
162
- this.pendingSet.delete(config.somaId);
163
- }
185
+ let result: EventHandlerResult = true;
186
+ const runsHandler = Boolean(config.funcPath && config.type !== 'NAV_STATIC');
187
+ let inTransaction = false;
188
+
189
+ if (runsHandler) {
190
+ this.callbacks.onBeginTransaction?.();
191
+ inTransaction = true;
164
192
  }
165
193
 
166
- if (result !== false) {
167
- await this.callbacks.onFlush();
168
- await this.postAction(config, element);
169
- } else if (runtime.status !== 'error') {
170
- runtime.status = 'blocked';
171
- runtime.message = runtime.message ?? 'business handler returned false';
194
+ try {
195
+ if (runsHandler) {
196
+ try {
197
+ this.pendingSet.add(config.somaId);
198
+ this.callbacks.onSyncModels?.();
199
+ const fn = this.resolveFunction(config.funcPath!, currentVar);
200
+ result = await fn(currentVar, originalEvent);
201
+ } catch (error) {
202
+ runtime.status = 'error';
203
+ runtime.message = error instanceof Error ? error.message : String(error);
204
+ result = false;
205
+ } finally {
206
+ this.pendingSet.delete(config.somaId);
207
+ }
208
+ }
209
+
210
+ const isError = runtime.status === 'error';
211
+
212
+ // DOM 同步:handler 正常返回后始终 commit(与成功/失败返回值无关)
213
+ if (runsHandler && !isError) {
214
+ const forceRefresh =
215
+ result !== false &&
216
+ config.type === 'UI_REFRESH' &&
217
+ config.refreshForce === true;
218
+
219
+ if (forceRefresh) {
220
+ this.callbacks.onDiscardPending?.();
221
+ await this.callbacks.onRefresh();
222
+ } else {
223
+ await this.callbacks.onCommit();
224
+ }
225
+ } else if (isError) {
226
+ this.callbacks.onDiscardPending?.();
227
+ }
228
+
229
+ // Post-action:仅成功(非 false)时继续后续流程(跳转 / 显隐)
230
+ if (result !== false && !isError) {
231
+ await this.postAction(config, element);
232
+ } else if (!isError && runsHandler && result === false) {
233
+ runtime.status = 'blocked';
234
+ runtime.message = runtime.message ?? 'business handler returned false';
235
+ }
236
+ } finally {
237
+ if (inTransaction) {
238
+ this.callbacks.onEndTransaction?.();
239
+ }
172
240
  }
173
241
  };
174
242
 
@@ -187,6 +255,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
187
255
  durationMs: this.adapter.now() - startedAt,
188
256
  message: context.message,
189
257
  });
258
+ recordMetric(`event.${config.type}`, this.adapter.now() - startedAt);
190
259
  }
191
260
 
192
261
  private getContext(element: HTMLElement): any {
@@ -206,8 +275,8 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
206
275
  return false;
207
276
  }
208
277
 
209
- if ((config as { confirm?: string }).confirm) {
210
- return this.adapter.confirm((config as { confirm?: string }).confirm!);
278
+ if (config.confirm) {
279
+ return this.adapter.confirm(config.confirm);
211
280
  }
212
281
 
213
282
  return true;
@@ -223,7 +292,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
223
292
  break;
224
293
 
225
294
  case 'UI_REFRESH':
226
- await this.callbacks.onRefresh();
295
+ // 非 force:commit 已在 handler 后完成;force 时 onRefresh 在 executeNow 中调用
227
296
  break;
228
297
 
229
298
  case 'UI_INTERACT':
@@ -0,0 +1,71 @@
1
+ // core/engine/on-change-engine.ts
2
+ // 解析 _ui.yaml bind.onChange 并注册属性变更回调
3
+
4
+ import type { SomaScopeResolver } from './scope-resolver';
5
+ import type { SomaPropertyWatcher } from './property-watcher';
6
+ import type { OnChangeRule } from '../types/watcher.types';
7
+ import type { UiConfig } from '../types/ui-config.types';
8
+
9
+ export interface SomaOnChangeEngineOptions {
10
+ propertyWatcher: SomaPropertyWatcher;
11
+ resolver: SomaScopeResolver;
12
+ uiConfig: UiConfig;
13
+ proxiedInstance: object;
14
+ onRefresh?: () => void | Promise<void>;
15
+ }
16
+
17
+ export class SomaOnChangeEngine {
18
+ private readonly unwatchers: Array<() => void> = [];
19
+
20
+ init(options: SomaOnChangeEngineOptions): void {
21
+ const rules = options.uiConfig.bind.onChange;
22
+ if (!rules || rules.length === 0) {
23
+ return;
24
+ }
25
+
26
+ const varName = options.uiConfig.bind.var;
27
+
28
+ for (const rule of rules) {
29
+ this.registerRule(rule, varName, options);
30
+ }
31
+ }
32
+
33
+ destroy(): void {
34
+ for (const unwatch of this.unwatchers) {
35
+ unwatch();
36
+ }
37
+ this.unwatchers.length = 0;
38
+ }
39
+
40
+ private registerRule(
41
+ rule: OnChangeRule,
42
+ varName: string,
43
+ options: SomaOnChangeEngineOptions,
44
+ ): void {
45
+ const resolvedCondition = options.resolver.resolvePath(rule.condition);
46
+ const funcPath = rule.callback.includes('.')
47
+ ? rule.callback
48
+ : `${varName}.${rule.callback}`;
49
+
50
+ const unwatch = options.propertyWatcher.watch(
51
+ resolvedCondition,
52
+ async (newValue, oldValue) => {
53
+ try {
54
+ const fn = options.resolver.resolveFunction(funcPath);
55
+ const result = await fn(newValue, oldValue);
56
+ if (rule.refresh && result !== false) {
57
+ await options.onRefresh?.();
58
+ }
59
+ } catch (e) {
60
+ console.error(`[SomaOnChangeEngine] "${funcPath}" error:`, e);
61
+ }
62
+ },
63
+ {
64
+ prefix: false,
65
+ debounce: rule.debounce,
66
+ },
67
+ );
68
+
69
+ this.unwatchers.push(unwatch);
70
+ }
71
+ }
@@ -0,0 +1,117 @@
1
+ // core/engine/property-watcher.ts
2
+ // 属性变更观察者注册表 — RenderEngine.watch / onChange / triggers 共用
3
+
4
+ import type { WatchCallback, WatcherOptions } from '../types/watcher.types';
5
+
6
+ interface WatcherEntry {
7
+ id: number;
8
+ watchPath: string;
9
+ prefix: boolean;
10
+ glob: boolean;
11
+ callback: WatchCallback;
12
+ debounce?: number;
13
+ timer?: ReturnType<typeof setTimeout>;
14
+ }
15
+
16
+ let nextWatcherId = 1;
17
+
18
+ export class SomaPropertyWatcher {
19
+ private entries: WatcherEntry[] = [];
20
+ private root: object = {};
21
+
22
+ setRoot(root: object): void {
23
+ this.root = root;
24
+ }
25
+
26
+ /**
27
+ * 注册属性监听器。
28
+ * @returns 取消监听的函数
29
+ */
30
+ watch(
31
+ watchPath: string,
32
+ callback: WatchCallback,
33
+ options: WatcherOptions = {},
34
+ ): () => void {
35
+ const entry: WatcherEntry = {
36
+ id: nextWatcherId++,
37
+ watchPath,
38
+ prefix: options.prefix ?? !watchPath.includes('*'),
39
+ glob: options.glob ?? watchPath.includes('*'),
40
+ callback,
41
+ debounce: options.debounce,
42
+ };
43
+ this.entries.push(entry);
44
+
45
+ if (options.immediate) {
46
+ void this.invoke(entry, undefined, undefined, watchPath);
47
+ }
48
+
49
+ return () => {
50
+ if (entry.timer) clearTimeout(entry.timer);
51
+ this.entries = this.entries.filter((e) => e.id !== entry.id);
52
+ };
53
+ }
54
+
55
+ /** Proxy set trap 驱动:通知所有匹配的 watcher */
56
+ notify(changedPath: string, newValue: unknown, oldValue: unknown): void {
57
+ for (const entry of this.entries) {
58
+ if (!this.matches(entry.watchPath, changedPath, entry.prefix, entry.glob)) {
59
+ continue;
60
+ }
61
+
62
+ if (entry.debounce && entry.debounce > 0) {
63
+ if (entry.timer) clearTimeout(entry.timer);
64
+ entry.timer = setTimeout(() => {
65
+ entry.timer = undefined;
66
+ void this.invoke(entry, newValue, oldValue, changedPath);
67
+ }, entry.debounce);
68
+ } else {
69
+ void this.invoke(entry, newValue, oldValue, changedPath);
70
+ }
71
+ }
72
+ }
73
+
74
+ destroy(): void {
75
+ for (const entry of this.entries) {
76
+ if (entry.timer) clearTimeout(entry.timer);
77
+ }
78
+ this.entries = [];
79
+ }
80
+
81
+ private matches(watchPath: string, changedPath: string, prefix: boolean, glob: boolean): boolean {
82
+ if (glob || watchPath.includes('*')) {
83
+ return matchGlobPath(watchPath, changedPath);
84
+ }
85
+ if (!prefix) {
86
+ return watchPath === changedPath;
87
+ }
88
+ return changedPath === watchPath || changedPath.startsWith(`${watchPath}.`);
89
+ }
90
+
91
+ private async invoke(
92
+ entry: WatcherEntry,
93
+ newValue: unknown,
94
+ oldValue: unknown,
95
+ path: string,
96
+ ): Promise<void> {
97
+ try {
98
+ await entry.callback(newValue, oldValue, { path, root: this.root });
99
+ } catch (e) {
100
+ console.error(`[SomaPropertyWatcher] callback error at "${path}":`, e);
101
+ }
102
+ }
103
+ }
104
+
105
+ /** 通配符路径匹配:`*` 匹配单段(如 a.*.c 匹配 a.b.c) */
106
+ export function matchGlobPath(pattern: string, path: string): boolean {
107
+ const patternParts = pattern.split('.');
108
+ const pathParts = path.split('.');
109
+ if (patternParts.length !== pathParts.length) {
110
+ return false;
111
+ }
112
+ for (let i = 0; i < patternParts.length; i++) {
113
+ if (patternParts[i] === '*') continue;
114
+ if (patternParts[i] !== pathParts[i]) return false;
115
+ }
116
+ return true;
117
+ }