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.
- package/app/api/page/route.ts +97 -0
- package/app/globals.css +3 -0
- package/app/layout.tsx +18 -0
- package/app/page.tsx +129 -0
- package/bin/soma.cjs +2 -0
- package/core/base/SomaApi.ts +14 -0
- package/core/base/SomaDict.ts +168 -0
- package/core/base/SomaEntity.ts +41 -0
- package/core/base/SomaHttpClient.ts +126 -0
- package/core/base/SomaLocaleOnlyPageRoot.ts +4 -0
- package/core/base/SomaPageRootBase.ts +54 -0
- package/core/base/SomaValidator.ts +147 -0
- package/core/base/index.ts +7 -0
- package/core/compiler/full-manifest-builder.ts +43 -0
- package/core/compiler/manifest-compiler.ts +237 -0
- package/core/compiler/route-builder.ts +31 -0
- package/core/compiler/soma-precompile.ts +48 -0
- package/core/compiler/soma-webpack-loader.js +35 -0
- package/core/compiler/vite-plugin-soma.ts +73 -0
- package/core/container/SomaContainerAdapter.ts +169 -0
- package/core/diagnostics/SomaDiagnostics.ts +186 -0
- package/core/engine/asset-resolver.ts +67 -0
- package/core/engine/dom-renderer.ts +366 -0
- package/core/engine/event-engine.ts +287 -0
- package/core/engine/lis.ts +60 -0
- package/core/engine/reactive-proxy.ts +225 -0
- package/core/engine/render-engine.ts +264 -0
- package/core/engine/runtime-builder.ts +100 -0
- package/core/engine/scope-resolver.ts +252 -0
- package/core/engine/soma-bootstrap.ts +244 -0
- package/core/index.ts +6 -0
- package/core/infra/auth/IAuthService.ts +13 -0
- package/core/infra/auth/TokenAuthService.ts +98 -0
- package/core/infra/cache/ICache.ts +13 -0
- package/core/infra/cache/MemoryCache.ts +95 -0
- package/core/infra/cache/ServerFileCache.ts +123 -0
- package/core/infra/config/IConfig.ts +9 -0
- package/core/infra/config/SomaConfig.ts +85 -0
- package/core/infra/event-bus/IEventBus.ts +9 -0
- package/core/infra/event-bus/SomaEventBus.ts +53 -0
- package/core/infra/http/IHttpClient.ts +21 -0
- package/core/infra/http/SomaHttpService.ts +141 -0
- package/core/infra/i18n/DefaultI18n.ts +41 -0
- package/core/infra/i18n/II18n.ts +7 -0
- package/core/infra/logger/ConsoleLogger.ts +81 -0
- package/core/infra/logger/ILogger.ts +19 -0
- package/core/infra/notify/DefaultNotifyService.ts +31 -0
- package/core/infra/notify/INotifyService.ts +14 -0
- package/core/infra/permission/IPermission.ts +10 -0
- package/core/infra/permission/SomaPermission.ts +48 -0
- package/core/infra/router/IRouter.ts +19 -0
- package/core/infra/router/SomaRouter.ts +66 -0
- package/core/infra/storage/IStorageService.ts +7 -0
- package/core/infra/storage/MemoryStorageService.ts +53 -0
- package/core/infra/timer/ITimer.ts +9 -0
- package/core/infra/timer/SomaTimer.ts +118 -0
- package/core/middleware/SomaMiddlewareChain.ts +29 -0
- package/core/parser/pipeline-parser.ts +276 -0
- package/core/parser/ui-config-parser.ts +336 -0
- package/core/parser/yaml-loader.ts +36 -0
- package/core/router/RouteHandler.ts +93 -0
- package/core/runtime/SomaSnapshotStore.ts +98 -0
- package/core/scheduler/SomaScheduler.ts +190 -0
- package/core/types/domain.types.ts +88 -0
- package/core/types/engine.types.ts +35 -0
- package/core/types/event.types.ts +57 -0
- package/core/types/keyboard.types.ts +18 -0
- package/core/types/manifest.types.ts +30 -0
- package/core/types/scheduler.types.ts +10 -0
- package/core/types/ui-config.types.ts +89 -0
- package/core/validation/contract-validator.ts +465 -0
- package/dist/cli/soma.js +49 -0
- package/global.d.ts +14 -0
- package/next.config.js +61 -0
- package/package.json +77 -0
- package/postcss.config.js +6 -0
- package/tailwind.config.ts +21 -0
- package/tsconfig.json +35 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { CacheOptions, ICache } from './ICache';
|
|
2
|
+
|
|
3
|
+
interface CacheEntry<V> {
|
|
4
|
+
value: V;
|
|
5
|
+
expiresAt: number | null;
|
|
6
|
+
lastAccessed: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class MemoryCache<V = any> implements ICache<V> {
|
|
10
|
+
private store: Map<string, CacheEntry<V>> = new Map();
|
|
11
|
+
private readonly defaultTtl: number | null;
|
|
12
|
+
private readonly maxSize: number | null;
|
|
13
|
+
|
|
14
|
+
constructor(options: CacheOptions = {}) {
|
|
15
|
+
this.defaultTtl = options.ttl ?? null;
|
|
16
|
+
this.maxSize = options.maxSize ?? null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
get(key: string): V | undefined {
|
|
20
|
+
const entry = this.store.get(key);
|
|
21
|
+
if (!entry) return undefined;
|
|
22
|
+
|
|
23
|
+
if (entry.expiresAt !== null && Date.now() > entry.expiresAt) {
|
|
24
|
+
this.store.delete(key);
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
entry.lastAccessed = Date.now();
|
|
29
|
+
return entry.value;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
set(key: string, value: V, ttl?: number): void {
|
|
33
|
+
const effectiveTtl = ttl ?? this.defaultTtl;
|
|
34
|
+
const expiresAt = effectiveTtl !== null ? Date.now() + effectiveTtl : null;
|
|
35
|
+
|
|
36
|
+
// If key already exists, update in place (no eviction needed)
|
|
37
|
+
if (this.store.has(key)) {
|
|
38
|
+
this.store.set(key, { value, expiresAt, lastAccessed: Date.now() });
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Evict if at capacity
|
|
43
|
+
if (this.maxSize !== null && this.store.size >= this.maxSize) {
|
|
44
|
+
this.evictLru();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
this.store.set(key, { value, expiresAt, lastAccessed: Date.now() });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
has(key: string): boolean {
|
|
51
|
+
const entry = this.store.get(key);
|
|
52
|
+
if (!entry) return false;
|
|
53
|
+
|
|
54
|
+
if (entry.expiresAt !== null && Date.now() > entry.expiresAt) {
|
|
55
|
+
this.store.delete(key);
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
delete(key: string): boolean {
|
|
63
|
+
return this.store.delete(key);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
clear(): void {
|
|
67
|
+
this.store.clear();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
size(): number {
|
|
71
|
+
// Purge expired entries before reporting size
|
|
72
|
+
for (const [key, entry] of this.store) {
|
|
73
|
+
if (entry.expiresAt !== null && Date.now() > entry.expiresAt) {
|
|
74
|
+
this.store.delete(key);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return this.store.size;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private evictLru(): void {
|
|
81
|
+
let oldestKey: string | null = null;
|
|
82
|
+
let oldestTime = Infinity;
|
|
83
|
+
|
|
84
|
+
for (const [key, entry] of this.store) {
|
|
85
|
+
if (entry.lastAccessed < oldestTime) {
|
|
86
|
+
oldestTime = entry.lastAccessed;
|
|
87
|
+
oldestKey = key;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (oldestKey !== null) {
|
|
92
|
+
this.store.delete(oldestKey);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, watch, type FSWatcher } from 'fs';
|
|
2
|
+
import { resolve, extname, normalize } from 'path';
|
|
3
|
+
import { MemoryCache } from './MemoryCache';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 服务端文件缓存单例
|
|
7
|
+
*
|
|
8
|
+
* 将磁盘文件内容和目录列表缓存到内存中,避免每次请求都执行 I/O。
|
|
9
|
+
* 支持 fs.watch 监听文件变化,自动失效对应缓存条目。
|
|
10
|
+
*/
|
|
11
|
+
export class ServerFileCache {
|
|
12
|
+
private static instance: ServerFileCache | null = null;
|
|
13
|
+
|
|
14
|
+
private fileCache = new MemoryCache<string>();
|
|
15
|
+
private dirCache = new MemoryCache<string[]>();
|
|
16
|
+
private watchers: FSWatcher[] = [];
|
|
17
|
+
|
|
18
|
+
private constructor() {}
|
|
19
|
+
|
|
20
|
+
static getInstance(): ServerFileCache {
|
|
21
|
+
if (!ServerFileCache.instance) {
|
|
22
|
+
ServerFileCache.instance = new ServerFileCache();
|
|
23
|
+
}
|
|
24
|
+
return ServerFileCache.instance;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 读取文件内容,命中缓存直接返回,未命中则读磁盘并缓存。
|
|
29
|
+
*/
|
|
30
|
+
readFile(filePath: string): string {
|
|
31
|
+
const key = normalize(filePath);
|
|
32
|
+
const cached = this.fileCache.get(key);
|
|
33
|
+
if (cached !== undefined) {
|
|
34
|
+
return cached;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const content = readFileSync(filePath, 'utf-8');
|
|
38
|
+
this.fileCache.set(key, content);
|
|
39
|
+
return content;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 尝试读取文件,不存在返回空字符串。
|
|
44
|
+
*/
|
|
45
|
+
tryReadFile(filePath: string): string {
|
|
46
|
+
try {
|
|
47
|
+
return this.readFile(filePath);
|
|
48
|
+
} catch {
|
|
49
|
+
return '';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 读取目录下指定扩展名的文件内容列表。
|
|
55
|
+
* 缓存目录扫描结果和每个文件的内容。
|
|
56
|
+
*/
|
|
57
|
+
readDirFiles(dirPath: string, ext: string): string[] {
|
|
58
|
+
const dirKey = `${normalize(dirPath)}:${ext}`;
|
|
59
|
+
const cached = this.dirCache.get(dirKey);
|
|
60
|
+
if (cached !== undefined) {
|
|
61
|
+
return cached;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const files = readdirSync(dirPath)
|
|
65
|
+
.filter(f => extname(f) === ext)
|
|
66
|
+
.map(f => this.readFile(resolve(dirPath, f)));
|
|
67
|
+
|
|
68
|
+
this.dirCache.set(dirKey, files);
|
|
69
|
+
return files;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
readDirNames(dirPath: string, ext: string): string[] {
|
|
73
|
+
const dirKey = `${normalize(dirPath)}:names:${ext}`;
|
|
74
|
+
const cached = this.dirCache.get(dirKey);
|
|
75
|
+
if (cached !== undefined) {
|
|
76
|
+
return cached;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const names = readdirSync(dirPath).filter(f => extname(f) === ext);
|
|
80
|
+
this.dirCache.set(dirKey, names);
|
|
81
|
+
return names;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 监听目录变化,自动失效缓存。
|
|
86
|
+
* 使用 fs.watch 递归监听。
|
|
87
|
+
*/
|
|
88
|
+
watchAndInvalidate(rootDir: string): void {
|
|
89
|
+
try {
|
|
90
|
+
const watcher = watch(rootDir, { recursive: true }, (_event, filename) => {
|
|
91
|
+
if (!filename) return;
|
|
92
|
+
|
|
93
|
+
const fullPath = normalize(resolve(rootDir, filename));
|
|
94
|
+
this.fileCache.delete(fullPath);
|
|
95
|
+
this.dirCache.clear();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
this.watchers.push(watcher);
|
|
99
|
+
} catch (e: any) {
|
|
100
|
+
// fs.watch recursive is not supported on Linux — cache won't auto-invalidate.
|
|
101
|
+
// Changes require a server restart in that environment.
|
|
102
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
103
|
+
console.warn(
|
|
104
|
+
`[soma-core] fs.watch recursive failed (${e.code ?? e.message}). ` +
|
|
105
|
+
'File cache will not auto-invalidate — restart the server after changes.',
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 清除所有缓存并关闭 watcher。
|
|
113
|
+
*/
|
|
114
|
+
dispose(): void {
|
|
115
|
+
this.fileCache.clear();
|
|
116
|
+
this.dirCache.clear();
|
|
117
|
+
for (const w of this.watchers) {
|
|
118
|
+
w.close();
|
|
119
|
+
}
|
|
120
|
+
this.watchers = [];
|
|
121
|
+
ServerFileCache.instance = null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface IConfig {
|
|
2
|
+
get<T>(key: string, defaultValue?: T): T;
|
|
3
|
+
set(key: string, value: any): void;
|
|
4
|
+
has(key: string): boolean;
|
|
5
|
+
getAll(): Record<string, any>;
|
|
6
|
+
load(data: Record<string, any>): void;
|
|
7
|
+
isFeatureEnabled(feature: string): boolean;
|
|
8
|
+
setFeatureFlag(feature: string, enabled: boolean): void;
|
|
9
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { IConfig } from './IConfig';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* SomaConfig — stores config in a plain object.
|
|
5
|
+
*
|
|
6
|
+
* Supports dot-notation paths for get (e.g., get('api.timeout')).
|
|
7
|
+
* Feature flags are stored separately.
|
|
8
|
+
*/
|
|
9
|
+
export class SomaConfig implements IConfig {
|
|
10
|
+
private data: Record<string, any> = {};
|
|
11
|
+
private featureFlags = new Map<string, boolean>();
|
|
12
|
+
|
|
13
|
+
get<T>(key: string, defaultValue?: T): T {
|
|
14
|
+
const value = this.getByPath(this.data, key);
|
|
15
|
+
return (value !== undefined ? value : defaultValue) as T;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
set(key: string, value: any): void {
|
|
19
|
+
this.setByPath(this.data, key, value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
has(key: string): boolean {
|
|
23
|
+
return this.getByPath(this.data, key) !== undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
getAll(): Record<string, any> {
|
|
27
|
+
return { ...this.data };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
load(data: Record<string, any>): void {
|
|
31
|
+
this.merge(this.data, data);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
isFeatureEnabled(feature: string): boolean {
|
|
35
|
+
return this.featureFlags.get(feature) ?? false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
setFeatureFlag(feature: string, enabled: boolean): void {
|
|
39
|
+
this.featureFlags.set(feature, enabled);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// --- private helpers ---
|
|
43
|
+
|
|
44
|
+
private getByPath(obj: Record<string, any>, path: string): any {
|
|
45
|
+
const parts = path.split('.');
|
|
46
|
+
let current: any = obj;
|
|
47
|
+
for (const part of parts) {
|
|
48
|
+
if (current === undefined || current === null || typeof current !== 'object') {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
current = current[part];
|
|
52
|
+
}
|
|
53
|
+
return current;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private setByPath(obj: Record<string, any>, path: string, value: any): void {
|
|
57
|
+
const parts = path.split('.');
|
|
58
|
+
let current: any = obj;
|
|
59
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
60
|
+
const part = parts[i];
|
|
61
|
+
if (current[part] === undefined || typeof current[part] !== 'object') {
|
|
62
|
+
current[part] = {};
|
|
63
|
+
}
|
|
64
|
+
current = current[part];
|
|
65
|
+
}
|
|
66
|
+
current[parts[parts.length - 1]] = value;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private merge(target: Record<string, any>, source: Record<string, any>): void {
|
|
70
|
+
for (const key of Object.keys(source)) {
|
|
71
|
+
if (
|
|
72
|
+
source[key] !== null &&
|
|
73
|
+
typeof source[key] === 'object' &&
|
|
74
|
+
!Array.isArray(source[key]) &&
|
|
75
|
+
target[key] !== null &&
|
|
76
|
+
typeof target[key] === 'object' &&
|
|
77
|
+
!Array.isArray(target[key])
|
|
78
|
+
) {
|
|
79
|
+
this.merge(target[key], source[key]);
|
|
80
|
+
} else {
|
|
81
|
+
target[key] = source[key];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type EventHandler<T = any> = (payload: T) => void;
|
|
2
|
+
|
|
3
|
+
export interface IEventBus {
|
|
4
|
+
on<T>(event: string, handler: EventHandler<T>): () => void;
|
|
5
|
+
once<T>(event: string, handler: EventHandler<T>): () => void;
|
|
6
|
+
emit<T>(event: string, payload?: T): void;
|
|
7
|
+
off(event: string, handler?: EventHandler): void;
|
|
8
|
+
clear(): void;
|
|
9
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { EventHandler, IEventBus } from './IEventBus';
|
|
2
|
+
|
|
3
|
+
export class SomaEventBus implements IEventBus {
|
|
4
|
+
private handlers: Map<string, Set<EventHandler>> = new Map();
|
|
5
|
+
|
|
6
|
+
on<T>(event: string, handler: EventHandler<T>): () => void {
|
|
7
|
+
if (!this.handlers.has(event)) {
|
|
8
|
+
this.handlers.set(event, new Set());
|
|
9
|
+
}
|
|
10
|
+
this.handlers.get(event)!.add(handler);
|
|
11
|
+
|
|
12
|
+
return () => {
|
|
13
|
+
this.off(event, handler);
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
once<T>(event: string, handler: EventHandler<T>): () => void {
|
|
18
|
+
const wrapper: EventHandler<T> = (payload: T) => {
|
|
19
|
+
this.off(event, wrapper);
|
|
20
|
+
handler(payload);
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
return this.on(event, wrapper);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
emit<T>(event: string, payload?: T): void {
|
|
27
|
+
const handlers = this.handlers.get(event);
|
|
28
|
+
if (!handlers) return;
|
|
29
|
+
|
|
30
|
+
for (const handler of [...handlers]) {
|
|
31
|
+
handler(payload);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
off(event: string, handler?: EventHandler): void {
|
|
36
|
+
if (!handler) {
|
|
37
|
+
this.handlers.delete(event);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const handlers = this.handlers.get(event);
|
|
42
|
+
if (handlers) {
|
|
43
|
+
handlers.delete(handler);
|
|
44
|
+
if (handlers.size === 0) {
|
|
45
|
+
this.handlers.delete(event);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
clear(): void {
|
|
51
|
+
this.handlers.clear();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface HttpRequestConfig {
|
|
2
|
+
headers?: Record<string, string>;
|
|
3
|
+
params?: Record<string, string>;
|
|
4
|
+
timeout?: number;
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface HttpResponse<T = any> {
|
|
9
|
+
data: T;
|
|
10
|
+
status: number;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface IHttpClient {
|
|
15
|
+
get<T>(url: string, config?: HttpRequestConfig): Promise<T>;
|
|
16
|
+
post<T>(url: string, data?: any, config?: HttpRequestConfig): Promise<T>;
|
|
17
|
+
put<T>(url: string, data?: any, config?: HttpRequestConfig): Promise<T>;
|
|
18
|
+
delete<T>(url: string, config?: HttpRequestConfig): Promise<T>;
|
|
19
|
+
upload<T>(url: string, file: Blob, onProgress?: (percent: number) => void): Promise<T>;
|
|
20
|
+
abortAll(): void;
|
|
21
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { SomaHttpClient, SomaHttpClientConfig } from '@/core/base/SomaHttpClient';
|
|
2
|
+
import { IHttpClient, HttpRequestConfig } from './IHttpClient';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* SomaHttpService — wraps the core SomaHttpClient and implements IHttpClient.
|
|
6
|
+
*
|
|
7
|
+
* Adds support for:
|
|
8
|
+
* - per-request headers, query params, timeout, and external AbortSignal
|
|
9
|
+
* - file upload via fetch with Blob body
|
|
10
|
+
*/
|
|
11
|
+
export class SomaHttpService implements IHttpClient {
|
|
12
|
+
private client: SomaHttpClient;
|
|
13
|
+
private baseURL: string;
|
|
14
|
+
private abortControllers: Set<AbortController> = new Set();
|
|
15
|
+
|
|
16
|
+
constructor(config: SomaHttpClientConfig) {
|
|
17
|
+
this.baseURL = config.baseURL;
|
|
18
|
+
this.client = new SomaHttpClient(config);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async get<T>(url: string, config?: HttpRequestConfig): Promise<T> {
|
|
22
|
+
if (config) {
|
|
23
|
+
return this.requestWithConfig<T>('GET', url, undefined, config);
|
|
24
|
+
}
|
|
25
|
+
return this.client.get<T>(url);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async post<T>(url: string, data?: any, config?: HttpRequestConfig): Promise<T> {
|
|
29
|
+
if (config) {
|
|
30
|
+
return this.requestWithConfig<T>('POST', url, data, config);
|
|
31
|
+
}
|
|
32
|
+
return this.client.post<T>(url, data);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async put<T>(url: string, data?: any, config?: HttpRequestConfig): Promise<T> {
|
|
36
|
+
if (config) {
|
|
37
|
+
return this.requestWithConfig<T>('PUT', url, data, config);
|
|
38
|
+
}
|
|
39
|
+
return this.client.put<T>(url, data);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async delete<T>(url: string, config?: HttpRequestConfig): Promise<T> {
|
|
43
|
+
if (config) {
|
|
44
|
+
return this.requestWithConfig<T>('DELETE', url, undefined, config);
|
|
45
|
+
}
|
|
46
|
+
return this.client.delete<T>(url);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async upload<T>(
|
|
50
|
+
url: string,
|
|
51
|
+
file: Blob,
|
|
52
|
+
onProgress?: (percent: number) => void,
|
|
53
|
+
): Promise<T> {
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
this.abortControllers.add(controller);
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
const fullUrl = `${this.baseURL}${url}`;
|
|
59
|
+
const res = await fetch(fullUrl, {
|
|
60
|
+
method: 'POST',
|
|
61
|
+
body: file,
|
|
62
|
+
signal: controller.signal,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
if (!res.ok) {
|
|
66
|
+
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Progress callback — since fetch does not natively support upload progress,
|
|
70
|
+
// we signal 100% once the response is received.
|
|
71
|
+
if (onProgress) {
|
|
72
|
+
onProgress(100);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return (await res.json()) as T;
|
|
76
|
+
} finally {
|
|
77
|
+
this.abortControllers.delete(controller);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
abortAll(): void {
|
|
82
|
+
this.client.abortAll();
|
|
83
|
+
this.abortControllers.forEach((c) => c.abort());
|
|
84
|
+
this.abortControllers.clear();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ── private ──────────────────────────────────────────────
|
|
88
|
+
|
|
89
|
+
private async requestWithConfig<T>(
|
|
90
|
+
method: string,
|
|
91
|
+
path: string,
|
|
92
|
+
body?: any,
|
|
93
|
+
config?: HttpRequestConfig,
|
|
94
|
+
): Promise<T> {
|
|
95
|
+
const controller = new AbortController();
|
|
96
|
+
this.abortControllers.add(controller);
|
|
97
|
+
|
|
98
|
+
const timeout = config?.timeout ?? 30000;
|
|
99
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
100
|
+
|
|
101
|
+
// If caller provides an external signal, forward its abort.
|
|
102
|
+
if (config?.signal) {
|
|
103
|
+
config.signal.addEventListener('abort', () => controller.abort(), { once: true });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
try {
|
|
107
|
+
let fullUrl = `${this.baseURL}${path}`;
|
|
108
|
+
|
|
109
|
+
if (config?.params) {
|
|
110
|
+
const qs = new URLSearchParams(config.params).toString();
|
|
111
|
+
fullUrl += (fullUrl.includes('?') ? '&' : '?') + qs;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const headers: Record<string, string> = {
|
|
115
|
+
'Content-Type': 'application/json',
|
|
116
|
+
...config?.headers,
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const options: RequestInit = {
|
|
120
|
+
method,
|
|
121
|
+
headers,
|
|
122
|
+
signal: controller.signal,
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
if (body !== undefined) {
|
|
126
|
+
options.body = JSON.stringify(body);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const res = await fetch(fullUrl, options);
|
|
130
|
+
|
|
131
|
+
if (!res.ok) {
|
|
132
|
+
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return (await res.json()) as T;
|
|
136
|
+
} finally {
|
|
137
|
+
clearTimeout(timeoutId);
|
|
138
|
+
this.abortControllers.delete(controller);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { II18n } from './II18n';
|
|
2
|
+
|
|
3
|
+
export class DefaultI18n implements II18n {
|
|
4
|
+
private locale: string = 'en';
|
|
5
|
+
private messages: Map<string, Record<string, string>> = new Map();
|
|
6
|
+
|
|
7
|
+
t(key: string, params?: Record<string, string | number>): string {
|
|
8
|
+
const localeMessages = this.messages.get(this.locale);
|
|
9
|
+
if (!localeMessages || !(key in localeMessages)) {
|
|
10
|
+
return key;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
let result = localeMessages[key];
|
|
14
|
+
|
|
15
|
+
if (params) {
|
|
16
|
+
for (const [param, value] of Object.entries(params)) {
|
|
17
|
+
result = result.replace(new RegExp(`\\{${param}\\}`, 'g'), String(value));
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
setLocale(locale: string): void {
|
|
25
|
+
this.locale = locale;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
getLocale(): string {
|
|
29
|
+
return this.locale;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
loadMessages(locale: string, messages: Record<string, string>): void {
|
|
33
|
+
const existing = this.messages.get(locale);
|
|
34
|
+
this.messages.set(locale, { ...existing, ...messages });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
hasKey(key: string): boolean {
|
|
38
|
+
const localeMessages = this.messages.get(this.locale);
|
|
39
|
+
return localeMessages !== undefined && key in localeMessages;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { ILogger, LogEntry, LogLevel } from './ILogger';
|
|
2
|
+
|
|
3
|
+
const LEVEL_PRIORITY: Record<LogLevel, number> = {
|
|
4
|
+
debug: 0,
|
|
5
|
+
info: 1,
|
|
6
|
+
warn: 2,
|
|
7
|
+
error: 3,
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const MAX_ENTRIES = 1000;
|
|
11
|
+
|
|
12
|
+
export class ConsoleLogger implements ILogger {
|
|
13
|
+
private level: LogLevel = 'debug';
|
|
14
|
+
private context: string = '';
|
|
15
|
+
private entries: LogEntry[] = [];
|
|
16
|
+
|
|
17
|
+
debug(message: string, data?: any): void {
|
|
18
|
+
this.log('debug', message, data);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
info(message: string, data?: any): void {
|
|
22
|
+
this.log('info', message, data);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
warn(message: string, data?: any): void {
|
|
26
|
+
this.log('warn', message, data);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
error(message: string, data?: any): void {
|
|
30
|
+
this.log('error', message, data);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
setLevel(level: LogLevel): void {
|
|
34
|
+
this.level = level;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
setContext(context: string): void {
|
|
38
|
+
this.context = context;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
getEntries(): LogEntry[] {
|
|
42
|
+
return [...this.entries];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private log(level: LogLevel, message: string, data?: any): void {
|
|
46
|
+
if (LEVEL_PRIORITY[level] < LEVEL_PRIORITY[this.level]) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const entry: LogEntry = {
|
|
51
|
+
level,
|
|
52
|
+
message,
|
|
53
|
+
timestamp: Date.now(),
|
|
54
|
+
...(this.context ? { context: this.context } : {}),
|
|
55
|
+
...(data !== undefined ? { data } : {}),
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
this.entries.push(entry);
|
|
59
|
+
if (this.entries.length > MAX_ENTRIES) {
|
|
60
|
+
this.entries.shift();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const prefix = this.context ? `[${this.context}] ` : '';
|
|
64
|
+
const formatted = `${prefix}${message}`;
|
|
65
|
+
|
|
66
|
+
switch (level) {
|
|
67
|
+
case 'debug':
|
|
68
|
+
console.debug(formatted, ...(data !== undefined ? [data] : []));
|
|
69
|
+
break;
|
|
70
|
+
case 'info':
|
|
71
|
+
console.info(formatted, ...(data !== undefined ? [data] : []));
|
|
72
|
+
break;
|
|
73
|
+
case 'warn':
|
|
74
|
+
console.warn(formatted, ...(data !== undefined ? [data] : []));
|
|
75
|
+
break;
|
|
76
|
+
case 'error':
|
|
77
|
+
console.error(formatted, ...(data !== undefined ? [data] : []));
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
2
|
+
|
|
3
|
+
export interface LogEntry {
|
|
4
|
+
level: LogLevel;
|
|
5
|
+
message: string;
|
|
6
|
+
context?: string;
|
|
7
|
+
data?: any;
|
|
8
|
+
timestamp: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ILogger {
|
|
12
|
+
debug(message: string, data?: any): void;
|
|
13
|
+
info(message: string, data?: any): void;
|
|
14
|
+
warn(message: string, data?: any): void;
|
|
15
|
+
error(message: string, data?: any): void;
|
|
16
|
+
setLevel(level: LogLevel): void;
|
|
17
|
+
setContext(context: string): void;
|
|
18
|
+
getEntries(): LogEntry[];
|
|
19
|
+
}
|