soma-core 2.2.7 → 2.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/core/build/compiler/full-manifest-builder.ts +1 -1
  2. package/core/build/compiler/host-config-sync.cjs +1 -1
  3. package/core/build/compiler/soma-manifest-webpack-plugin.js +2 -6
  4. package/core/build/compiler/soma-precompile.js +80 -4
  5. package/core/client/a11y/announcer.ts +2 -16
  6. package/core/client/base/SomaPageRootBase.ts +2 -2
  7. package/core/client/base/defineSomaView.ts +11 -2
  8. package/core/client/base/runtime-services.types.ts +57 -0
  9. package/core/client/data/data-object-resolver.ts +36 -5
  10. package/core/client/data/role-gate.ts +2 -8
  11. package/core/client/engine/event-engine.ts +1 -0
  12. package/core/client/engines/chart/adapter-echarts.ts +75 -2
  13. package/core/client/engines/chart/index.ts +18 -0
  14. package/core/client/engines/chart/port.ts +13 -0
  15. package/core/client/engines/diff/adapter-jsdiff.ts +27 -8
  16. package/core/client/engines/diff/index.ts +81 -6
  17. package/core/client/engines/diff/items.ts +212 -0
  18. package/core/client/engines/diff/port.ts +140 -3
  19. package/core/client/engines/diff/prose.ts +443 -0
  20. package/core/client/engines/engine-adapters.ts +6 -0
  21. package/core/client/engines/highlight/adapter-lezer.ts +109 -0
  22. package/core/client/engines/highlight/index.ts +135 -0
  23. package/core/client/engines/highlight/port.ts +92 -0
  24. package/core/client/engines/markdown/adapter-markdown-it.ts +65 -0
  25. package/core/client/engines/markdown/blocks.ts +335 -0
  26. package/core/client/engines/markdown/index.ts +51 -0
  27. package/core/client/engines/markdown/port.ts +94 -0
  28. package/core/client/engines/markdown/vendor-modules.d.ts +6 -0
  29. package/core/client/engines/structured/adapter-js-yaml.ts +33 -0
  30. package/core/client/engines/structured/index.ts +139 -0
  31. package/core/client/engines/structured/port.ts +59 -0
  32. package/core/client/infra/http/SomaHttpService.ts +2 -4
  33. package/core/client/infra/notify/DefaultNotifyService.ts +2 -3
  34. package/core/client/infra/permission/SomaPermission.ts +1 -1
  35. package/core/client/render-ports/notify-renderer.ts +2 -46
  36. package/core/client/runtime/SomaRuntimeServices.ts +16 -45
  37. package/core/server/host/app-config-composer.ts +6 -52
  38. package/core/server/host/host-config-paths.cjs +2 -100
  39. package/core/server/host/precompiled-manifest.ts +69 -0
  40. package/core/server/infra/host-config-paths.cjs +100 -0
  41. package/core/server/page-assets.ts +2 -70
  42. package/core/server/runtime-space/bindings.ts +76 -1
  43. package/core/server/runtime-space/digest.ts +6 -0
  44. package/core/server/runtime-space/index.ts +1 -1
  45. package/core/server/runtime-space/prewarm.ts +8 -8
  46. package/core/server/runtime-space/store.ts +23 -7
  47. package/core/server/runtime-space/types.ts +3 -2
  48. package/core/shared/app-config-merge.ts +59 -0
  49. package/core/shared/registry-generated/limits.ts +80 -4
  50. package/core/shared/types/announcer.types.ts +18 -0
  51. package/core/shared/types/notify.types.ts +26 -0
  52. package/core/shared/types/role-gate.types.ts +11 -0
  53. package/dist/browser/runtime-bundle.manifest.json +50 -7
  54. package/dist/browser/soma-runtime.js +120022 -103991
  55. package/dist/core/index.cjs +113888 -97846
  56. package/dist/host-native/aot-builder.cjs +277 -189
  57. package/dist/host-native/native-server.cjs +245 -84
  58. package/dist/lsp/component-tree.cjs +80 -4
  59. package/dist/types/build/compiler/full-manifest-builder.d.ts +1 -1
  60. package/dist/types/client/a11y/announcer.d.ts +2 -14
  61. package/dist/types/client/base/SomaPageRootBase.d.ts +2 -2
  62. package/dist/types/client/base/runtime-services.types.d.ts +50 -0
  63. package/dist/types/client/data/role-gate.d.ts +2 -8
  64. package/dist/types/client/engines/chart/index.d.ts +1 -1
  65. package/dist/types/client/engines/chart/port.d.ts +15 -0
  66. package/dist/types/client/engines/diff/index.d.ts +1 -1
  67. package/dist/types/client/engines/diff/items.d.ts +24 -0
  68. package/dist/types/client/engines/diff/port.d.ts +124 -2
  69. package/dist/types/client/engines/diff/prose.d.ts +80 -0
  70. package/dist/types/client/engines/engine-adapters.d.ts +6 -0
  71. package/dist/types/client/engines/highlight/adapter-lezer.d.ts +6 -0
  72. package/dist/types/client/engines/highlight/index.d.ts +15 -0
  73. package/dist/types/client/engines/highlight/port.d.ts +64 -0
  74. package/dist/types/client/engines/markdown/adapter-markdown-it.d.ts +6 -0
  75. package/dist/types/client/engines/markdown/blocks.d.ts +29 -0
  76. package/dist/types/client/engines/markdown/index.d.ts +9 -0
  77. package/dist/types/client/engines/markdown/port.d.ts +166 -0
  78. package/dist/types/client/engines/structured/adapter-js-yaml.d.ts +6 -0
  79. package/dist/types/client/engines/structured/index.d.ts +29 -0
  80. package/dist/types/client/engines/structured/port.d.ts +45 -0
  81. package/dist/types/client/infra/http/SomaHttpService.d.ts +1 -1
  82. package/dist/types/client/infra/notify/DefaultNotifyService.d.ts +2 -3
  83. package/dist/types/client/infra/permission/SomaPermission.d.ts +1 -1
  84. package/dist/types/client/render-ports/notify-renderer.d.ts +1 -56
  85. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +9 -44
  86. package/dist/types/server/host/app-config-composer.d.ts +2 -3
  87. package/dist/types/server/host/host-config-paths.d.cts +2 -7
  88. package/dist/types/server/host/precompiled-manifest.d.ts +5 -0
  89. package/dist/types/server/infra/host-config-paths.d.cts +7 -0
  90. package/dist/types/server/page-assets.d.ts +2 -5
  91. package/dist/types/server/runtime-space/bindings.d.ts +9 -0
  92. package/dist/types/server/runtime-space/digest.d.ts +5 -0
  93. package/dist/types/server/runtime-space/index.d.ts +1 -1
  94. package/dist/types/server/runtime-space/prewarm.d.ts +2 -2
  95. package/dist/types/server/runtime-space/store.d.ts +4 -0
  96. package/dist/types/server/runtime-space/types.d.ts +3 -2
  97. package/dist/types/shared/app-config-merge.d.ts +3 -0
  98. package/dist/types/shared/registry-generated/limits.d.ts +78 -4
  99. package/dist/types/shared/types/announcer.types.d.ts +14 -0
  100. package/dist/types/shared/types/notify.types.d.ts +36 -0
  101. package/dist/types/shared/types/role-gate.types.d.ts +8 -0
  102. package/host-native/src/aot-builder.ts +12 -5
  103. package/host-native/src/dev-chunk-gc.ts +104 -0
  104. package/host-native/src/host-prepare.ts +19 -2
  105. package/host-native/src/manifest-http.ts +1 -1
  106. package/host-native/src/native-server.ts +16 -0
  107. package/host-native/src/page-http.ts +2 -67
  108. package/host-native/src/page-payload-cache.ts +68 -0
  109. package/package.json +16 -2
