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
@@ -6,21 +6,111 @@ export type SomaBootstrapConfigurator = (ctx: {
6
6
  getServices: () => SomaRuntimeServices | undefined;
7
7
  }) => Partial<SomaBootstrapOptions>;
8
8
 
9
+ export const HOST_BOOTSTRAP_MODULE = '@soma-host/bootstrap/soma-bootstrap';
10
+
11
+ /**
12
+ * 解包测试运行器或装载器可能附加的包装错误(如 Error.cause)。
13
+ */
14
+ export function unwrapLoaderError(error: unknown): unknown {
15
+ if (typeof error === 'object' && error !== null && 'cause' in error) {
16
+ const cause = (error as { cause?: unknown }).cause;
17
+ if (cause !== undefined && cause !== null) {
18
+ return cause;
19
+ }
20
+ }
21
+ return error;
22
+ }
23
+
9
24
  /**
10
- * 这个异常是不是「宿主没有这个模块」。
11
- *
12
- * 宿主钩子是可选的,缺模块是正常情形,静默跳过;模块在却在执行时抛错(`configureSomaBootstrap` 里的配方与
13
- * foundation 取值域漂开、宿主自己的 bug……)不是正常情形,必须留痕——否则返回 `{}` 之后页面不带组件表、
14
- * 不带主题,生成区域一片错误提示,而原因被抹得干干净净。
15
- * 判据按各打包器的缺模块错误形态:CJS / webpack 的 `code: 'MODULE_NOT_FOUND'`、Node ESM 的 `ERR_MODULE_NOT_FOUND`,
16
- * 以及消息里的 `Cannot find module` / `Module not found`。
17
- * 局限:缺的若是宿主钩子**内部**依赖的模块,错误形态与「钩子本身缺失」相同,同样按缺模块静默。
25
+ * 这个异常是否具备「模块未找到」的特征(CJS/ESM/Webpack/Vite 等运行时形态)。
18
26
  */
