soma-core 2.1.5 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +2 -2
  2. package/bin/soma.cjs +1 -1
  3. package/bin/soma.ts +64 -15
  4. package/core/build/compiler/soma-precompile.js +11 -1
  5. package/core/client/base/SomaHttpClient.ts +85 -12
  6. package/core/client/data/data-object-resolver.ts +12 -1
  7. package/core/client/engine/event-engine.ts +3 -3
  8. package/core/client/engine/soma-bootstrap.ts +30 -30
  9. package/core/client/host-bridge/load-host-domain-class.ts +74 -20
  10. package/core/client/host-bridge/resolve-host-bootstrap.ts +125 -23
  11. package/core/client/infra/http/IHttpClient.ts +3 -1
  12. package/core/client/infra/http/SomaHttpService.ts +15 -6
  13. package/core/client/parser/data-config-parser.ts +6 -1
  14. package/core/server/api/dispatch-service-api.ts +212 -0
  15. package/core/server/api/load-host-service.ts +230 -56
  16. package/core/server/api/service-path.ts +78 -14
  17. package/core/server/engines/style/candidate-guard.ts +57 -0
  18. package/core/server/engines/style/index.ts +1 -1
  19. package/core/server/engines/style/tailwind-adapter.ts +83 -16
  20. package/core/server/host/source-packages.cjs +96 -30
  21. package/core/server/host/source-packages.ts +12 -5
  22. package/core/server/index.ts +39 -17
  23. package/core/server/infra/cache/ServerFileCache.ts +138 -25
  24. package/core/server/node.ts +32 -8
  25. package/core/shared/registry-generated/error-codes.ts +5 -0
  26. package/core/shared/registry-generated/limits.ts +5 -0
  27. package/core/shared/types/data-config.types.ts +2 -0
  28. package/dist/browser/soma-runtime.js +197 -49
  29. package/dist/cli/soma.js +68 -14
  30. package/dist/core/index.cjs +284 -64
  31. package/dist/host-native/aot-builder.cjs +850 -0
  32. package/dist/host-native/native-server.cjs +15338 -0
  33. package/dist/lsp/component-tree.cjs +11 -1
  34. package/dist/types/client/base/SomaHttpClient.d.ts +1 -8
  35. package/dist/types/client/data/data-object-resolver.d.ts +1 -0
  36. package/dist/types/client/engine/event-engine.d.ts +2 -2
  37. package/dist/types/client/engine/soma-bootstrap.d.ts +3 -2
  38. package/dist/types/client/host-bridge/load-host-domain-class.d.ts +1 -0
  39. package/dist/types/client/host-bridge/resolve-host-bootstrap.d.ts +20 -0
  40. package/dist/types/client/infra/http/IHttpClient.d.ts +2 -0
  41. package/dist/types/server/api/dispatch-service-api.d.ts +18 -0
  42. package/dist/types/server/api/load-host-service.d.ts +7 -2
  43. package/dist/types/server/api/service-path.d.ts +21 -1
  44. package/dist/types/server/engines/style/candidate-guard.d.ts +10 -0
  45. package/dist/types/server/engines/style/index.d.ts +1 -1
  46. package/dist/types/server/engines/style/tailwind-adapter.d.ts +12 -0
  47. package/dist/types/server/host/source-packages.d.cts +13 -1
  48. package/dist/types/server/host/source-packages.d.ts +7 -4
  49. package/dist/types/server/index.d.ts +18 -17
  50. package/dist/types/server/infra/cache/ServerFileCache.d.ts +28 -5
  51. package/dist/types/server/node.d.ts +10 -7
  52. package/dist/types/shared/registry-generated/error-codes.d.ts +4 -0
  53. package/dist/types/shared/registry-generated/limits.d.ts +4 -0
  54. package/dist/types/shared/types/data-config.types.d.ts +2 -0
  55. package/host-native/bin/host-native.cjs +204 -0
  56. package/host-native/client/browser-entry.ts +499 -0
  57. package/{host-next/app → host-native/client}/page-access.ts +12 -0
  58. package/host-native/client/router-bridge.ts +120 -0
  59. package/host-native/src/aot-builder.ts +486 -0
  60. package/host-native/src/csp-headers.ts +75 -0
  61. package/host-native/src/host-prepare.ts +123 -0
  62. package/{host-next/app/soma/manifest/route.ts → host-native/src/manifest-http.ts} +10 -10
  63. package/host-native/src/native-server.ts +691 -0
  64. package/host-native/src/page-http.ts +223 -0
  65. package/host-native/src/public-packages.cjs +167 -0
  66. package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts} +17 -19
  67. package/{host-next → host-native}/src/shell-routes.cjs +23 -13
  68. package/host-native/src/static-file.ts +172 -0
  69. package/host-native/src/workspace.ts +185 -0
  70. package/{host-next/app → host-native/styles}/globals.css +2 -2
  71. package/package.json +13 -32
  72. package/tsconfig.json +1 -1
  73. package/host-next/app/SomaPageClient.tsx +0 -359
  74. package/host-next/app/[...path]/page.tsx +0 -22
  75. package/host-next/app/api/[...path]/route.ts +0 -98
  76. package/host-next/app/components/SomaHostPage.tsx +0 -128
  77. package/host-next/app/components/SomaHydrationShell.tsx +0 -20
  78. package/host-next/app/components/SomaPageClientBoundary.tsx +0 -13
  79. package/host-next/app/components/SomaPageForbidden.tsx +0 -19
  80. package/host-next/app/favicon.ico/route.ts +0 -13
  81. package/host-next/app/layout.tsx +0 -27
  82. package/host-next/app/page.tsx +0 -9
  83. package/host-next/app/router-bridge.ts +0 -42
  84. package/host-next/app/soma/[...path]/route.ts +0 -9
  85. package/host-next/app/soma/_shared/host-prepare.ts +0 -33
  86. package/host-next/app/soma/_shared/page-http.ts +0 -86
  87. package/host-next/app/soma/page/route.ts +0 -36
  88. package/host-next/app/soma/route.ts +0 -9
  89. package/host-next/app/soma-runtime/[...file]/route.ts +0 -21
  90. package/host-next/app/soma-runtime/_shared/static-file.ts +0 -89
  91. package/host-next/bin/host-next.cjs +0 -60
  92. package/host-next/instrumentation.ts +0 -18
  93. package/host-next/next-env.d.ts +0 -7
  94. package/host-next/next.config.js +0 -410
  95. package/host-next/proxy.ts +0 -43
  96. package/host-next/src/workspace.ts +0 -543
