soma-core 1.3.2 → 1.3.4
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 +43 -0
- package/app/SomaPageClient.tsx +22 -68
- 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/bin/soma-lsp.cjs +1 -4
- package/core/build/compiler/full-manifest-builder.ts +19 -23
- package/core/build/compiler/html-include-expander.ts +56 -0
- package/core/build/compiler/page-assets.ts +26 -0
- package/core/build/compiler/page-declaration-compiler.ts +85 -0
- package/core/build/compiler/rollup-plugin-soma.ts +4 -13
- package/core/build/compiler/route-builder.ts +0 -2
- package/core/build/compiler/rspack-plugin-soma.js +1 -10
- package/core/build/compiler/soma-manifest-webpack-plugin.js +54 -9
- package/core/build/compiler/soma-precompile.js +3581 -2387
- package/core/build/compiler/soma-precompile.ts +44 -2
- package/core/build/compiler/soma-rspack-yaml-loader.js +5 -8
- package/core/build/compiler/soma-webpack-loader.js +6 -15
- package/core/build/compiler/vite-plugin-soma.ts +9 -21
- package/core/build/component/pack-from-dir.ts +58 -0
- package/core/build/component/package-loader.ts +281 -0
- package/core/build/eject/apply-eject.ts +133 -0
- package/core/build/eject/plan-eject.ts +133 -0
- package/core/build/lsp/cross-file-diagnostics.cjs +82 -113
- package/core/build/lsp/extra-completion.cjs +14 -8
- package/core/build/lsp/lsp-navigation.cjs +50 -43
- package/core/build/lsp/soma-declaration.cjs +85 -0
- package/core/build/lsp/ui-yaml-completion.cjs +98 -104
- package/core/build/v2/block-compile.ts +200 -0
- package/core/build/v2/block-loader.ts +33 -0
- package/core/build/v2/html-index.ts +120 -0
- package/core/build/v2/migrate-v1.ts +370 -0
- package/core/build/v2/soma-file-loader.ts +216 -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 +277 -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 +445 -0
- package/core/client/component/component-registry.ts +71 -0
- package/core/client/component/contract-compat.ts +132 -0
- package/core/client/component/example-v2.ts +132 -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 +249 -24
- 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 +11 -10
- package/core/client/engine/render-engine.ts +39 -4
- package/core/client/engine/runtime-builder.ts +23 -0
- package/core/client/engine/soma-bootstrap.ts +380 -7
- package/core/client/engine/style-binder.ts +47 -1
- 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/parser/v2/namespace.ts +182 -0
- package/core/client/parser/v2/page-parser.ts +359 -0
- package/core/client/parser/v2/use-parser.ts +412 -0
- package/core/client/parser/value-lang.ts +340 -0
- package/core/client/pipes/pipe-registry.ts +249 -0
- package/core/client/quality/SomaQualityRegistry.ts +3 -0
- package/core/client/registry/declaration-renderer.ts +161 -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/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/harmony.ts +307 -0
- package/core/client/theme/scene-tokens.ts +134 -0
- package/core/client/theme/theme-axes.ts +228 -0
- package/core/client/theme/theme-engine.ts +1196 -0
- package/core/client/theme/tone-solver.ts +118 -0
- package/core/client/typography/typography-base.ts +34 -0
- package/core/client/validation/contract-validator.ts +48 -5
- package/core/index.ts +262 -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 +34 -7
- package/core/server/host/soma-page-compile.ts +33 -0
- package/core/server/index.ts +45 -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 +99 -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 +932 -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 +96 -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 +54 -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 +67 -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 +120 -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 +7811 -1380
- package/dist/types/build/compiler/full-manifest-builder.d.ts +6 -2
- package/dist/types/build/compiler/html-include-expander.d.ts +19 -0
- package/dist/types/build/compiler/page-assets.d.ts +3 -0
- package/dist/types/build/compiler/page-declaration-compiler.d.ts +33 -0
- package/dist/types/build/compiler/rollup-plugin-soma.d.ts +0 -2
- package/dist/types/build/compiler/route-builder.d.ts +0 -1
- package/dist/types/build/compiler/soma-precompile.d.ts +17 -0
- package/dist/types/build/compiler/vite-plugin-soma.d.ts +2 -7
- package/dist/types/build/component/pack-from-dir.d.ts +17 -0
- package/dist/types/build/component/package-loader.d.ts +40 -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/build/v2/block-compile.d.ts +28 -0
- package/dist/types/build/v2/block-loader.d.ts +9 -0
- package/dist/types/build/v2/html-index.d.ts +37 -0
- package/dist/types/build/v2/migrate-v1.d.ts +32 -0
- package/dist/types/build/v2/soma-file-loader.d.ts +45 -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 +110 -0
- package/dist/types/client/component/component-registry.d.ts +12 -0
- package/dist/types/client/component/contract-compat.d.ts +16 -0
- package/dist/types/client/component/example-v2.d.ts +9 -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 +51 -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 +25 -1
- package/dist/types/client/engine/runtime-builder.d.ts +7 -0
- package/dist/types/client/engine/soma-bootstrap.d.ts +118 -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/parser/v2/namespace.d.ts +52 -0
- package/dist/types/client/parser/v2/page-parser.d.ts +21 -0
- package/dist/types/client/parser/v2/use-parser.d.ts +72 -0
- package/dist/types/client/parser/value-lang.d.ts +63 -0
- package/dist/types/client/pipes/pipe-registry.d.ts +38 -0
- package/dist/types/client/registry/declaration-renderer.d.ts +50 -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/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/harmony.d.ts +77 -0
- package/dist/types/client/theme/scene-tokens.d.ts +25 -0
- package/dist/types/client/theme/theme-axes.d.ts +81 -0
- package/dist/types/client/theme/theme-engine.d.ts +77 -0
- package/dist/types/client/theme/tone-solver.d.ts +47 -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 +47 -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 +2 -0
- package/dist/types/server/host/soma-page-compile.d.ts +7 -0
- package/dist/types/server/index.d.ts +6 -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 +12 -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 +78 -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/editor/vscode/package.json +1 -24
- package/global.d.ts +5 -11
- package/next.config.js +85 -28
- package/package.json +33 -11
- package/proxy.ts +62 -0
- package/tailwind.config.ts +0 -1
- package/core/build/lsp/event-yaml-completion.cjs +0 -106
- 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/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +0 -30
- package/middleware.ts +0 -33
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// 声明态页面的发布期预编译(P-a)。
|
|
2
|
+
//
|
|
3
|
+
// 页面声明一旦发布就是不可变的,统一 SOMA DSL 应在服务端落库时编译一次,
|
|
4
|
+
// 浏览器只接收运行时配置对象,不保留源声明解析回退。
|
|
5
|
+
//
|
|
6
|
+
// 三条纪律,第一条最重要:
|
|
7
|
+
// 1. **预编译是缓存,不是真理**。parser 一旦升级,库里躺着的产物就可能与新语义不符。
|
|
8
|
+
// 所以每份产物带 `compilerVersion`,服务端版本对不上就从统一源声明重新编译。
|
|
9
|
+
// 2. **编译失败不阻断发布**。声明本身已经过校验闸门;预编译只是加速,
|
|
10
|
+
// 它挂了就当没有这份缓存——绝不能让一个性能优化变成发布的新失败面。
|
|
11
|
+
// 3. **只编译纯数据部分**。html 不编译(它本来就是字符串),
|
|
12
|
+
// locale / appConfig 归宿主而不归声明。
|
|
13
|
+
|
|
14
|
+
import { createRequire } from 'node:module';
|
|
15
|
+
import { compilePageDeclaration } from '../../build/compiler/page-declaration-compiler';
|
|
16
|
+
import type { PageRegistryDeclaration } from './page-registry-store';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 编译器版本。与 soma-core 的包版本对齐——语义变更必然伴随版本号变化,
|
|
20
|
+
* 拿它当"这份缓存还能不能用"的判据,比自己再造一套指纹可靠。
|
|
21
|
+
*
|
|
22
|
+
* 读不到版本时**故意返回一个永不相等的值**(带进程随机后缀),而不是回落成 '0'。
|
|
23
|
+
* 回落成固定值会让版本闸恒真——库里的旧产物照样被采用,那正是这道闸要防的事。
|
|
24
|
+
* 失败方向必须是"不用缓存",不是"照用"。
|
|
25
|
+
*/
|
|
26
|
+
export const DECLARATION_COMPILER_VERSION = readCoreVersion();
|
|
27
|
+
|
|
28
|
+
function readCoreVersion(): string {
|
|
29
|
+
try {
|
|
30
|
+
const require = createRequire(import.meta.url);
|
|
31
|
+
const version = (require('../../../package.json') as { version?: string }).version;
|
|
32
|
+
if (typeof version === 'string' && version !== '') {
|
|
33
|
+
return version;
|
|
34
|
+
}
|
|
35
|
+
} catch {
|
|
36
|
+
// 落到下面的不可用标记
|
|
37
|
+
}
|
|
38
|
+
console.warn('[soma-core][注册中心] 读不到 soma-core 包版本,本进程一律不采用预编译产物');
|
|
39
|
+
return `unknown-${Math.random().toString(36).slice(2, 10)}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 落库的完整运行时产物。 */
|
|
43
|
+
export interface CompiledDeclaration {
|
|
44
|
+
compilerVersion: string;
|
|
45
|
+
uiConfig?: unknown;
|
|
46
|
+
eventConfig?: unknown;
|
|
47
|
+
triggerConfig?: unknown;
|
|
48
|
+
timerConfig?: unknown;
|
|
49
|
+
styleConfig?: unknown;
|
|
50
|
+
dataConfig?: unknown;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 把统一声明一次编译成运行时可直接消费的完整配置对象。
|
|
55
|
+
* 编译失败返回 null,不产生可被误用的半成品。
|
|
56
|
+
*/
|
|
57
|
+
export function precompileDeclaration(
|
|
58
|
+
declaration: PageRegistryDeclaration,
|
|
59
|
+
): CompiledDeclaration | null {
|
|
60
|
+
try {
|
|
61
|
+
const page = compilePageDeclaration({
|
|
62
|
+
html: declaration.html,
|
|
63
|
+
uiYaml: declaration.uiYaml,
|
|
64
|
+
...(declaration.eventYaml ? { eventYaml: declaration.eventYaml } : {}),
|
|
65
|
+
...(declaration.styleYaml ? { styleYaml: declaration.styleYaml } : {}),
|
|
66
|
+
...(declaration.dataYaml ? { dataYaml: declaration.dataYaml } : {}),
|
|
67
|
+
});
|
|
68
|
+
return {
|
|
69
|
+
compilerVersion: DECLARATION_COMPILER_VERSION,
|
|
70
|
+
uiConfig: page.uiConfig,
|
|
71
|
+
eventConfig: page.eventConfig,
|
|
72
|
+
triggerConfig: page.triggers,
|
|
73
|
+
timerConfig: page.timers,
|
|
74
|
+
...(page.styleConfig ? { styleConfig: page.styleConfig } : {}),
|
|
75
|
+
...(page.dataConfig ? { dataConfig: page.dataConfig } : {}),
|
|
76
|
+
};
|
|
77
|
+
} catch (error) {
|
|
78
|
+
console.warn(`[soma-core][注册中心] SOMA DSL 预编译失败:${message(error)}`);
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 消费端的版本闸:编译器版本对不上就整份丢弃。
|
|
85
|
+
* 这是"缓存不是真理"那条纪律的执行点。
|
|
86
|
+
*/
|
|
87
|
+
export function isCompiledUsable(
|
|
88
|
+
compiled: CompiledDeclaration | null | undefined,
|
|
89
|
+
runtimeVersion = DECLARATION_COMPILER_VERSION,
|
|
90
|
+
): boolean {
|
|
91
|
+
if (!compiled || typeof compiled !== 'object') return false;
|
|
92
|
+
return compiled.compilerVersion === runtimeVersion
|
|
93
|
+
&& compiled.uiConfig !== undefined
|
|
94
|
+
&& compiled.eventConfig !== undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function message(error: unknown): string {
|
|
98
|
+
return error instanceof Error ? error.message : String(error);
|
|
99
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ConditionalObjectStore,
|
|
3
|
+
ConditionalWriteResult,
|
|
4
|
+
ObjectSnapshot,
|
|
5
|
+
WriteCondition,
|
|
6
|
+
} from './conditional-object-store';
|
|
7
|
+
|
|
8
|
+
interface StoredObject {
|
|
9
|
+
text: string;
|
|
10
|
+
revision: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** 可运行参考与测试后端;单进程内串行比较并交换,语义等同远端原子条件写。 */
|
|
14
|
+
export class InMemoryConditionalObjectStore implements ConditionalObjectStore {
|
|
15
|
+
private readonly objects = new Map<string, StoredObject>();
|
|
16
|
+
|
|
17
|
+
async read(key: string): Promise<ObjectSnapshot | null> {
|
|
18
|
+
const stored = this.objects.get(key);
|
|
19
|
+
return stored
|
|
20
|
+
? { key, text: stored.text, revision: String(stored.revision) }
|
|
21
|
+
: null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async list(prefix: string): Promise<readonly string[]> {
|
|
25
|
+
return [...this.objects.keys()].filter((key) => key.startsWith(prefix)).sort();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async compareAndSet(
|
|
29
|
+
key: string,
|
|
30
|
+
expected: WriteCondition,
|
|
31
|
+
text: string,
|
|
32
|
+
): Promise<ConditionalWriteResult> {
|
|
33
|
+
const current = this.objects.get(key);
|
|
34
|
+
if (expected.kind === 'absent') {
|
|
35
|
+
if (current) return { committed: false };
|
|
36
|
+
} else if (!current || String(current.revision) !== expected.revision) {
|
|
37
|
+
return { committed: false };
|
|
38
|
+
}
|
|
39
|
+
const revision = (current?.revision ?? 0) + 1;
|
|
40
|
+
this.objects.set(key, { text, revision });
|
|
41
|
+
return { committed: true, revision: String(revision) };
|
|
42
|
+
}
|
|
43
|
+
}
|