19
- function isModuleNotFound(error: unknown): boolean {
20
- if (typeof error !== 'object' || error === null) return false;
21
- const { code, message } = error as { code?: unknown; message?: unknown };
27
+ export function hasModuleNotFoundSignature(error: unknown): boolean {
28
+ const unwrapped = unwrapLoaderError(error);
29
+ if (typeof unwrapped !== 'object' || unwrapped === null) return false;
30
+ const { code, message } = unwrapped as { code?: unknown; message?: unknown };
22
31
  if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') return true;
23
- return typeof message === 'string' && /Cannot find module|Module not found/.test(message);
32
+ return typeof message === 'string' && /Cannot find module|Module not found|Can't resolve|Unknown variable dynamic import/i.test(message);
33
+ }
34
+
35
+ /**
36
+ * 从缺模块错误信息中提取被引用的说明符(如 'X' 或 "X")。
37
+ */
38
+ export function extractMissingModuleSpecifier(message: string): string | null {
39
+ if (!message || typeof message !== 'string') return null;
40
+ // 支持 Vite 等基于 import.meta.glob 抛出的 Unknown variable dynamic import: <path>
41
+ const viteMatch = message.match(/Unknown variable dynamic import:\s*(.+)$/i);
42
+ if (viteMatch && viteMatch[1]) {
43
+ return viteMatch[1].trim();
44
+ }
45
+ const primaryMatch = message.match(
46
+ /(?:Cannot find (?:module|package)|Can't resolve|Failed to resolve import)\s+['"]([^'"]+)['"]/i,
47
+ );
48
+ if (primaryMatch && primaryMatch[1]) {
49
+ return primaryMatch[1];
50
+ }
51
+ const quoteMatch = message.match(/['"]([^'"]+)['"]/);
52
+ if (quoteMatch && quoteMatch[1]) {
53
+ return quoteMatch[1];
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * 校验 spec 是否指向 expected 入口本身。
60
+ */
61
+ function matchesEntrySpecifier(spec: string, expected: string): boolean {
62
+ if (spec === expected) return true;
63
+
64
+ const normalizedExpected = expected.replace(/\.(?:ts|js|mjs|cjs)$/, '');
65
+ const normalizedSpec = spec.replace(/\.(?:ts|js|mjs|cjs)$/, '');
66
+ if (normalizedSpec === normalizedExpected) return true;
67
+
68
+ const expectedSegments = normalizedExpected.split('/');
69
+ const expectedBase = expectedSegments[expectedSegments.length - 1];
70
+ if (!expectedBase) return false;
71
+
72
+ // 检查 spec 是否以 expectedBase (加上可选扩展名) 作为路径结尾
73
+ const baseRegex = new RegExp(`(?:^|[\\\\/])${expectedBase}(?:\\.(?:ts|js|mjs|cjs))?$`);
74
+ if (!baseRegex.test(spec)) {
75
+ return false;
76
+ }
77
+
78
+ // 若 expected 有父级路径(例如 bootstrap/soma-bootstrap 或 domain/ui/XClass),且 spec 中含有路径分隔符,则父级也必须匹配
79
+ if (expectedSegments.length > 1) {
80
+ const parentSegment = expectedSegments[expectedSegments.length - 2];
81
+ if (normalizedSpec.includes('/') || normalizedSpec.includes('\\')) {
82
+ const parentRegex = new RegExp(`(?:^|[\\\\/])${parentSegment}[\\\\/]${expectedBase}$`);
83
+ return parentRegex.test(normalizedSpec);
84
+ }
85
+ }
86
+
87
+ return true;
88
+ }
89
+
90
+ /**
91
+ * 精确判定异常是否为「目标可选入口模块自身不存在」。
92
+ * - 若不具备缺模块特征 -> false
93
+ * - 若从 message 中提取出具体说明符 spec -> 仅当 spec 指向 expectedSpecifiers 时返回 true,否则(子依赖缺失)返回 false
94
+ * - 若没有引号包裹的具体模块名(无引号泛化缺模块错误) -> 视为入口自身缺失返回 true
95
+ */
96
+ export function isOptionalEntryAbsent(
97
+ error: unknown,
98
+ expectedSpecifiers: string | readonly string[],
99
+ ): boolean {
100
+ const unwrapped = unwrapLoaderError(error);
101
+ if (!hasModuleNotFoundSignature(unwrapped)) return false;
102
+
103
+ const message = typeof (unwrapped as { message?: unknown })?.message === 'string'
104
+ ? (unwrapped as { message: string }).message
105
+ : '';
106
+
107
+ const spec = extractMissingModuleSpecifier(message);
108
+ if (spec === null) {
109
+ return true;
110
+ }
111
+
112
+ const list = Array.isArray(expectedSpecifiers) ? expectedSpecifiers : [expectedSpecifiers];
113
+ return list.some((expected) => matchesEntrySpecifier(spec, expected));
24
114
  }
25
115
 
26
116
  /** 分片加载失败的重试退避(由 Host 装配注入,值取自 soma-design 限值表 hostDefaults.chunkLoadBackoffMs;core 不留数字) */
@@ -45,20 +135,21 @@ export async function resolveHostBootstrapOptions(
45
135
  if (bootstrapResolvingPromise) return bootstrapResolvingPromise;
46
136
  bootstrapResolvingPromise = (async () => {
47
137
  try {
138
+ let mod: { configureSomaBootstrap?: SomaBootstrapConfigurator } | null = null;
48
139
  for (let attempt = 0; attempt < 5; attempt++) {
49
140
  try {
50
- const mod = await import(
141
+ mod = await import(
51
142
  /* webpackChunkName: "soma-host-bootstrap" */
52
143
  '@soma-host/bootstrap/soma-bootstrap'
53
144
  ) as { configureSomaBootstrap?: SomaBootstrapConfigurator };
54
- if (typeof mod.configureSomaBootstrap === 'function') {
55
- const opts = mod.configureSomaBootstrap({ getServices }) ?? {};
56
- bootstrapOptionsCache = opts;
57
- return opts;
58
- }
59
- return {};
60
- } catch (error) {
61
- if (isModuleNotFound(error)) {
145
+ break;
146
+ } catch (rawError) {
147
+ const error = unwrapLoaderError(rawError);
148
+ if (hasModuleNotFoundSignature(error)) {
149
+ if (isOptionalEntryAbsent(error, HOST_BOOTSTRAP_MODULE)) {
150
+ return {};
151
+ }
152
+ console.error('[soma-core][引擎] 宿主引导模块内部依赖缺失,宿主装配被整体跳过:', error);
62
153
  return {};
63
154
  }
64
155
  const isChunkError = error instanceof Error
@@ -68,13 +159,24 @@ export async function resolveHostBootstrapOptions(
68
159
  continue;
69
160
  }
70
161
  console.error('[soma-core][引擎] configureSomaBootstrap 抛出异常,宿主装配被整体跳过:', error);
71
- break;
162
+ return {};
163
+ }
164
+ }
165
+
166
+ if (mod && typeof mod.configureSomaBootstrap === 'function') {
167
+ try {
168
+ const opts = mod.configureSomaBootstrap({ getServices }) ?? {};
169
+ bootstrapOptionsCache = opts;
170
+ return opts;
171
+ } catch (error) {
172
+ console.error('[soma-core][引擎] configureSomaBootstrap 抛出异常,宿主装配被整体跳过:', error);
173
+ return {};
72
174
  }
73
175
  }
176
+ return {};
74
177
  } finally {
75
178
  bootstrapResolvingPromise = null;
76
179
  }
77
- return {};
78
180
  })();
79
181
  return bootstrapResolvingPromise;
80
182
  }
@@ -4,7 +4,9 @@ export interface HttpRequestConfig {
4
4
  timeout?: number;
5
5
  signal?: AbortSignal;
6
6
  /** 响应成功(2xx)后回调一次,带回 HTTP 状态码(C-r18:数据端口据此识别 202 受理);失败走抛错,不回调 */
7
- onResponse?: (info: { readonly status: number }) => void;
7
+ onResponse?: (info: { readonly status: number }) => void;
8
+ /** 为 true 时非 2xx 响应只抛异常、不触发全局 onHttpError 提示,供上层自带语义错误处理的调用方按需抑制重复弹窗 */
9
+ silentErrorToast?: boolean;
8
10
  }
9
11
 
10
12
  export interface UploadOptions {
@@ -82,8 +82,12 @@ export class SomaHttpService implements IHttpClient {
82
82
  try {
83
83
  const res = await fetch(fullUrl, { method: 'POST', body: form, signal: controller.signal });
84
84
  if (!res.ok) {
85
- this.onHttpError?.(res.status, res.statusText);
86
- throw new Error(`HTTP ${res.status}: ${res.statusText}`);
85
+ const body = typeof res.text === 'function'
86
+ ? await res.text().catch(() => '')
87
+ : '';
88
+ const readable = describeHttpErrorBody(body, res.statusText, res.status);
89
+ this.onHttpError?.(res.status, readable);
90
+ throw new Error(`HTTP ${res.status}: ${readable}`);
87
91
  }
88
92
  onProgress?.(100);
89
93
  return (await res.json()) as T;
@@ -122,8 +126,10 @@ export class SomaHttpService implements IHttpClient {
122
126
  reject(new Error('Invalid JSON response'));
123
127
  }
124
128
  } else {
125
- this.onHttpError?.(xhr.status, xhr.statusText);
126
- reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
129
+ const body = xhr.responseText ?? '';
130
+ const readable = describeHttpErrorBody(body, xhr.statusText, xhr.status);
131
+ this.onHttpError?.(xhr.status, readable);
132
+ reject(new Error(`HTTP ${xhr.status}: ${readable}`));
127
133
  }
128
134
  });
129
135
  xhr.addEventListener('error', () => {
@@ -197,8 +203,11 @@ export class SomaHttpService implements IHttpClient {
197
203
  const body = typeof res.text === 'function'
198
204
  ? await res.text().catch(() => '')
199
205
  : '';
200
- this.onHttpError?.(res.status, body || res.statusText);
201
- throw new Error(`HTTP ${res.status}: ${describeHttpErrorBody(body, res.statusText)}`);
206
+ const readable = describeHttpErrorBody(body, res.statusText, res.status);
207
+ if (config?.silentErrorToast !== true) {
208
+ this.onHttpError?.(res.status, readable);
209
+ }
210
+ throw new Error(`HTTP ${res.status}: ${readable}`);
202
211
  }
203
212
 
204
213
  try { config?.onResponse?.({ status: res.status }); } catch { /* 状态回调抛错不影响请求结果 */ }
@@ -274,8 +274,13 @@ function parseSource(
274
274
  source.failWhen = value as SomaFieldPredicate;
275
275
  } else if (key === 'messagePath') {
276
276
  source.messagePath = value as string;
277
+ } else if (key === 'dataPath') {
278
+ if (typeof value !== 'string' || value.trim() === '') {
279
+ throw new SomaDataConfigError(`dataPath 必须是非空的响应体点路径`, `${path}.dataPath`);
280
+ }
281
+ source.dataPath = value.trim();
277
282
  } else {
278
- throw new SomaDataConfigError(`未知的来源字段 "${key}"(支持: api / params / into / require / failWhen / messagePath)`, `${path}.${key}`);
283
+ throw new SomaDataConfigError(`未知的来源字段 "${key}"(支持: api / params / into / require / failWhen / messagePath / dataPath)`, `${path}.${key}`);
279
284
  }
280
285
  }
281
286
  if (source.failWhen !== undefined || source.messagePath !== undefined) {
@@ -0,0 +1,212 @@
1
+ import type { IService } from "./IService";
2
+ import {
3
+ getAotServiceResolver,
4
+ loadHostService,
5
+ resolveServiceExport,
6
+ } from "./load-host-service";
7
+ import { invokeHostRequestHook } from "../host/invoke-host-request-hook";
8
+ import { withHostResponseHeaders } from "../host/host-response-headers";
9
+
10
+ export interface RequestCookie {
11
+ readonly name: string;
12
+ readonly value: string;
13
+ }
14
+
15
+ export interface RequestCookiesAdapter {
16
+ get(name: string): RequestCookie | undefined;
17
+ getAll(name?: string): RequestCookie[];
18
+ has(name: string): boolean;
19
+ }
20
+
21
+ export interface DispatchHostServiceApiOptions {
22
+ readonly segments?: readonly string[];
23
+ readonly hostDir?: string;
24
+ }
25
+
26
+ function parseCookieHeader(headerValue: string | null): RequestCookiesAdapter {
27
+ const parsed: RequestCookie[] = [];
28
+ const map = new Map<string, string>();
29
+ if (headerValue) {
30
+ const pairs = headerValue.split(";");
31
+ for (const pair of pairs) {
32
+ const trimmed = pair.trim();
33
+ if (!trimmed) continue;
34
+ const eqIndex = trimmed.indexOf("=");
35
+ if (eqIndex === -1) {
36
+ const name = trimmed;
37
+ parsed.push({ name, value: "" });
38
+ if (!map.has(name)) map.set(name, "");
39
+ } else {
40
+ const name = trimmed.slice(0, eqIndex).trim();
41
+ const rawValue = trimmed.slice(eqIndex + 1).trim();
42
+ const value = rawValue.startsWith(`"`) && rawValue.endsWith(`"`)
43
+ ? rawValue.slice(1, -1)
44
+ : rawValue;
45
+ parsed.push({ name, value });
46
+ if (!map.has(name)) map.set(name, value);
47
+ }
48
+ }
49
+ }
50
+
51
+ return {
52
+ get(name: string): RequestCookie | undefined {
53
+ const value = map.get(name);
54
+ return value !== undefined ? { name, value } : undefined;
55
+ },
56
+ getAll(name?: string): RequestCookie[] {
57
+ if (name !== undefined) {
58
+ return parsed.filter((c) => c.name === name);
59
+ }
60
+ return [...parsed];
61
+ },
62
+ has(name: string): boolean {
63
+ return map.has(name);
64
+ },
65
+ };
66
+ }
67
+
68
+ export function polyfillServiceRequest<T extends Request>(request: T): T & { nextUrl: URL; cookies: RequestCookiesAdapter } {
69
+ const req = request as unknown as { nextUrl?: URL; cookies?: RequestCookiesAdapter; url: string; headers: Headers };
70
+ if (!("nextUrl" in req) || !req.nextUrl) {
71
+ let nextUrlCache: URL | undefined;
72
+ Object.defineProperty(req, "nextUrl", {
73
+ get() {
74
+ if (!nextUrlCache) {
75
+ nextUrlCache = new URL(request.url, "http://soma.local");
76
+ }
77
+ return nextUrlCache;
78
+ },
79
+ configurable: true,
80
+ enumerable: true,
81
+ });
82
+ }
83
+ if (!("cookies" in req) || !req.cookies) {
84
+ let cookiesCache: RequestCookiesAdapter | undefined;
85
+ Object.defineProperty(req, "cookies", {
86
+ get() {
87
+ if (!cookiesCache) {
88
+ cookiesCache = parseCookieHeader(request.headers.get("cookie"));
89
+ }
90
+ return cookiesCache;
91
+ },
92
+ configurable: true,
93
+ enumerable: true,
94
+ });
95
+ }
96
+ return request as T & { nextUrl: URL; cookies: RequestCookiesAdapter };
97
+ }
98
+
99
+ function getAllowHeader(service: IService): string {
100
+ const methods: string[] = [];
101
+ if (typeof service.get === "function") methods.push("GET");
102
+ if (typeof service.post === "function") methods.push("POST");
103
+ if (typeof service.put === "function") methods.push("PUT");
104
+ if (typeof service.patch === "function") methods.push("PATCH");
105
+ if (typeof service.delete === "function") methods.push("DELETE");
106
+ return methods.join(", ");
107
+ }
108
+
109
+ export async function dispatchHostServiceApiRequest(
110
+ request: Request,
111
+ segmentsOrOptions?: readonly string[] | DispatchHostServiceApiOptions,
112
+ ): Promise<Response> {
113
+ const polyfilledReq = polyfillServiceRequest(request);
114
+ const options: DispatchHostServiceApiOptions | undefined =
115
+ Array.isArray(segmentsOrOptions)
116
+ ? { segments: segmentsOrOptions }
117
+ : (segmentsOrOptions as DispatchHostServiceApiOptions | undefined);
118
+
119
+ const hostDir = options?.hostDir ?? process.env.SOMA_HOST_DIR;
120
+
121
+ let segments: string[];
122
+ if (options?.segments && options.segments.length > 0) {
123
+ segments = [...options.segments];
124
+ } else {
125
+ const pathname = polyfilledReq.nextUrl.pathname;
126
+ const pathParts = pathname.split("/").filter(Boolean);
127
+ if (pathParts[0] === "api") {
128
+ segments = pathParts.slice(1);
129
+ } else {
130
+ segments = pathParts;
131
+ }
132
+ }
133
+
134
+ const pathname = polyfilledReq.nextUrl.pathname;
135
+ const rejected = await invokeHostRequestHook(polyfilledReq, {
136
+ kind: "api",
137
+ path: pathname,
138
+ });
139
+ if (rejected) {
140
+ return withHostResponseHeaders(rejected, {
141
+ method: request.method,
142
+ pathname,
143
+ }, hostDir);
144
+ }
145
+
146
+ if (segments.length === 0) {
147
+ const res = Response.json(
148
+ { error: "Missing API path. Expected: /api/{module}/{action}" },
149
+ { status: 400 },
150
+ );
151
+ return withHostResponseHeaders(res, { method: request.method, pathname }, hostDir);
152
+ }
153
+
154
+ let service: IService | null = null;
155
+ if (hostDir) {
156
+ const prevHostDir = process.env.SOMA_HOST_DIR;
157
+ try {
158
+ process.env.SOMA_HOST_DIR = hostDir;
159
+ service = loadHostService(segments);
160
+ if (!service) {
161
+ const aotResolver = getAotServiceResolver(hostDir);
162
+ if (aotResolver) {
163
+ const routeKey = segments.join("/");
164
+ const resolved = await aotResolver(routeKey, segments);
165
+ if (resolved) {
166
+ service = resolveServiceExport(resolved, `[aot:${routeKey}]`);
167
+ }
168
+ }
169
+ }
170
+ } finally {
171
+ if (prevHostDir === undefined) {
172
+ delete process.env.SOMA_HOST_DIR;
173
+ } else {
174
+ process.env.SOMA_HOST_DIR = prevHostDir;
175
+ }
176
+ }
177
+ } else {
178
+ service = loadHostService(segments);
179
+ }
180
+
181
+ if (!service) {
182
+ const res = Response.json(
183
+ { error: `API not found: /api/${segments.join("/")}` },
184
+ { status: 404 },
185
+ );
186
+ return withHostResponseHeaders(res, { method: request.method, pathname }, hostDir);
187
+ }
188
+
189
+ const method = request.method.toUpperCase();
190
+ const methodKey = method.toLowerCase() as keyof IService;
191
+ const handlerFn = service[methodKey];
192
+ if (typeof handlerFn !== "function") {
193
+ const res = Response.json(
194
+ { error: `Method ${method} not allowed: /api/${segments.join("/")}` },
195
+ { status: 405, headers: { Allow: getAllowHeader(service) } },
196
+ );
197
+ return withHostResponseHeaders(res, { method: request.method, pathname }, hostDir);
198
+ }
199
+
200
+ try {
201
+ const response = await handlerFn.call(service, polyfilledReq);
202
+ return withHostResponseHeaders(response, { method: request.method, pathname }, hostDir);
203
+ } catch (e: unknown) {
204
+ const message = e instanceof Error ? e.message : String(e);
205
+ console.error(`[soma-core][接口] ${method} /api/${segments.join("/")}:`, message);
206
+ const res = Response.json(
207
+ { error: message || "Internal server error" },
208
+ { status: 500 },
209
+ );
210
+ return withHostResponseHeaders(res, { method: request.method, pathname }, hostDir);
211
+ }
212
+ }