soma-core 1.3.1 → 1.3.3
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/README.md +42 -0
- package/app/SomaPageClient.tsx +39 -2
- package/app/[...path]/page.tsx +7 -6
- package/app/api/[...path]/route.ts +3 -3
- package/app/api/soma-registry/[...path]/route.ts +67 -0
- package/app/components/SomaHostPage.tsx +3 -8
- package/app/components/SomaPageClientBoundary.tsx +13 -0
- package/app/layout.tsx +6 -1
- package/app/page.tsx +3 -3
- package/app/soma/manifest/route.ts +1 -0
- package/app/soma/page-object/route.ts +1 -1
- package/core/build/compiler/full-manifest-builder.ts +6 -1
- package/core/build/compiler/rollup-plugin-soma.ts +6 -0
- package/core/build/compiler/soma-manifest-webpack-plugin.js +4 -0
- package/core/build/compiler/soma-precompile.js +3507 -2387
- package/core/build/compiler/soma-precompile.ts +31 -2
- package/core/build/compiler/soma-rspack-yaml-loader.js +3 -0
- package/core/build/compiler/soma-webpack-loader.js +7 -1
- package/core/build/compiler/vite-plugin-soma.ts +11 -1
- package/core/build/component/package-loader.ts +135 -0
- package/core/build/eject/apply-eject.ts +133 -0
- package/core/build/eject/plan-eject.ts +139 -0
- package/core/client/adaptive/flush-scheduler.ts +96 -0
- package/core/client/adaptive/hysteresis.ts +56 -0
- package/core/client/adaptive/index.ts +23 -0
- package/core/client/adaptive/observer-pool.ts +90 -0
- package/core/client/base/SomaPageRootBase.ts +50 -0
- package/core/client/compiler/adaptive-compile.ts +136 -0
- package/core/client/compiler/manifest-compiler.ts +155 -27
- package/core/client/component/ai-catalog.ts +262 -0
- package/core/client/component/component-definition.types.ts +65 -0
- package/core/client/component/component-expander.ts +119 -0
- package/core/client/component/component-manager.ts +933 -0
- package/core/client/component/component-pack.ts +271 -0
- package/core/client/component/component-registry.ts +71 -0
- package/core/client/component/pack-styles.ts +94 -0
- package/core/client/component/scoped-adapter.ts +85 -0
- package/core/client/component/verify-pack.ts +247 -0
- package/core/client/container/MiniProgramContainerAdapter.ts +15 -1
- package/core/client/container/ReactNativeContainerAdapter.ts +15 -1
- package/core/client/container/SomaContainerAdapter.ts +186 -180
- package/core/client/data/data-object-resolver.ts +417 -0
- package/core/client/diagnostics/SomaDiagnostics.ts +187 -186
- package/core/client/diagnostics/boot-timings.ts +152 -0
- package/core/client/engine/asset-resolver.ts +12 -2
- package/core/client/engine/dom-renderer.ts +235 -16
- package/core/client/engine/emit-event.ts +21 -0
- package/core/client/engine/event-engine.ts +34 -4
- package/core/client/engine/on-change-engine.ts +1 -1
- package/core/client/engine/property-watcher.ts +1 -1
- package/core/client/engine/reactive-proxy.ts +3 -3
- package/core/client/engine/render-engine.ts +43 -4
- package/core/client/engine/runtime-builder.ts +23 -0
- package/core/client/engine/soma-bootstrap.ts +389 -5
- package/core/client/engine/style-binder.ts +47 -1
- package/core/client/host-bridge/empty-host/data/README.md +17 -0
- package/core/client/infra/http/SomaHttpService.ts +5 -0
- package/core/client/observability/error-reporter.ts +173 -0
- package/core/client/parser/adaptive-parser.ts +264 -0
- package/core/client/parser/data-config-parser.ts +396 -0
- package/core/client/parser/pipeline-parser.ts +15 -3
- package/core/client/parser/style-config-parser.ts +65 -2
- package/core/client/parser/ui-config-parser.ts +52 -3
- package/core/client/pipes/pipe-registry.ts +249 -0
- package/core/client/quality/SomaQualityRegistry.ts +3 -0
- package/core/client/registry/declaration-renderer.ts +159 -0
- package/core/client/registry/index.ts +28 -0
- package/core/client/registry/page-lifecycle.ts +171 -0
- package/core/client/registry/remote-page.ts +139 -0
- package/core/client/runtime/SomaRuntimeServices.ts +24 -0
- package/core/client/scheduler/SomaScheduler.ts +29 -1
- package/core/client/security/attribute-presence.ts +70 -0
- package/core/client/security/html-sanitizer.ts +113 -0
- package/core/client/security/url-guard.ts +0 -0
- package/core/client/theme/theme-engine.ts +936 -0
- package/core/client/typography/typography-base.ts +34 -0
- package/core/client/validation/contract-validator.ts +48 -5
- package/core/index.ts +190 -2
- package/core/server/api/IService.ts +18 -6
- package/core/server/api/load-host-service.ts +3 -3
- package/core/server/host/content-security-policy.ts +190 -0
- package/core/server/host/csp-nonce-metadata.ts +75 -0
- package/core/server/host/resolve-host-request-hook.ts +5 -0
- package/core/server/host/server-page-assets.ts +10 -0
- package/core/server/index.ts +30 -1
- package/core/server/infra/cache/ServerFileCache.ts +1 -1
- package/core/server/mock/node/cli.mjs +2 -2
- package/core/server/registry/api-registry-store.ts +518 -0
- package/core/server/registry/conditional-object-store.ts +29 -0
- package/core/server/registry/declaration-precompiler.ts +129 -0
- package/core/server/registry/in-memory-conditional-object-store.ts +43 -0
- package/core/server/registry/index.ts +142 -0
- package/core/server/registry/page-registry-repository.ts +373 -0
- package/core/server/registry/page-registry-store.ts +903 -0
- package/core/server/registry/registry-error.ts +17 -0
- package/core/server/registry/registry-file-lock.ts +173 -0
- package/core/server/registry/registry-response.ts +71 -0
- package/core/server/registry/registry-subjects.ts +194 -0
- package/core/server/registry/registry-write-pipeline.ts +240 -0
- package/core/server/registry/request-body-limit.ts +99 -0
- package/core/server/registry/services/apis/Get.ts +25 -0
- package/core/server/registry/services/apis/List.ts +41 -0
- package/core/server/registry/services/apis/Register.ts +39 -0
- package/core/server/registry/services/apis/Unregister.ts +24 -0
- package/core/server/registry/services/index.ts +40 -0
- package/core/server/registry/services/pages/Get.ts +86 -0
- package/core/server/registry/services/pages/List.ts +53 -0
- package/core/server/registry/services/pages/Register.ts +49 -0
- package/core/server/registry/services/pages/Rollback.ts +36 -0
- package/core/server/registry/services/pages/Unregister.ts +23 -0
- package/core/server/registry/services/service-utils.ts +21 -0
- package/core/server/registry/validation/compile-gate.ts +71 -0
- package/core/server/registry/validation/component-existence.ts +55 -0
- package/core/server/registry/validation/credential-ban.ts +86 -0
- package/core/server/registry/validation/cross-check.ts +77 -0
- package/core/server/registry/validation/declaration-safety-scan.ts +102 -0
- package/core/shared/types/adaptive.types.ts +109 -0
- package/core/shared/types/component-contract.types.ts +110 -0
- package/core/shared/types/data-config.types.ts +105 -0
- package/core/shared/types/domain.types.ts +6 -0
- package/core/shared/types/engine.types.ts +41 -35
- package/core/shared/types/manifest.types.ts +55 -32
- package/core/shared/types/scope-manifest.types.ts +96 -0
- package/core/shared/types/style-config.types.ts +9 -0
- package/core/shared/types/ui-config.types.ts +118 -98
- package/dist/cli/soma.js +20 -5
- package/dist/core/index.cjs +5388 -888
- package/dist/types/build/compiler/full-manifest-builder.d.ts +4 -0
- package/dist/types/build/compiler/rollup-plugin-soma.d.ts +1 -0
- package/dist/types/build/compiler/soma-precompile.d.ts +9 -0
- package/dist/types/build/compiler/vite-plugin-soma.d.ts +3 -0
- package/dist/types/build/component/package-loader.d.ts +9 -0
- package/dist/types/build/eject/apply-eject.d.ts +22 -0
- package/dist/types/build/eject/plan-eject.d.ts +32 -0
- package/dist/types/client/adaptive/flush-scheduler.d.ts +13 -0
- package/dist/types/client/adaptive/hysteresis.d.ts +16 -0
- package/dist/types/client/adaptive/index.d.ts +5 -0
- package/dist/types/client/adaptive/observer-pool.d.ts +15 -0
- package/dist/types/client/base/SomaPageRootBase.d.ts +33 -0
- package/dist/types/client/compiler/adaptive-compile.d.ts +26 -0
- package/dist/types/client/compiler/manifest-compiler.d.ts +13 -2
- package/dist/types/client/component/ai-catalog.d.ts +73 -0
- package/dist/types/client/component/component-definition.types.d.ts +54 -0
- package/dist/types/client/component/component-expander.d.ts +25 -0
- package/dist/types/client/component/component-manager.d.ts +160 -0
- package/dist/types/client/component/component-pack.d.ts +90 -0
- package/dist/types/client/component/component-registry.d.ts +12 -0
- package/dist/types/client/component/pack-styles.d.ts +22 -0
- package/dist/types/client/component/scoped-adapter.d.ts +18 -0
- package/dist/types/client/component/verify-pack.d.ts +14 -0
- package/dist/types/client/data/data-object-resolver.d.ts +71 -0
- package/dist/types/client/diagnostics/SomaDiagnostics.d.ts +2 -1
- package/dist/types/client/diagnostics/boot-timings.d.ts +30 -0
- package/dist/types/client/engine/asset-resolver.d.ts +7 -1
- package/dist/types/client/engine/dom-renderer.d.ts +49 -1
- package/dist/types/client/engine/emit-event.d.ts +6 -0
- package/dist/types/client/engine/event-engine.d.ts +6 -0
- package/dist/types/client/engine/render-engine.d.ts +26 -1
- package/dist/types/client/engine/runtime-builder.d.ts +7 -0
- package/dist/types/client/engine/soma-bootstrap.d.ts +122 -0
- package/dist/types/client/infra/http/SomaHttpService.d.ts +2 -0
- package/dist/types/client/observability/error-reporter.d.ts +51 -0
- package/dist/types/client/parser/adaptive-parser.d.ts +28 -0
- package/dist/types/client/parser/data-config-parser.d.ts +34 -0
- package/dist/types/client/parser/pipeline-parser.d.ts +2 -0
- package/dist/types/client/parser/style-config-parser.d.ts +5 -3
- package/dist/types/client/parser/ui-config-parser.d.ts +22 -1
- package/dist/types/client/pipes/pipe-registry.d.ts +38 -0
- package/dist/types/client/registry/declaration-renderer.d.ts +51 -0
- package/dist/types/client/registry/index.d.ts +10 -0
- package/dist/types/client/registry/page-lifecycle.d.ts +61 -0
- package/dist/types/client/registry/remote-page.d.ts +52 -0
- package/dist/types/client/runtime/SomaRuntimeServices.d.ts +16 -0
- package/dist/types/client/scheduler/SomaScheduler.d.ts +8 -0
- package/dist/types/client/security/attribute-presence.d.ts +7 -0
- package/dist/types/client/security/html-sanitizer.d.ts +37 -0
- package/dist/types/client/security/url-guard.d.ts +11 -0
- package/dist/types/client/theme/theme-engine.d.ts +49 -0
- package/dist/types/client/typography/typography-base.d.ts +15 -0
- package/dist/types/client/validation/contract-validator.d.ts +2 -0
- package/dist/types/index.d.ts +36 -2
- package/dist/types/server/api/IService.d.ts +18 -6
- package/dist/types/server/host/content-security-policy.d.ts +53 -0
- package/dist/types/server/host/csp-nonce-metadata.d.ts +32 -0
- package/dist/types/server/host/resolve-host-request-hook.d.ts +5 -0
- package/dist/types/server/host/server-page-assets.d.ts +5 -0
- package/dist/types/server/index.d.ts +4 -1
- package/dist/types/server/registry/api-registry-store.d.ts +141 -0
- package/dist/types/server/registry/conditional-object-store.d.ts +27 -0
- package/dist/types/server/registry/declaration-precompiler.d.ts +30 -0
- package/dist/types/server/registry/in-memory-conditional-object-store.d.ts +8 -0
- package/dist/types/server/registry/index.d.ts +29 -0
- package/dist/types/server/registry/page-registry-repository.d.ts +58 -0
- package/dist/types/server/registry/page-registry-store.d.ts +259 -0
- package/dist/types/server/registry/registry-error.d.ts +12 -0
- package/dist/types/server/registry/registry-file-lock.d.ts +20 -0
- package/dist/types/server/registry/registry-response.d.ts +18 -0
- package/dist/types/server/registry/registry-subjects.d.ts +59 -0
- package/dist/types/server/registry/registry-write-pipeline.d.ts +48 -0
- package/dist/types/server/registry/request-body-limit.d.ts +31 -0
- package/dist/types/server/registry/services/apis/Get.d.ts +10 -0
- package/dist/types/server/registry/services/apis/List.d.ts +10 -0
- package/dist/types/server/registry/services/apis/Register.d.ts +13 -0
- package/dist/types/server/registry/services/apis/Unregister.d.ts +12 -0
- package/dist/types/server/registry/services/index.d.ts +3 -0
- package/dist/types/server/registry/services/pages/Get.d.ts +10 -0
- package/dist/types/server/registry/services/pages/List.d.ts +13 -0
- package/dist/types/server/registry/services/pages/Register.d.ts +11 -0
- package/dist/types/server/registry/services/pages/Rollback.d.ts +9 -0
- package/dist/types/server/registry/services/pages/Unregister.d.ts +9 -0
- package/dist/types/server/registry/services/service-utils.d.ts +10 -0
- package/dist/types/server/registry/validation/compile-gate.d.ts +10 -0
- package/dist/types/server/registry/validation/component-existence.d.ts +14 -0
- package/dist/types/server/registry/validation/credential-ban.d.ts +15 -0
- package/dist/types/server/registry/validation/cross-check.d.ts +16 -0
- package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +15 -0
- package/dist/types/shared/types/adaptive.types.d.ts +88 -0
- package/dist/types/shared/types/component-contract.types.d.ts +68 -0
- package/dist/types/shared/types/data-config.types.d.ts +81 -0
- package/dist/types/shared/types/domain.types.d.ts +6 -0
- package/dist/types/shared/types/engine.types.d.ts +6 -0
- package/dist/types/shared/types/manifest.types.d.ts +23 -0
- package/dist/types/shared/types/scope-manifest.types.d.ts +82 -0
- package/dist/types/shared/types/style-config.types.d.ts +8 -0
- package/dist/types/shared/types/ui-config.types.d.ts +20 -0
- package/global.d.ts +12 -0
- package/next.config.js +76 -1
- package/package.json +32 -11
- package/proxy.ts +62 -0
- package/core/client/engine/theme-variables.ts +0 -37
- package/dist/tsconfig.types.tsbuildinfo +0 -1
- package/dist/types/client/engine/theme-variables.d.ts +0 -3
- package/middleware.ts +0 -33
|
@@ -22,6 +22,11 @@ export interface SomaServerPageAssets {
|
|
|
22
22
|
ui: string;
|
|
23
23
|
event: string;
|
|
24
24
|
styleYaml: string;
|
|
25
|
+
/**
|
|
26
|
+
* 数据对象层声明(*_data.yaml,五件套可选件)。
|
|
27
|
+
* 按约定发现 data/<page>_data.yaml(回退 ui/ 同目录);无文件时该字段缺省,零影响。
|
|
28
|
+
*/
|
|
29
|
+
dataYaml?: string;
|
|
25
30
|
localeYaml: string;
|
|
26
31
|
appConfigYaml: string;
|
|
27
32
|
includes?: Record<string, string>;
|
|
@@ -169,6 +174,10 @@ export function loadSomaServerPageAssets(options: {
|
|
|
169
174
|
};
|
|
170
175
|
}
|
|
171
176
|
|
|
177
|
+
// 数据对象层(可选件):约定优先 data/<page>_data.yaml,回退 ui/ 同目录
|
|
178
|
+
const dataYaml = cache.tryReadFile(join(source.assetRoot, 'data', base + '_data.yaml'))
|
|
179
|
+
|| cache.tryReadFile(join(source.assetRoot, 'ui', base + '_data.yaml'));
|
|
180
|
+
|
|
172
181
|
return {
|
|
173
182
|
base,
|
|
174
183
|
sourceType: source.type,
|
|
@@ -177,6 +186,7 @@ export function loadSomaServerPageAssets(options: {
|
|
|
177
186
|
ui,
|
|
178
187
|
event: cache.tryReadFile(join(source.assetRoot, 'event', base + '_event.yaml')),
|
|
179
188
|
styleYaml: cache.tryReadFile(join(source.assetRoot, 'ui', base + '_style.yaml')),
|
|
189
|
+
...(dataYaml ? { dataYaml } : {}),
|
|
180
190
|
localeYaml,
|
|
181
191
|
appConfigYaml,
|
|
182
192
|
includes: collectIncludes(sources),
|
package/core/server/index.ts
CHANGED
|
@@ -15,7 +15,7 @@ export {
|
|
|
15
15
|
type SomaServerRequestContextOptions,
|
|
16
16
|
} from './infra/http/soma-server-request-context';
|
|
17
17
|
|
|
18
|
-
export type { IService } from './api/IService';
|
|
18
|
+
export type { IService, SomaServiceRequest } from './api/IService';
|
|
19
19
|
export { loadHostService } from './api/load-host-service';
|
|
20
20
|
export { resolveServiceFilePath, toPascalCase } from './api/service-path';
|
|
21
21
|
|
|
@@ -26,6 +26,29 @@ export {
|
|
|
26
26
|
type SomaHostRequestKind,
|
|
27
27
|
type SomaRequestHook,
|
|
28
28
|
} from './host/resolve-host-request-hook';
|
|
29
|
+
export {
|
|
30
|
+
createSomaCspHeader,
|
|
31
|
+
createSomaCspNonce,
|
|
32
|
+
buildSomaCspDirectives,
|
|
33
|
+
buildSomaCspHeaderValue,
|
|
34
|
+
resolveSomaCspMode,
|
|
35
|
+
resolveSomaCspOptionsFromEnv,
|
|
36
|
+
somaCspHeaderName,
|
|
37
|
+
SOMA_CSP_MODE_ENV,
|
|
38
|
+
SOMA_CSP_CONNECT_SRC_ENV,
|
|
39
|
+
SOMA_CSP_IMG_SRC_ENV,
|
|
40
|
+
SOMA_CSP_FRAME_SRC_ENV,
|
|
41
|
+
SOMA_CSP_REPORT_URI_ENV,
|
|
42
|
+
SOMA_CSP_NONCE_HEADER,
|
|
43
|
+
type SomaCspMode,
|
|
44
|
+
type SomaCspOptions,
|
|
45
|
+
type SomaCspHeader,
|
|
46
|
+
} from './host/content-security-policy';
|
|
47
|
+
export {
|
|
48
|
+
readSomaCspNonce,
|
|
49
|
+
somaCspNonceMetadata,
|
|
50
|
+
type SomaCspHeaderBag,
|
|
51
|
+
} from './host/csp-nonce-metadata';
|
|
29
52
|
export {
|
|
30
53
|
loadSomaServerPageAssets,
|
|
31
54
|
SomaPageAssetError,
|
|
@@ -33,6 +56,12 @@ export {
|
|
|
33
56
|
type SomaPageAssetLoadProfile,
|
|
34
57
|
} from './host/server-page-assets';
|
|
35
58
|
|
|
59
|
+
export {
|
|
60
|
+
loadComponentPackage,
|
|
61
|
+
loadComponentPackages,
|
|
62
|
+
SomaComponentPackageError,
|
|
63
|
+
} from '../build/component/package-loader';
|
|
64
|
+
|
|
36
65
|
export {
|
|
37
66
|
setSomaDb,
|
|
38
67
|
getSomaDb,
|
|
@@ -101,7 +101,7 @@ export class ServerFileCache {
|
|
|
101
101
|
// Changes require a server restart in that environment.
|
|
102
102
|
if (process.env.NODE_ENV !== 'production') {
|
|
103
103
|
console.warn(
|
|
104
|
-
`[soma-core] fs.watch recursive failed (${e.code ?? e.message}). ` +
|
|
104
|
+
`[soma-core][缓存] fs.watch recursive failed (${e.code ?? e.message}). ` +
|
|
105
105
|
'File cache will not auto-invalidate — restart the server after changes.',
|
|
106
106
|
);
|
|
107
107
|
}
|
|
@@ -83,10 +83,10 @@ function sanitizeMockEnvironment(environment, preloadUrl, options = {}) {
|
|
|
83
83
|
|
|
84
84
|
function assertSupportedNode(version = process.versions.node) {
|
|
85
85
|
const [major, minor] = String(version).split('.').map(Number);
|
|
86
|
-
if (major <
|
|
86
|
+
if (major < 20 || (major === 20 && minor < 9)) {
|
|
87
87
|
throw new SomaMockCliError(
|
|
88
88
|
'NODE_VERSION_UNSUPPORTED',
|
|
89
|
-
`Server Mock preloading requires Node >=
|
|
89
|
+
`Server Mock preloading requires Node >=20.9; current version is ${version}`,
|
|
90
90
|
);
|
|
91
91
|
}
|
|
92
92
|
}
|
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
// API 注册表:登记业务应用的后端接口——**只登记与校验,不代理、不持凭据**。
|
|
2
|
+
//
|
|
3
|
+
// 它是页面取数的白名单:页面声明里 `data.<对象>.from[].api` 指向的路径必须在这里
|
|
4
|
+
// 登记过(交叉校验见 validation/cross-check.ts)。于是"AI 生成的页面能调哪些接口"
|
|
5
|
+
// 由注册表这份数据决定,而不是靠模型自觉——安全边界由校验闸门数学保证。
|
|
6
|
+
//
|
|
7
|
+
// 三条纪律:
|
|
8
|
+
// 1. **不做代理**:注册的是接口的描述(路径/方法/字段字典),业务请求仍由页面直连
|
|
9
|
+
// 宿主自己的后端。平台从不转发,也就永远不需要持有任何凭据。
|
|
10
|
+
// 2. **凭据禁令**:登记内容里出现 Authorization / 密钥类字段即拒(credential-ban)。
|
|
11
|
+
// 鉴权永远是宿主运行时的事(与 soma-voice「凭据由宿主持有」同源纪律)。
|
|
12
|
+
// 3. **字段字典复用 core 词汇**:直接用数据对象层的 SomaDataFieldConfig,
|
|
13
|
+
// 不发明第二套——注册表登记的字典与页面消费的字典必须是同一种东西。
|
|
14
|
+
//
|
|
15
|
+
// 存储与页面表同底座:一名一文件、跨进程写锁、原子落盘、按落盘指纹失效的读缓存。
|
|
16
|
+
// 与页面表的区别:API 记录**不做版本历史**(接口描述是"当下事实",不是可回滚的资产),
|
|
17
|
+
// 重复注册即更新(upsert),响应用 created 位区分新建与更新。
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import type { SomaDataFieldConfig } from '../../shared/types/data-config.types';
|
|
22
|
+
import { withRegistryLock, writeFileAtomic } from './registry-file-lock';
|
|
23
|
+
import { RegistryError } from './registry-error';
|
|
24
|
+
import { scanCredentialLeak } from './validation/credential-ban';
|
|
25
|
+
|
|
26
|
+
/** 注册名约束:与页面名同形(可直接用作文件名与 URL 片段) */
|
|
27
|
+
export const API_NAME_PATTERN = /^[a-z0-9-]{1,64}$/;
|
|
28
|
+
|
|
29
|
+
/** 应用命名空间约束:与页面表同形 */
|
|
30
|
+
export const API_APP_PATTERN = /^[a-z0-9-]{1,32}$/;
|
|
31
|
+
|
|
32
|
+
/** 允许登记的 HTTP 方法(白名单;登记不是代理,方法只用于描述与自查) */
|
|
33
|
+
export const API_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const;
|
|
34
|
+
export type ApiMethod = (typeof API_METHODS)[number];
|
|
35
|
+
|
|
36
|
+
/** 单条 API 记录的体积上限:字典再大也不该有 64KB */
|
|
37
|
+
export const API_RECORD_MAX_BYTES = 64 * 1024;
|
|
38
|
+
|
|
39
|
+
export const ApiRegistryErrorCodes = {
|
|
40
|
+
/** 注册名非法 */
|
|
41
|
+
API_NAME_INVALID: 4531,
|
|
42
|
+
/** 记录缺必填字段 / 字段类型不对 / 体积超限 */
|
|
43
|
+
API_RECORD_INVALID: 4532,
|
|
44
|
+
/** 接口不存在 */
|
|
45
|
+
API_NOT_FOUND: 4533,
|
|
46
|
+
/** 登记内容里出现凭据类字段(鉴权归宿主运行时,注册表不许持有) */
|
|
47
|
+
API_CREDENTIAL_FORBIDDEN: 4534,
|
|
48
|
+
} as const;
|
|
49
|
+
|
|
50
|
+
export type ApiRegistryErrorCode =
|
|
51
|
+
(typeof ApiRegistryErrorCodes)[keyof typeof ApiRegistryErrorCodes];
|
|
52
|
+
|
|
53
|
+
export class ApiRegistryError extends RegistryError {
|
|
54
|
+
declare readonly code: ApiRegistryErrorCode;
|
|
55
|
+
|
|
56
|
+
constructor(code: ApiRegistryErrorCode, message: string) {
|
|
57
|
+
super(code, message);
|
|
58
|
+
this.name = 'ApiRegistryError';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 存储单元:一个接口的当下描述 */
|
|
63
|
+
export interface ApiRecord {
|
|
64
|
+
/** 注册名(页面与人引用它的稳定标识) */
|
|
65
|
+
name: string;
|
|
66
|
+
/** HTTP 方法 */
|
|
67
|
+
method: ApiMethod;
|
|
68
|
+
/** 后端接口路径——**交叉校验的匹配键**,必须以 / 开头 */
|
|
69
|
+
path: string;
|
|
70
|
+
/** 一句话说明这个接口给什么 */
|
|
71
|
+
description?: string;
|
|
72
|
+
/** 字段字典(字段名 → 条目),复用数据对象层词汇;生成链据此绑字段 */
|
|
73
|
+
fields?: Record<string, SomaDataFieldConfig>;
|
|
74
|
+
/** 应用命名空间(缺省 'default') */
|
|
75
|
+
app: string;
|
|
76
|
+
/** 标签(目录化 / 过滤) */
|
|
77
|
+
tags: string[];
|
|
78
|
+
createdAt: number;
|
|
79
|
+
updatedAt: number;
|
|
80
|
+
/** 操作者标识(可选) */
|
|
81
|
+
operator?: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface ApiRegisterInput {
|
|
85
|
+
method?: unknown;
|
|
86
|
+
path?: unknown;
|
|
87
|
+
description?: unknown;
|
|
88
|
+
fields?: unknown;
|
|
89
|
+
app?: unknown;
|
|
90
|
+
tags?: unknown;
|
|
91
|
+
operator?: unknown;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface ApiRegistryListOptions {
|
|
95
|
+
/** 只看某应用命名空间 */
|
|
96
|
+
app?: string;
|
|
97
|
+
/** 关键词:命中注册名 / 路径 / 描述(不区分大小写) */
|
|
98
|
+
keyword?: string;
|
|
99
|
+
offset?: number;
|
|
100
|
+
limit?: number;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface ApiRegistryListItem {
|
|
104
|
+
name: string;
|
|
105
|
+
method: ApiMethod;
|
|
106
|
+
path: string;
|
|
107
|
+
app: string;
|
|
108
|
+
tags: string[];
|
|
109
|
+
description?: string;
|
|
110
|
+
/** 字段字典条数(清单不返回字典本体,取详情再拿) */
|
|
111
|
+
fieldCount: number;
|
|
112
|
+
updatedAt: number;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface ApiRegistryListResult {
|
|
116
|
+
apis: ApiRegistryListItem[];
|
|
117
|
+
total: number;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface ApiRegistryStoreOptions {
|
|
121
|
+
/** 持久化目录(每接口一个 <name>.json),默认 data/soma-runtime/apis */
|
|
122
|
+
baseDir?: string;
|
|
123
|
+
/** 时钟注入点,默认 Date.now;测试传确定性时钟 */
|
|
124
|
+
now?: () => number;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export class ApiRegistryStore {
|
|
128
|
+
private readonly baseDir: string;
|
|
129
|
+
private readonly now: () => number;
|
|
130
|
+
/** 读缓存:注册名 → { 记录, 落盘指纹 }。指纹变了就重读(与页面表同口径) */
|
|
131
|
+
private readonly cache = new Map<string, { record: ApiRecord; stamp: string }>();
|
|
132
|
+
|
|
133
|
+
constructor(options: ApiRegistryStoreOptions = {}) {
|
|
134
|
+
this.baseDir = path.resolve(options.baseDir ?? path.join('data', 'soma-runtime', 'apis'));
|
|
135
|
+
this.now = options.now ?? Date.now;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
storageDirectory(): string {
|
|
139
|
+
return this.baseDir;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 注册(upsert):名字已存在即更新描述,返回记录与 created 位 */
|
|
143
|
+
register(name: string, input: ApiRegisterInput): { record: ApiRecord; created: boolean } {
|
|
144
|
+
const safeName = assertApiName(name);
|
|
145
|
+
return withRegistryLock(this.baseDir, `api-${safeName}`, () => {
|
|
146
|
+
this.cache.delete(safeName);
|
|
147
|
+
const existing = this.read(safeName);
|
|
148
|
+
const normalized = normalizeApiInput(input);
|
|
149
|
+
const now = this.now();
|
|
150
|
+
const record: ApiRecord = {
|
|
151
|
+
name: safeName,
|
|
152
|
+
method: normalized.method,
|
|
153
|
+
path: normalized.path,
|
|
154
|
+
...(normalized.description ? { description: normalized.description } : {}),
|
|
155
|
+
...(normalized.fields ? { fields: normalized.fields } : {}),
|
|
156
|
+
app: normalized.app,
|
|
157
|
+
tags: normalized.tags,
|
|
158
|
+
createdAt: existing?.createdAt ?? now,
|
|
159
|
+
updatedAt: now,
|
|
160
|
+
...(normalized.operator ? { operator: normalized.operator } : {}),
|
|
161
|
+
};
|
|
162
|
+
assertRecordSize(record);
|
|
163
|
+
this.save(safeName, record);
|
|
164
|
+
return { record: cloneApiRecord(record), created: existing === null };
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** 取一条;不存在报 API_NOT_FOUND */
|
|
169
|
+
get(name: string): ApiRecord {
|
|
170
|
+
const safeName = assertApiName(name);
|
|
171
|
+
const record = this.read(safeName);
|
|
172
|
+
if (!record) {
|
|
173
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_NOT_FOUND, `接口未注册:${safeName}`);
|
|
174
|
+
}
|
|
175
|
+
return cloneApiRecord(record);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** 注销:删掉记录(接口描述不是可回滚资产,不留墓碑);不存在报 API_NOT_FOUND */
|
|
179
|
+
unregister(name: string): ApiRecord {
|
|
180
|
+
const safeName = assertApiName(name);
|
|
181
|
+
return withRegistryLock(this.baseDir, `api-${safeName}`, () => {
|
|
182
|
+
const record = this.read(safeName);
|
|
183
|
+
if (!record) {
|
|
184
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_NOT_FOUND, `接口未注册:${safeName}`);
|
|
185
|
+
}
|
|
186
|
+
fs.rmSync(this.fileOf(safeName), { force: true });
|
|
187
|
+
this.cache.delete(safeName);
|
|
188
|
+
return cloneApiRecord(record);
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 清单(按注册名排序,分页协议 { apis, total }) */
|
|
193
|
+
list(options: ApiRegistryListOptions = {}): ApiRegistryListResult {
|
|
194
|
+
const keyword = typeof options.keyword === 'string' ? options.keyword.trim().toLowerCase() : '';
|
|
195
|
+
const items: ApiRegistryListItem[] = [];
|
|
196
|
+
for (const name of this.names()) {
|
|
197
|
+
const record = this.read(name);
|
|
198
|
+
if (!record) continue;
|
|
199
|
+
if (options.app !== undefined && record.app !== options.app) continue;
|
|
200
|
+
if (keyword) {
|
|
201
|
+
const haystack = [record.name, record.path, record.description ?? ''].join('\n').toLowerCase();
|
|
202
|
+
if (!haystack.includes(keyword)) continue;
|
|
203
|
+
}
|
|
204
|
+
items.push({
|
|
205
|
+
name: record.name,
|
|
206
|
+
method: record.method,
|
|
207
|
+
path: record.path,
|
|
208
|
+
app: record.app,
|
|
209
|
+
tags: [...record.tags],
|
|
210
|
+
...(record.description ? { description: record.description } : {}),
|
|
211
|
+
fieldCount: record.fields ? Object.keys(record.fields).length : 0,
|
|
212
|
+
updatedAt: record.updatedAt,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
items.sort((left, right) => left.name.localeCompare(right.name));
|
|
216
|
+
const total = items.length;
|
|
217
|
+
const offset = normalizePageParam(options.offset) ?? 0;
|
|
218
|
+
const limit = normalizePageParam(options.limit);
|
|
219
|
+
return { apis: items.slice(offset, limit === undefined ? undefined : offset + limit), total };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 已注册的接口路径集合——交叉校验的判据来源。
|
|
224
|
+
* 路径是匹配键而非注册名:页面声明里写的是路径。
|
|
225
|
+
*
|
|
226
|
+
* 成本:每次调用扫一遍目录并 stat 每条记录(内容没变就命中缓存,不重复解析)。
|
|
227
|
+
* 刻意不给这个集合再加一层缓存——它只在**页面注册**这条低频路径上被调用,
|
|
228
|
+
* 而一层"目录级"缓存必须靠目录 mtime 失效,那在原地改写某条记录时不会变,
|
|
229
|
+
* 会把白名单卡在旧值上:判据宁可每次重算,也不能有可能是错的。
|
|
230
|
+
*/
|
|
231
|
+
registeredPaths(): ReadonlySet<string> {
|
|
232
|
+
const paths = new Set<string>();
|
|
233
|
+
for (const name of this.names()) {
|
|
234
|
+
const record = this.read(name);
|
|
235
|
+
if (record) paths.add(record.path);
|
|
236
|
+
}
|
|
237
|
+
return paths;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ── 内部 ──
|
|
241
|
+
|
|
242
|
+
private names(): string[] {
|
|
243
|
+
const names = new Set<string>(this.cache.keys());
|
|
244
|
+
if (fs.existsSync(this.baseDir)) {
|
|
245
|
+
for (const file of fs.readdirSync(this.baseDir)) {
|
|
246
|
+
if (!file.endsWith('.json')) continue;
|
|
247
|
+
const name = file.slice(0, -'.json'.length);
|
|
248
|
+
if (API_NAME_PATTERN.test(name)) names.add(name);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return [...names];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private read(name: string): ApiRecord | null {
|
|
255
|
+
const filePath = this.fileOf(name);
|
|
256
|
+
const stamp = this.stampOf(filePath);
|
|
257
|
+
if (stamp === null) {
|
|
258
|
+
this.cache.delete(name);
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
const cached = this.cache.get(name);
|
|
262
|
+
if (cached && cached.stamp === stamp) return cached.record;
|
|
263
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
264
|
+
let parsed: unknown;
|
|
265
|
+
try {
|
|
266
|
+
parsed = JSON.parse(raw);
|
|
267
|
+
} catch (error) {
|
|
268
|
+
throw new Error(`[ApiRegistryStore] 接口记录损坏(非法 JSON):${filePath}`, { cause: error });
|
|
269
|
+
}
|
|
270
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
271
|
+
throw new Error(`[ApiRegistryStore] 接口记录损坏(应为对象):${filePath}`);
|
|
272
|
+
}
|
|
273
|
+
const record = normalizeStoredApiRecord(parsed as Record<string, unknown>, name);
|
|
274
|
+
this.cache.set(name, { record, stamp });
|
|
275
|
+
this.trimCache();
|
|
276
|
+
return record;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
private save(name: string, record: ApiRecord): void {
|
|
280
|
+
fs.mkdirSync(this.baseDir, { recursive: true });
|
|
281
|
+
const filePath = this.fileOf(name);
|
|
282
|
+
writeFileAtomic(filePath, `${JSON.stringify(record, null, 2)}\n`);
|
|
283
|
+
const stamp = this.stampOf(filePath);
|
|
284
|
+
if (stamp !== null) {
|
|
285
|
+
this.cache.set(name, { record, stamp });
|
|
286
|
+
this.trimCache();
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** 缓存上限:一条记录很小,但仓库可以很大——不留无上限的 Map(2GB 机器纪律) */
|
|
291
|
+
private trimCache(): void {
|
|
292
|
+
const MAX_CACHED = 512;
|
|
293
|
+
while (this.cache.size > MAX_CACHED) {
|
|
294
|
+
const oldest = this.cache.keys().next();
|
|
295
|
+
if (oldest.done) break;
|
|
296
|
+
this.cache.delete(oldest.value);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private stampOf(filePath: string): string | null {
|
|
301
|
+
try {
|
|
302
|
+
const stat = fs.statSync(filePath);
|
|
303
|
+
return `${stat.mtimeMs}:${stat.size}`;
|
|
304
|
+
} catch {
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private fileOf(name: string): string {
|
|
310
|
+
return path.join(this.baseDir, `${name}.json`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export function assertApiName(name: unknown): string {
|
|
315
|
+
if (typeof name !== 'string' || !API_NAME_PATTERN.test(name)) {
|
|
316
|
+
throw new ApiRegistryError(
|
|
317
|
+
ApiRegistryErrorCodes.API_NAME_INVALID,
|
|
318
|
+
'接口注册名必须匹配 [a-z0-9-]{1,64}(小写字母 / 数字 / 连字符)',
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
return name;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
interface NormalizedApiInput {
|
|
325
|
+
method: ApiMethod;
|
|
326
|
+
path: string;
|
|
327
|
+
description?: string;
|
|
328
|
+
fields?: Record<string, SomaDataFieldConfig>;
|
|
329
|
+
app: string;
|
|
330
|
+
tags: string[];
|
|
331
|
+
operator?: string;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** 结构校验 + 凭据禁令:两道一起过,拒绝时点名违规项 */
|
|
335
|
+
export function normalizeApiInput(input: ApiRegisterInput): NormalizedApiInput {
|
|
336
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
337
|
+
throw new ApiRegistryError(
|
|
338
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
339
|
+
'注册体必须是 { method, path, description?, fields?, app?, tags? } 对象',
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
const method = typeof input.method === 'string' ? input.method.toUpperCase() : '';
|
|
343
|
+
if (!(API_METHODS as readonly string[]).includes(method)) {
|
|
344
|
+
throw new ApiRegistryError(
|
|
345
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
346
|
+
`method 必须是 ${API_METHODS.join(' / ')} 之一:${String(input.method)}`,
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
if (typeof input.path !== 'string' || !input.path.startsWith('/')) {
|
|
350
|
+
throw new ApiRegistryError(
|
|
351
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
352
|
+
'path 必须是以 / 开头的接口路径(后端接口是唯一数据边界,不接受整条 URL)',
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
if (/^\/\//.test(input.path) || /^https?:/i.test(input.path)) {
|
|
356
|
+
throw new ApiRegistryError(
|
|
357
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
358
|
+
'path 不接受跨站地址:数据只允许来自宿主自己的后端',
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
const normalized: NormalizedApiInput = {
|
|
362
|
+
method: method as ApiMethod,
|
|
363
|
+
path: input.path,
|
|
364
|
+
app: 'default',
|
|
365
|
+
tags: [],
|
|
366
|
+
};
|
|
367
|
+
if (input.description !== undefined) {
|
|
368
|
+
if (typeof input.description !== 'string') {
|
|
369
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_RECORD_INVALID, 'description 提供时必须是字符串');
|
|
370
|
+
}
|
|
371
|
+
if (input.description !== '') normalized.description = input.description;
|
|
372
|
+
}
|
|
373
|
+
if (input.fields !== undefined) {
|
|
374
|
+
normalized.fields = normalizeFieldDict(input.fields);
|
|
375
|
+
}
|
|
376
|
+
if (input.app !== undefined) {
|
|
377
|
+
if (typeof input.app !== 'string' || !API_APP_PATTERN.test(input.app)) {
|
|
378
|
+
throw new ApiRegistryError(
|
|
379
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
380
|
+
'app 必须匹配 [a-z0-9-]{1,32}(应用命名空间)',
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
normalized.app = input.app;
|
|
384
|
+
}
|
|
385
|
+
if (input.tags !== undefined) {
|
|
386
|
+
if (!Array.isArray(input.tags) || input.tags.some((tag) => typeof tag !== 'string' || tag === '')) {
|
|
387
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_RECORD_INVALID, 'tags 必须是非空字符串数组');
|
|
388
|
+
}
|
|
389
|
+
normalized.tags = input.tags as string[];
|
|
390
|
+
}
|
|
391
|
+
if (input.operator !== undefined) {
|
|
392
|
+
if (typeof input.operator !== 'string') {
|
|
393
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_RECORD_INVALID, 'operator 提供时必须是字符串');
|
|
394
|
+
}
|
|
395
|
+
normalized.operator = input.operator;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// 凭据禁令:登记内容里不许出现凭据。放在结构校验之后、落库之前的唯一咽喉上。
|
|
399
|
+
const leaks = scanCredentialLeak({
|
|
400
|
+
path: normalized.path,
|
|
401
|
+
description: normalized.description,
|
|
402
|
+
fields: normalized.fields,
|
|
403
|
+
});
|
|
404
|
+
if (leaks.length > 0) {
|
|
405
|
+
throw new ApiRegistryError(
|
|
406
|
+
ApiRegistryErrorCodes.API_CREDENTIAL_FORBIDDEN,
|
|
407
|
+
`接口登记未通过凭据禁令:${leaks.join(';')}`,
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
return normalized;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** 字段字典归一化:白名单字段,未知键丢弃(字典是描述,不是自由容器) */
|
|
414
|
+
function normalizeFieldDict(fields: unknown): Record<string, SomaDataFieldConfig> {
|
|
415
|
+
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
|
|
416
|
+
throw new ApiRegistryError(
|
|
417
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
418
|
+
'fields 必须是 { 字段名: { name?, type?, permission?, rules?, options? } } 对象',
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
const source = fields as Record<string, unknown>;
|
|
422
|
+
const normalized: Record<string, SomaDataFieldConfig> = {};
|
|
423
|
+
for (const [key, value] of Object.entries(source)) {
|
|
424
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
425
|
+
throw new ApiRegistryError(
|
|
426
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
427
|
+
`fields.${key} 必须是对象`,
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
const entry = value as Record<string, unknown>;
|
|
431
|
+
const config: SomaDataFieldConfig = {};
|
|
432
|
+
if (entry.name !== undefined) {
|
|
433
|
+
if (typeof entry.name !== 'string') {
|
|
434
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_RECORD_INVALID, `fields.${key}.name 必须是字符串`);
|
|
435
|
+
}
|
|
436
|
+
config.name = entry.name;
|
|
437
|
+
}
|
|
438
|
+
if (entry.type !== undefined) {
|
|
439
|
+
if (typeof entry.type !== 'string') {
|
|
440
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_RECORD_INVALID, `fields.${key}.type 必须是字符串`);
|
|
441
|
+
}
|
|
442
|
+
config.type = entry.type as SomaDataFieldConfig['type'];
|
|
443
|
+
}
|
|
444
|
+
if (entry.permission !== undefined) {
|
|
445
|
+
if (entry.permission !== 'r' && entry.permission !== 'w') {
|
|
446
|
+
throw new ApiRegistryError(
|
|
447
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
448
|
+
`fields.${key}.permission 只能是 r / w`,
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
config.permission = entry.permission;
|
|
452
|
+
}
|
|
453
|
+
if (entry.rules !== undefined) {
|
|
454
|
+
if (!Array.isArray(entry.rules)) {
|
|
455
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_RECORD_INVALID, `fields.${key}.rules 必须是数组`);
|
|
456
|
+
}
|
|
457
|
+
config.rules = entry.rules as SomaDataFieldConfig['rules'];
|
|
458
|
+
}
|
|
459
|
+
if (entry.options !== undefined) {
|
|
460
|
+
if (!Array.isArray(entry.options)) {
|
|
461
|
+
throw new ApiRegistryError(ApiRegistryErrorCodes.API_RECORD_INVALID, `fields.${key}.options 必须是数组`);
|
|
462
|
+
}
|
|
463
|
+
config.options = entry.options as SomaDataFieldConfig['options'];
|
|
464
|
+
}
|
|
465
|
+
normalized[key] = config;
|
|
466
|
+
}
|
|
467
|
+
return normalized;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** 体积闸门:字典再大也不该有 64KB(超限即拒,复用记录非法码) */
|
|
471
|
+
function assertRecordSize(record: ApiRecord): void {
|
|
472
|
+
const bytes = Buffer.byteLength(JSON.stringify(record), 'utf8');
|
|
473
|
+
if (bytes <= API_RECORD_MAX_BYTES) return;
|
|
474
|
+
throw new ApiRegistryError(
|
|
475
|
+
ApiRegistryErrorCodes.API_RECORD_INVALID,
|
|
476
|
+
`接口记录体积超限:当前 ${bytes} 字节 / 上限 ${API_RECORD_MAX_BYTES} 字节。`
|
|
477
|
+
+ '字段字典是接口响应的语义化描述,不是样本数据仓库。',
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** 存量记录归一化:补 app/tags 缺省值,名字以文件名为准 */
|
|
482
|
+
export function normalizeStoredApiRecord(raw: Record<string, unknown>, name: string): ApiRecord {
|
|
483
|
+
const record = { ...raw } as unknown as ApiRecord;
|
|
484
|
+
record.name = name;
|
|
485
|
+
if (typeof record.app !== 'string' || !API_APP_PATTERN.test(record.app)) record.app = 'default';
|
|
486
|
+
if (!Array.isArray(record.tags)) {
|
|
487
|
+
record.tags = [];
|
|
488
|
+
} else {
|
|
489
|
+
record.tags = record.tags.filter((tag): tag is string => typeof tag === 'string');
|
|
490
|
+
}
|
|
491
|
+
return record;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export function cloneApiRecord(record: ApiRecord): ApiRecord {
|
|
495
|
+
return JSON.parse(JSON.stringify(record)) as ApiRecord;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function normalizePageParam(value: unknown): number | undefined {
|
|
499
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) return undefined;
|
|
500
|
+
return value;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// ---------------------------------------------------------------------------
|
|
504
|
+
// 进程级共享实例:端点与交叉校验经此取店,测试可注入后复位。
|
|
505
|
+
// ---------------------------------------------------------------------------
|
|
506
|
+
|
|
507
|
+
let sharedStore: ApiRegistryStore | undefined;
|
|
508
|
+
|
|
509
|
+
/** 共享实例:baseDir 可用环境变量 SOMA_API_REGISTRY_DIR 覆盖(默认 data/soma-runtime/apis) */
|
|
510
|
+
export function getApiRegistryStore(): ApiRegistryStore {
|
|
511
|
+
sharedStore ??= new ApiRegistryStore({ baseDir: process.env.SOMA_API_REGISTRY_DIR });
|
|
512
|
+
return sharedStore;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** 替换 / 复位共享实例(测试用;不传参即清空,下次访问按当前环境重建) */
|
|
516
|
+
export function resetApiRegistryStore(store?: ApiRegistryStore): void {
|
|
517
|
+
sharedStore = store;
|
|
518
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type ObjectRevision = string;
|
|
2
|
+
|
|
3
|
+
export interface ObjectSnapshot {
|
|
4
|
+
readonly key: string;
|
|
5
|
+
readonly text: string;
|
|
6
|
+
readonly revision: ObjectRevision;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type WriteCondition =
|
|
10
|
+
| { readonly kind: 'absent' }
|
|
11
|
+
| { readonly kind: 'revision'; readonly revision: ObjectRevision };
|
|
12
|
+
|
|
13
|
+
export type ConditionalWriteResult =
|
|
14
|
+
| { readonly committed: true; readonly revision: ObjectRevision }
|
|
15
|
+
| { readonly committed: false };
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 对象存储最小一致性契约:点读必须 read-after-write,revision/ETag 是不透明值。
|
|
19
|
+
* S3 对应 If-None-Match:* / If-Match:<etag>;数据库对应版本列条件 UPDATE。
|
|
20
|
+
*/
|
|
21
|
+
export interface ConditionalObjectStore {
|
|
22
|
+
read(key: string): Promise<ObjectSnapshot | null>;
|
|
23
|
+
list(prefix: string): Promise<readonly string[]>;
|
|
24
|
+
compareAndSet(
|
|
25
|
+
key: string,
|
|
26
|
+
expected: WriteCondition,
|
|
27
|
+
text: string,
|
|
28
|
+
): Promise<ConditionalWriteResult>;
|
|
29
|
+
}
|