@@ -1,64 +1,18 @@
1
1
  import fs from 'node:fs';
2
2
  import yaml from 'js-yaml';
3
+ import {
4
+ mergeSourcePackageAppConfig,
5
+ parseAppConfigYaml,
6
+ } from '../../shared/app-config-merge';
3
7
  import { resolveHostAppConfigPath } from './host-config-paths';
4
8
  import { currentHostDir } from './host-dir';
5
9
 
6
- type AppConfigRecord = Record<string, unknown>;
10
+ export { mergeSourcePackageAppConfig, parseAppConfigYaml };
7
11
 
8
- const UNSAFE_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
9
-
10
- function isRecord(value: unknown): value is AppConfigRecord {
12
+ function isRecord(value: unknown): value is Record<string, unknown> {
11
13
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
12
14
  }
13
15
 
14
- function cloneValue(value: unknown): unknown {
15
- if (Array.isArray(value)) {
16
- return value.map((item) => cloneValue(item));
17
- }
18
- if (!isRecord(value)) {
19
- return value;
20
- }
21
- const result: AppConfigRecord = {};
22
- for (const [key, child] of Object.entries(value)) {
23
- if (!UNSAFE_KEYS.has(key)) {
24
- result[key] = cloneValue(child);
25
- }
26
- }
27
- return result;
28
- }
29
-
30
- function mergeRecords(defaults: AppConfigRecord, host: AppConfigRecord): AppConfigRecord {
31
- const result = cloneValue(defaults) as AppConfigRecord;
32
- for (const [key, hostValue] of Object.entries(host)) {
33
- if (UNSAFE_KEYS.has(key)) {
34
- continue;
35
- }
36
- const defaultValue = result[key];
37
- result[key] = isRecord(defaultValue) && isRecord(hostValue)
38
- ? mergeRecords(defaultValue, hostValue)
39
- : cloneValue(hostValue);
40
- }
41
- return result;
42
- }
43
-
44
- export function parseAppConfigYaml(source: string): unknown {
45
- return source.trim() ? yaml.load(source) ?? {} : {};
46
- }
47
-
48
- /** Source packages provide defaults; the Host remains the final App-config owner. */
49
- export function mergeSourcePackageAppConfig(
50
- sourcePackageConfig: unknown,
51
- hostConfig: unknown,
52
- ): unknown {
53
- if (isRecord(sourcePackageConfig) && isRecord(hostConfig)) {
54
- return mergeRecords(sourcePackageConfig, hostConfig);
55
- }
56
- if (hostConfig !== undefined && hostConfig !== null) {
57
- return cloneValue(hostConfig);
58
- }
59
- return cloneValue(sourcePackageConfig ?? {});
60
- }
61
-
62
16
  export function composeAppConfigYaml(
63
17
  sourcePackageConfigYaml: string,
64
18
  hostConfigYaml: string,
@@ -1,100 +1,2 @@
1
- /** CJS mirror of host-config-paths.ts for next.config.js / webpack plugin. */
2
- const fs = require('node:fs');
3
- const path = require('node:path');
4
-
5
- function readJson(filePath) {
6
- try {
7
- if (!fs.existsSync(filePath)) return null;
8
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
9
- } catch {
10
- return null;
11
- }
12
- }
13
-
14
- function resolveSafeChildRoot(parent, relativePath, options = {}) {
15
- const trimmed = typeof relativePath === 'string' ? relativePath.trim() : '';
16
- if (!trimmed) return parent;
17
-
18
- const resolved = path.resolve(parent, trimmed);
19
- const normalizedParent = path.resolve(parent);
20
- if (resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)) {
21
- if (options.requireExists && !fs.existsSync(resolved)) {
22
- return normalizedParent;
23
- }
24
- return resolved;
25
- }
26
- return options.fallback ?? normalizedParent;
27
- }
28
-
29
- function normalizeSomaEnv(raw) {
30
- const value = String(raw ?? '').trim().toLowerCase();
31
- if (!value) return 'test';
32
- if (
33
- ['test', 'testing', 'dev', 'development', 'local', 'qa', 'staging', 'pre', 'prepub', 'uat']
34
- .includes(value)
35
- ) {
36
- return 'test';
37
- }
38
- return 'prod';
39
- }
40
-
41
- /** Priority: SOMA_ENV → APP_ENV → NODE_ENV (framework-neutral only). */
42
- function readSomaEnv(env = process.env) {
43
- return normalizeSomaEnv(env.SOMA_ENV ?? env.APP_ENV ?? env.NODE_ENV);
44
- }
45
-
46
- function resolveHostConfigRoot(hostDir) {
47
- const normalizedHostDir = path.resolve(hostDir);
48
- const packageJson = readJson(path.join(normalizedHostDir, 'package.json'));
49
- const configured = packageJson?.soma?.configRoot?.trim();
50
- if (configured) {
51
- return resolveSafeChildRoot(normalizedHostDir, configured, {
52
- fallback: path.join(normalizedHostDir, 'config'),
53
- });
54
- }
55
-
56
- const hostSourceRoot = resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot, {
57
- requireExists: true,
58
- });
59
- const candidates = [
60
- path.join(normalizedHostDir, 'config'),
61
- path.join(hostSourceRoot, 'config'),
62
- ];
63
- for (const candidate of candidates) {
64
- if (fs.existsSync(candidate)) {
65
- return candidate;
66
- }
67
- }
68
- return path.join(hostSourceRoot, 'config');
69
- }
70
-
71
- function getSomaHostConfigRoot(hostDir) {
72
- return resolveHostConfigRoot(hostDir);
73
- }
74
-
75
- function resolveAppConfigPath(configRoot, envName) {
76
- const env = envName ?? readSomaEnv();
77
- const candidates = [
78
- path.join(configRoot, `app.config.${env}.yaml`),
79
- path.join(configRoot, 'app.config.yaml'),
80
- ];
81
- for (const candidate of candidates) {
82
- if (fs.existsSync(candidate)) {
83
- return candidate;
84
- }
85
- }
86
- return null;
87
- }
88
-
89
- function resolveHostAppConfigPath(hostDir, envName) {
90
- return resolveAppConfigPath(resolveHostConfigRoot(hostDir), envName);
91
- }
92
-
93
- module.exports = {
94
- normalizeSomaEnv,
95
- readSomaEnv,
96
- resolveHostConfigRoot,
97
- getSomaHostConfigRoot,
98
- resolveAppConfigPath,
99
- resolveHostAppConfigPath,
100
- };
1
+ /** Backward-compatible re-export of core/server/infra/host-config-paths.cjs (CORE-L02). */
2
+ module.exports = require('../infra/host-config-paths.cjs');
@@ -0,0 +1,69 @@
1
+ // 预编译产物载入(CORE-L04:由 server/page-assets.ts 迁入 server/host 应用层;page-assets.ts 仅作薄契约重导出)。
2
+ import type { SomaPrecompiledManifest, SomaPrecompiledPage } from '../../build/compiler/full-manifest-builder';
3
+ import { readPrewarmCompiled } from '../runtime-space/prewarm';
4
+ import { resolveSomaRuntimeLayout } from '../runtime-space/root';
5
+ import { urlPathToCandidates } from '../../build/compiler/page-base-resolver';
6
+ import { assertRuntimeArtifact } from '../../shared/component-tree-artifact';
7
+ import { verifyTreeRuntimeAssets } from '../../build/component-tree/artifact-codec';
8
+
9
+ function validatePages(raw: SomaPrecompiledManifest): SomaPrecompiledManifest | null {
10
+ if (!raw?.pages || !Array.isArray(raw.pages)) return null;
11
+ for (const page of raw.pages) {
12
+ assertRuntimeArtifact(page);
13
+ if (page.sourceMarkup === 'component-tree' && (!page.uiConfig || !Array.isArray(page.eventConfig))) return null;
14
+ if (page.sourceMarkup === 'component-tree' && !verifyTreeRuntimeAssets(page)) return null;
15
+ }
16
+ return raw;
17
+ }
18
+
19
+ interface PrewarmMeta {
20
+ readonly routes?: SomaPrecompiledManifest['routes'];
21
+ readonly locale?: SomaPrecompiledManifest['locale'];
22
+ readonly appConfig?: unknown;
23
+ }
24
+
25
+ /** 新来源:runtime 空间的预热(`<root>/prewarm/`,RT3)。没有预热、预热里没有静态页编译结果、或旁档与索引摘要对不上 → undefined(让位给旧文件);对得上但页面校验不过 → null */
26
+ function loadFromPrewarm(hostDir: string, env: Readonly<Record<string, string | undefined>>): SomaPrecompiledManifest | null | undefined {
27
+ let layout;
28
+ try {
29
+ layout = resolveSomaRuntimeLayout(hostDir, env);
30
+ } catch {
31
+ return undefined; // 根越界由启动期诊断负责;这里不拖垮预编译清单的读取
32
+ }
33
+ const read = readPrewarmCompiled<SomaPrecompiledPage, PrewarmMeta>(layout);
34
+ if (read === null) return undefined;
35
+ try {
36
+ return validatePages({
37
+ routes: read.meta?.routes ?? [],
38
+ locale: read.meta?.locale ?? {},
39
+ appConfig: read.meta?.appConfig ?? null,
40
+ pages: [...read.pages],
41
+ });
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ /** 读构建期预编译清单:只读 runtime 空间的预热;没有预热或页面校验不过都返回 null。 */
48
+ export function loadPrecompiledManifest(
49
+ hostDir: string,
50
+ env: Readonly<Record<string, string | undefined>> = process.env,
51
+ ): SomaPrecompiledManifest | null {
52
+ return loadFromPrewarm(hostDir, env) ?? null;
53
+ }
54
+
55
+ /** Find precompiled page by route (supports /items → items/index short path) */
56
+ export function findPrecompiledPage(
57
+ manifest: SomaPrecompiledManifest,
58
+ urlPath: string,
59
+ ): SomaPrecompiledPage | null {
60
+ for (const base of urlPathToCandidates(urlPath)) {
61
+ const route = base === 'index' ? '/' : `/${base}`;
62
+ const page = manifest.pages.find((p) => {
63
+ const pageBase = p.path.replace(/^\//, '').replace(/\.html$/i, '');
64
+ return p.path === route || pageBase === base;
65
+ });
66
+ if (page) return page;
67
+ }
68
+ return null;
69
+ }
@@ -0,0 +1,100 @@
1
+ /** CJS host config path resolution (CORE-L02: sunk to server/infra foundation layer). */
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+
5
+ function readJson(filePath) {
6
+ try {
7
+ if (!fs.existsSync(filePath)) return null;
8
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ function resolveSafeChildRoot(parent, relativePath, options = {}) {
15
+ const trimmed = typeof relativePath === 'string' ? relativePath.trim() : '';
16
+ if (!trimmed) return parent;
17
+
18
+ const resolved = path.resolve(parent, trimmed);
19
+ const normalizedParent = path.resolve(parent);
20
+ if (resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)) {
21
+ if (options.requireExists && !fs.existsSync(resolved)) {
22
+ return normalizedParent;
23
+ }
24
+ return resolved;
25
+ }
26
+ return options.fallback ?? normalizedParent;
27
+ }
28
+
29
+ function normalizeSomaEnv(raw) {
30
+ const value = String(raw ?? '').trim().toLowerCase();
31
+ if (!value) return 'test';
32
+ if (
33
+ ['test', 'testing', 'dev', 'development', 'local', 'qa', 'staging', 'pre', 'prepub', 'uat']
34
+ .includes(value)
35
+ ) {
36
+ return 'test';
37
+ }
38
+ return 'prod';
39
+ }
40
+
41
+ /** Priority: SOMA_ENV → APP_ENV → NODE_ENV (framework-neutral only). */
42
+ function readSomaEnv(env = process.env) {
43
+ return normalizeSomaEnv(env.SOMA_ENV ?? env.APP_ENV ?? env.NODE_ENV);
44
+ }
45
+
46
+ function resolveHostConfigRoot(hostDir) {
47
+ const normalizedHostDir = path.resolve(hostDir);
48
+ const packageJson = readJson(path.join(normalizedHostDir, 'package.json'));
49
+ const configured = packageJson?.soma?.configRoot?.trim();
50
+ if (configured) {
51
+ return resolveSafeChildRoot(normalizedHostDir, configured, {
52
+ fallback: path.join(normalizedHostDir, 'config'),
53
+ });
54
+ }
55
+
56
+ const hostSourceRoot = resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot, {
57
+ requireExists: true,
58
+ });
59
+ const candidates = [
60
+ path.join(normalizedHostDir, 'config'),
61
+ path.join(hostSourceRoot, 'config'),
62
+ ];
63
+ for (const candidate of candidates) {
64
+ if (fs.existsSync(candidate)) {
65
+ return candidate;
66
+ }
67
+ }
68
+ return path.join(hostSourceRoot, 'config');
69
+ }
70
+
71
+ function getSomaHostConfigRoot(hostDir) {
72
+ return resolveHostConfigRoot(hostDir);
73
+ }
74
+
75
+ function resolveAppConfigPath(configRoot, envName) {
76
+ const env = envName ?? readSomaEnv();
77
+ const candidates = [
78
+ path.join(configRoot, `app.config.${env}.yaml`),
79
+ path.join(configRoot, 'app.config.yaml'),
80
+ ];
81
+ for (const candidate of candidates) {
82
+ if (fs.existsSync(candidate)) {
83
+ return candidate;
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function resolveHostAppConfigPath(hostDir, envName) {
90
+ return resolveAppConfigPath(resolveHostConfigRoot(hostDir), envName);
91
+ }
92
+
93
+ module.exports = {
94
+ normalizeSomaEnv,
95
+ readSomaEnv,
96
+ resolveHostConfigRoot,
97
+ getSomaHostConfigRoot,
98
+ resolveAppConfigPath,
99
+ resolveHostAppConfigPath,
100
+ };
@@ -3,79 +3,11 @@
3
3
  *
4
4
  * 刻意不 `import 'server-only'`:soma-ai 的冒烟探测器在经 jiti 加载的宿主服务里
5
5
  * 动态 import 本入口,server-only 在纯 Node 语境下会抛错(理由同 `server/page-declaration.ts`)。
6
+ * CORE-L04:本文件为纯薄契约重导出。
6
7
  */
7
8
 
8
9
  export { compilePageAssets } from '../build/compiler/page-assets';
9
10
  // 入口对拍(D7)取 core 的编译入口:宿主文件页访问期编译、已发布页重编
10
11
  export { compileSomaPageAssets } from './host/soma-page-compile';
11
12
  export { compilePublishedPageArtifact } from './host/published-page-artifact-cache';
12
-
13
- // 预编译产物载入依赖服务端runtime空间,归本入口,不由构建层反向依赖server。
14
- import type { SomaPrecompiledManifest, SomaPrecompiledPage } from '../build/compiler/full-manifest-builder';
15
- import { readPrewarmCompiled } from './runtime-space/prewarm';
16
- import { resolveSomaRuntimeLayout } from './runtime-space/root';
17
- import { urlPathToCandidates } from '../build/compiler/page-base-resolver';
18
- import { assertRuntimeArtifact } from '../shared/component-tree-artifact';
19
- import { verifyTreeRuntimeAssets } from '../build/component-tree/artifact-codec';
20
-
21
- function validatePages(raw: SomaPrecompiledManifest): SomaPrecompiledManifest | null {
22
- if (!raw?.pages || !Array.isArray(raw.pages)) return null;
23
- for (const page of raw.pages) {
24
- assertRuntimeArtifact(page);
25
- if (page.sourceMarkup === 'component-tree' && (!page.uiConfig || !Array.isArray(page.eventConfig))) return null;
26
- if (page.sourceMarkup === 'component-tree' && !verifyTreeRuntimeAssets(page)) return null;
27
- }
28
- return raw;
29
- }
30
-
31
- interface PrewarmMeta {
32
- readonly routes?: SomaPrecompiledManifest['routes'];
33
- readonly locale?: SomaPrecompiledManifest['locale'];
34
- readonly appConfig?: unknown;
35
- }
36
-
37
- /** 新来源:runtime 空间的预热(`<root>/prewarm/`,RT3)。没有预热、预热里没有静态页编译结果、或旁档与索引摘要对不上 → undefined(让位给旧文件);对得上但页面校验不过 → null */
38
- function loadFromPrewarm(hostDir: string, env: Readonly<Record<string, string | undefined>>): SomaPrecompiledManifest | null | undefined {
39
- let layout;
40
- try {
41
- layout = resolveSomaRuntimeLayout(hostDir, env);
42
- } catch {
43
- return undefined; // 根越界由启动期诊断负责;这里不拖垮预编译清单的读取
44
- }
45
- const read = readPrewarmCompiled<SomaPrecompiledPage, PrewarmMeta>(layout);
46
- if (read === null) return undefined;
47
- try {
48
- return validatePages({
49
- routes: read.meta?.routes ?? [],
50
- locale: read.meta?.locale ?? {},
51
- appConfig: read.meta?.appConfig ?? null,
52
- pages: [...read.pages],
53
- });
54
- } catch {
55
- return null;
56
- }
57
- }
58
-
59
- /** 读构建期预编译清单:只读 runtime 空间的预热;没有预热或页面校验不过都返回 null。 */
60
- export function loadPrecompiledManifest(
61
- hostDir: string,
62
- env: Readonly<Record<string, string | undefined>> = process.env,
63
- ): SomaPrecompiledManifest | null {
64
- return loadFromPrewarm(hostDir, env) ?? null;
65
- }
66
-
67
- /** Find precompiled page by route (supports /items → items/index short path) */
68
- export function findPrecompiledPage(
69
- manifest: SomaPrecompiledManifest,
70
- urlPath: string,
71
- ): SomaPrecompiledPage | null {
72
- for (const base of urlPathToCandidates(urlPath)) {
73
- const route = base === 'index' ? '/' : `/${base}`;
74
- const page = manifest.pages.find((p) => {
75
- const pageBase = p.path.replace(/^\//, '').replace(/\.html$/i, '');
76
- return p.path === route || pageBase === base;
77
- });
78
- if (page) return page;
79
- }
80
- return null;
81
- }
13
+ export { loadPrecompiledManifest, findPrecompiledPage } from './host/precompiled-manifest';
@@ -8,6 +8,8 @@
8
8
  // 不管:载荷校验与摘要(inject.ts)、取页与编译(resolve.ts)。
9
9
 
10
10
  import { currentHostDir } from '../host/host-dir';
11
+ import { readFlatEnvelope } from '../../build/compiler/flat-page';
12
+ import { SOMA_PAGE_FORMAT_VERSION } from '../../shared/page-envelope';
11
13
  import {
12
14
  addressKindOf,
13
15
  addressShapeKey,
@@ -31,6 +33,9 @@ import type {
31
33
  SomaStandardPageEnvelope,
32
34
  } from './types';
33
35
 
36
+ /** 方言所有者给的版本守卫:`version` 是它随产物给出的不透明版本号;返回 false = 该产物不是本版产出方编的,不得恢复 */
37
+ export type OwnerVersionGuard = (version: string | undefined) => boolean;
38
+
34
39
  /** 前缀解析器交回的东西:标准格式载荷,或兼容旧入口已经拼好的运行时资产(虚拟页的 `artifact` / 声明分支) */
35
40
  export type PrefixPageResult =
36
41
  | { readonly kind: 'page'; readonly page: SomaStandardPage; readonly title?: string }
@@ -74,6 +79,8 @@ interface SpaceState {
74
79
  readonly stores: Map<string, SomaRuntimeStore>;
75
80
  layoutMemo: { readonly signature: string; readonly layout: SomaRuntimeLayout } | null;
76
81
  rootErrorReported: boolean;
82
+ /** owner → 版本守卫(方言所有者登记;core 不解释 version) */
83
+ readonly ownerGuards: Map<string, OwnerVersionGuard>;
77
84
  }
78
85
 
79
86
  const SLOT = Symbol.for('soma-core.runtime-space');
@@ -91,6 +98,7 @@ export function space(): SpaceState {
91
98
  stores: new Map(),
92
99
  layoutMemo: null,
93
100
  rootErrorReported: false,
101
+ ownerGuards: new Map(),
94
102
  });
95
103
  }
96
104
 
@@ -106,6 +114,43 @@ export function resetRuntimeSpace(): void {
106
114
  state.stores.clear();
107
115
  state.layoutMemo = null;
108
116
  state.rootErrorReported = false;
117
+ state.ownerGuards.clear();
118
+ }
119
+
120
+ /**
121
+ * 方言所有者登记版本守卫(升级隐患闸):持久绑定恢复时,owner 相同的条目其 `version` 须被守卫接受,否则丢弃(连绑定文件),
122
+ * 页面由所有者按本版编译器重新注入。登记时已装入的同 owner 持久条目立刻对一遍。core 只存守卫、不解释 version(缓存键 = URL + version)。
123
+ */
124
+ export function registerOwnerVersionGuard(owner: string, guard: OwnerVersionGuard): void {
125
+ const state = space();
126
+ state.ownerGuards.set(owner, guard);
127
+ let dropped = 0;
128
+ const digests = new Set<string>();
129
+ for (const [key, entry] of state.entries) {
130
+ const binding = entry.binding;
131
+ if (binding.owner !== owner || !binding.persisted || binding.origin !== 'inject' || guard(binding.version)) continue;
132
+ state.entries.delete(key);
133
+ try {
134
+ runtimeStore().removeBinding(binding.address);
135
+ } catch {
136
+ /* 根不可用:没有落盘可清 */
137
+ }
138
+ if (binding.digest !== null) digests.add(binding.digest);
139
+ dropped += 1;
140
+ }
141
+ if (dropped > 0) {
142
+ bumpNavGeneration();
143
+ // 升级丢弃旧产物:汇总一行日志 + 清掉不再被引用的产物文件
144
+ const live = new Set([...state.entries.values()].flatMap((e) => (e.binding.digest !== null ? [e.binding.digest] : [])));
145
+ let cleaned = 0;
146
+ try {
147
+ const store = runtimeStore();
148
+ for (const digest of digests) if (!live.has(digest) && store.removeArtifact(digest)) cleaned += 1;
149
+ } catch {
150
+ /* 根不可用:没有落盘可清 */
151
+ }
152
+ console.warn(`[soma-core][引擎] 升级后丢弃旧页面产物 ${dropped} 个(产出方 ${owner} 的版本不符),已清理产物文件 ${cleaned} 个;由产出方重新编译注入。`);
153
+ }
109
154
  }
110
155
 
111
156
  // ── 布局与存储 ────────────────────────────────────────────────────────────────
@@ -172,6 +217,10 @@ export function ensureLoaded(): void {
172
217
  state.loadedRoots.add(layout.root);
173
218
  const store = runtimeStore(layout);
174
219
  const now = Date.now();
220
+ // 升级丢弃的旧产物:按原因计数(落盘格式版本 / 标准格式版本 = 格式;产出方版本守卫 = 所有者),其产物文件在装入结束后清掉(没有别的绑定引用时)
221
+ const dropped = { format: 0, owner: 0 };
222
+ const droppedDigests = new Set<string>();
223
+ const legacyBefore = store.legacyDiscarded;
175
224
  for (const read of store.listBindings()) {
176
225
  const binding = read.binding;
177
226
  if (binding.origin !== 'inject' || binding.digest === null || binding.kind === 'prefix') continue;
@@ -186,16 +235,42 @@ export function ensureLoaded(): void {
186
235
  console.warn(`[soma-core][引擎] 持久绑定 ${binding.address} 的产物缺失或损坏(${binding.digest.slice(0, 12)}…),已跳过;重新 inject 即可恢复。`);
187
236
  continue;
188
237
  }
238
+ // 恢复的信封与注入口同一读法:载荷 `envelope` 优先,其次 `_ui.yaml` 顶层 `envelope:`
239
+ const envelope = page.envelope ?? (readFlatEnvelope(page.uiYaml) as SomaStandardPageEnvelope | null);
240
+ // 标准格式版本不符的旧产物不恢复:丢弃并清掉绑定文件,由方言所有者重新编译注入(信封可缺:原生页信封是可选的,
241
+ // 缺信封的方言旧产物由落盘格式版本与产出方版本守卫拦下)
242
+ if (page.format !== SOMA_PAGE_FORMAT_VERSION) {
243
+ store.removeBinding(binding.address);
244
+ dropped.format += 1;
245
+ droppedDigests.add(binding.digest);
246
+ continue;
247
+ }
248
+ // 产出方版本指纹闸(见 registerOwnerVersionGuard):已登记守卫且不认这个 version → 丢弃
249
+ const guard = binding.owner === undefined ? undefined : state.ownerGuards.get(binding.owner);
250
+ if (guard !== undefined && !guard(binding.version)) {
251
+ store.removeBinding(binding.address);
252
+ dropped.owner += 1;
253
+ droppedDigests.add(binding.digest);
254
+ continue;
255
+ }
189
256
  state.generations.set(key, Math.max(state.generations.get(key) ?? 0, binding.generation));
190
257
  state.entries.set(key, {
191
258
  binding: { ...binding, persisted: true },
192
259
  page,
193
- envelope: page.envelope ?? null,
260
+ envelope,
194
261
  prefix: null,
195
262
  registryName: null,
196
263
  mtimeMs: read.mtimeMs,
197
264
  });
198
265
  }
266
+ const legacy = store.legacyDiscarded - legacyBefore;
267
+ dropped.format += legacy;
268
+ if (dropped.format + dropped.owner > 0) {
269
+ const live = new Set([...state.entries.values()].flatMap((entry) => (entry.binding.digest !== null ? [entry.binding.digest] : [])));
270
+ let cleaned = 0;
271
+ for (const digest of droppedDigests) if (!live.has(digest) && store.removeArtifact(digest)) cleaned += 1;
272
+ console.warn(`[soma-core][引擎] 升级后丢弃旧页面产物 ${dropped.format + dropped.owner} 个(格式版本不符 ${dropped.format},产出方版本不符 ${dropped.owner}),已清理产物文件 ${cleaned} 个;由产出方重新编译注入。`);
273
+ }
199
274
  if (process.env.SOMA_RUNTIME_GC !== 'off') {
200
275
  try {
201
276
  const referenced = [...state.entries.values()].flatMap((entry) => (entry.binding.digest !== null ? [entry.binding.digest] : []));
@@ -4,6 +4,12 @@ import { createHash } from 'node:crypto';
4
4
  import { addressShapeKey } from '../../shared/runtime-address';
5
5
  import type { SomaStandardPage } from './types';
6
6
 
7
+ /**
8
+ * core 落盘产物的格式版本(绑定记录、预热索引与旁档、预热元数据共用)。落盘结构(信封、闸门等)有不兼容变化时递增;
9
+ * 读回时版本不符一律视为无效并丢弃,由方言所有者重新编译注入,不做迁移也不手工清目录。
10
+ */
11
+ export const SOMA_RUNTIME_STORE_FORMAT = 2;
12
+
7
13
  /** 摘要形状:64 位小写十六进制 */
8
14
  export const SOMA_RUNTIME_DIGEST_PATTERN = /^[0-9a-f]{64}$/;
9
15
 
@@ -31,7 +31,7 @@ export {
31
31
  } from './dynamic-pages';
32
32
  export { resolveAddress, loadPageByAddress, listBindings, runtimeSpaceStats, type SomaLoadedPage, type SomaLoadPageOptions } from './resolve';
33
33
  export { SomaRuntimeError, type SomaRuntimeBatchFailure, type SomaRuntimeErrorCode } from './errors';
34
- export { setNavProvider, type NavProvider } from './bindings';
34
+ export { setNavProvider, registerOwnerVersionGuard, type NavProvider, type OwnerVersionGuard } from './bindings';
35
35
  export {
36
36
  registerPage,
37
37
  registerPages,
@@ -15,7 +15,7 @@ import { createHash } from 'node:crypto';
15
15
  import fs from 'node:fs';
16
16
  import path from 'node:path';
17
17
  import { writeFileAtomic } from '../registry/registry-file-lock';
18
- import { bindingFileName, canonicalJson } from './digest';
18
+ import { bindingFileName, canonicalJson, SOMA_RUNTIME_STORE_FORMAT } from './digest';
19
19
  import { resolveSomaRuntimeLayout } from './root';
20
20
  import { SomaRuntimeStore } from './store';
21
21
  import type { SomaRuntimeLayout, SomaStandardPage } from './types';
@@ -25,7 +25,7 @@ export const SOMA_PREWARM_META_FILE = 'meta.json';
25
25
 
26
26
  /** 旁档:一个静态页的构建期编译结果 */
27
27
  export interface SomaPrewarmCompiledRecord<T = unknown> {
28
- readonly schemaVersion: 1;
28
+ readonly schemaVersion: number;
29
29
  readonly address: string;
30
30
  /** 对应标准格式产物的摘要;与索引不一致即视为失效 */
31
31
  readonly digest: string;
@@ -36,7 +36,7 @@ export interface SomaPrewarmCompiledRecord<T = unknown> {
36
36
 
37
37
  /** 全局元数据(路由表、词表、应用配置):不属于某一页 */
38
38
  export interface SomaPrewarmMeta<M = unknown> {
39
- readonly schemaVersion: 1;
39
+ readonly schemaVersion: number;
40
40
  readonly meta: M;
41
41
  }
42
42
 
@@ -105,7 +105,7 @@ function writeIfChanged(file: string, content: string): void {
105
105
  function readCompiledRecord<T>(file: string): SomaPrewarmCompiledRecord<T> | null {
106
106
  try {
107
107
  const record = JSON.parse(fs.readFileSync(file, 'utf8')) as SomaPrewarmCompiledRecord<T>;
108
- return record.schemaVersion === 1 && typeof record.digest === 'string' ? record : null;
108
+ return record.schemaVersion === SOMA_RUNTIME_STORE_FORMAT && typeof record.digest === 'string' ? record : null;
109
109
  } catch {
110
110
  return null;
111
111
  }
@@ -150,7 +150,7 @@ export async function runPrewarm<T = unknown, M = unknown>(options: SomaPrewarmO
150
150
  continue;
151
151
  }
152
152
  const record: SomaPrewarmCompiledRecord<T> = {
153
- schemaVersion: 1,
153
+ schemaVersion: SOMA_RUNTIME_STORE_FORMAT,
154
154
  address: item.address,
155
155
  digest,
156
156
  inputsDigest: item.inputsDigest,
@@ -174,7 +174,7 @@ export async function runPrewarm<T = unknown, M = unknown>(options: SomaPrewarmO
174
174
  }
175
175
 
176
176
  if (options.meta !== undefined) {
177
- const record: SomaPrewarmMeta<M> = { schemaVersion: 1, meta: options.meta };
177
+ const record: SomaPrewarmMeta<M> = { schemaVersion: SOMA_RUNTIME_STORE_FORMAT, meta: options.meta };
178
178
  writeIfChanged(path.join(layout.dirs.prewarm, SOMA_PREWARM_META_FILE), `${JSON.stringify(record)}\n`);
179
179
  }
180
180
 
@@ -194,7 +194,7 @@ export async function runPrewarm<T = unknown, M = unknown>(options: SomaPrewarmO
194
194
  }
195
195
 
196
196
  const sorted = Object.fromEntries(Object.entries(entries).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
197
- const indexText = `${JSON.stringify({ schemaVersion: 1, entries: sorted }, null, 2)}\n`;
197
+ const indexText = `${JSON.stringify({ schemaVersion: SOMA_RUNTIME_STORE_FORMAT, entries: sorted }, null, 2)}\n`;
198
198
  writeIfChanged(path.join(layout.dirs.prewarm, 'index.json'), indexText);
199
199
 
200
200
  return {
@@ -226,7 +226,7 @@ export function readPrewarmCompiled<T = unknown, M = unknown>(
226
226
  let meta: M | null = null;
227
227
  try {
228
228
  const parsed = JSON.parse(fs.readFileSync(path.join(layout.dirs.prewarm, SOMA_PREWARM_META_FILE), 'utf8')) as SomaPrewarmMeta<M>;
229
- if (parsed.schemaVersion === 1) meta = parsed.meta;
229
+ if (parsed.schemaVersion === SOMA_RUNTIME_STORE_FORMAT) meta = parsed.meta;
230
230
  } catch {
231
231
  /* 缺失:meta 为空 */
232
232
  }