package/README.md CHANGED
@@ -28,8 +28,8 @@ Host 文件页优先,Registry 页面在 Host 404 时兜底;存量 `/pages/<n
28
28
  Temporal 值语义(`temporal`)、图表(`chart`)、拖放(`dnd`)、文本差异(`diff`)、二维码(`qrcode`)各一个子路径;
29
29
  引擎库只在 `adapter-*.ts` 里动态 import,可经 `SomaBootstrapOptions.engines` 逐槽替换。
30
30
  - **渲染端口**:`render-ports` 的 notify / regionFallback 由 UI 体系注入,缺省无头(只记录 / 只打标记)。
31
- - **宿主与 CLI**:core 运行时不含 Next / React;Next App Router 宿主壳在包内 `host-next/`(next / react / react-dom 为可选 peer),`soma dev/build/start` 以子进程转调它;`soma` CLI
32
- (`dev/build/start` 转调包内 host-next、`db generate|migrate|pull|prisma|codegen`、`sync`、`lsp`、`component eject|diff|upgrade` 与 `pack init` 转调 soma-ui,见 `bin/` 与 `soma help`)。
31
+ - **宿主与 CLI**:core 运行时与宿主壳均零 Next / React 依赖;原生极速单进程宿主壳在包内 `host-native/`(含客户端分片与后端服务预先静态编译,支持 `--web-dir` / `--api-dir` 前后端分目录同进程运行),`soma dev/build/start` 以子进程转调它;`soma` CLI
32
+ (`dev/build/start` 转调包内 host-native、`codegen`、`sync`、`lsp`、`component eject|diff|upgrade` 与 `pack init` 转调 soma-ui,见 `bin/` 与 `soma help`)。
33
33
  mock 服务器与 `soma-mock` 已迁 soma-testkit;`verify` 在 soma-testkit。
34
34
 
35
35
  ## 文档索引
package/bin/soma.cjs CHANGED
@@ -158,7 +158,7 @@ function printHelp() {
158
158
  console.log([
159
159
  'Usage: soma <命令> [...参数]',
160
160
  '',
161
- ' dev | build | start 在 Host 根启动 Next 开发 / 生产构建 / 启动产物(转调包内 host-next)',
161
+ ' dev | build | start 在 Host 根启动原生开发 / AOT 预编译 / 启动产物(转调包内 host-native)',
162
162
  ' codegen [service] ... Domain Class 装饰器 → 页面声明;service 分支生成 IService 骨架',
163
163
  ' sync [--from <目录>] [--to <目录>] 把包内预构建的浏览器运行包拷到 <runtime 根>/static/(--to 可改)',
164
164
  ' lsp [--check <文件或目录>] stdio JSON-RPC 语言服务(同 soma-lsp);--check 单次诊断,有错退出码 1',
package/bin/soma.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { spawnSync } from 'node:child_process';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
 
@@ -134,9 +134,9 @@ if (command === 'check') {
134
134
  process.exit(1);
135
135
  });
136
136
  }
137
- /** Next 宿主壳命令行:随 soma-core 包发布的 host-next/bin/host-next.cjs(包内相对定位,不去 node_modules 找外部包) */
138
- function locateHostNextCli(): string | null {
139
- const candidate = path.join(packageRoot, 'host-next', 'bin', 'host-next.cjs');
137
+ /** 原生宿主壳命令行:随 soma-core 包发布的 host-native/bin/host-native.cjs(包内相对定位,不去 node_modules 找外部包) */
138
+ function locateHostNativeCli(): string | null {
139
+ const candidate = path.join(packageRoot, 'host-native', 'bin', 'host-native.cjs');
140
140
  return fs.existsSync(candidate) ? candidate : null;
141
141
  }
142
142
 
@@ -149,23 +149,72 @@ if (command !== 'check') {
149
149
  process.exit(1);
150
150
  }
151
151
 
152
- // `soma dev|build|start`:Next 宿主壳(app/、next.config、proxy、Next 工作区装配)在包内 host-next/ 目录,
153
- // core 运行时(core/**)不 import 它、不含 Next / React;这里以子进程转调它的命令行,参数、环境变量与退出码透传。
152
+ // `soma dev|build|start`:原生宿主壳(AOT 预编译 + 原生单进程内核)在包内 host-native/ 目录,
153
+ // core 运行时(core/**)不 import 它;这里以子进程转调它的命令行,参数、环境变量与退出码透传。
154
154
  // Host 目录取当前目录,覆盖外部陈旧的 SOMA_HOST_DIR。
155
155
  const hostDir = path.resolve(process.cwd());
156
156
  process.env.SOMA_HOST_DIR = hostDir;
157
- const hostNextCli = locateHostNextCli();
158
- if (!hostNextCli) {
157
+
158
+ const restArgs = args.slice(1);
159
+ for (let i = 0; i < restArgs.length; i++) {
160
+ const arg = restArgs[i];
161
+ if (arg === '--web-dir' && i + 1 < restArgs.length) {
162
+ process.env.SOMA_WEB_DIR = path.resolve(process.cwd(), restArgs[i + 1]);
163
+ } else if (arg.startsWith('--web-dir=')) {
164
+ process.env.SOMA_WEB_DIR = path.resolve(process.cwd(), arg.slice('--web-dir='.length));
165
+ } else if (arg === '--api-dir' && i + 1 < restArgs.length) {
166
+ process.env.SOMA_API_DIR = path.resolve(process.cwd(), restArgs[i + 1]);
167
+ } else if (arg.startsWith('--api-dir=')) {
168
+ process.env.SOMA_API_DIR = path.resolve(process.cwd(), arg.slice('--api-dir='.length));
169
+ }
170
+ }
171
+
172
+ const hostNativeCli = locateHostNativeCli();
173
+ if (!hostNativeCli) {
159
174
  console.error(
160
- `[soma ${command}] 找不到 Next 宿主壳入口 host-next/bin/host-next.cjs:soma-core 包不完整,请重新安装。`,
175
+ `[soma ${command}] 找不到原生宿主壳入口 host-native/bin/host-native.cjs:soma-core 包不完整,请重新安装。`,
161
176
  );
162
177
  process.exit(1);
163
178
  }
164
- const child = spawnSync(process.execPath, [hostNextCli, command, ...args.slice(1)], {
165
- cwd: process.cwd(),
166
- stdio: 'inherit',
167
- env: { ...process.env, SOMA_HOST_DIR: hostDir },
168
- });
179
+ const hasHeapArg = process.execArgv.some((a) => a.includes('--max-old-space-size'))
180
+ || (process.env.NODE_OPTIONS || '').includes('--max-old-space-size');
181
+ const nodeArgs: string[] = [];
182
+ if (!hasHeapArg && !process.env.SOMA_DISABLE_HEAP_CAP) {
183
+ const defaultCap = command === 'dev' ? 1024 : 512;
184
+ const cap = process.env.SOMA_MAX_OLD_SPACE_MB
185
+ ? parseInt(process.env.SOMA_MAX_OLD_SPACE_MB, 10)
186
+ : defaultCap;
187
+ if (Number.isFinite(cap) && cap > 0) {
188
+ nodeArgs.push(`--max-old-space-size=${cap}`);
189
+ }
190
+ }
191
+ nodeArgs.push(hostNativeCli, command, ...args.slice(1));
192
+ const childEnv = {
193
+ ...process.env,
194
+ SOMA_HOST_DIR: hostDir,
195
+ SOMA_NATIVE_HEAP_APPLIED: '1',
196
+ };
169
197
 
170
- process.exit(child.status === null ? 1 : child.status);
198
+ if (command === 'build') {
199
+ const child = spawnSync(process.execPath, nodeArgs, {
200
+ cwd: process.cwd(),
201
+ stdio: 'inherit',
202
+ env: childEnv,
203
+ });
204
+ process.exit(child.status === null ? 1 : child.status);
205
+ } else {
206
+ const child = spawn(process.execPath, nodeArgs, {
207
+ cwd: process.cwd(),
208
+ stdio: 'inherit',
209
+ env: childEnv,
210
+ });
211
+ const forward = (sig: NodeJS.Signals) => {
212
+ try { child.kill(sig); } catch {}
213
+ };
214
+ process.on('SIGINT', () => forward('SIGINT'));
215
+ process.on('SIGTERM', () => forward('SIGTERM'));
216
+ child.on('exit', (code, signal) => {
217
+ process.exit(code ?? (signal ? 0 : 0));
218
+ });
219
+ }
171
220
  }
@@ -7826,6 +7826,11 @@ var SOMA_PIPELINE_LIMITS = {
7826
7826
  "module": "soma-lite",
7827
7827
  "file": "src/app/server/provenance-limit.ts",
7828
7828
  "symbol": "SOMA_PIPELINE_LIMITS"
7829
+ },
7830
+ {
7831
+ "module": "soma-robot",
7832
+ "file": "src/common/limits.ts",
7833
+ "symbol": "SOMA_PIPELINE_LIMITS_AI_ROBOT"
7829
7834
  }
7830
7835
  ],
7831
7836
  "registry": {
@@ -8136,8 +8141,13 @@ function parseSource(raw, path, objectNames, selfName, deps) {
8136
8141
  source.failWhen = value;
8137
8142
  } else if (key === "messagePath") {
8138
8143
  source.messagePath = value;
8144
+ } else if (key === "dataPath") {
8145
+ if (typeof value !== "string" || value.trim() === "") {
8146
+ throw new SomaDataConfigError(`dataPath \u5FC5\u987B\u662F\u975E\u7A7A\u7684\u54CD\u5E94\u4F53\u70B9\u8DEF\u5F84`, `${path}.dataPath`);
8147
+ }
8148
+ source.dataPath = value.trim();
8139
8149
  } else {
8140
- throw new SomaDataConfigError(`\u672A\u77E5\u7684\u6765\u6E90\u5B57\u6BB5 "${key}"\uFF08\u652F\u6301: api / params / into / require / failWhen / messagePath\uFF09`, `${path}.${key}`);
8150
+ throw new SomaDataConfigError(`\u672A\u77E5\u7684\u6765\u6E90\u5B57\u6BB5 "${key}"\uFF08\u652F\u6301: api / params / into / require / failWhen / messagePath / dataPath\uFF09`, `${path}.${key}`);
8141
8151
  }
8142
8152
  }
8143
8153
  if (source.failWhen !== void 0 || source.messagePath !== void 0) {
@@ -25,24 +25,97 @@ const ERROR_BODY_MAX_LENGTH = 500;
25
25
  * 只留 statusText 等于把它整条丢掉。正文也可能是 HTML 错误页或空串,
26
26
  * 因此 JSON 解析必须容错——解析失败只是"没有结构化字段",不该把请求变成另一种崩法。
27
27
  */
28
- export function describeHttpErrorBody(body: string, statusText: string): string {
29
- const text = (body ?? '').trim();
30
- if (text === '') return statusText;
28
+ const CANDIDATE_KEYS = [
29
+ "error",
30
+ "message",
31
+ "msg",
32
+ "errMsg",
33
+ "err_msg",
34
+ "errmsg",
35
+ "reason",
36
+ "detail",
37
+ ] as const;
38
+
39
+ function pickMessageField(record: Record<string, unknown>): string | undefined {
40
+ for (const key of CANDIDATE_KEYS) {
41
+ const val = record[key];
42
+ if (typeof val === "string" && val.trim() !== "") {
43
+ return val.trim();
44
+ }
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+ function extractHtmlTitle(text: string): string | undefined {
50
+ const match = text.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
51
+ if (!match) return undefined;
52
+ const plain = match[1].replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
53
+ if (plain === "") return undefined;
54
+ return plain.length > 120 ? `${plain.slice(0, 120)}…` : plain;
55
+ }
56
+
57
+ export function describeHttpErrorBody(body: string, statusText: string, status?: number): string {
58
+ const text = (body ?? "").trim();
59
+ const fallbackStatus = statusText.trim() || (status ? `请求失败(HTTP ${status})` : "请求失败");
60
+
61
+ if (text === "") return fallbackStatus;
31
62
 
32
- let message = text;
63
+ // 3. 拦截 HTML 错误页源码外泄(忽略大小写和前导空白)
64
+ if (/^\s*<(?:!doctype\s+html|html)/i.test(text)) {
65
+ const title = extractHtmlTitle(text);
66
+ if (title) return title;
67
+ return statusText.trim() || (status ? `服务异常(HTTP ${status})` : "服务异常");
68
+ }
69
+
70
+ // 1 & 2. 尝试 JSON 解析
33
71
  try {
34
72
  const parsed = JSON.parse(text);
35
- if (parsed && typeof parsed === 'object') {
36
- const field = (parsed as Record<string, unknown>).error ?? (parsed as Record<string, unknown>).message;
37
- if (typeof field === 'string' && field.trim() !== '') message = field.trim();
73
+ if (parsed && typeof parsed === "object") {
74
+ if (!Array.isArray(parsed)) {
75
+ const obj = parsed as Record<string, unknown>;
76
+ // 顶层候选字段
77
+ const top = pickMessageField(obj);
78
+ if (top) return truncate(top);
79
+
80
+ // 嵌套一层 error 对象
81
+ if (obj.error && typeof obj.error === "object" && !Array.isArray(obj.error)) {
82
+ const nested = pickMessageField(obj.error as Record<string, unknown>);
83
+ if (nested) return truncate(nested);
84
+ }
85
+
86
+ // 嵌套一层 data 对象
87
+ if (obj.data && typeof obj.data === "object" && !Array.isArray(obj.data)) {
88
+ const nested = pickMessageField(obj.data as Record<string, unknown>);
89
+ if (nested) return truncate(nested);
90
+ }
91
+
92
+ // 若存在短字符串 code(如 {"ret":502,"code":"BAD_GATEWAY"})可作为可读提示
93
+ if (typeof obj.code === "string" && obj.code.trim() !== "" && obj.code.trim().length <= 40) {
94
+ return truncate(obj.code.trim());
95
+ }
96
+ }
97
+
98
+ // 拦截裸 JSON 信封外泄:合法 JSON 对象/数组但无可读描述字段,绝不把原始 JSON 返回
99
+ return fallbackStatus;
38
100
  }
39
101
  } catch {
40
- // 非 JSON(HTML 错误页、纯文本)就用正文原文
102
+ // 非 JSON:若以 < 开头(如未带完整 html 根的网页片段),防标签源码外泄
103
+ if (text.startsWith("<")) {
104
+ const title = extractHtmlTitle(text);
105
+ if (title) return title;
106
+ return statusText.trim() || (status ? `服务异常(HTTP ${status})` : "服务异常");
107
+ }
108
+ // 普通纯文本正文
109
+ return truncate(text);
41
110
  }
42
111
 
43
- return message.length > ERROR_BODY_MAX_LENGTH
44
- ? `${message.slice(0, ERROR_BODY_MAX_LENGTH)}…`
45
- : message;
112
+ return fallbackStatus;
113
+ }
114
+
115
+ function truncate(msg: string): string {
116
+ return msg.length > ERROR_BODY_MAX_LENGTH
117
+ ? `${msg.slice(0, ERROR_BODY_MAX_LENGTH)}…`
118
+ : msg;
46
119
  }
47
120
 
48
121
  /**
@@ -149,7 +222,7 @@ export class SomaHttpClient {
149
222
  const errorBody = typeof res.text === 'function'
150
223
  ? await res.text().catch(() => '')
151
224
  : '';
152
- throw new Error(`HTTP ${res.status}: ${describeHttpErrorBody(errorBody, res.statusText)}`);
225
+ throw new Error(`HTTP ${res.status}: ${describeHttpErrorBody(errorBody, res.statusText, res.status)}`);
153
226
  }
154
227
 
155
228
  return (await res.json()) as T;
@@ -1051,14 +1051,25 @@ export class SomaDataObjectResolver {
1051
1051
  });
1052
1052
  }
1053
1053
 
1054
+ private pickDotted(root: unknown, path: string): unknown {
1055
+ let current: unknown = root;
1056
+ for (const segment of path.split('.')) {
1057
+ if (segment === '') continue;
1058
+ if (current === null || typeof current !== 'object') return undefined;
1059
+ current = (current as Record<string, unknown>)[segment];
1060
+ }
1061
+ return current;
1062
+ }
1063
+
1054
1064
  /** 聚合来源结果:into 写入子键;缺省先解开宿主信封,再浅合并进根(数组整体替换) */
1055
1065
  mergeSource(current: unknown, source: SomaDataSourceConfig, data: unknown): unknown {
1056
- const payload = source.into ? data : unwrapHostPayload(data);
1057
1066
  if (source.into) {
1058
1067
  const target = isPlainObject(current) ? current : {};
1059
1068
  target[source.into] = data;
1060
1069
  return target;
1061
1070
  }
1071
+ const rawData = source.dataPath ? this.pickDotted(data, source.dataPath) : data;
1072
+ const payload = unwrapHostPayload(rawData);
1062
1073
  if (isPlainObject(payload)) {
1063
1074
  if (isPlainObject(current)) {
1064
1075
  Object.assign(current, payload);
@@ -46,7 +46,7 @@ export interface SomaEventEngineOptions<TContext extends Record<string, unknown>
46
46
  container: HTMLElement;
47
47
  adapter: IContainerAdapter;
48
48
  /**
49
- * 分级确认执行口(R-23):typed / consent 级交给它(通知服务 -> 渲染端口);plain 级与未注入时一律走 `adapter.confirm(text)`。
49
+ * 分级确认执行口(R-23):注入时全级别(plain / consent / typed)交给它(通知服务 -> 渲染端口);未注入时安全回退 `adapter.confirm(spec.text)`。
50
50
  * 返回 false = 用户取消。
51
51
  */
52
52
  confirmGraded?: (spec: SomaConfirmSpec) => boolean | Promise<boolean>;
@@ -689,9 +689,9 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
689
689
  return undefined;
690
690
  }
691
691
 
692
- /** 分级确认的唯一出口:typed / consent 且注入了执行口 -> 执行口;否则回落 plain(一句话 `adapter.confirm`) */
692
+ /** 分级确认的唯一出口:注入了执行口 -> 执行口(plain / consent / typed 全级别);否则安全回退 adapter.confirm(spec.text) */
693
693
  private askConfirm(spec: SomaConfirmSpec): boolean | Promise<boolean> {
694
- if (spec.level !== 'plain' && this.confirmGraded) return this.confirmGraded(spec);
694
+ if (this.confirmGraded) return this.confirmGraded(spec);
695
695
  return this.adapter.confirm(spec.text);
696
696
  }
697
697
 
@@ -43,10 +43,15 @@ import type { SomaIdentityProvider } from '../infra/identity/identity-port';
43
43
  import { getBrowserUrlPath, readQueryParam } from '../infra/router/router-path';
44
44
  import { parseDataYaml } from '../parser/data-config-parser';
45
45
  import { createDataWriteActions } from '../data/data-write-actions';
46
- import { SomaDataObjectResolver } from '../data/data-object-resolver';
46
+ import {
47
+ SomaDataObjectResolver,
48
+ createSomaDataPort,
49
+ createDataPortHostState,
50
+ type SomaDataPortHostState,
51
+ } from '../data/data-object-resolver';
47
52
  import { attachDataSubscriptions, type SomaDataSubscriptionHandle } from '../data/data-subscriptions';
48
53
  import { attachDataPolling, type SomaDataPollingHandle } from '../data/data-polling';
49
- import { createWriteOutcomeStore, type SomaWriteOutcomeStore } from '../data/write-outcome-store';
54
+ import type { SomaWriteOutcomeStore } from '../data/write-outcome-store';
50
55
  import type { SomaDataPort } from '../../shared/types/data-config.types';
51
56
  import type { SomaDataConfig, SomaDataDicts } from '../../shared/types/data-config.types';
52
57
  import type { WatchCallback, WatcherOptions } from '../../shared/types/watcher.types';
@@ -684,8 +689,11 @@ export class SomaBootstrap {
684
689
  private dataResolver: SomaDataObjectResolver | null = null;
685
690
  private dataLoadEpoch = 0;
686
691
  private dataOwnerEpoch = 0;
687
- /** 写入结果存储:与 bootstrap 同寿(字段错误、冲突、乐观叠层),`services.data.writeOutcome` 读它 */
688
- private readonly writeOutcomeStore: SomaWriteOutcomeStore = createWriteOutcomeStore();
692
+ /** 数据端口宿主状态(单一真源):持有写入结果存储与写入事件执行口,端口重建同寿 */
693
+ private readonly dataPortHostState: SomaDataPortHostState = createDataPortHostState();
694
+ private get writeOutcomeStore(): SomaWriteOutcomeStore {
695
+ return this.dataPortHostState.writeOutcomes();
696
+ }
689
697
  /** 快捷键注册中心(C-r18):唯一一份,`services.shortcuts` 直通 */
690
698
  private shortcutsInstance!: SomaShortcutRegistry;
691
699
  private componentStyleNonce?: string | null;
@@ -1930,38 +1938,27 @@ export class SomaBootstrap {
1930
1938
  */
1931
1939
  private createStableDataPort(): SomaDataPort {
1932
1940
  const owner = this.dataOwnerEpoch;
1933
- const current = (): SomaDataObjectResolver | null => owner === this.dataOwnerEpoch ? this.dataResolver : null;
1934
- const notReady = (action: string): { ok: false; message: string } => ({
1935
- ok: false,
1936
- message: `数据对象尚未就绪,无法${action}(本页可能没有在页面块声明 data:)`,
1937
- });
1938
- const port = {
1939
- getObject: (name: string) => current()?.getObject(name),
1940
- getObjectStatus: (name: string) => current()?.getObjectStatus(name),
1941
- getDict: (name: string) => current()?.getDict(name) ?? {},
1942
- submit: async (name: string, model: Record<string, unknown>, mode: 'create' | 'update', options?: Parameters<SomaDataObjectResolver['submit']>[3]) => {
1943
- const resolver = current();
1944
- if (!resolver) return notReady(`提交 "${name}"`);
1945
- const result = await resolver.submit(name, model, mode, options);
1946
- this.dataPolling?.arm(); // 写入后的重取可能带来新的进行中记录
1941
+ const current = (): SomaDataObjectResolver | null => (owner === this.dataOwnerEpoch ? this.dataResolver : null);
1942
+ const base = createSomaDataPort(current, this.dataPortHostState);
1943
+ return {
1944
+ ...base,
1945
+ submit: async (name, model, mode, options) => {
1946
+ const result = await base.submit(name, model, mode, options);
1947
+ if (current()) {
1948
+ this.dataPolling?.arm(); // 写入后的重取可能带来新的进行中记录
1949
+ }
1947
1950
  return result;
1948
1951
  },
1949
- remove: async (name: string, target: Parameters<SomaDataObjectResolver['remove']>[1]) => {
1950
- const resolver = current();
1951
- return resolver ? resolver.remove(name, target) : notReady(`删除 "${name}" 的记录`);
1952
+ reload: async (names) => {
1953
+ await base.reload(names);
1954
+ this.dataPolling?.arm();
1952
1955
  },
1953
- reload: async (names?: readonly string[]) => {
1954
- await current()?.reload(names === undefined ? undefined : [...names]);
1956
+ dispatch: async (name, payload) => {
1957
+ if (owner !== this.dataOwnerEpoch) return;
1958
+ await base.dispatch(name, payload);
1955
1959
  this.dataPolling?.arm();
1956
1960
  },
1957
- validate: (name: string, model: Record<string, unknown>, trigger?: Parameters<SomaDataObjectResolver['validate']>[2]) =>
1958
- current()?.validate(name, model, trigger) ?? {},
1959
- writeOutcome: (scope: string) => this.writeOutcomeStore.get(scope),
1960
- onWriteOutcome: (listener: (scope: string) => void) => this.writeOutcomeStore.subscribe(listener),
1961
- clearWriteOptimistic: (scope: string, key?: string) => this.writeOutcomeStore.clearOptimistic(scope, key),
1962
- clearOutcome: (scope: string) => this.writeOutcomeStore.clear(scope),
1963
1961
  };
1964
- return port as unknown as SomaDataPort;
1965
1962
  }
1966
1963
 
1967
1964
  /** 推送失效 → 刷新:对象 reload(依赖它的下游随 DAG 一起重取) */
@@ -2207,6 +2204,7 @@ export class SomaBootstrap {
2207
2204
  if (!this.container || !this.domainInstance) return;
2208
2205
 
2209
2206
  this.stopDeclarativeTimers();
2207
+ this.dataPortHostState.setActionDispatcher(undefined);
2210
2208
  this.eventEngine?.destroy();
2211
2209
  this.renderEngine?.destroy();
2212
2210
  this.styleBinder?.destroy();
@@ -2247,6 +2245,7 @@ export class SomaBootstrap {
2247
2245
  const writeEngine = this.eventEngine;
2248
2246
  const builtinActions = createDataWriteActions({ resolver: () => this.dataResolver, store: this.writeOutcomeStore });
2249
2247
  writeEngine.setBuiltinActions(builtinActions);
2248
+ this.dataPortHostState.setActionDispatcher((name, payload) => writeEngine.dispatchAction(name, payload));
2250
2249
  this.eventEngine.setScopeHandler(this.createScopeEventHandler());
2251
2250
  this.eventEngine.setRoleGate((roles) => this.domainInstance?._services?.permission?.hasAnyRole([...roles]) === true);
2252
2251
  this.assertNamedActionsResolvable(parsed.eventConfig, this.domainInstance, builtinActions);
@@ -2416,6 +2415,7 @@ export class SomaBootstrap {
2416
2415
  this.componentManager?.destroy();
2417
2416
  this.componentManager = null;
2418
2417
  this.proxy?.dispose();
2418
+ this.dataPortHostState.setActionDispatcher(undefined);
2419
2419
  this.eventEngine?.destroy();
2420
2420
  this.renderEngine?.destroy();
2421
2421
  this.styleBinder?.destroy();
@@ -9,6 +9,9 @@ import {
9
9
  type SomaDomainLoaderModule,
10
10
  type SomaDomainModule,
11
11
  } from './soma-domain-loaders';
12
+ import { isOptionalEntryAbsent, unwrapLoaderError } from './resolve-host-bootstrap';
13
+
14
+ const HOST_DOMAIN_LOADERS_MODULE = '@soma-host/bootstrap/soma-domain-loaders';
12
15
 
13
16
  export type SomaDomainConstructor = new () => SomaPageRoot;
14
17
 
@@ -44,16 +47,39 @@ const domainModulePromises = new Map<string, Promise<SomaDomainModule>>();
44
47
 
45
48
  export async function loadHostDomainClass(
46
49
  context: SomaDomainLoadContext,
47
- options: { allowLocaleOnlyFallback?: boolean } = {},
50
+ options: {
51
+ allowLocaleOnlyFallback?: boolean;
52
+ loadFallbackModule?: (base: string) => Promise<SomaDomainModule>;
53
+ } = {},
48
54
  ): Promise<SomaDomainConstructor> {
49
55
  let registryFailure: unknown;
50
56
  try {
51
- const registry = await import('@soma-host/bootstrap/soma-domain-loaders')
52
- .catch(() => null) as SomaDomainLoaderModule | null;
53
- const module = await loadSomaDomainModuleFromRegistry(registry, context);
54
- if (module) {
55
- const label = (context.sourcePackage ?? 'host') + ':' + context.base + 'Class';
56
- return resolveSomaDomainConstructor(module, label);
57
+ let registry: SomaDomainLoaderModule | null = null;
58
+ try {
59
+ registry = await import(
60
+ /* webpackChunkName: "soma-host-domain-loaders" */
61
+ '@soma-host/bootstrap/soma-domain-loaders'
62
+ ) as SomaDomainLoaderModule;
63
+ } catch (rawErr) {
64
+ const err = unwrapLoaderError(rawErr);
65
+ if (isOptionalEntryAbsent(err, HOST_DOMAIN_LOADERS_MODULE)) {
66
+ registry = null;
67
+ } else {
68
+ console.error('[soma-core][引擎] 加载 soma-domain-loaders 失败:', err);
69
+ if (context.sourcePackage) {
70
+ throw err;
71
+ }
72
+ registryFailure = err;
73
+ registry = null;
74
+ }
75
+ }
76
+
77
+ if (registry) {
78
+ const module = await loadSomaDomainModuleFromRegistry(registry, context);
79
+ if (module) {
80
+ const label = (context.sourcePackage ?? 'host') + ':' + context.base + 'Class';
81
+ return resolveSomaDomainConstructor(module, label);
82
+ }
57
83
  }
58
84
  } catch (error) {
59
85
  registryFailure = error;
@@ -69,27 +95,55 @@ export async function loadHostDomainClass(
69
95
  );
70
96
  }
71
97
 
98
+ const entrySpecifier = `@soma-host/domain/ui/${context.base}Class.ts`;
99
+ let module: SomaDomainModule;
72
100
  try {
73
- let promise = domainModulePromises.get(context.base);
74
- if (!promise) {
75
- promise = import(
76
- /* webpackInclude: /\/domain\/ui\/.*Class\.ts$/ */
77
- `@soma-host/domain/ui/${context.base}Class.ts`
78
- ) as Promise<SomaDomainModule>;
79
- domainModulePromises.set(context.base, promise);
101
+ if (options.loadFallbackModule) {
102
+ module = await options.loadFallbackModule(context.base);
103
+ } else {
104
+ let promise = domainModulePromises.get(context.base);
105
+ if (!promise) {
106
+ promise = import(
107
+ /* webpackInclude: /\/domain\/ui\/.*Class\.ts$/ */
108
+ `@soma-host/domain/ui/${context.base}Class.ts`
109
+ ) as Promise<SomaDomainModule>;
110
+ domainModulePromises.set(context.base, promise);
111
+ }
112
+ module = await promise;
80
113
  }
81
- const module = await promise;
82
- return resolveSomaDomainConstructor(module, context.base + 'Class');
83
- } catch (error) {
114
+ } catch (rawImportError) {
115
+ const importError = unwrapLoaderError(rawImportError);
84
116
  domainModulePromises.delete(context.base);
117
+ const isAbsent = isOptionalEntryAbsent(importError, entrySpecifier);
85
118
  if (options.allowLocaleOnlyFallback !== false) {
119
+ if (!isAbsent) {
120
+ console.error(`[soma-core][引擎] 加载页面领域类 ${context.base}Class 失败,已降级为空页面根:`, importError);
121
+ }
86
122
  return SomaLocaleOnlyPageRoot;
87
123
  }
88
- const detail = error instanceof Error
89
- ? error.message
124
+ const detail = importError instanceof Error
125
+ ? importError.message
90
126
  : registryFailure instanceof Error
91
127
  ? registryFailure.message
92
- : String(error);
128
+ : String(importError);
129
+ throw new SomaDomainLoadError(
130
+ context,
131
+ 'Domain class missing: ' + context.base + 'Class (' + detail + ')',
132
+ );
133
+ }
134
+
135
+ try {
136
+ return resolveSomaDomainConstructor(module, context.base + 'Class');
137
+ } catch (rawResolveError) {
138
+ const resolveError = unwrapLoaderError(rawResolveError);
139
+ if (options.allowLocaleOnlyFallback !== false) {
140
+ console.error(`[soma-core][引擎] 加载页面领域类 ${context.base}Class 失败,已降级为空页面根:`, resolveError);
141
+ return SomaLocaleOnlyPageRoot;
142
+ }
143
+ if (resolveError instanceof SomaDomainLoadError) {
144
+ throw resolveError;
145
+ }
146
+ const detail = resolveError instanceof Error ? resolveError.message : String(resolveError);
93
147
  throw new SomaDomainLoadError(
94
148
  context,
95
149
  'Domain class missing: ' + context.base + 'Class (' + detail + ')',