soma-core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/app/api/page/route.ts +97 -0
  2. package/app/globals.css +3 -0
  3. package/app/layout.tsx +18 -0
  4. package/app/page.tsx +129 -0
  5. package/bin/soma.cjs +2 -0
  6. package/core/base/SomaApi.ts +14 -0
  7. package/core/base/SomaDict.ts +168 -0
  8. package/core/base/SomaEntity.ts +41 -0
  9. package/core/base/SomaHttpClient.ts +126 -0
  10. package/core/base/SomaLocaleOnlyPageRoot.ts +4 -0
  11. package/core/base/SomaPageRootBase.ts +54 -0
  12. package/core/base/SomaValidator.ts +147 -0
  13. package/core/base/index.ts +7 -0
  14. package/core/compiler/full-manifest-builder.ts +43 -0
  15. package/core/compiler/manifest-compiler.ts +237 -0
  16. package/core/compiler/route-builder.ts +31 -0
  17. package/core/compiler/soma-precompile.ts +48 -0
  18. package/core/compiler/soma-webpack-loader.js +35 -0
  19. package/core/compiler/vite-plugin-soma.ts +73 -0
  20. package/core/container/SomaContainerAdapter.ts +169 -0
  21. package/core/diagnostics/SomaDiagnostics.ts +186 -0
  22. package/core/engine/asset-resolver.ts +67 -0
  23. package/core/engine/dom-renderer.ts +366 -0
  24. package/core/engine/event-engine.ts +287 -0
  25. package/core/engine/lis.ts +60 -0
  26. package/core/engine/reactive-proxy.ts +225 -0
  27. package/core/engine/render-engine.ts +264 -0
  28. package/core/engine/runtime-builder.ts +100 -0
  29. package/core/engine/scope-resolver.ts +252 -0
  30. package/core/engine/soma-bootstrap.ts +244 -0
  31. package/core/index.ts +6 -0
  32. package/core/infra/auth/IAuthService.ts +13 -0
  33. package/core/infra/auth/TokenAuthService.ts +98 -0
  34. package/core/infra/cache/ICache.ts +13 -0
  35. package/core/infra/cache/MemoryCache.ts +95 -0
  36. package/core/infra/cache/ServerFileCache.ts +123 -0
  37. package/core/infra/config/IConfig.ts +9 -0
  38. package/core/infra/config/SomaConfig.ts +85 -0
  39. package/core/infra/event-bus/IEventBus.ts +9 -0
  40. package/core/infra/event-bus/SomaEventBus.ts +53 -0
  41. package/core/infra/http/IHttpClient.ts +21 -0
  42. package/core/infra/http/SomaHttpService.ts +141 -0
  43. package/core/infra/i18n/DefaultI18n.ts +41 -0
  44. package/core/infra/i18n/II18n.ts +7 -0
  45. package/core/infra/logger/ConsoleLogger.ts +81 -0
  46. package/core/infra/logger/ILogger.ts +19 -0
  47. package/core/infra/notify/DefaultNotifyService.ts +31 -0
  48. package/core/infra/notify/INotifyService.ts +14 -0
  49. package/core/infra/permission/IPermission.ts +10 -0
  50. package/core/infra/permission/SomaPermission.ts +48 -0
  51. package/core/infra/router/IRouter.ts +19 -0
  52. package/core/infra/router/SomaRouter.ts +66 -0
  53. package/core/infra/storage/IStorageService.ts +7 -0
  54. package/core/infra/storage/MemoryStorageService.ts +53 -0
  55. package/core/infra/timer/ITimer.ts +9 -0
  56. package/core/infra/timer/SomaTimer.ts +118 -0
  57. package/core/middleware/SomaMiddlewareChain.ts +29 -0
  58. package/core/parser/pipeline-parser.ts +276 -0
  59. package/core/parser/ui-config-parser.ts +336 -0
  60. package/core/parser/yaml-loader.ts +36 -0
  61. package/core/router/RouteHandler.ts +93 -0
  62. package/core/runtime/SomaSnapshotStore.ts +98 -0
  63. package/core/scheduler/SomaScheduler.ts +190 -0
  64. package/core/types/domain.types.ts +88 -0
  65. package/core/types/engine.types.ts +35 -0
  66. package/core/types/event.types.ts +57 -0
  67. package/core/types/keyboard.types.ts +18 -0
  68. package/core/types/manifest.types.ts +30 -0
  69. package/core/types/scheduler.types.ts +10 -0
  70. package/core/types/ui-config.types.ts +89 -0
  71. package/core/validation/contract-validator.ts +465 -0
  72. package/dist/cli/soma.js +49 -0
  73. package/global.d.ts +14 -0
  74. package/next.config.js +61 -0
  75. package/package.json +77 -0
  76. package/postcss.config.js +6 -0
  77. package/tailwind.config.ts +21 -0
  78. package/tsconfig.json +35 -0
