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,97 @@
1
+ // soma-core/app/api/page/route.ts — URL 直接映射 html/ui/event 文件
2
+ // 规则:/ → index.html,其他 /xxx → xxx.html,/xxx/yyy → xxx/yyy.html
3
+
4
+ import { join, normalize, resolve } from 'path';
5
+ import { NextRequest } from 'next/server';
6
+ import { ServerFileCache } from '../../../core/infra/cache/ServerFileCache';
7
+
8
+ const cache = ServerFileCache.getInstance();
9
+
10
+ function getHostDir(): string | undefined {
11
+ return process.env.SOMA_HOST_DIR || undefined;
12
+ }
13
+
14
+ let watchedRoot: string | null = null;
15
+
16
+ function ensureWatch(root: string) {
17
+ if (watchedRoot === root) return;
18
+ watchedRoot = root;
19
+ cache.watchAndInvalidate(root);
20
+ }
21
+
22
+ function urlToBase(urlPath: string): string {
23
+ const clean = urlPath.replace(/^\//, '').replace(/\.html$/, '');
24
+ return clean || 'index';
25
+ }
26
+
27
+ function isPathSafe(base: string): boolean {
28
+ const normalized = normalize(base);
29
+ return !normalized.startsWith('..') && !normalized.includes('\0') && !/^[a-zA-Z]:/.test(normalized);
30
+ }
31
+
32
+ function collectIncludes(hostDir: string): Record<string, string> {
33
+ const includes: Record<string, string> = {};
34
+ const sharedDir = join(hostDir, 'html', 'shared');
35
+ try {
36
+ const files = cache.readDirFiles(sharedDir, '.html');
37
+ const names = cache.readDirNames(sharedDir, '.html');
38
+ for (let i = 0; i < names.length; i++) {
39
+ includes[`shared/${names[i]}`] = files[i];
40
+ }
41
+ } catch {}
42
+ return includes;
43
+ }
44
+
45
+ export async function GET(req: NextRequest) {
46
+ const hostDir = getHostDir();
47
+ if (!hostDir) {
48
+ return Response.json(
49
+ { error: 'SOMA_HOST_DIR 未设置。请在宿主应用根目录执行:npx soma dev。' },
50
+ { status: 503 },
51
+ );
52
+ }
53
+
54
+ ensureWatch(hostDir);
55
+
56
+ const urlPath = req.nextUrl.searchParams.get('path') || '/';
57
+ const base = urlToBase(urlPath);
58
+
59
+ if (!isPathSafe(base)) {
60
+ return Response.json({ error: 'Invalid path' }, { status: 400 });
61
+ }
62
+
63
+ const htmlPath = join(hostDir, 'html', `${base}.html`);
64
+ const resolvedHtml = resolve(htmlPath);
65
+ const resolvedHostHtml = resolve(hostDir, 'html');
66
+ if (!resolvedHtml.startsWith(resolvedHostHtml)) {
67
+ return Response.json({ error: 'Invalid path' }, { status: 400 });
68
+ }
69
+
70
+ try {
71
+ const html = cache.readFile(htmlPath);
72
+
73
+ let ui: string, event: string, localeYaml: string, appConfigYaml: string;
74
+ try {
75
+ ui = cache.tryReadFile(join(hostDir, 'ui', `${base}_ui.yaml`));
76
+ event = cache.tryReadFile(join(hostDir, 'event', `${base}_event.yaml`));
77
+ localeYaml = cache.tryReadFile(join(hostDir, 'config', 'locale.yaml'));
78
+ appConfigYaml = cache.tryReadFile(join(hostDir, 'config', 'app.config.yaml'));
79
+ } catch (e: any) {
80
+ return Response.json({ error: `Asset read error: ${e.message}` }, { status: 500 });
81
+ }
82
+
83
+ const includes = collectIncludes(hostDir);
84
+
85
+ return Response.json({
86
+ base,
87
+ html,
88
+ ui,
89
+ event,
90
+ localeYaml,
91
+ appConfigYaml,
92
+ includes,
93
+ });
94
+ } catch (e: any) {
95
+ return Response.json({ error: `Page not found: ${base}.html` }, { status: 404 });
96
+ }
97
+ }
@@ -0,0 +1,3 @@
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
package/app/layout.tsx ADDED
@@ -0,0 +1,18 @@
1
+ import './globals.css';
2
+
3
+ export const metadata = {
4
+ title: process.env.SOMA_APP_TITLE || 'SOMA App',
5
+ description: process.env.SOMA_APP_DESC || 'SOMA Framework',
6
+ };
7
+
8
+ export default function RootLayout({
9
+ children,
10
+ }: {
11
+ children: React.ReactNode;
12
+ }) {
13
+ return (
14
+ <html lang="en">
15
+ <body>{children}</body>
16
+ </html>
17
+ );
18
+ }
package/app/page.tsx ADDED
@@ -0,0 +1,129 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useRef, useState } from 'react';
4
+ import { usePathname } from 'next/navigation';
5
+ import type { SomaBootstrap as SomaBootstrapType } from '../core/engine/soma-bootstrap';
6
+
7
+ const isDev = process.env.NODE_ENV !== 'production';
8
+
9
+ export default function SomaEntry() {
10
+ const pathname = usePathname();
11
+ return <SomaPageRenderer path={pathname} />;
12
+ }
13
+
14
+ function urlToBase(urlPath: string): string {
15
+ const clean = urlPath.replace(/^\//, '').replace(/\.html$/, '');
16
+ return clean || 'index';
17
+ }
18
+
19
+ type PagePayload = {
20
+ html: string;
21
+ ui: string;
22
+ event: string;
23
+ includes?: Record<string, string>;
24
+ localeYaml: string;
25
+ appConfigYaml: string;
26
+ };
27
+
28
+ const pageAssetCache = new Map<string, PagePayload>();
29
+
30
+ function SomaPageRenderer({ path }: { path: string }) {
31
+ const containerRef = useRef<HTMLDivElement>(null);
32
+ const bootstrapRef = useRef<SomaBootstrapType | null>(null);
33
+ const [error, setError] = useState<string | null>(null);
34
+
35
+ useEffect(() => {
36
+ if (!containerRef.current) return;
37
+
38
+ const base = urlToBase(path);
39
+ let cancelled = false;
40
+
41
+ const run = async () => {
42
+ try {
43
+ setError(null);
44
+
45
+ let DomainClass: new () => any;
46
+ try {
47
+ const mod = await import(
48
+ /* webpackInclude: /\.ts$/ */
49
+ `@soma-host/domain/ui/${base}Class`
50
+ );
51
+ DomainClass = mod.default ?? mod[Object.keys(mod)[0]];
52
+ } catch {
53
+ const { SomaLocaleOnlyPageRoot } = await import('../core/base/SomaLocaleOnlyPageRoot');
54
+ DomainClass = SomaLocaleOnlyPageRoot;
55
+ }
56
+
57
+ const { SomaBootstrap } = await import('../core/engine/soma-bootstrap');
58
+
59
+ // dev 模式不使用客户端 payload 缓存(服务端文件变更需实时反映)
60
+ if (!isDev) {
61
+ const cached = pageAssetCache.get(path);
62
+ if (cached) {
63
+ await mountInto(DomainClass, SomaBootstrap, cached);
64
+ return;
65
+ }
66
+ }
67
+
68
+ const res = await fetch(
69
+ `/api/page?path=${encodeURIComponent(path)}`,
70
+ );
71
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
72
+
73
+ const data = await res.json();
74
+ if (cancelled) return;
75
+
76
+ const payload: PagePayload = {
77
+ html: data.html,
78
+ ui: data.ui,
79
+ event: data.event,
80
+ includes: data.includes,
81
+ localeYaml: data.localeYaml ?? '',
82
+ appConfigYaml: data.appConfigYaml ?? '',
83
+ };
84
+
85
+ if (!isDev) {
86
+ pageAssetCache.set(path, payload);
87
+ }
88
+ await mountInto(DomainClass, SomaBootstrap, payload);
89
+ } catch (err: any) {
90
+ if (!cancelled) setError(err?.message ?? String(err));
91
+ }
92
+ };
93
+
94
+ const mountInto = async (DomainClass: new () => any, SomaBootstrap: any, payload: PagePayload) => {
95
+ await bootstrapRef.current?.unmount();
96
+ const bs = new SomaBootstrap();
97
+ bootstrapRef.current = bs;
98
+
99
+ await bs.mount(containerRef.current!, {
100
+ html: payload.html,
101
+ includes: payload.includes,
102
+ DomainClass,
103
+ uiYaml: payload.ui,
104
+ eventYaml: payload.event,
105
+ localeYaml: payload.localeYaml ?? '',
106
+ appConfigYaml: payload.appConfigYaml ?? '',
107
+ });
108
+ };
109
+
110
+ void run();
111
+
112
+ return () => {
113
+ cancelled = true;
114
+ void bootstrapRef.current?.unmount();
115
+ bootstrapRef.current = null;
116
+ };
117
+ }, [path]);
118
+
119
+ if (error) {
120
+ return (
121
+ <div className="p-8 text-red-600">
122
+ <p className="font-bold">页面加载失败</p>
123
+ <p className="text-sm mt-1">{error}</p>
124
+ </div>
125
+ );
126
+ }
127
+
128
+ return <div ref={containerRef} />;
129
+ }
package/bin/soma.cjs ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../dist/cli/soma.js');
@@ -0,0 +1,14 @@
1
+ // soma-core/core/base/SomaApi.ts
2
+ // 业务 API 处理类基类,用户继承此类实现具体接口
3
+
4
+ export abstract class SomaApi {
5
+ abstract handle(req: Request): Promise<Response>;
6
+
7
+ protected json(data: unknown, status = 200): Response {
8
+ return Response.json(data, { status });
9
+ }
10
+
11
+ protected error(message: string, status = 400): Response {
12
+ return Response.json({ error: message }, { status });
13
+ }
14
+ }
@@ -0,0 +1,168 @@
1
+ // core/base/SomaDict.ts — 字典基类
2
+ // 封装缓存、去重加载、TTL 机制的字典数据管理
3
+ // 不依赖任何 DOM API,可在 Node.js 环境下独立运行
4
+
5
+ /**
6
+ * 缓存条目
7
+ */
8
+ interface CacheEntry<T> {
9
+ /** 缓存的数据 */
10
+ data: T;
11
+ /** 缓存写入时的时间戳(ms) */
12
+ timestamp: number;
13
+ }
14
+
15
+ /**
16
+ * SomaDict — 字典基类
17
+ *
18
+ * 为常量对象/字典数据提供以下能力:
19
+ * - 数据缓存:避免重复请求同一字典
20
+ * - 去重加载:同一 key 在并发请求时只发起一次实际加载
21
+ * - TTL 过期:缓存可配置生存时间,过期后自动重新加载
22
+ *
23
+ * 子类需实现 fetchData() 方法,定义具体的数据加载逻辑。
24
+ *
25
+ * @template T 字典数据类型
26
+ *
27
+ * 使用示例:
28
+ * ```typescript
29
+ * class DeviceTypeDict extends SomaDict<string[]> {
30
+ * protected async fetchData(key: string): Promise<string[]> {
31
+ * const res = await fetch(`/api/dict/${key}`);
32
+ * return res.json();
33
+ * }
34
+ * }
35
+ *
36
+ * const dict = new DeviceTypeDict();
37
+ * const types = await dict.get('device_types');
38
+ * ```
39
+ */
40
+ export abstract class SomaDict<T = any> {
41
+ /** 数据缓存:key -> CacheEntry */
42
+ private cache: Map<string, CacheEntry<T>> = new Map();
43
+
44
+ /** 进行中的请求:key -> Promise(用于去重) */
45
+ private pending: Map<string, Promise<T>> = new Map();
46
+
47
+ /** 缓存生存时间(毫秒),默认 5 分钟。子类可 override */
48
+ protected ttl: number = 5 * 60 * 1000;
49
+
50
+ /**
51
+ * 子类必须实现:定义具体的数据加载逻辑
52
+ *
53
+ * @param key 字典键
54
+ * @returns 加载到的数据
55
+ */
56
+ protected abstract fetchData(key: string): Promise<T>;
57
+
58
+ /**
59
+ * 获取字典数据
60
+ * 优先从缓存读取,缓存未命中或已过期时从后端加载
61
+ * 并发请求同一 key 时自动去重,共享同一个 Promise
62
+ *
63
+ * @param key 字典键
64
+ * @param forceRefresh 是否强制刷新(忽略缓存)
65
+ * @returns 字典数据
66
+ */
67
+ async get(key: string, forceRefresh: boolean = false): Promise<T> {
68
+ // 检查缓存是否有效
69
+ if (!forceRefresh) {
70
+ const cached = this.cache.get(key);
71
+ if (cached && !this.isExpired(cached)) {
72
+ return cached.data;
73
+ }
74
+ }
75
+
76
+ // 检查是否有进行中的相同请求(去重)
77
+ const inflight = this.pending.get(key);
78
+ if (inflight) {
79
+ return inflight;
80
+ }
81
+
82
+ // 发起新的加载请求
83
+ const promise = this.loadAndCache(key);
84
+ this.pending.set(key, promise);
85
+
86
+ try {
87
+ return await promise;
88
+ } finally {
89
+ this.pending.delete(key);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * 批量获取多个字典数据
95
+ *
96
+ * @param keys 字典键数组
97
+ * @returns key -> data 的映射
98
+ */
99
+ async getMany(keys: string[]): Promise<Map<string, T>> {
100
+ const results = new Map<string, T>();
101
+ const promises = keys.map(async (key) => {
102
+ const data = await this.get(key);
103
+ results.set(key, data);
104
+ });
105
+ await Promise.all(promises);
106
+ return results;
107
+ }
108
+
109
+ /**
110
+ * 手动设置缓存(用于预热或测试)
111
+ *
112
+ * @param key 字典键
113
+ * @param data 数据
114
+ */
115
+ set(key: string, data: T): void {
116
+ this.cache.set(key, {
117
+ data,
118
+ timestamp: Date.now(),
119
+ });
120
+ }
121
+
122
+ /**
123
+ * 使指定 key 的缓存失效
124
+ *
125
+ * @param key 字典键
126
+ */
127
+ invalidate(key: string): void {
128
+ this.cache.delete(key);
129
+ }
130
+
131
+ /**
132
+ * 清空所有缓存
133
+ */
134
+ clear(): void {
135
+ this.cache.clear();
136
+ this.pending.clear();
137
+ }
138
+
139
+ /**
140
+ * 检查指定 key 是否已缓存且未过期
141
+ *
142
+ * @param key 字典键
143
+ * @returns 是否有有效缓存
144
+ */
145
+ has(key: string): boolean {
146
+ const cached = this.cache.get(key);
147
+ return cached != null && !this.isExpired(cached);
148
+ }
149
+
150
+ /**
151
+ * 加载数据并写入缓存
152
+ */
153
+ private async loadAndCache(key: string): Promise<T> {
154
+ const data = await this.fetchData(key);
155
+ this.cache.set(key, {
156
+ data,
157
+ timestamp: Date.now(),
158
+ });
159
+ return data;
160
+ }
161
+
162
+ /**
163
+ * 检查缓存条目是否已过期
164
+ */
165
+ private isExpired(entry: CacheEntry<T>): boolean {
166
+ return Date.now() - entry.timestamp > this.ttl;
167
+ }
168
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * SomaEntity - 业务实体基类
3
+ * 封装通用的异步操作状态管理和序列化能力
4
+ */
5
+ export abstract class SomaEntity<T extends Record<string, any> = Record<string, any>> {
6
+ /** 实体级 loading 状态(Proxy 响应式) */
7
+ loading: boolean = false;
8
+
9
+ /** 实体级错误信息(Proxy 响应式) */
10
+ error: string | null = null;
11
+
12
+ /**
13
+ * 封装异步操作:自动管理 loading/error 状态
14
+ */
15
+ protected async runAsync<R>(fn: () => Promise<R>): Promise<R | null> {
16
+ this.loading = true;
17
+ this.error = null;
18
+ try {
19
+ return await fn();
20
+ } catch (e) {
21
+ this.error = e instanceof Error ? e.message : String(e);
22
+ return null;
23
+ } finally {
24
+ this.loading = false;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * 序列化为纯对象(提交给后端)
30
+ * 排除以 _ 开头的私有字段和 loading/error 状态字段
31
+ */
32
+ toJSON(): Partial<T> {
33
+ const result: any = {};
34
+ for (const key of Object.keys(this)) {
35
+ if (!key.startsWith('_') && key !== 'loading' && key !== 'error') {
36
+ result[key] = (this as any)[key];
37
+ }
38
+ }
39
+ return result;
40
+ }
41
+ }
@@ -0,0 +1,126 @@
1
+ // core/base/SomaHttpClient.ts — API 请求封装
2
+ // 统一的 HTTP 客户端,处理 baseURL、超时、错误拦截、请求取消
3
+ // 不依赖任何 DOM API,可在 Node.js 环境下独立运行
4
+ // 使用全局 fetch(Node.js 18+ 原生支持,或通过 polyfill 提供)
5
+
6
+ /**
7
+ * HTTP 客户端配置
8
+ */
9
+ export interface SomaHttpClientConfig {
10
+ /** API 基础地址(如 "https://api.example.com") */
11
+ baseURL: string;
12
+ /** 请求超时时间(毫秒),默认 30000 */
13
+ timeout?: number;
14
+ }
15
+
16
+ /**
17
+ * SomaHttpClient — API 请求封装
18
+ *
19
+ * 提供以下能力:
20
+ * - GET / POST / PUT / DELETE 四种 HTTP 方法
21
+ * - baseURL 自动拼接
22
+ * - 超时控制(基于 AbortController)
23
+ * - 请求取消:abortAll() 可一键取消所有进行中的请求
24
+ * - JSON 自动序列化/反序列化
25
+ *
26
+ * 使用示例:
27
+ * ```typescript
28
+ * const http = new SomaHttpClient({ baseURL: 'https://api.example.com' });
29
+ * const data = await http.get<User[]>('/users');
30
+ * ```
31
+ */
32
+ export class SomaHttpClient {
33
+ private baseURL: string;
34
+ private timeout: number;
35
+ private abortControllers: Set<AbortController> = new Set();
36
+
37
+ constructor(config: SomaHttpClientConfig) {
38
+ this.baseURL = config.baseURL;
39
+ this.timeout = config.timeout ?? 30000;
40
+ }
41
+
42
+ /**
43
+ * 发送 GET 请求
44
+ * @param path 请求路径(拼接在 baseURL 后面)
45
+ * @returns 响应 JSON 解析后的数据
46
+ */
47
+ async get<T>(path: string): Promise<T> {
48
+ return this.request<T>('GET', path);
49
+ }
50
+
51
+ /**
52
+ * 发送 POST 请求
53
+ * @param path 请求路径
54
+ * @param body 请求体(将被 JSON.stringify 序列化)
55
+ * @returns 响应 JSON 解析后的数据
56
+ */
57
+ async post<T>(path: string, body?: any): Promise<T> {
58
+ return this.request<T>('POST', path, body);
59
+ }
60
+
61
+ /**
62
+ * 发送 PUT 请求
63
+ * @param path 请求路径
64
+ * @param body 请求体
65
+ * @returns 响应 JSON 解析后的数据
66
+ */
67
+ async put<T>(path: string, body?: any): Promise<T> {
68
+ return this.request<T>('PUT', path, body);
69
+ }
70
+
71
+ /**
72
+ * 发送 DELETE 请求
73
+ * @param path 请求路径
74
+ * @returns 响应 JSON 解析后的数据
75
+ */
76
+ async delete<T>(path: string): Promise<T> {
77
+ return this.request<T>('DELETE', path);
78
+ }
79
+
80
+ /**
81
+ * 取消所有进行中的请求
82
+ * 通常在 onUnmount 生命周期钩子中调用
83
+ */
84
+ abortAll(): void {
85
+ this.abortControllers.forEach((c) => c.abort());
86
+ this.abortControllers.clear();
87
+ }
88
+
89
+ /**
90
+ * 内部统一请求方法
91
+ */
92
+ private async request<T>(method: string, path: string, body?: any): Promise<T> {
93
+ const controller = new AbortController();
94
+ this.abortControllers.add(controller);
95
+
96
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
97
+
98
+ try {
99
+ const url = `${this.baseURL}${path}`;
100
+ const headers: Record<string, string> = {
101
+ 'Content-Type': 'application/json',
102
+ };
103
+
104
+ const options: RequestInit = {
105
+ method,
106
+ headers,
107
+ signal: controller.signal,
108
+ };
109
+
110
+ if (body !== undefined) {
111
+ options.body = JSON.stringify(body);
112
+ }
113
+
114
+ const res = await fetch(url, options);
115
+
116
+ if (!res.ok) {
117
+ throw new Error(`HTTP ${res.status}: ${res.statusText}`);
118
+ }
119
+
120
+ return (await res.json()) as T;
121
+ } finally {
122
+ clearTimeout(timeoutId);
123
+ this.abortControllers.delete(controller);
124
+ }
125
+ }
126
+ }
@@ -0,0 +1,4 @@
1
+ import { SomaPageRootBase } from './SomaPageRootBase';
2
+
3
+ /** 无独立 Domain 实现时的占位页(仅 locale/appConfig 文案) */
4
+ export class SomaLocaleOnlyPageRoot extends SomaPageRootBase {}
@@ -0,0 +1,54 @@
1
+ // core/base/SomaPageRootBase.ts — 页面聚合根基类
2
+ // 不依赖任何 DOM API,可在 Node.js 环境下独立运行
3
+
4
+ import type { SomaPageRoot, SomaAppConfig } from '../types/domain.types';
5
+
6
+ /**
7
+ * SomaPageRootBase — 页面聚合根基类
8
+ *
9
+ * 与物理页面(如 index.html)严格 1:1 绑定的聚合根对象。
10
+ * 提供页面级状态管理和生命周期钩子的默认实现。
11
+ *
12
+ * 子类应当:
13
+ * - override onMount() 实现页面初始化逻辑(加载数据、字典等)
14
+ * - override onUnmount() 实现页面清理逻辑(取消请求、清除定时器等)
15
+ * - 聚合业务对象和常量对象作为属性
16
+ */
17
+ export abstract class SomaPageRootBase implements SomaPageRoot {
18
+ /** 页面级 loading 状态(Proxy 响应式) */
19
+ pageLoading: boolean = false;
20
+
21
+ /** 页面级错误信息(Proxy 响应式) */
22
+ pageError: string | null = null;
23
+
24
+ /**
25
+ * 由引擎注入的 locale 配置
26
+ * 包含页面上的固定文案(按钮文字、标题、提示语等)
27
+ * Class 不负责加载此数据,由编排层(SomaBootstrap)统一加载并注入
28
+ */
29
+ _locale: Record<string, string> = {};
30
+
31
+ /**
32
+ * 由引擎注入的应用配置
33
+ * 包含 API 地址、分页大小、超时时间等外部配置
34
+ */
35
+ _config: SomaAppConfig = {} as SomaAppConfig;
36
+
37
+ /**
38
+ * 页面初始化生命周期钩子
39
+ * 引擎在渲染完成后调用
40
+ * 子类 override 实现具体初始化逻辑
41
+ */
42
+ async onMount(): Promise<void> {
43
+ // 子类 override 实现具体初始化
44
+ }
45
+
46
+ /**
47
+ * 页面销毁前生命周期钩子
48
+ * 引擎在卸载时调用
49
+ * 子类 override 实现清理逻辑
50
+ */
51
+ onUnmount(): void {
52
+ // 子类 override 实现清理
53
+ }
54
+ }