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,190 @@
1
+ import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
2
+ import type {
3
+ SomaSchedulerOptions,
4
+ SomaSchedulerTaskOptions,
5
+ SomaTaskPriority,
6
+ } from '../types/scheduler.types';
7
+
8
+ interface QueuedTask {
9
+ run: () => unknown | Promise<unknown>;
10
+ resolve: (value: unknown) => void;
11
+ reject: (reason?: unknown) => void;
12
+ priority: SomaTaskPriority;
13
+ label?: string;
14
+ }
15
+
16
+ const PRIORITY_ORDER: SomaTaskPriority[] = ['immediate', 'visible', 'background'];
17
+
18
+ export class SomaScheduler {
19
+ private readonly autoFlush: boolean;
20
+ private readonly queues = new Map<SomaTaskPriority, QueuedTask[]>([
21
+ ['immediate', []],
22
+ ['visible', []],
23
+ ['background', []],
24
+ ]);
25
+ private diagnostics: SomaDiagnostics | null = null;
26
+ private flushQueued = false;
27
+ private flushing = false;
28
+
29
+ constructor(
30
+ options: SomaSchedulerOptions & {
31
+ diagnostics?: SomaDiagnostics;
32
+ } = {},
33
+ ) {
34
+ this.autoFlush = options.autoFlush ?? true;
35
+ this.diagnostics = options.diagnostics ?? null;
36
+ }
37
+
38
+ setDiagnostics(diagnostics: SomaDiagnostics | null): void {
39
+ this.diagnostics = diagnostics;
40
+ }
41
+
42
+ schedule<T>(
43
+ run: () => T | Promise<T>,
44
+ options: SomaSchedulerTaskOptions = {},
45
+ ): Promise<T> {
46
+ const priority = options.priority ?? 'visible';
47
+
48
+ return new Promise<T>((resolve, reject) => {
49
+ this.queues.get(priority)?.push({
50
+ run,
51
+ resolve: resolve as (value: unknown) => void,
52
+ reject,
53
+ priority,
54
+ label: options.label,
55
+ });
56
+
57
+ if (this.autoFlush) {
58
+ this.queueFlush();
59
+ }
60
+ });
61
+ }
62
+
63
+ cancelAll(reason: string = 'cancelled'): void {
64
+ for (const priority of PRIORITY_ORDER) {
65
+ const queue = this.queues.get(priority) ?? [];
66
+ for (const task of queue) {
67
+ task.reject(new Error(`[SomaScheduler] Task cancelled: ${reason}`));
68
+ }
69
+ this.queues.set(priority, []);
70
+ }
71
+ this.flushQueued = false;
72
+ }
73
+
74
+ async flush(): Promise<void> {
75
+ if (this.flushing) {
76
+ return;
77
+ }
78
+
79
+ this.flushQueued = false;
80
+ this.flushing = true;
81
+
82
+ try {
83
+ let hadWork = true;
84
+ while (hadWork) {
85
+ hadWork = false;
86
+ for (const priority of PRIORITY_ORDER) {
87
+ const queue = this.queues.get(priority);
88
+ while (queue && queue.length > 0) {
89
+ hadWork = true;
90
+ const task = queue.shift()!;
91
+ const startedAt = this.now();
92
+ try {
93
+ const result = await task.run();
94
+ task.resolve(result);
95
+ this.diagnostics?.recordScheduler({
96
+ priority: task.priority,
97
+ label: task.label,
98
+ durationMs: this.now() - startedAt,
99
+ status: 'success',
100
+ });
101
+ } catch (error) {
102
+ task.reject(error);
103
+ this.diagnostics?.recordScheduler({
104
+ priority: task.priority,
105
+ label: task.label,
106
+ durationMs: this.now() - startedAt,
107
+ status: 'error',
108
+ });
109
+ }
110
+ }
111
+ }
112
+ }
113
+ } finally {
114
+ this.flushing = false;
115
+ if (this.autoFlush && this.hasPendingTasks()) {
116
+ this.queueFlush();
117
+ }
118
+ }
119
+ }
120
+
121
+ private hasPendingTasks(): boolean {
122
+ return PRIORITY_ORDER.some((priority) => (this.queues.get(priority)?.length ?? 0) > 0);
123
+ }
124
+
125
+ private queueFlush(): void {
126
+ if (this.flushQueued || this.flushing) {
127
+ return;
128
+ }
129
+
130
+ this.flushQueued = true;
131
+
132
+ // 根据队列中最高优先级选择调度策略
133
+ const highestPriority = this.getHighestPendingPriority();
134
+
135
+ switch (highestPriority) {
136
+ case 'immediate':
137
+ // 微任务:最快执行
138
+ queueMicrotask(() => { void this.flush(); });
139
+ break;
140
+
141
+ case 'visible':
142
+ // rAF:保证视觉更新在下一帧执行(仅真实浏览器环境使用)
143
+ if (this.hasTrueRAF()) {
144
+ requestAnimationFrame(() => { void this.flush(); });
145
+ } else {
146
+ queueMicrotask(() => { void this.flush(); });
147
+ }
148
+ break;
149
+
150
+ case 'background':
151
+ // rIC:空闲时执行,不阻塞主线程
152
+ if (typeof requestIdleCallback === 'function' && this.hasTrueRAF()) {
153
+ requestIdleCallback(() => { void this.flush(); });
154
+ } else if (this.hasTrueRAF()) {
155
+ requestAnimationFrame(() => { void this.flush(); });
156
+ } else {
157
+ queueMicrotask(() => { void this.flush(); });
158
+ }
159
+ break;
160
+
161
+ default:
162
+ queueMicrotask(() => { void this.flush(); });
163
+ }
164
+ }
165
+
166
+ private getHighestPendingPriority(): SomaTaskPriority {
167
+ for (const priority of PRIORITY_ORDER) {
168
+ if ((this.queues.get(priority)?.length ?? 0) > 0) {
169
+ return priority;
170
+ }
171
+ }
172
+ return 'visible';
173
+ }
174
+
175
+ /**
176
+ * 检测是否在真实浏览器环境中(非 jsdom/Node)。
177
+ * jsdom 的 rAF 是简单的 setTimeout polyfill,时序不可靠。
178
+ */
179
+ private hasTrueRAF(): boolean {
180
+ return typeof requestAnimationFrame === 'function' &&
181
+ typeof document !== 'undefined' &&
182
+ typeof (document as any)?.createRange === 'function' &&
183
+ typeof navigator !== 'undefined' &&
184
+ !/jsdom/i.test(navigator?.userAgent ?? '');
185
+ }
186
+
187
+ private now(): number {
188
+ return globalThis.performance?.now?.() ?? Date.now();
189
+ }
190
+ }
@@ -0,0 +1,88 @@
1
+ // 业务领域类型定义 — 对应模块 6
2
+ // 定义 SOMA 框架中业务领域对象的 TypeScript 类型
3
+
4
+ /**
5
+ * 页面聚合根接口
6
+ * 展示对象必须实现此接口,提供页面生命周期钩子
7
+ */
8
+ export interface SomaPageRoot {
9
+ /** 国际化文本(引擎在 mount 时注入) */
10
+ _locale?: Record<string, unknown>;
11
+ /** 应用配置(引擎在 mount 时注入) */
12
+ _config?: unknown;
13
+ /** 页面初始化(引擎在渲染完成后调用) */
14
+ onMount?(): void | Promise<void>;
15
+ /** 页面销毁前(引擎在卸载时调用) */
16
+ onUnmount?(): void;
17
+ }
18
+
19
+ /**
20
+ * 应用配置接口
21
+ * 外部配置通过引擎注入到 Class 的 _config 属性
22
+ */
23
+ export interface SomaAppConfig {
24
+ /** API 基础地址 */
25
+ apiBaseUrl: string;
26
+ /** 默认分页大小 */
27
+ defaultPageSize: number;
28
+ /** 请求超时时间(毫秒) */
29
+ requestTimeout: number;
30
+ }
31
+
32
+ /**
33
+ * 校验规则
34
+ * 定义单个字段的校验条件
35
+ */
36
+ export interface ValidationRule {
37
+ /** 是否必填 */
38
+ required?: boolean;
39
+ /** 最小长度(字符串) */
40
+ minLength?: number;
41
+ /** 最大长度(字符串) */
42
+ maxLength?: number;
43
+ /** 最小值(数字) */
44
+ min?: number;
45
+ /** 最大值(数字) */
46
+ max?: number;
47
+ /** 正则表达式匹配 */
48
+ pattern?: RegExp;
49
+ /** 校验失败时的错误消息 */
50
+ message: string;
51
+ /** 自定义校验函数,返回 true 表示通过 */
52
+ custom?: (value: any) => boolean;
53
+ }
54
+
55
+ /**
56
+ * 校验结果
57
+ * validate 方法返回的结构化结果
58
+ */
59
+ export interface ValidationResult {
60
+ /** 整体校验是否通过 */
61
+ valid: boolean;
62
+ /** 各字段的错误消息集合 */
63
+ errors: Record<string, string[]>;
64
+ }
65
+
66
+ /**
67
+ * 业务事件处理函数签名
68
+ * 所有被 _event.yaml 引用的方法必须符合此签名
69
+ */
70
+ export interface SomaEventHandler {
71
+ (...args: any[]): Promise<boolean> | boolean | void;
72
+ }
73
+
74
+ /**
75
+ * 常量对象接口
76
+ * 提供静态枚举值或配置项
77
+ */
78
+ export interface SomaConstant {
79
+ readonly [key: string]: any;
80
+ }
81
+
82
+ /**
83
+ * 可加载常量接口
84
+ * 支持从后端加载动态字典数据
85
+ */
86
+ export interface SomaLoadableConstant extends SomaConstant {
87
+ loadFromAPI(): Promise<void>;
88
+ }
@@ -0,0 +1,35 @@
1
+ import type { ShowMapping } from './ui-config.types';
2
+
3
+ export type BindingType =
4
+ | 'text'
5
+ | 'attr'
6
+ | 'html'
7
+ | 'list'
8
+ | 'obj'
9
+ | 'model'
10
+ | 'when'
11
+ | 'class';
12
+
13
+ export interface BindingEntry {
14
+ somaId?: string;
15
+ dataPath: string;
16
+ watchPaths?: string[];
17
+ element: HTMLElement;
18
+ type: BindingType;
19
+ templateCache?: DocumentFragment;
20
+ childShowConfig?: ShowMapping;
21
+ attrName?: string;
22
+ negate?: boolean;
23
+ classRules?: Record<string, string>;
24
+
25
+ // ── 编译优化:mount 阶段生成,运行时直接调用 ──
26
+ /** 预编译的属性访问器:消除 path.split + 循环 */
27
+ compiledGetter?: (root: any) => any;
28
+ /** 预编译的渲染函数:消除 switch 分支 + 类型判断 */
29
+ compiledRender?: (value: any) => void;
30
+ }
31
+
32
+ export interface PendingPatch {
33
+ path: string;
34
+ value: any;
35
+ }
@@ -0,0 +1,57 @@
1
+ // 事件配置类型定义 — 对应模块 3
2
+ // 定义 SOMA 框架中 _event.yaml 配置文件的 TypeScript 类型
3
+
4
+ /**
5
+ * 事件类型枚举
6
+ * 定义 Pipeline DSL 支持的四种事件处理类型
7
+ */
8
+ export type EventType =
9
+ | 'NAV_STATIC' // 静态页面跳转
10
+ | 'NAV_ACTION' // 逻辑驱动跳转(先执行函数,成功后跳转)
11
+ | 'UI_REFRESH' // 数据刷新(执行函数后触发 UI 重新渲染)
12
+ | 'UI_INTERACT'; // UI 交互操作(显隐控制)
13
+
14
+ /**
15
+ * UI 交互动作枚举
16
+ * 用于 UI_INTERACT 类型的动作指令
17
+ */
18
+ export type InteractAction = 'open' | 'close' | 'toggle';
19
+
20
+ /**
21
+ * 解析后的事件配置
22
+ * Pipeline DSL 解析器将 YAML 中的事件声明解析为此结构
23
+ */
24
+ export interface ParsedEvent {
25
+ /** 目标元素的 data-soma-id 值 */
26
+ somaId: string;
27
+
28
+ /** DOM 事件类型(click, input, change, keydown 等) */
29
+ domEvent: string;
30
+
31
+ /** Pipeline 类型 */
32
+ type: EventType;
33
+
34
+ /** 业务逻辑函数路径(如 "boardCard.funcName1"),null 表示不执行逻辑 */
35
+ funcPath?: string | null;
36
+
37
+ /** 目标页面 URL(NAV_STATIC / NAV_ACTION 使用) */
38
+ targetUrl?: string;
39
+
40
+ /** 操作目标的 data-soma-id(UI_INTERACT 使用),undefined 时默认 self */
41
+ targetId?: string;
42
+
43
+ /** UI 动作指令(UI_INTERACT 使用),默认 toggle */
44
+ action?: InteractAction;
45
+
46
+ /**
47
+ * 键盘事件修饰符(如 "enter", "escape", "tab")
48
+ * 仅用于 keydown/keyup 事件,引擎在触发时检查 event.key 是否匹配
49
+ */
50
+ keyModifier?: string;
51
+ }
52
+
53
+ /**
54
+ * 事件配置原始结构
55
+ * YAML 反序列化后的嵌套对象,叶节点为 Pipeline 表达式字符串
56
+ */
57
+ export type EventConfigRaw = Record<string, string | Record<string, any>>;
@@ -0,0 +1,18 @@
1
+ // 键盘修饰符常量 — parser 和 engine 的唯一真实来源
2
+
3
+ /** 键盘修饰符别名 → KeyboardEvent.key 值的映射 */
4
+ export const SOMA_KEY_MODIFIERS: Record<string, string> = {
5
+ enter: 'Enter',
6
+ escape: 'Escape',
7
+ tab: 'Tab',
8
+ space: ' ',
9
+ backspace: 'Backspace',
10
+ delete: 'Delete',
11
+ arrowup: 'ArrowUp',
12
+ arrowdown: 'ArrowDown',
13
+ arrowleft: 'ArrowLeft',
14
+ arrowright: 'ArrowRight',
15
+ };
16
+
17
+ /** 所有合法的键盘修饰符名称集合(用于 parser 校验) */
18
+ export const VALID_KEY_MODIFIER_NAMES = new Set(Object.keys(SOMA_KEY_MODIFIERS));
@@ -0,0 +1,30 @@
1
+ import type { BindingType } from './engine.types';
2
+ import type { ParsedEvent } from './event.types';
3
+ import type { SomaTaskPriority } from './scheduler.types';
4
+ import type { ShowMapping } from './ui-config.types';
5
+
6
+ export interface SomaCompiledBinding {
7
+ id: string;
8
+ somaId: string;
9
+ type: BindingType;
10
+ dataPath: string;
11
+ watchPaths: string[];
12
+ attrName?: string;
13
+ negate?: boolean;
14
+ classRules?: Record<string, string>;
15
+ childShowConfig?: ShowMapping;
16
+ /** 静态提升标记:值在初始化后不会变化,不需要注册 watchPaths */
17
+ static?: boolean;
18
+ }
19
+
20
+ export interface SomaCompiledEvent extends ParsedEvent {
21
+ eventKey: string;
22
+ priority: SomaTaskPriority;
23
+ }
24
+
25
+ export interface SomaRuntimeManifest {
26
+ bindings: SomaCompiledBinding[];
27
+ bindingIndex: Map<string, SomaCompiledBinding[]>;
28
+ events: SomaCompiledEvent[];
29
+ eventIndex: Map<string, SomaCompiledEvent>;
30
+ }
@@ -0,0 +1,10 @@
1
+ export type SomaTaskPriority = 'immediate' | 'visible' | 'background';
2
+
3
+ export interface SomaSchedulerTaskOptions {
4
+ priority?: SomaTaskPriority;
5
+ label?: string;
6
+ }
7
+
8
+ export interface SomaSchedulerOptions {
9
+ autoFlush?: boolean;
10
+ }
@@ -0,0 +1,89 @@
1
+ // UI 配置类型定义 — 对应模块 2
2
+ // 定义 SOMA 框架中 _ui.yaml 配置文件的 TypeScript 类型
3
+
4
+ /**
5
+ * 作用域声明
6
+ * 定义数据源路径和当前作用域别名
7
+ */
8
+ export interface BindDeclaration {
9
+ /** 数据源路径。顶层 = Class 标识;嵌套层 = 父 var.属性路径 */
10
+ obj: string;
11
+ /** 当前层级别名,子层级和事件配置通过此别名引用数据 */
12
+ var: string;
13
+ }
14
+
15
+ /**
16
+ * 展示映射值 - 支持多种绑定类型
17
+ *
18
+ * 可以是以下形式之一:
19
+ * - 简单文本绑定字符串:"var.prop"
20
+ * - 嵌套绑定:包含 bind + show 的嵌套结构
21
+ * - 扩展绑定:包含 text / model / when / class 等高级绑定
22
+ */
23
+ export type ShowValue =
24
+ | string // 简单文本绑定:"var.prop"
25
+ | NestedShowMapping // 嵌套绑定(对象/列表)
26
+ | ExtendedShowValue; // 扩展绑定
27
+
28
+ /**
29
+ * 嵌套展示映射
30
+ * 用于对象或列表级别的子作用域绑定
31
+ */
32
+ export interface NestedShowMapping {
33
+ /** 子作用域声明 */
34
+ bind: BindDeclaration;
35
+ /** 子级展示映射 */
36
+ show: ShowMapping;
37
+ }
38
+
39
+ /**
40
+ * 扩展绑定值
41
+ * 支持 text、model、when、class 等高级绑定类型
42
+ */
43
+ export interface ExtendedShowValue {
44
+ /** 文本绑定路径 */
45
+ text?: string;
46
+ /** 双向绑定路径(表单控件) */
47
+ model?: string;
48
+ /** 条件渲染路径(truthy 显示,"!path" 取反) */
49
+ when?: string;
50
+ /** CSS 类名动态绑定 { "class-names": "condition-path" } */
51
+ class?: Record<string, string>;
52
+ /** 子级展示映射 */
53
+ show?: ShowMapping;
54
+ }
55
+
56
+ /**
57
+ * 展示映射
58
+ * 键为 data-soma-id 属性值,值为 ShowValue
59
+ *
60
+ * 键的格式:
61
+ * - "somaId" — 默认文本绑定
62
+ * - "somaId@attr" — 属性绑定(如 somaId@src, somaId@href)
63
+ * - "somaId@html" — HTML 内容注入
64
+ */
65
+ export type ShowMapping = Record<string, ShowValue>;
66
+
67
+ /**
68
+ * UI 配置顶层结构
69
+ * 对应 _ui.yaml 文件的完整结构
70
+ */
71
+ export interface UiConfig {
72
+ /** 顶级作用域声明 */
73
+ bind: BindDeclaration;
74
+ /** 顶级展示映射 */
75
+ show: ShowMapping;
76
+ }
77
+
78
+ /**
79
+ * 解析后的 show 条目
80
+ * somaId@attr 语法拆分为 somaId + attrName
81
+ */
82
+ export interface ParsedShowEntry {
83
+ /** 纯 data-soma-id(不含 @attr 后缀) */
84
+ somaId: string;
85
+ /** 属性绑定时的属性名(如 src、href、value) */
86
+ attrName?: string;
87
+ /** 原始绑定值 */
88
+ value: ShowValue;
89
+ }