@@ -0,0 +1,225 @@
1
+ // core/engine/reactive-proxy.ts
2
+
3
+ import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
4
+
5
+ const ARRAY_MUTATING_METHODS = new Set([
6
+ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill',
7
+ ]);
8
+
9
+ /**
10
+ * SOMA 响应式代理
11
+ *
12
+ * 封装 ES6 Proxy 深度劫持,对外暴露唯一接口 wrap()。
13
+ * - 使用 WeakMap 缓存,同一对象只创建一个 Proxy
14
+ * - 跳过内置类型(Set/Map/Date 等);数组通过引用替换触发更新
15
+ * - 函数绑定到 Proxy receiver,确保 this 正确
16
+ * - devMode 开启时,数组变异方法调用会发出 warn(提示改用引用替换)
17
+ */
18
+ export class SomaReactiveProxy {
19
+ /** 原始对象 → Proxy 实例的缓存(仅用于顶层 wrap 调用) */
20
+ private cache = new WeakMap<object, any>();
21
+
22
+ /** 子对象 Proxy 缓存:避免每次 get 嵌套对象都 new Proxy() */
23
+ private childProxyCache = new WeakMap<object, any>();
24
+
25
+ /** 变更回调(可延迟设置) */
26
+ private onChange: ((path: string, value: any) => void) | null = null;
27
+ private diagnostics: SomaDiagnostics | null = null;
28
+ private readonly devMode: boolean;
29
+
30
+ constructor(
31
+ onChange?: (path: string, value: any) => void,
32
+ diagnostics?: SomaDiagnostics,
33
+ devMode: boolean = true,
34
+ ) {
35
+ this.onChange = onChange ?? null;
36
+ this.diagnostics = diagnostics ?? null;
37
+ this.devMode = devMode;
38
+ }
39
+
40
+ /** 延迟设置变更回调 */
41
+ setOnChange(fn: ((path: string, value: any) => void) | null): void {
42
+ this.onChange = fn;
43
+ }
44
+
45
+ // ─── 批量变更支持 ──────────────────────────────────────
46
+
47
+ private batchDepth = 0;
48
+ private batchedPaths = new Map<string, any>();
49
+
50
+ /**
51
+ * 开始批量变更事务。
52
+ * batch 期间,onChange 回调暂停,所有变更路径被收集。
53
+ * 支持嵌套调用。
54
+ */
55
+ beginBatch(): void {
56
+ this.batchDepth++;
57
+ }
58
+
59
+ /**
60
+ * 结束批量变更事务。
61
+ * 最外层 endBatch 时,一次性触发所有收集的变更路径的 onChange 回调。
62
+ */
63
+ endBatch(): void {
64
+ if (this.batchDepth <= 0) return;
65
+ this.batchDepth--;
66
+
67
+ if (this.batchDepth === 0 && this.batchedPaths.size > 0) {
68
+ const paths = new Map(this.batchedPaths);
69
+ this.batchedPaths.clear();
70
+
71
+ // 一次性触发所有变更通知
72
+ for (const [path, value] of paths) {
73
+ try {
74
+ if (this.onChange) this.onChange(path, value);
75
+ } catch (e) {
76
+ console.error('[SomaReactiveProxy] batch onChange error:', e);
77
+ }
78
+ }
79
+ }
80
+ }
81
+
82
+ setDiagnostics(diagnostics: SomaDiagnostics | null): void {
83
+ this.diagnostics = diagnostics;
84
+ }
85
+
86
+ /** 销毁:断开回调,清空缓存 */
87
+ dispose(): void {
88
+ this.onChange = null;
89
+ this.diagnostics = null;
90
+ this.cache = new WeakMap();
91
+ this.childProxyCache = new WeakMap();
92
+ }
93
+
94
+ /**
95
+ * 将对象包装为深度响应式代理。
96
+ * 对象的任何属性赋值(包括嵌套对象)都会触发 onChange 回调。
97
+ * 仅缓存顶层 wrap() 调用创建的 Proxy,避免 basePath 污染。
98
+ */
99
+ wrap<T extends object>(obj: T, basePath: string = ''): T {
100
+ // 内置类型不代理
101
+ if (this.shouldSkip(obj)) return obj;
102
+
103
+ // 缓存命中(仅顶层 Proxy)
104
+ const cached = this.cache.get(obj);
105
+ if (cached) return cached as T;
106
+
107
+ const proxy = new Proxy(obj, this.createHandler(basePath));
108
+ this.cache.set(obj, proxy);
109
+ return proxy;
110
+ }
111
+
112
+ /**
113
+ * 创建 Proxy handler(get/set trap)。
114
+ * 子对象在 get trap 中每次创建新 Proxy(不缓存),确保 basePath 正确。
115
+ */
116
+ private createHandler(basePath: string): ProxyHandler<any> {
117
+ const self = this;
118
+ return {
119
+ get(target: any, prop: string | symbol, receiver: any): any {
120
+ // symbol 属性直接返回(快速路径)
121
+ if (typeof prop === 'symbol') return Reflect.get(target, prop, target);
122
+
123
+ const value = Reflect.get(target, prop, target);
124
+
125
+ // 快速路径:原始值和 null/undefined 直接返回,无需任何判断
126
+ if (value === null || value === undefined) return value;
127
+ const t = typeof value;
128
+ if (t === 'string' || t === 'number' || t === 'boolean') return value;
129
+
130
+ // 函数绑定到 receiver(Proxy 本身),确保方法内 this 赋值触发响应式
131
+ if (t === 'function') {
132
+ return value.bind(receiver);
133
+ }
134
+
135
+ // 数组:dev 模式下拦截变异方法,发出警告
136
+ if (Array.isArray(value) && self.devMode) {
137
+ return self.wrapArrayDevGuard(value, basePath ? `${basePath}.${String(prop)}` : String(prop));
138
+ }
139
+
140
+ // 嵌套对象返回 Proxy 包装版本(缓存子 Proxy 减少 GC 压力)
141
+ if (!self.shouldSkip(value)) {
142
+ const cachedChild = self.childProxyCache.get(value);
143
+ if (cachedChild) return cachedChild;
144
+
145
+ const childPath = basePath ? `${basePath}.${String(prop)}` : String(prop);
146
+ const childProxy = new Proxy(value, self.createHandler(childPath));
147
+ self.childProxyCache.set(value, childProxy);
148
+ return childProxy;
149
+ }
150
+
151
+ return value;
152
+ },
153
+
154
+ set(target: any, prop: string | symbol, value: any): boolean {
155
+ const key = String(prop);
156
+ const path = basePath ? `${basePath}.${key}` : key;
157
+
158
+ // 旧值的子 Proxy 缓存失效
159
+ const oldValue = target[prop];
160
+ if (oldValue != null && typeof oldValue === 'object') {
161
+ self.childProxyCache.delete(oldValue);
162
+ }
163
+
164
+ // 执行赋值
165
+ target[prop] = value;
166
+
167
+ // 通知变更(带异常防护)
168
+ try {
169
+ self.diagnostics?.recordMutation(path, value);
170
+ if (self.batchDepth > 0) {
171
+ // batch 模式:收集变更路径,延迟到 endBatch 统一触发
172
+ self.batchedPaths.set(path, value);
173
+ } else if (self.onChange) {
174
+ self.onChange(path, value);
175
+ }
176
+ } catch (e) {
177
+ console.error('[SomaReactiveProxy] onChange error:', e);
178
+ }
179
+
180
+ return true;
181
+ },
182
+ };
183
+ }
184
+
185
+ /**
186
+ * 为数组创建一个轻量 Proxy,仅在 dev 模式下拦截变异方法。
187
+ * 纯读方法(map/filter/length 等)直接透传,不影响性能。
188
+ * 不缓存,每次 get 都创建新 Proxy,保证 arrayPath 路径准确。
189
+ */
190
+ private wrapArrayDevGuard(arr: any[], arrayPath: string): any[] {
191
+ return new Proxy(arr, {
192
+ get(target, prop) {
193
+ const value = Reflect.get(target, prop);
194
+ if (typeof prop === 'string' && ARRAY_MUTATING_METHODS.has(prop) && typeof value === 'function') {
195
+ return (...args: any[]) => {
196
+ console.warn(
197
+ `[SomaReactiveProxy] Direct mutation "${prop}" on array at "${arrayPath}" will NOT trigger reactive updates. ` +
198
+ `Use reference replacement instead: this.${arrayPath} = [...this.${arrayPath}]`,
199
+ );
200
+ return value.apply(target, args);
201
+ };
202
+ }
203
+ return value;
204
+ },
205
+ });
206
+ }
207
+
208
+ /** 判断对象是否应跳过代理 */
209
+ private shouldSkip(obj: any): boolean {
210
+ if (obj == null) return true;
211
+ if (Array.isArray(obj)) return true; // 数组不代理,通过引用替换触发更新
212
+ return (
213
+ obj instanceof Set ||
214
+ obj instanceof Map ||
215
+ obj instanceof Date ||
216
+ obj instanceof RegExp ||
217
+ obj instanceof Promise ||
218
+ obj instanceof AbortController ||
219
+ obj instanceof Error ||
220
+ obj instanceof WeakMap ||
221
+ obj instanceof WeakSet ||
222
+ typeof obj.then === 'function'
223
+ );
224
+ }
225
+ }
@@ -0,0 +1,264 @@
1
+ import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
2
+ import type { BindingEntry } from '../types/engine.types';
3
+ import type { SomaRuntimeManifest } from '../types/manifest.types';
4
+ import { SomaScheduler } from '../scheduler/SomaScheduler';
5
+ import { SomaMiddlewareChain } from '../middleware/SomaMiddlewareChain';
6
+ import type { SomaContainerAdapter } from '../container/SomaContainerAdapter';
7
+ import { SomaScopeResolver } from './scope-resolver';
8
+ import { SomaDomRenderer } from './dom-renderer';
9
+
10
+ export interface SomaRenderEngineOptions {
11
+ container: HTMLElement;
12
+ adapter: SomaContainerAdapter;
13
+ manifest: SomaRuntimeManifest;
14
+ proxiedInstance: any;
15
+ resolver: SomaScopeResolver;
16
+ scheduler?: SomaScheduler;
17
+ diagnostics?: SomaDiagnostics;
18
+ middleware?: SomaMiddlewareChain<SomaRenderMiddlewareContext>;
19
+ }
20
+
21
+ export interface SomaRenderMiddlewareContext {
22
+ phase: 'full-render' | 'patch';
23
+ path?: string;
24
+ changedPaths: string[];
25
+ bindings: BindingEntry[];
26
+ }
27
+
28
+ export class SomaRenderEngine {
29
+ private readonly container: HTMLElement;
30
+ private readonly adapter: SomaContainerAdapter;
31
+ private readonly resolver: SomaScopeResolver;
32
+ private readonly renderer: SomaDomRenderer;
33
+ private readonly scheduler: SomaScheduler;
34
+ private readonly diagnostics: SomaDiagnostics | null;
35
+ private readonly middleware: SomaMiddlewareChain<SomaRenderMiddlewareContext> | null;
36
+ private bindingTable: BindingEntry[] = [];
37
+ private bindingIndex = new Map<string, BindingEntry[]>();
38
+ private scopeTracker = new WeakMap<HTMLElement, any>();
39
+ private pendingPatches = new Map<string, any>();
40
+ private flushScheduled = false;
41
+ private destroyed = false;
42
+ private proxiedInstance: any;
43
+
44
+ constructor(options: SomaRenderEngineOptions) {
45
+ this.container = options.container;
46
+ this.adapter = options.adapter;
47
+ this.resolver = options.resolver;
48
+ this.scheduler = options.scheduler ?? new SomaScheduler();
49
+ this.diagnostics = options.diagnostics ?? null;
50
+ this.middleware = options.middleware ?? null;
51
+ this.proxiedInstance = options.proxiedInstance;
52
+
53
+ this.renderer = new SomaDomRenderer();
54
+ this.renderer.init(this.adapter, this.resolver, this.scopeTracker);
55
+ this.renderer.setModelWriteBack((path, value) => this.writeToProxy(path, value));
56
+
57
+ this.bindingTable = options.manifest.bindings
58
+ .map((binding) => this.renderer.bindEntry(binding, this.container))
59
+ .filter((entry): entry is BindingEntry => entry !== null);
60
+
61
+ // 编译属性访问器:将 "a.b.c" → (root) => root?.a?.b?.c
62
+ for (const entry of this.bindingTable) {
63
+ entry.compiledGetter = this.resolver.compileGetter(entry.dataPath);
64
+ }
65
+
66
+ this.buildIndex();
67
+ }
68
+
69
+ getScopeTracker(): WeakMap<HTMLElement, any> {
70
+ return this.scopeTracker;
71
+ }
72
+
73
+ render(): void {
74
+ void this.executeRender({
75
+ phase: 'full-render',
76
+ changedPaths: [],
77
+ bindings: this.bindingTable,
78
+ });
79
+ }
80
+
81
+ flush(): Promise<void> {
82
+ return this.flushPatches();
83
+ }
84
+
85
+ destroy(): void {
86
+ this.destroyed = true;
87
+ this.pendingPatches.clear();
88
+ this.bindingTable = [];
89
+ this.bindingIndex.clear();
90
+ this.renderer.destroy();
91
+ }
92
+
93
+ schedulePatch(path: string, value: any): void {
94
+ if (this.destroyed) {
95
+ return;
96
+ }
97
+
98
+ this.pendingPatches.set(path, value);
99
+ if (this.flushScheduled) {
100
+ return;
101
+ }
102
+
103
+ this.flushScheduled = true;
104
+ this.scheduler.schedule(
105
+ () => this.flushPatches(),
106
+ {
107
+ priority: 'visible',
108
+ label: `render:${path}`,
109
+ },
110
+ ).catch(() => {
111
+ // 静默忽略:unmount 时 cancelAll 会 reject 未执行的任务
112
+ });
113
+ }
114
+
115
+ private buildIndex(): void {
116
+ this.bindingIndex.clear();
117
+ for (const entry of this.bindingTable) {
118
+ const watchPaths = entry.watchPaths && entry.watchPaths.length > 0
119
+ ? entry.watchPaths
120
+ : entry.dataPath
121
+ ? [entry.dataPath]
122
+ : [];
123
+
124
+ for (const path of watchPaths) {
125
+ if (!path) {
126
+ continue;
127
+ }
128
+ // 精确索引
129
+ const existing = this.bindingIndex.get(path);
130
+ if (existing) {
131
+ existing.push(entry);
132
+ } else {
133
+ this.bindingIndex.set(path, [entry]);
134
+ }
135
+
136
+ // 祖先路径索引:当父路径变更时也能命中子绑定
137
+ const segments = path.split('.');
138
+ for (let i = 1; i < segments.length; i++) {
139
+ const ancestor = segments.slice(0, i).join('.');
140
+ const ancestorEntries = this.bindingIndex.get(ancestor);
141
+ if (ancestorEntries) {
142
+ if (!ancestorEntries.includes(entry)) {
143
+ ancestorEntries.push(entry);
144
+ }
145
+ } else {
146
+ this.bindingIndex.set(ancestor, [entry]);
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+
153
+ private findAffectedEntries(path: string): BindingEntry[] {
154
+ // 祖先路径已在 buildIndex 时索引,直接查找即可覆盖精确匹配和前缀匹配
155
+ const indexed = this.bindingIndex.get(path);
156
+ if (indexed && indexed.length > 0) {
157
+ return indexed;
158
+ }
159
+
160
+ // 子路径变更时向上查找父绑定(如 path="a.b.c" 查找 "a.b" 和 "a" 的绑定)
161
+ const segments = path.split('.');
162
+ const result: BindingEntry[] = [];
163
+ const seen = new Set<BindingEntry>();
164
+ for (let i = segments.length - 1; i >= 1; i--) {
165
+ const ancestor = segments.slice(0, i).join('.');
166
+ const entries = this.bindingIndex.get(ancestor);
167
+ if (entries) {
168
+ for (const entry of entries) {
169
+ if (!seen.has(entry)) {
170
+ seen.add(entry);
171
+ result.push(entry);
172
+ }
173
+ }
174
+ }
175
+ }
176
+ return result;
177
+ }
178
+
179
+ private async flushPatches(): Promise<void> {
180
+ this.flushScheduled = false;
181
+ if (this.destroyed || this.pendingPatches.size === 0) {
182
+ return;
183
+ }
184
+
185
+ const patches = new Map(this.pendingPatches);
186
+ this.pendingPatches.clear();
187
+
188
+ // 合并所有变更到 binding 层面去重:同一 DOM 节点只操作一次
189
+ const affectedBindings = new Map<BindingEntry, any>();
190
+ const changedPaths: string[] = [];
191
+
192
+ for (const [path, value] of patches) {
193
+ changedPaths.push(path);
194
+ const entries = this.findAffectedEntries(path);
195
+ for (const entry of entries) {
196
+ // 如果 binding 的 dataPath 精确匹配变更路径,使用 patch 值
197
+ // 否则标记为需要从 root 重新读取
198
+ if (!affectedBindings.has(entry)) {
199
+ affectedBindings.set(entry, entry.dataPath === path ? value : undefined);
200
+ }
201
+ }
202
+ }
203
+
204
+ if (affectedBindings.size === 0) {
205
+ return;
206
+ }
207
+
208
+ // 批量渲染:每个 binding 最多操作一次 DOM
209
+ const bindings = [...affectedBindings.keys()];
210
+ const patchValues = affectedBindings;
211
+ await this.executeRender({
212
+ phase: 'patch',
213
+ changedPaths,
214
+ bindings,
215
+ }, patchValues);
216
+ }
217
+
218
+ private async executeRender(
219
+ context: SomaRenderMiddlewareContext,
220
+ patchValues?: Map<BindingEntry, any>,
221
+ ): Promise<void> {
222
+ const startedAt = this.adapter.now();
223
+ const terminal = async (current: SomaRenderMiddlewareContext): Promise<void> => {
224
+ for (const entry of current.bindings) {
225
+ // 优先使用 patch 值(精确匹配),否则用编译后的 getter 直接读取
226
+ const patchValue = patchValues?.get(entry);
227
+ const value = patchValue !== undefined
228
+ ? patchValue
229
+ : entry.compiledGetter
230
+ ? entry.compiledGetter(this.proxiedInstance)
231
+ : this.resolver.readFromRoot(entry.dataPath);
232
+ this.renderer.renderEntry(entry, value);
233
+ }
234
+
235
+ this.diagnostics?.recordRender({
236
+ phase: current.phase,
237
+ path: current.path,
238
+ bindingCount: this.bindingTable.length,
239
+ affectedCount: current.bindings.length,
240
+ durationMs: this.adapter.now() - startedAt,
241
+ });
242
+ };
243
+
244
+ if (this.middleware) {
245
+ await this.middleware.execute(context, terminal);
246
+ return;
247
+ }
248
+
249
+ await terminal(context);
250
+ }
251
+
252
+ private writeToProxy(path: string, value: any): void {
253
+ const segments = path.split('.');
254
+ let current = this.proxiedInstance;
255
+ for (let index = 0; index < segments.length - 1; index++) {
256
+ current = current?.[segments[index]];
257
+ if (current == null) {
258
+ return;
259
+ }
260
+ }
261
+
262
+ current[segments[segments.length - 1]] = value;
263
+ }
264
+ }
@@ -0,0 +1,100 @@
1
+ // core/engine/runtime-builder.ts
2
+ // 职责:从解析后的资产 + DOM 容器组装完整的运行时引擎组
3
+
4
+ import { SomaManifestCompiler } from '../compiler/manifest-compiler';
5
+ import type { SomaContainerAdapter } from '../container/SomaContainerAdapter';
6
+ import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
7
+ import type { SomaMiddlewareChain } from '../middleware/SomaMiddlewareChain';
8
+ import type { SomaScheduler } from '../scheduler/SomaScheduler';
9
+ import type { ParsedEvent } from '../types/event.types';
10
+ import type { UiConfig } from '../types/ui-config.types';
11
+ import { SomaContractValidator } from '../validation/contract-validator';
12
+ import { SomaEventEngine, type SomaEventMiddlewareContext } from './event-engine';
13
+ import type { SomaRenderMiddlewareContext } from './render-engine';
14
+ import { SomaRenderEngine } from './render-engine';
15
+ import { SomaScopeResolver } from './scope-resolver';
16
+
17
+ export interface RuntimeBuildInput {
18
+ container: HTMLElement;
19
+ adapter: SomaContainerAdapter;
20
+ uiConfig: UiConfig;
21
+ eventConfig: ParsedEvent[];
22
+ proxiedInstance: any;
23
+ scheduler: SomaScheduler;
24
+ diagnostics: SomaDiagnostics;
25
+ renderMiddleware?: SomaMiddlewareChain<SomaRenderMiddlewareContext>;
26
+ eventMiddleware?: SomaMiddlewareChain<SomaEventMiddlewareContext>;
27
+ }
28
+
29
+ export interface SomaRuntime {
30
+ renderEngine: SomaRenderEngine;
31
+ eventEngine: SomaEventEngine;
32
+ resolver: SomaScopeResolver;
33
+ }
34
+
35
+ /**
36
+ * 运行时构建器:将配置 + 实例 + DOM 组装为可运行的引擎组。
37
+ *
38
+ * 编排流程:
39
+ * 1. SomaScopeResolver 构建变量映射
40
+ * 2. SomaContractValidator 校验契约
41
+ * 3. SomaManifestCompiler 编译 manifest
42
+ * 4. SomaRenderEngine 创建 + 首次渲染
43
+ * 5. SomaEventEngine 创建 + 事件绑定
44
+ */
45
+ export class SomaRuntimeBuilder {
46
+ private readonly manifestCompiler = new SomaManifestCompiler();
47
+
48
+ build(input: RuntimeBuildInput): SomaRuntime {
49
+ const resolver = new SomaScopeResolver();
50
+ resolver.build(input.uiConfig, input.proxiedInstance);
51
+
52
+ const validator = new SomaContractValidator(input.diagnostics);
53
+ validator.validate({
54
+ container: input.container,
55
+ uiConfig: input.uiConfig,
56
+ eventConfig: input.eventConfig,
57
+ resolver,
58
+ rootInstance: input.proxiedInstance,
59
+ });
60
+
61
+ const manifest = this.manifestCompiler.compile({
62
+ container: input.container,
63
+ adapter: input.adapter,
64
+ uiConfig: input.uiConfig,
65
+ eventConfig: input.eventConfig,
66
+ resolver,
67
+ });
68
+
69
+ const renderEngine = new SomaRenderEngine({
70
+ container: input.container,
71
+ adapter: input.adapter,
72
+ manifest,
73
+ proxiedInstance: input.proxiedInstance,
74
+ resolver,
75
+ scheduler: input.scheduler,
76
+ diagnostics: input.diagnostics,
77
+ middleware: input.renderMiddleware,
78
+ });
79
+
80
+ renderEngine.render();
81
+
82
+ const eventEngine = new SomaEventEngine({
83
+ manifest,
84
+ container: input.container,
85
+ adapter: input.adapter,
86
+ resolver,
87
+ scopeTracker: renderEngine.getScopeTracker(),
88
+ callbacks: {
89
+ onRefresh: () => renderEngine.render(),
90
+ onFlush: () => renderEngine.flush() ?? Promise.resolve(),
91
+ },
92
+ diagnostics: input.diagnostics,
93
+ scheduler: input.scheduler,
94
+ middleware: input.eventMiddleware,
95
+ });
96
+ eventEngine.init();
97
+
98
+ return { renderEngine, eventEngine, resolver };
99
+ }
100
+ }