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,252 @@
1
+ // core/engine/scope-resolver.ts
2
+
3
+ import type { UiConfig, NestedShowMapping } from '../types/ui-config.types';
4
+
5
+ /**
6
+ * SOMA 作用域解析器
7
+ *
8
+ * 统一管理 var 别名的注册和解析。
9
+ * 渲染引擎和事件引擎共用同一个实例,确保路径解析一致。
10
+ */
11
+ export class SomaScopeResolver {
12
+ /** var 别名 → 属性路径(用于渲染引擎的绑定表编译) */
13
+ private varMap = new Map<string, string>();
14
+
15
+ /** var 别名 → 实际对象引用(用于事件引擎的函数调用) */
16
+ private scopeChain = new Map<string, any>();
17
+
18
+ /** 根实例引用 */
19
+ private rootInstance: object = {};
20
+
21
+ /**
22
+ * 从 UiConfig 构建 var 映射和作用域链。
23
+ *
24
+ * 规则:
25
+ * - 顶级 bind:var 指向根实例本身(obj 是 Class 标识符,非属性路径)
26
+ * - 嵌套 bind:var 指向 obj 路径对应的子对象
27
+ */
28
+ build(config: UiConfig, rootInstance: object): void {
29
+ this.rootInstance = rootInstance;
30
+ this.varMap.clear();
31
+ this.scopeChain.clear();
32
+ this.walkConfig(config, rootInstance, true);
33
+ }
34
+
35
+ /**
36
+ * 将含 var 别名的路径解析为实际属性路径。
37
+ * 如 "page.boardCard.name" → "boardCard.name"(page 映射到空路径)
38
+ * 如 "s.name" → "s.name"(如果 s 是列表迭代变量,不在 varMap 中时原样返回)
39
+ */
40
+ resolvePath(path: string): string {
41
+ const segments = path.split('.');
42
+ const firstSeg = segments[0];
43
+ const resolvedBase = this.varMap.get(firstSeg);
44
+
45
+ if (resolvedBase !== undefined) {
46
+ const rest = segments.slice(1).join('.');
47
+ if (!resolvedBase) {
48
+ // var 指向根实例(路径为空)
49
+ return rest || firstSeg;
50
+ }
51
+ return rest ? `${resolvedBase}.${rest}` : resolvedBase;
52
+ }
53
+
54
+ return path;
55
+ }
56
+
57
+ /**
58
+ * 从实例上读取属性路径对应的值。
59
+ */
60
+ readValue(instance: object, path: string): any {
61
+ if (!path) return instance;
62
+ const segments = path.split('.');
63
+ let current: any = instance;
64
+ for (const seg of segments) {
65
+ if (current == null) return undefined;
66
+ current = current[seg];
67
+ }
68
+ return current;
69
+ }
70
+
71
+ /**
72
+ * 从根实例读取已解析路径的值。
73
+ */
74
+ readFromRoot(path: string): any {
75
+ return this.readValue(this.rootInstance, path);
76
+ }
77
+
78
+ // ─── 编译优化:预编译属性访问器 ────────────────────────
79
+
80
+ /** 编译缓存:path → compiled getter */
81
+ private getterCache = new Map<string, (root: any) => any>();
82
+
83
+ /**
84
+ * 将属性路径编译为直接访问函数。
85
+ *
86
+ * 消除运行时的 path.split('.') + 循环读取,
87
+ * 编译为 (root) => root?.seg0?.seg1?.seg2 形式的直接属性链。
88
+ *
89
+ * 等价于 C++ 编译器将 obj.a.b.c 编译为连续的偏移量寻址。
90
+ */
91
+ compileGetter(path: string): (root: any) => any {
92
+ if (!path) return (root: any) => root;
93
+
94
+ const cached = this.getterCache.get(path);
95
+ if (cached) return cached;
96
+
97
+ const segments = path.split('.');
98
+
99
+ // 特化短路径:避免闭包+循环开销
100
+ let getter: (root: any) => any;
101
+ switch (segments.length) {
102
+ case 1:
103
+ getter = (root) => root?.[segments[0]];
104
+ break;
105
+ case 2:
106
+ getter = (root) => root?.[segments[0]]?.[segments[1]];
107
+ break;
108
+ case 3:
109
+ getter = (root) => root?.[segments[0]]?.[segments[1]]?.[segments[2]];
110
+ break;
111
+ default:
112
+ // 通用路径:预存 segments 避免运行时 split
113
+ getter = (root) => {
114
+ let current = root;
115
+ for (let i = 0; i < segments.length; i++) {
116
+ if (current == null) return undefined;
117
+ current = current[segments[i]];
118
+ }
119
+ return current;
120
+ };
121
+ }
122
+
123
+ this.getterCache.set(path, getter);
124
+ return getter;
125
+ }
126
+
127
+ /**
128
+ * 使用编译后的 getter 从根实例读取值。
129
+ * 比 readFromRoot 快:无 split,无动态循环。
130
+ */
131
+ readFromRootCompiled(path: string): any {
132
+ const getter = this.compileGetter(path);
133
+ return getter(this.rootInstance);
134
+ }
135
+
136
+ /**
137
+ * 解析函数路径并返回 bound function。
138
+ * 函数通过 .bind(owner) 绑定到方法所属的对象。
139
+ *
140
+ * @throws Error 如果路径无法解析或结果不是函数
141
+ */
142
+ resolveFunction(funcPath: string): Function {
143
+ const segments = funcPath.split('.');
144
+ const rootKey = segments[0];
145
+
146
+ // 从 scopeChain 查找
147
+ let current: any = this.scopeChain.get(rootKey);
148
+ if (current === undefined) {
149
+ // 回退到 rootInstance
150
+ current = (this.rootInstance as any)[rootKey];
151
+ }
152
+ if (current === undefined) {
153
+ throw new Error(`[SomaScopeResolver] Cannot resolve "${rootKey}" in "${funcPath}"`);
154
+ }
155
+
156
+ // 遍历剩余段,保留 owner
157
+ let owner: any = current;
158
+ for (let i = 1; i < segments.length; i++) {
159
+ owner = current;
160
+ current = current[segments[i]];
161
+ if (current === undefined) {
162
+ throw new Error(`[SomaScopeResolver] Cannot resolve "${segments[i]}" in "${funcPath}"`);
163
+ }
164
+ }
165
+
166
+ if (typeof current !== 'function') {
167
+ throw new Error(`[SomaScopeResolver] "${funcPath}" is not a function`);
168
+ }
169
+
170
+ return current.bind(owner);
171
+ }
172
+
173
+ /**
174
+ * 获取 var 别名对应的路径(供绑定编译器使用)。
175
+ */
176
+ getVarPath(varName: string): string | undefined {
177
+ return this.varMap.get(varName);
178
+ }
179
+
180
+ /**
181
+ * 检查是否有指定的 var 别名。
182
+ */
183
+ hasVar(varName: string): boolean {
184
+ return this.varMap.has(varName);
185
+ }
186
+
187
+ /**
188
+ * 判断某个 var 别名是否指向集合元素(即路径非空,而非顶级根实例)。
189
+ * 用于事件引擎区分"列表项上下文"和"根实例上下文"。
190
+ */
191
+ isListVar(varName: string): boolean {
192
+ const path = this.varMap.get(varName);
193
+ return path !== undefined && path !== '';
194
+ }
195
+
196
+ // ─── 内部方法 ──────────────────────────────────────────────
197
+
198
+ private walkConfig(
199
+ config: UiConfig | NestedShowMapping,
200
+ parentInstance: object,
201
+ isRoot: boolean
202
+ ): void {
203
+ const varName = config.bind?.var;
204
+ const objPath = config.bind?.obj;
205
+
206
+ if (varName) {
207
+ if (isRoot) {
208
+ // 顶级:var 直接指向根实例本身
209
+ this.varMap.set(varName, '');
210
+ this.scopeChain.set(varName, parentInstance);
211
+ } else if (objPath) {
212
+ // 嵌套:解析 obj 路径到实际对象
213
+ const resolvedPath = this.resolvePath(objPath);
214
+ this.varMap.set(varName, resolvedPath);
215
+
216
+ const resolvedObj = this.resolveObjFromChain(objPath, parentInstance);
217
+ if (resolvedObj !== undefined) {
218
+ this.scopeChain.set(varName, resolvedObj);
219
+ }
220
+ }
221
+ }
222
+
223
+ // 递归处理嵌套的 NestedShowMapping
224
+ if (config.show) {
225
+ for (const value of Object.values(config.show)) {
226
+ if (typeof value === 'object' && value !== null && 'bind' in value) {
227
+ const childInstance = varName
228
+ ? this.scopeChain.get(varName) || parentInstance
229
+ : parentInstance;
230
+ this.walkConfig(value as NestedShowMapping, childInstance, false);
231
+ }
232
+ }
233
+ }
234
+ }
235
+
236
+ /**
237
+ * 通过 obj 路径从 scopeChain 或 parentInstance 解析到对象。
238
+ */
239
+ private resolveObjFromChain(objPath: string, parentInstance: any): any {
240
+ const segments = objPath.split('.');
241
+ let current: any = this.scopeChain.get(segments[0]);
242
+ const startIdx = current !== undefined ? 1 : 0;
243
+ if (current === undefined) {
244
+ current = parentInstance;
245
+ }
246
+ for (let i = startIdx; i < segments.length; i++) {
247
+ if (current == null) return undefined;
248
+ current = current[segments[i]];
249
+ }
250
+ return current;
251
+ }
252
+ }
@@ -0,0 +1,244 @@
1
+ // core/engine/soma-bootstrap.ts
2
+ // 职责:生命周期编排(唯一职责)
3
+
4
+ import { SomaContainerAdapter } from '../container/SomaContainerAdapter';
5
+ import { SomaDiagnostics, type SomaDiagnosticsSnapshot } from '../diagnostics/SomaDiagnostics';
6
+ import type { SomaMiddlewareChain } from '../middleware/SomaMiddlewareChain';
7
+ import { SomaScheduler } from '../scheduler/SomaScheduler';
8
+ import type { ParsedEvent } from '../types/event.types';
9
+ import type { UiConfig } from '../types/ui-config.types';
10
+ import type { SomaPageRoot } from '../types/domain.types';
11
+ import { SomaSnapshotStore } from '../runtime/SomaSnapshotStore';
12
+ import { SomaAssetResolver } from './asset-resolver';
13
+ import type { SomaEventMiddlewareContext } from './event-engine';
14
+ import { SomaReactiveProxy } from './reactive-proxy';
15
+ import type { SomaRenderEngine, SomaRenderMiddlewareContext } from './render-engine';
16
+ import type { SomaEventEngine } from './event-engine';
17
+ import { SomaRuntimeBuilder } from './runtime-builder';
18
+
19
+ // ─── 类型定义 ──────────────────────────────────────────
20
+
21
+ export interface SomaPageAssets {
22
+ html: string;
23
+ includes?: Record<string, string>;
24
+ DomainClass: new () => SomaPageRoot;
25
+
26
+ // ── 字符串模式(运行时解析,向后兼容) ──
27
+ uiYaml?: string;
28
+ eventYaml?: string;
29
+ localeYaml?: string;
30
+ appConfigYaml?: string;
31
+
32
+ // ── 预编译模式(构建阶段已解析,运行时零开销) ──
33
+ uiConfig?: UiConfig;
34
+ eventConfig?: ParsedEvent[];
35
+ locale?: Record<string, unknown>;
36
+ appConfig?: unknown;
37
+ }
38
+
39
+ export interface SomaBootstrapOptions {
40
+ adapter?: SomaContainerAdapter;
41
+ scheduler?: SomaScheduler;
42
+ diagnostics?: SomaDiagnostics;
43
+ assetResolver?: SomaAssetResolver;
44
+ renderMiddleware?: SomaMiddlewareChain<SomaRenderMiddlewareContext>;
45
+ eventMiddleware?: SomaMiddlewareChain<any>;
46
+ }
47
+
48
+ export interface ParsedRuntimeAssets {
49
+ uiConfig: UiConfig;
50
+ eventConfig: ParsedEvent[];
51
+ locale: Record<string, unknown>;
52
+ appConfig: unknown;
53
+ }
54
+
55
+ // ─── 生命周期编排器 ──────────────────────────────────────
56
+
57
+ export class SomaBootstrap {
58
+ private readonly adapter: SomaContainerAdapter;
59
+ private readonly scheduler: SomaScheduler;
60
+ private readonly assetResolver: SomaAssetResolver;
61
+ private readonly runtimeBuilder = new SomaRuntimeBuilder();
62
+ private readonly snapshotStore = new SomaSnapshotStore();
63
+ private readonly renderMiddleware: SomaMiddlewareChain<SomaRenderMiddlewareContext> | null;
64
+ private readonly eventMiddleware: SomaMiddlewareChain<SomaEventMiddlewareContext> | null;
65
+
66
+ private renderEngine: SomaRenderEngine | null = null;
67
+ private eventEngine: SomaEventEngine | null = null;
68
+ private proxy: SomaReactiveProxy | null = null;
69
+ private domainInstance: SomaPageRoot | null = null;
70
+ private mounted = false;
71
+ private diagnostics: SomaDiagnostics;
72
+ private container: HTMLElement | null = null;
73
+ private assets: SomaPageAssets | null = null;
74
+
75
+ constructor(options: SomaBootstrapOptions = {}) {
76
+ this.adapter = options.adapter ?? new SomaContainerAdapter();
77
+ this.scheduler = options.scheduler ?? new SomaScheduler();
78
+ this.diagnostics = options.diagnostics ?? new SomaDiagnostics();
79
+ this.assetResolver = options.assetResolver ?? new SomaAssetResolver();
80
+ this.renderMiddleware = options.renderMiddleware ?? null;
81
+ this.eventMiddleware = options.eventMiddleware ?? null;
82
+ }
83
+
84
+ async mount(container: HTMLElement, assets: SomaPageAssets): Promise<void> {
85
+ try {
86
+ // 仅当未注入时才创建新的 diagnostics
87
+ if (!this.mounted) {
88
+ this.scheduler.setDiagnostics(this.diagnostics);
89
+ }
90
+ this.container = container;
91
+ this.assets = { ...assets };
92
+
93
+ // 1. 解析资产(委托给 AssetResolver)
94
+ const parsed = this.assetResolver.resolve(assets);
95
+
96
+ // 2. 挂载 HTML
97
+ this.adapter.mount(container, assets.html, assets.includes);
98
+
99
+ // 3. 创建领域实例并注入配置
100
+ const raw = new assets.DomainClass();
101
+ raw._locale = parsed.locale;
102
+ if (parsed.appConfig) {
103
+ raw._config = parsed.appConfig;
104
+ }
105
+
106
+ // 4. 包装响应式代理
107
+ this.proxy = new SomaReactiveProxy(undefined, this.diagnostics);
108
+ this.domainInstance = this.proxy.wrap(raw);
109
+
110
+ // 5. 构建运行时(委托给 RuntimeBuilder)
111
+ await this.buildRuntime(parsed);
112
+
113
+ this.mounted = true;
114
+ if (typeof this.domainInstance.onMount === 'function') {
115
+ await this.domainInstance.onMount();
116
+ }
117
+ } catch (error) {
118
+ console.error('[SomaBootstrap] Mount failed:', error);
119
+ this.cleanup();
120
+ throw error;
121
+ }
122
+ }
123
+
124
+ async hotSwap(
125
+ overrides: Partial<Omit<SomaPageAssets, 'DomainClass'>>,
126
+ options?: { resetDiagnostics?: boolean },
127
+ ): Promise<void> {
128
+ if (!this.mounted || !this.container || !this.assets || !this.domainInstance) {
129
+ throw new Error('[SomaBootstrap] Cannot hotSwap before mount');
130
+ }
131
+
132
+ const merged: SomaPageAssets = {
133
+ ...this.assets,
134
+ ...overrides,
135
+ DomainClass: this.assets.DomainClass,
136
+ };
137
+
138
+ if (options?.resetDiagnostics) {
139
+ this.diagnostics = new SomaDiagnostics();
140
+ this.scheduler.setDiagnostics(this.diagnostics);
141
+ }
142
+
143
+ const parsed = this.assetResolver.resolve(merged);
144
+ this.adapter.mount(this.container, merged.html, merged.includes);
145
+ this.domainInstance._locale = parsed.locale;
146
+ if (parsed.appConfig) {
147
+ this.domainInstance._config = parsed.appConfig;
148
+ }
149
+
150
+ this.assets = merged;
151
+ await this.buildRuntime(parsed);
152
+ }
153
+
154
+ captureSnapshot(): number {
155
+ if (!this.domainInstance) {
156
+ throw new Error('[SomaBootstrap] Cannot capture snapshot before mount');
157
+ }
158
+ return this.snapshotStore.capture(this.domainInstance);
159
+ }
160
+
161
+ restoreSnapshot(snapshotId: number): void {
162
+ if (!this.domainInstance) {
163
+ throw new Error('[SomaBootstrap] Cannot restore snapshot before mount');
164
+ }
165
+ this.snapshotStore.restore(snapshotId, this.domainInstance);
166
+ this.renderEngine?.render();
167
+ }
168
+
169
+ batch(fn: () => void): void {
170
+ if (!this.proxy) {
171
+ throw new Error('[SomaBootstrap] Cannot batch before mount');
172
+ }
173
+ this.proxy.beginBatch();
174
+ try {
175
+ fn();
176
+ } finally {
177
+ this.proxy.endBatch();
178
+ }
179
+ }
180
+
181
+ async unmount(): Promise<void> {
182
+ if (!this.mounted) return;
183
+
184
+ try {
185
+ if (this.domainInstance && typeof this.domainInstance.onUnmount === 'function') {
186
+ this.domainInstance.onUnmount();
187
+ }
188
+ } catch (error) {
189
+ console.error('[SomaBootstrap] onUnmount error:', error);
190
+ }
191
+
192
+ this.cleanup();
193
+ }
194
+
195
+ getDiagnosticsSnapshot(): SomaDiagnosticsSnapshot {
196
+ return this.diagnostics.snapshot();
197
+ }
198
+
199
+ // ─── 私有方法 ──────────────────────────────────────────
200
+
201
+ private async buildRuntime(parsed: ParsedRuntimeAssets): Promise<void> {
202
+ if (!this.container || !this.domainInstance) return;
203
+
204
+ // 销毁旧运行时
205
+ this.eventEngine?.destroy();
206
+ this.renderEngine?.destroy();
207
+
208
+ // 构建新运行时(委托给 RuntimeBuilder)
209
+ const runtime = this.runtimeBuilder.build({
210
+ container: this.container,
211
+ adapter: this.adapter,
212
+ uiConfig: parsed.uiConfig,
213
+ eventConfig: parsed.eventConfig,
214
+ proxiedInstance: this.domainInstance,
215
+ scheduler: this.scheduler,
216
+ diagnostics: this.diagnostics,
217
+ renderMiddleware: this.renderMiddleware ?? undefined,
218
+ eventMiddleware: this.eventMiddleware ?? undefined,
219
+ });
220
+
221
+ this.renderEngine = runtime.renderEngine;
222
+ this.eventEngine = runtime.eventEngine;
223
+
224
+ // 连线:Proxy 变更 → RenderEngine 调度
225
+ this.proxy?.setOnChange((path, value) => {
226
+ this.renderEngine?.schedulePatch(path, value);
227
+ });
228
+ }
229
+
230
+ private cleanup(): void {
231
+ this.scheduler.cancelAll('unmount');
232
+ this.proxy?.dispose();
233
+ this.eventEngine?.destroy();
234
+ this.renderEngine?.destroy();
235
+
236
+ this.eventEngine = null;
237
+ this.renderEngine = null;
238
+ this.proxy = null;
239
+ this.domainInstance = null;
240
+ this.mounted = false;
241
+ this.container = null;
242
+ this.assets = null;
243
+ }
244
+ }
package/core/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * soma-core — 宿主通过 bundler 解析子路径时请使用 exports。
3
+ */
4
+ export * from './base/index';
5
+
6
+ export type { SomaAppConfig, SomaPageRoot } from './types/domain.types';
@@ -0,0 +1,13 @@
1
+ export interface LoginCredentials {
2
+ email: string;
3
+ password: string;
4
+ }
5
+
6
+ export interface IAuthService {
7
+ login(credentials: LoginCredentials): Promise<boolean>;
8
+ logout(): Promise<void>;
9
+ getToken(): string | null;
10
+ isAuthenticated(): boolean;
11
+ refreshToken(): Promise<boolean>;
12
+ onAuthStateChange(callback: (isAuth: boolean) => void): () => void;
13
+ }
@@ -0,0 +1,98 @@
1
+ import { IAuthService, LoginCredentials } from './IAuthService';
2
+ import { IHttpClient } from '../http/IHttpClient';
3
+ import { IStorageService } from '../storage/IStorageService';
4
+
5
+ const TOKEN_KEY = 'soma_auth_token';
6
+ const TOKEN_EXPIRY_KEY = 'soma_auth_token_expiry';
7
+
8
+ /**
9
+ * TokenAuthService — JWT-style token authentication.
10
+ *
11
+ * Dependencies are injected via constructor so the service stays testable
12
+ * and decoupled from concrete HTTP / storage implementations.
13
+ */
14
+ export class TokenAuthService implements IAuthService {
15
+ private listeners = new Set<(isAuth: boolean) => void>();
16
+
17
+ constructor(
18
+ private http: IHttpClient,
19
+ private storage: IStorageService,
20
+ private loginUrl: string = '/auth/login',
21
+ private refreshUrl: string = '/auth/refresh',
22
+ ) {}
23
+
24
+ async login(credentials: LoginCredentials): Promise<boolean> {
25
+ try {
26
+ const res = await this.http.post<{ token: string; expiresIn: number }>(
27
+ this.loginUrl,
28
+ credentials,
29
+ );
30
+ this.storeToken(res.token, res.expiresIn);
31
+ this.notify(true);
32
+ return true;
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ async logout(): Promise<void> {
39
+ this.storage.remove(TOKEN_KEY);
40
+ this.storage.remove(TOKEN_EXPIRY_KEY);
41
+ this.notify(false);
42
+ }
43
+
44
+ getToken(): string | null {
45
+ if (!this.isAuthenticated()) return null;
46
+ return this.storage.get<string>(TOKEN_KEY);
47
+ }
48
+
49
+ isAuthenticated(): boolean {
50
+ const token = this.storage.get<string>(TOKEN_KEY);
51
+ if (!token) return false;
52
+
53
+ const expiry = this.storage.get<number>(TOKEN_EXPIRY_KEY);
54
+ if (expiry !== null && Date.now() > expiry) {
55
+ this.storage.remove(TOKEN_KEY);
56
+ this.storage.remove(TOKEN_EXPIRY_KEY);
57
+ return false;
58
+ }
59
+
60
+ return true;
61
+ }
62
+
63
+ async refreshToken(): Promise<boolean> {
64
+ const currentToken = this.storage.get<string>(TOKEN_KEY);
65
+ if (!currentToken) return false;
66
+
67
+ try {
68
+ const res = await this.http.post<{ token: string; expiresIn: number }>(
69
+ this.refreshUrl,
70
+ { token: currentToken },
71
+ );
72
+ this.storeToken(res.token, res.expiresIn);
73
+ this.notify(true);
74
+ return true;
75
+ } catch {
76
+ await this.logout();
77
+ return false;
78
+ }
79
+ }
80
+
81
+ onAuthStateChange(callback: (isAuth: boolean) => void): () => void {
82
+ this.listeners.add(callback);
83
+ return () => {
84
+ this.listeners.delete(callback);
85
+ };
86
+ }
87
+
88
+ // ── private ──────────────────────────────────────────────
89
+
90
+ private storeToken(token: string, expiresIn: number): void {
91
+ this.storage.set(TOKEN_KEY, token);
92
+ this.storage.set(TOKEN_EXPIRY_KEY, Date.now() + expiresIn * 1000);
93
+ }
94
+
95
+ private notify(isAuth: boolean): void {
96
+ this.listeners.forEach((cb) => cb(isAuth));
97
+ }
98
+ }
@@ -0,0 +1,13 @@
1
+ export interface CacheOptions {
2
+ ttl?: number; // milliseconds
3
+ maxSize?: number;
4
+ }
5
+
6
+ export interface ICache<V = any> {
7
+ get(key: string): V | undefined;
8
+ set(key: string, value: V, ttl?: number): void;
9
+ has(key: string): boolean;
10
+ delete(key: string): boolean;
11
+ clear(): void;
12
+ size(): number;
13
+ }