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
@@ -1,89 +0,0 @@
1
- // /soma-runtime/* 静态路由的文件解析与响应:读 `<runtime 根>/static/` 下的文件(浏览器运行包等),只读。
2
- // 安全:路径段逐个校验(拒 `..`、`.` 起首、反斜杠、空段、控制字符与 NUL);解析后做 realpath,落在 static 根之外
3
- // (符号链接逃逸)一律 404;只服务普通文件。不泄漏 runtime 根的绝对路径。
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import { createHash } from 'node:crypto';
7
- import { resolveSomaRuntimeLayout } from '../../../core/server/runtime-space/root';
8
-
9
- const CONTENT_TYPES: Readonly<Record<string, string>> = {
10
- '.js': 'text/javascript; charset=utf-8',
11
- '.mjs': 'text/javascript; charset=utf-8',
12
- '.map': 'application/json; charset=utf-8',
13
- '.json': 'application/json; charset=utf-8',
14
- '.css': 'text/css; charset=utf-8',
15
- '.txt': 'text/plain; charset=utf-8',
16
- '.wasm': 'application/wasm',
17
- '.svg': 'image/svg+xml',
18
- '.png': 'image/png',
19
- '.jpg': 'image/jpeg',
20
- '.jpeg': 'image/jpeg',
21
- '.webp': 'image/webp',
22
- '.woff': 'font/woff',
23
- '.woff2': 'font/woff2',
24
- };
25
-
26
- /** 文件名带内容哈希(`name-3fa9c0de.js`)才可 immutable;其余短缓存 + 条件请求 */
27
- const HASHED_NAME = /[-.][0-9a-f]{8,}\.[a-z0-9]+$/i;
28
-
29
- export type StaticResolution =
30
- | { readonly ok: true; readonly file: string; readonly size: number; readonly mtimeMs: number }
31
- | { readonly ok: false };
32
-
33
- export function isSafeSegments(segments: readonly string[]): boolean {
34
- return segments.length > 0 && segments.every((segment) => (
35
- segment !== '' && !segment.startsWith('.') && !/[\\/\u0000-\u001f]/.test(segment)
36
- ));
37
- }
38
-
39
- export function resolveStaticFile(staticRoot: string, segments: readonly string[]): StaticResolution {
40
- if (!isSafeSegments(segments)) return { ok: false };
41
- try {
42
- const rootReal = fs.realpathSync(staticRoot);
43
- const candidate = path.join(rootReal, ...segments);
44
- const real = fs.realpathSync(candidate);
45
- if (real !== rootReal && !real.startsWith(rootReal + path.sep)) return { ok: false };
46
- const stat = fs.statSync(real);
47
- if (!stat.isFile()) return { ok: false };
48
- return { ok: true, file: real, size: stat.size, mtimeMs: stat.mtimeMs };
49
- } catch {
50
- return { ok: false };
51
- }
52
- }
53
-
54
- export function staticRootOf(hostDir: string, env: Readonly<Record<string, string | undefined>> = process.env): string {
55
- return resolveSomaRuntimeLayout(hostDir, env).dirs.static;
56
- }
57
-
58
- export function staticResponse(
59
- segments: readonly string[],
60
- request: { readonly method: string; readonly headers: { get(name: string): string | null } },
61
- env: Readonly<Record<string, string | undefined>> = process.env,
62
- ): Response {
63
- const notFound = () => new Response('Not found', { status: 404, headers: { 'cache-control': 'no-store', 'content-type': 'text/plain; charset=utf-8' } });
64
- const hostDir = env.SOMA_HOST_DIR;
65
- if (!hostDir) return notFound();
66
- let root: string;
67
- try {
68
- root = staticRootOf(hostDir, env);
69
- } catch {
70
- return notFound(); // 越界的 runtime 根由 core 启动期拒绝;这里不透露细节
71
- }
72
- const resolved = resolveStaticFile(root, segments);
73
- if (!resolved.ok) return notFound();
74
-
75
- const etag = `W/"${createHash('sha1').update(`${resolved.size}:${resolved.mtimeMs}`).digest('hex').slice(0, 20)}"`;
76
- const hashed = HASHED_NAME.test(path.basename(resolved.file));
77
- const headers: Record<string, string> = {
78
- 'content-type': CONTENT_TYPES[path.extname(resolved.file).toLowerCase()] ?? 'application/octet-stream',
79
- 'cache-control': hashed ? 'public, max-age=31536000, immutable' : 'public, max-age=300, must-revalidate',
80
- etag,
81
- 'x-content-type-options': 'nosniff',
82
- };
83
- if (request.headers.get('if-none-match')?.split(',').some((value) => value.trim() === etag)) {
84
- return new Response(null, { status: 304, headers });
85
- }
86
- headers['content-length'] = String(resolved.size);
87
- if (request.method.toUpperCase() === 'HEAD') return new Response(null, { status: 200, headers });
88
- return new Response(new Uint8Array(fs.readFileSync(resolved.file)), { status: 200, headers });
89
- }
@@ -1,60 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Next 宿主壳命令行:`host-next.cjs <dev|build|start> [next 参数...]`(soma-core 包内,不单独发布成 bin)。
4
- *
5
- * 在 Host 目录(SOMA_HOST_DIR,缺省当前目录)下生成 Next 工作区(src/workspace.ts 的 ensureNextWorkspace),
6
- * 再以子进程跑 Next,标准流与退出码透传。`soma dev|build|start`(bin/soma.ts)经子进程转调本入口。
7
- * 源码是 TypeScript,经运行时依赖 jiti 直接加载。
8
- */
9
- const path = require('node:path');
10
- const { spawnSync } = require('node:child_process');
11
-
12
- const packageRoot = path.resolve(__dirname, '..');
13
- const [command, ...rest] = process.argv.slice(2);
14
-
15
- if (!['dev', 'build', 'start'].includes(command)) {
16
- console.error('Usage: host-next.cjs <dev|build|start> [...next args]');
17
- process.exit(1);
18
- }
19
-
20
- const createJiti = require('jiti');
21
- const load = createJiti(__filename, { interopDefault: true });
22
- const { ensureNextWorkspace, resolveNextBin } = load(path.join(packageRoot, 'src', 'workspace.ts'));
23
-
24
- const nextBin = resolveNextBin();
25
- if (!nextBin) {
26
- console.error('[soma] next not found. Install next, react and react-dom next to soma-core (soma-core lists them as optional peer dependencies).');
27
- process.exit(1);
28
- }
29
-
30
- const hostDir = path.resolve(process.env.SOMA_HOST_DIR && process.env.SOMA_HOST_DIR.trim() !== ''
31
- ? process.env.SOMA_HOST_DIR
32
- : process.cwd());
33
- process.env.SOMA_HOST_DIR = hostDir;
34
- let nextWorkspace;
35
- try {
36
- nextWorkspace = ensureNextWorkspace(hostDir);
37
- } catch (error) {
38
- console.error(error instanceof Error ? error.message : String(error));
39
- process.exit(1);
40
- }
41
-
42
- const child = spawnSync(process.execPath, [
43
- nextBin,
44
- command,
45
- nextWorkspace,
46
- ...((command === 'dev' || command === 'build') ? ['--webpack'] : []),
47
- ...rest,
48
- ], {
49
- cwd: nextWorkspace,
50
- stdio: 'inherit',
51
- env: {
52
- ...process.env,
53
- SOMA_HOST_DIR: hostDir,
54
- ...(process.env.SOMA_NEXT_WORKSPACE_DIR === undefined
55
- ? {}
56
- : { SOMA_NEXT_WORKSPACE_DIR: nextWorkspace }),
57
- },
58
- });
59
-
60
- process.exit(child.status === null ? 1 : child.status);
@@ -1,18 +0,0 @@
1
- // Next instrumentation:服务启动时执行 Host 装配的 `startup()`(一次),失败即拒绝启动。
2
- //
3
- // 时机:`soma dev` / `soma start` 的服务进程启动时(Node 运行时);`soma build` 不执行(build 只跑装配的 `prewarm`)。
4
- // 这里加载 `soma.app.ts` 并等服务端面(`server()`)装配完,再 await `startup()`;装配或启动钩子抛错,`register` 随之抛错,
5
- // 服务不进入可用状态(`soma start` 进程报错退出)。没有 `soma.app.ts` 或装配没写 `startup` 时只完成装配(无副作用)。
6
- //
7
- // Node/Edge 编译隔离:必须使用 `if (process.env.NEXT_RUNTIME === 'nodejs')` 块级条件包裹,
8
- // 让 Next.js 在为 Edge 运行时编译 instrumentation.ts 时通过死代码消除(DCE)直接抹除对 host-assembly 的依赖,
9
- // 严禁使用顶层 early return(early return 无法阻止 Webpack 分析后续的动态 import 进而触发 Can't resolve 'fs')。
10
- export async function register(): Promise<void> {
11
- if (process.env.NEXT_RUNTIME === 'nodejs') {
12
- if (process.env.NEXT_PHASE === 'phase-production-build') return;
13
- const hostDir = process.env.SOMA_HOST_DIR;
14
- if (!hostDir || !hostDir.trim()) return;
15
- const { runHostStartup } = await import('./core/server/host/host-assembly');
16
- await runHostStartup(hostDir);
17
- }
18
- }
@@ -1,7 +0,0 @@
1
- /// <reference types="next" />
2
- /// <reference types="next/image-types/global" />
3
- import "./.next/types/routes.d.ts";
4
- import "./.next/types/root-params.d.ts";
5
-
6
- // NOTE: This file should not be edited
7
- // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
@@ -1,410 +0,0 @@
1
- /** @type {import('next').NextConfig} */
2
- const fs = require('fs');
3
- const path = require('path');
4
-
5
- // soma-core 包根:本文件在 soma-core/host-next/ 下,包根就是上一级(壳与 core 同包,代码隔离见《soma Next 宿主壳》§1)。
6
- const coreRoot = path.resolve(__dirname, '..');
7
- const { SomaManifestWebpackPlugin } = require(path.join(coreRoot, 'core/build/compiler/soma-manifest-webpack-plugin'));
8
- const { listSomaSourcePackageNames, getSomaHostSourceRoot } = require(path.join(coreRoot, 'core/server/host/source-packages.cjs'));
9
-
10
- function readSomaWebpackCacheMode(env = process.env) {
11
- const mode = env.SOMA_WEBPACK_CACHE_MODE;
12
- if (mode === undefined) {
13
- return null;
14
- }
15
- if (mode !== 'memory') {
16
- throw new Error(
17
- '[soma-core] Unsupported SOMA_WEBPACK_CACHE_MODE '
18
- + JSON.stringify(mode)
19
- + '; expected "memory" or leave it unset.',
20
- );
21
- }
22
- return mode;
23
- }
24
-
25
- const { enumerateShellRoutes } = require('./src/shell-routes.cjs');
26
-
27
- const rawHostDir = process.env.SOMA_HOST_DIR;
28
- if (!rawHostDir || !String(rawHostDir).trim()) {
29
- throw new Error(
30
- '[soma-core] Set SOMA_HOST_DIR to your host app root. Use `npx soma` or set it in npm scripts.',
31
- );
32
- }
33
- const hostDir = path.resolve(rawHostDir);
34
- process.env.SOMA_HOST_DIR = hostDir;
35
- const webpackCacheMode = readSomaWebpackCacheMode();
36
-
37
- // 壳自有路由(app/ 枚举):经环境变量交给页面入口并入装配的 reservedRoutes(app/soma/_shared/host-prepare.ts)。
38
- // next.config.js 的 __dirname 是 host-next 目录(工作区里的 next.config.js 只是转 require),app/ 与工作区里复制的 app/ 同源。
39
- process.env.SOMA_SHELL_ROUTES = JSON.stringify(enumerateShellRoutes(path.join(__dirname, 'app')));
40
-
41
- function readJson(filePath) {
42
- try {
43
- if (!fs.existsSync(filePath)) return null;
44
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
45
- } catch {
46
- return null;
47
- }
48
- }
49
-
50
- /**
51
- * The generated Next workspace is intentionally isolated from a Host's
52
- * node_modules. Resolve source-linked packages from their public exports map,
53
- * never from a broad package-root alias: the latter makes unexported deep
54
- * imports appear valid locally and fail after publication.
55
- *
56
- * Webpack aliases do not model package-export wildcards. Never map a wildcard
57
- * to a directory-prefix alias: Webpack normalises `..` after that replacement,
58
- * which can turn an exported namespace into an escape hatch. Instead, expand
59
- * matching files into individual `$` exact aliases alongside concrete entries.
60
- */
61
- function isSafePackageChild(packageRoot, candidate) {
62
- return candidate === packageRoot || candidate.startsWith(`${packageRoot}${path.sep}`);
63
- }
64
-
65
- function collectFiles(root) {
66
- if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];
67
- const files = [];
68
- for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
69
- const fullPath = path.join(root, entry.name);
70
- if (entry.isDirectory()) files.push(...collectFiles(fullPath));
71
- else if (entry.isFile()) files.push(fullPath);
72
- }
73
- return files;
74
- }
75
-
76
- function isSafeExportWildcardValue(value) {
77
- return value.length > 0
78
- && !path.isAbsolute(value)
79
- && value.split(/[\\/]/).every((segment) => segment !== '' && segment !== '.' && segment !== '..');
80
- }
81
-
82
- function expandWildcardExportAliases(packageName, packageRoot, entry, target) {
83
- if ((entry.match(/\*/g) ?? []).length !== 1 || (target.match(/\*/g) ?? []).length !== 1) return {};
84
- const entryStar = entry.indexOf('*');
85
- const targetStar = target.indexOf('*');
86
- const entryPrefix = entry.slice(0, entryStar);
87
- const entrySuffix = entry.slice(entryStar + 1);
88
- const targetPrefix = target.slice(0, targetStar);
89
- const targetSuffix = target.slice(targetStar + 1);
90
- const sourceRoot = path.resolve(packageRoot, targetPrefix);
91
- if (!isSafePackageChild(packageRoot, sourceRoot)) return {};
92
-
93
- const aliases = {};
94
- for (const filePath of collectFiles(sourceRoot)) {
95
- const relative = path.relative(sourceRoot, filePath).split(path.sep).join('/');
96
- if (!relative.endsWith(targetSuffix)) continue;
97
- const wildcardValue = relative.slice(0, relative.length - targetSuffix.length);
98
- if (!isSafeExportWildcardValue(wildcardValue)) continue;
99
- const publicPath = `${entryPrefix.slice(2)}${wildcardValue}${entrySuffix}`;
100
- if (!isSafeExportWildcardValue(publicPath)) continue;
101
- aliases[`${packageName}/${publicPath}$`] = filePath;
102
- }
103
- return aliases;
104
- }
105
-
106
- function readPublicWebpackAliases(packageName, packageRoot) {
107
- const exportsMap = readJson(path.join(packageRoot, 'package.json'))?.exports;
108
- if (!exportsMap || typeof exportsMap !== 'object') return {};
109
-
110
- const exactAliases = {};
111
- const wildcardAliases = {};
112
- for (const [entry, descriptor] of Object.entries(exportsMap)) {
113
- if (entry !== '.' && !entry.startsWith('./')) continue;
114
- const target = typeof descriptor === 'string'
115
- ? descriptor
116
- : descriptor?.import ?? descriptor?.default;
117
- if (typeof target !== 'string' || !target.startsWith('./')) continue;
118
-
119
- const isWildcard = entry.includes('*') || target.includes('*');
120
- if (entry.includes('*') !== target.includes('*')) continue;
121
- if (isWildcard) {
122
- Object.assign(wildcardAliases, expandWildcardExportAliases(packageName, packageRoot, entry, target));
123
- continue;
124
- }
125
-
126
- const resolved = path.resolve(packageRoot, target);
127
- if (!isSafePackageChild(packageRoot, resolved) || !fs.existsSync(resolved)) continue;
128
- const publicPath = entry === '.' ? '' : entry.slice(2);
129
- const specifier = publicPath ? `${packageName}/${publicPath}` : packageName;
130
- exactAliases[`${specifier}$`] = resolved;
131
- }
132
- // A concrete export wins if it overlaps an expanded wildcard pattern.
133
- return { ...wildcardAliases, ...exactAliases };
134
- }
135
-
136
- function readCorePublicWebpackAliases() {
137
- return readPublicWebpackAliases('soma-core', coreRoot);
138
- }
139
-
140
- function resolveSafeChildRoot(parent, relativePath) {
141
- const trimmed = typeof relativePath === 'string' ? relativePath.trim() : '';
142
- if (!trimmed) return parent;
143
-
144
- const resolved = path.resolve(parent, trimmed);
145
- if ((resolved === parent || resolved.startsWith(`${parent}${path.sep}`)) && fs.existsSync(resolved)) {
146
- return resolved;
147
- }
148
- return parent;
149
- }
150
-
151
- // Host 源码根同取 core 的唯一实现(source-packages.cjs)。
152
- const hostSourceRoot = getSomaHostSourceRoot(hostDir);
153
- function runtimeWatchIgnoreDirectories(env = process.env) {
154
- // runtime 根(唯一解析,含 prewarm/、static/、bindings/ 等全部子目录)+ 各目录环境变量。
155
- // 复核结论(R-18):缺省根 <host>/.soma/runtime 与工作区 <host>/.soma/next 是同级目录,互不包含;
156
- // 根被配到别处时仍由 resolveSomaRuntimeRoot 的结果覆盖,所以监听清单只需这一项加别名。
157
- const { resolveSomaRuntimeRoot } = require(path.join(coreRoot, 'core/server/runtime-space/root.cjs'));
158
- let runtimeRoot;
159
- try {
160
- runtimeRoot = resolveSomaRuntimeRoot(hostDir, env);
161
- } catch {
162
- runtimeRoot = undefined; // 越界由 core 启动期拒绝;这里只负责监听清单,不重复抛错
163
- }
164
- const directories = [
165
- runtimeRoot,
166
- env.SOMA_RUNTIME_DIR && path.resolve(hostDir, env.SOMA_RUNTIME_DIR),
167
- env.SOMA_AI_METRICS_DIR,
168
- env.SOMA_AI_FAILURE_DIR,
169
- ].filter((value) => typeof value === 'string' && value.trim() !== '');
170
- return [...new Set(directories.map((directory) => path.resolve(directory).replaceAll(path.sep, '/')))];
171
- }
172
-
173
- function escapeRegExp(value) {
174
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
175
- }
176
-
177
- function mergeWatchIgnored(existingIgnored) {
178
- const directories = runtimeWatchIgnoreDirectories();
179
- const patterns = directories.map((directory) => `${directory}/**`);
180
- if (existingIgnored === undefined) return patterns;
181
- if (existingIgnored instanceof RegExp) {
182
- const runtimeSource = directories
183
- .map((directory) => `${escapeRegExp(directory)}(?:[\\\\/]|$)`)
184
- .join('|');
185
- return new RegExp(`(?:${existingIgnored.source})|(?:${runtimeSource})`, existingIgnored.flags);
186
- }
187
- return [...(Array.isArray(existingIgnored) ? existingIgnored : [existingIgnored]), ...patterns];
188
- }
189
-
190
- function resolveOptionalHostSourceFile(relativePath, fallbackPath) {
191
- const hostFile = path.resolve(hostSourceRoot, relativePath);
192
- if (fs.existsSync(hostFile)) {
193
- return hostFile;
194
- }
195
- return path.resolve(coreRoot, fallbackPath);
196
- }
197
-
198
- function readHostFileDependencyEntries() {
199
- const packageJsonPath = path.join(hostDir, 'package.json');
200
- if (!fs.existsSync(packageJsonPath)) {
201
- return [];
202
- }
203
-
204
- try {
205
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
206
- const dependencies = {
207
- ...(packageJson.dependencies ?? {}),
208
- ...(packageJson.devDependencies ?? {}),
209
- };
210
- return Object.entries(dependencies)
211
- .filter(([, version]) => typeof version === 'string' && version.startsWith('file:'))
212
- .map(([name, version]) => ({
213
- name,
214
- root: path.resolve(hostDir, String(version).slice('file:'.length)),
215
- }))
216
- .filter((entry) => fs.existsSync(entry.root));
217
- } catch {
218
- return [];
219
- }
220
- }
221
-
222
- function readEnvTranspilePackages() {
223
- return String(process.env.SOMA_TRANSPILE_PACKAGES ?? '')
224
- .split(',')
225
- .map((item) => item.trim())
226
- .filter(Boolean);
227
- }
228
-
229
- // 源包名清单取自 core 的唯一实现(server/host/source-packages.cjs),壳里不再自带「哪些包是源包」的判定。
230
- function readHostSourcePackageNames() {
231
- return listSomaSourcePackageNames(hostDir);
232
- }
233
-
234
- const hostFileDependencyEntries = readHostFileDependencyEntries();
235
- const transpilePackages = [
236
- ...new Set([
237
- 'soma-core',
238
- ...hostFileDependencyEntries.map((entry) => entry.name),
239
- ...readHostSourcePackageNames(),
240
- ...readEnvTranspilePackages(),
241
- ]),
242
- ];
243
-
244
- /**
245
- * 构建期是否再跑一遍类型检查 / lint。
246
- *
247
- * 缺省跑(单机开发时这是最后一道拦截)。设 SOMA_BUILD_SKIP_CHECKS=1 可跳过——
248
- * 两种场景需要它:
249
- * 1. CI 里 `npm run verify` 已经按包跑过 `tsc --noEmit` 与 eslint,构建期重复一遍
250
- * 只是把同一件事做两次;
251
- * 2. **小内存机器**:实测本仓在 2GB 机器上做生产构建,编译阶段能过,
252
- * 到"Linting and checking validity of types"时可用内存掉到 197MB,
253
- * 构建 worker 直接被 SIGTERM(而 Next 只留下一句
254
- * `build worker exited with code: null and signal: SIGTERM`,很容易被当成玄学)。
255
- */
256
- const skipBuildChecks = process.env.SOMA_BUILD_SKIP_CHECKS === '1';
257
-
258
- /**
259
- * dev 服务器允许的访问来源。
260
- *
261
- * Next 16 起 dev 资源(HMR 与按需 chunk)默认只认 `localhost`,从 `127.0.0.1` 打开同一台
262
- * 机器上的同一个服务会被判为跨 origin 而拦截。症状很有欺骗性:页面本身 200,
263
- * 但 `next/dynamic` 的 chunk 永远拿不到,整页停在 "Loading page…",看起来像 SOMA 没挂载。
264
- * 回环地址与 localhost 指向同一主机,这里补齐;反代域名等额外来源用
265
- * `SOMA_DEV_ORIGINS`(逗号分隔)追加,不放宽到通配。
266
- */
267
- const allowedDevOrigins = [
268
- ...new Set([
269
- 'localhost',
270
- '127.0.0.1',
271
- '[::1]',
272
- ...String(process.env.SOMA_DEV_ORIGINS ?? '')
273
- .split(',')
274
- .map((item) => item.trim())
275
- .filter(Boolean),
276
- ]),
277
- ];
278
-
279
- const nextConfig = {
280
- env: {
281
- SOMA_SHELL_ROUTES: process.env.SOMA_SHELL_ROUTES,
282
- SOMA_HOST_DIR: hostDir,
283
- },
284
-
285
- allowedDevOrigins,
286
- // 关掉 Next 开发浮层(<nextjs-portal>):它会压住控件、污染可用性门的截图与遮挡检查
287
- devIndicators: false,
288
-
289
- ...(skipBuildChecks
290
- ? { typescript: { ignoreBuildErrors: true } }
291
- : {}),
292
-
293
- serverExternalPackages: ['jiti'],
294
-
295
- experimental: {
296
- externalDir: true,
297
- // Next 16.4+ 默认开启 reactDebugChannel,水合前会阻塞等待 /_next/hmr WebSocket;
298
- // 通过仅代理 HTTP、不代理 WebSocket 的反代网关(如配合 SOMA_DEV_ORIGINS)访问 soma dev 时会卡死在 Loading page…,故默认关闭。
299
- ...(function resolveReactDebugChannel() {
300
- try {
301
- const sharedPath = require.resolve("next/dist/server/config-shared", { paths: [hostDir, __dirname, coreRoot] });
302
- const exp = require(sharedPath)?.defaultConfig?.experimental;
303
- if (exp && !("reactDebugChannel" in exp)) return {};
304
- } catch {}
305
- return { reactDebugChannel: false };
306
- })(),
307
- // 低内存构建:并行 worker 是构建期内存的主要来源,小内存机器上把它压到 1
308
- ...(skipBuildChecks ? { cpus: 1, workerThreads: false } : {}),
309
- },
310
-
311
- transpilePackages,
312
-
313
- webpack: (config, { dev, isServer, nextRuntime, webpack: webpackInstance }) => {
314
- if (webpackCacheMode === 'memory' && dev) {
315
- config.cache = { type: 'memory' };
316
- }
317
- if (dev) {
318
- config.watchOptions = {
319
- ...config.watchOptions,
320
- ignored: mergeWatchIgnored(config.watchOptions?.ignored),
321
- };
322
- }
323
- // Node/Edge 与浏览器编译隔离:非 Node.js 运行时一律排除 jiti 与 Node 原生模块回退
324
- if (nextRuntime === 'edge' || !isServer) {
325
- config.resolve.alias = {
326
- ...config.resolve.alias,
327
- jiti: false,
328
- };
329
- config.resolve.fallback = {
330
- ...config.resolve.fallback,
331
- fs: false,
332
- path: false,
333
- module: false,
334
- };
335
- }
336
- config.resolve.alias['@'] = coreRoot;
337
- Object.assign(config.resolve.alias, readCorePublicWebpackAliases());
338
- config.resolve.alias['@core'] = path.resolve(coreRoot, 'core');
339
- for (const entry of hostFileDependencyEntries) {
340
- // soma-core is resolved above from its own exports map. Other source
341
- // linked packages get the same treatment instead of a broad root alias.
342
- if (entry.name === 'soma-core') continue;
343
- const packageJson = readJson(path.join(entry.root, 'package.json'));
344
- if (packageJson?.soma?.configRoot) {
345
- config.resolve.alias[`${entry.name}/config`] = resolveSafeChildRoot(
346
- entry.root,
347
- packageJson.soma.configRoot,
348
- );
349
- }
350
- const publicAliases = readPublicWebpackAliases(entry.name, entry.root);
351
- Object.assign(config.resolve.alias, publicAliases);
352
- }
353
- // 浏览器引导选项:只取 soma.app.ts(defineSomaApp 装配)的 host.bootstrap();没有 soma.app.ts 走桩(空选项)
354
- config.resolve.alias['@soma-host/bootstrap/soma-bootstrap'] = path.resolve(
355
- coreRoot,
356
- fs.existsSync(path.resolve(hostSourceRoot, 'soma.app.ts'))
357
- ? 'core/client/host-bridge/soma-bootstrap-from-app.ts'
358
- : 'core/client/host-bridge/soma-bootstrap-host.stub.ts',
359
- );
360
- // soma.app.ts 用 `server: () => import('./soma.server')` 惰性交入服务端面(身份 / 虚拟页 / 请求钩子,含 fs 等);
361
- // Next.js Client Component 的 SSR 与 Browser 编译层均不得跟进服务端面,统一用 IgnorePlugin 截断。
362
- const hasHostDomainUi = fs.existsSync(path.resolve(hostSourceRoot, 'domain/ui'));
363
- if (webpackInstance) {
364
- config.plugins.push(new webpackInstance.IgnorePlugin({
365
- checkResource(resource) {
366
- if (/soma\.server/.test(resource)) return true;
367
- if (!hasHostDomainUi && resource.startsWith('@soma-host/domain/ui')) return true;
368
- if (nextRuntime === 'edge' || !isServer) {
369
- if (/host-assembly/.test(resource) || resource === 'jiti' || resource.startsWith('jiti/')) return true;
370
- }
371
- return false;
372
- },
373
- }));
374
- }
375
- config.resolve.alias['@soma-host/bootstrap/soma-domain-loaders'] = resolveOptionalHostSourceFile(
376
- 'bootstrap/soma-domain-loaders.ts',
377
- 'core/client/host-bridge/soma-domain-loaders.stub.ts',
378
- );
379
- config.resolve.alias['@soma-host'] = hostSourceRoot;
380
-
381
- config.plugins.push(new SomaManifestWebpackPlugin({ hostDir }));
382
-
383
- config.module.rules.push(
384
- {
385
- test: /_(ui|event|style)\.ya?ml$/,
386
- type: 'javascript/auto',
387
- use: [
388
- { loader: path.resolve(coreRoot, 'core/build/compiler/soma-webpack-loader.js') },
389
- ],
390
- },
391
- {
392
- test: /\.(config|locale(\.[a-zA-Z-]+)?)\.ya?ml$/,
393
- type: 'javascript/auto',
394
- use: [
395
- { loader: path.resolve(coreRoot, 'core/build/compiler/soma-webpack-loader.js') },
396
- ],
397
- },
398
- { test: /\.html$/, type: 'asset/source' },
399
- {
400
- test: /\.ya?ml$/,
401
- exclude: /_(ui|event|style)\.ya?ml$|\.(config|locale(\.[a-zA-Z-]+)?)\.ya?ml$/,
402
- type: 'asset/source',
403
- },
404
- { test: /\.md$/, type: 'asset/source' },
405
- );
406
- return config;
407
- },
408
- };
409
-
410
- module.exports = nextConfig;
@@ -1,43 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
- import {
3
- createSomaCspHeader,
4
- resolveSomaCspOptionsFromEnv,
5
- SOMA_CSP_NONCE_HEADER,
6
- } from './core/server/host/content-security-policy';
7
- import { resolveHostResponseHeaders } from './core/server/host/host-response-headers';
8
-
9
- /** Host 装配的响应头出口(`responseHeaders`):页面、`/api/*`、静态资源统一在这里合并;同名头以装配为准 */
10
- async function applyHostHeaders(request: NextRequest, response: NextResponse): Promise<NextResponse> {
11
- const extra = await resolveHostResponseHeaders({ method: request.method, pathname: request.nextUrl.pathname });
12
- if (extra !== undefined) {
13
- for (const [name, value] of Object.entries(extra)) response.headers.set(name, value);
14
- }
15
- return response;
16
- }
17
-
18
- export async function proxy(request: NextRequest) {
19
- // CSP 默认关(SOMA_CSP 未设);开启时同时写请求头与响应头——
20
- // 写请求头是 Next 的约定:框架据此给自己注入的内联脚本自动打 nonce。
21
- const csp = createSomaCspHeader(resolveSomaCspOptionsFromEnv(process.env));
22
- const requestHeaders = new Headers(request.headers);
23
- if (csp) {
24
- // 请求头恒用规范名(即使响应发的是 report-only):Next 只认这个名字来提取 nonce,
25
- // 用 report-only 名字会让框架自己的内联脚本拿不到 nonce,report 档全是噪声违规
26
- requestHeaders.set('content-security-policy', csp.value);
27
- if (csp.nonce) {
28
- requestHeaders.set(SOMA_CSP_NONCE_HEADER, csp.nonce);
29
- }
30
- }
31
-
32
- const response = csp
33
- ? NextResponse.next({ request: { headers: requestHeaders } })
34
- : NextResponse.next();
35
- if (csp) {
36
- response.headers.set(csp.name, csp.value);
37
- }
38
- return applyHostHeaders(request, response);
39
- }
40
-
41
- export const config = {
42
- matcher: ['/:path*'],
43
- };