soma-core 2.0.1 → 2.1.1

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 (161) hide show
  1. package/README.md +2 -2
  2. package/bin/eject.cjs +5 -5
  3. package/bin/soma-runtime.cjs +5 -123
  4. package/bin/soma.cjs +2 -2
  5. package/bin/soma.ts +8 -20
  6. package/core/build/compiler/page-declaration-compiler.ts +5 -6
  7. package/core/build/lsp/soma-declaration.cjs +0 -6
  8. package/core/client/container/SomaContainerAdapter.ts +1 -1
  9. package/core/client/data/region-scope-views.ts +1 -1
  10. package/core/client/engine/event-engine.ts +1 -6
  11. package/core/client/engine/soma-bootstrap.ts +5 -13
  12. package/core/client/host-bridge/soma-bootstrap-from-app.ts +2 -2
  13. package/core/client/infra/i18n/II18n.ts +5 -6
  14. package/core/client/infra/i18n/locale-catalog.ts +8 -5
  15. package/core/client/infra/identity/identity-port.ts +1 -1
  16. package/core/client/keyboard/index.ts +0 -1
  17. package/core/client/keyboard/wiring.ts +0 -3
  18. package/core/client/parser/ui-config-parser.ts +6 -9
  19. package/core/client/registry/declaration-renderer.ts +1 -1
  20. package/core/client/runtime/SomaRuntimeServices.ts +1 -1
  21. package/core/inspect/check-runtime.ts +2 -3
  22. package/core/server/host/content-security-policy.ts +2 -11
  23. package/core/server/host/host-assembly-entry.ts +10 -2
  24. package/core/server/host/host-assembly.ts +28 -10
  25. package/core/server/host/host-caller.ts +52 -0
  26. package/core/server/host/host-response-headers.ts +49 -0
  27. package/core/server/host/locale-yaml.ts +7 -5
  28. package/core/server/host/published-page-assets.ts +1 -1
  29. package/core/server/host/resolve-host-request-hook.ts +2 -11
  30. package/core/server/host/resolve-host-tree-context.ts +7 -41
  31. package/core/server/host/server-page-assets.ts +0 -22
  32. package/core/server/host/source-packages.cjs +3 -4
  33. package/core/server/host/virtual-pages.ts +12 -70
  34. package/core/server/index.ts +1 -3
  35. package/core/server/node.ts +0 -1
  36. package/core/server/page-assets.ts +2 -20
  37. package/core/server/page-declaration.ts +1 -1
  38. package/core/server/registry/api-registry-store.ts +5 -25
  39. package/core/server/registry/asset-store.ts +5 -23
  40. package/core/server/registry/page-registry-repository.ts +9 -13
  41. package/core/server/registry/page-registry-store.ts +44 -82
  42. package/core/server/registry/publish-asset-pin.ts +3 -4
  43. package/core/server/registry/registry-subjects.ts +6 -6
  44. package/core/server/registry/rollback-plan.ts +5 -8
  45. package/core/server/registry/source/version-store.ts +8 -30
  46. package/core/server/registry/standard-product.ts +1 -1
  47. package/core/server/runtime-space/bindings.ts +1 -4
  48. package/core/server/runtime-space/gc.ts +2 -3
  49. package/core/server/runtime-space/inject.ts +4 -5
  50. package/core/server/runtime-space/resolve.ts +13 -27
  51. package/core/server/runtime-space/root.cjs +9 -100
  52. package/core/server/runtime-space/root.ts +3 -23
  53. package/core/server/runtime-space/types.ts +0 -11
  54. package/core/shared/artifact-compatibility.ts +6 -16
  55. package/core/shared/component-tree-artifact.ts +4 -8
  56. package/core/shared/core-diagnostic-codes.ts +1 -3
  57. package/core/shared/pipeline-error-codes-view.ts +1 -2
  58. package/core/shared/published-page-route.ts +1 -6
  59. package/core/shared/registry-generated/diagnostic-registry-index.ts +0 -2
  60. package/core/shared/registry-generated/diagnostic-registry.ts +0 -14
  61. package/core/shared/source-file-suffix.ts +8 -0
  62. package/core/shared/types/component-tree-artifact.types.ts +2 -15
  63. package/core/shared/types/host-assembly.types.ts +31 -2
  64. package/core/shared/types/locale.types.ts +3 -3
  65. package/core/shared/types/region-scope.types.ts +1 -1
  66. package/core/shared/types/ui-config.types.ts +2 -7
  67. package/core/shared/types/write.types.ts +1 -1
  68. package/dist/browser/soma-runtime.js +20 -36
  69. package/dist/cli/soma.js +8 -21
  70. package/dist/core/index.cjs +20 -38
  71. package/dist/lsp/component-tree.cjs +7 -14
  72. package/dist/types/client/container/SomaContainerAdapter.d.ts +1 -1
  73. package/dist/types/client/engine/event-engine.d.ts +0 -2
  74. package/dist/types/client/engine/soma-bootstrap.d.ts +2 -3
  75. package/dist/types/client/host-bridge/soma-bootstrap-from-app.d.ts +2 -2
  76. package/dist/types/client/infra/i18n/II18n.d.ts +5 -6
  77. package/dist/types/client/infra/i18n/locale-catalog.d.ts +3 -3
  78. package/dist/types/client/infra/identity/identity-port.d.ts +1 -1
  79. package/dist/types/client/keyboard/index.d.ts +1 -1
  80. package/dist/types/client/keyboard/wiring.d.ts +0 -2
  81. package/dist/types/client/registry/declaration-renderer.d.ts +1 -1
  82. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +1 -1
  83. package/dist/types/server/host/content-security-policy.d.ts +0 -5
  84. package/dist/types/server/host/host-assembly-entry.d.ts +5 -2
  85. package/dist/types/server/host/host-assembly.d.ts +9 -4
  86. package/dist/types/server/host/host-caller.d.ts +10 -0
  87. package/dist/types/server/host/host-response-headers.d.ts +16 -0
  88. package/dist/types/server/host/published-page-assets.d.ts +1 -1
  89. package/dist/types/server/host/resolve-host-request-hook.d.ts +0 -4
  90. package/dist/types/server/host/resolve-host-tree-context.d.ts +1 -1
  91. package/dist/types/server/host/server-page-assets.d.ts +0 -2
  92. package/dist/types/server/host/virtual-pages.d.ts +4 -14
  93. package/dist/types/server/index.d.ts +1 -2
  94. package/dist/types/server/node.d.ts +1 -1
  95. package/dist/types/server/page-assets.d.ts +1 -4
  96. package/dist/types/server/page-declaration.d.ts +1 -1
  97. package/dist/types/server/registry/api-registry-store.d.ts +1 -6
  98. package/dist/types/server/registry/asset-store.d.ts +2 -11
  99. package/dist/types/server/registry/page-registry-repository.d.ts +4 -4
  100. package/dist/types/server/registry/page-registry-store.d.ts +22 -30
  101. package/dist/types/server/registry/registry-subjects.d.ts +2 -2
  102. package/dist/types/server/registry/rollback-plan.d.ts +0 -3
  103. package/dist/types/server/registry/source/version-store.d.ts +1 -9
  104. package/dist/types/server/registry/standard-product.d.ts +1 -1
  105. package/dist/types/server/runtime-space/resolve.d.ts +0 -3
  106. package/dist/types/server/runtime-space/root.d.cts +6 -29
  107. package/dist/types/server/runtime-space/root.d.ts +2 -7
  108. package/dist/types/server/runtime-space/types.d.ts +0 -9
  109. package/dist/types/shared/artifact-compatibility.d.ts +1 -3
  110. package/dist/types/shared/core-diagnostic-codes.d.ts +1 -1
  111. package/dist/types/shared/published-page-route.d.ts +1 -3
  112. package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +0 -12
  113. package/dist/types/shared/types/component-tree-artifact.types.d.ts +2 -15
  114. package/dist/types/shared/types/host-assembly.types.d.ts +27 -1
  115. package/dist/types/shared/types/locale.types.d.ts +1 -1
  116. package/dist/types/shared/types/region-scope.types.d.ts +1 -1
  117. package/dist/types/shared/types/ui-config.types.d.ts +2 -7
  118. package/dist/types/shared/types/write.types.d.ts +1 -1
  119. package/global.d.ts +0 -9
  120. package/host-next/app/SomaPageClient.tsx +359 -0
  121. package/host-next/app/[...path]/page.tsx +22 -0
  122. package/host-next/app/api/[...path]/route.ts +98 -0
  123. package/host-next/app/api/soma-registry/[...path]/route.ts +79 -0
  124. package/host-next/app/components/SomaHostPage.tsx +128 -0
  125. package/host-next/app/components/SomaHydrationShell.tsx +20 -0
  126. package/host-next/app/components/SomaPageClientBoundary.tsx +13 -0
  127. package/host-next/app/components/SomaPageForbidden.tsx +19 -0
  128. package/host-next/app/favicon.ico/route.ts +13 -0
  129. package/host-next/app/globals.css +177 -0
  130. package/host-next/app/layout.tsx +27 -0
  131. package/host-next/app/page-access.ts +47 -0
  132. package/host-next/app/page.tsx +9 -0
  133. package/host-next/app/router-bridge.ts +42 -0
  134. package/host-next/app/soma/[...path]/route.ts +9 -0
  135. package/host-next/app/soma/_shared/host-prepare.ts +33 -0
  136. package/host-next/app/soma/_shared/page-http.ts +86 -0
  137. package/host-next/app/soma/manifest/route.ts +98 -0
  138. package/host-next/app/soma/page/route.ts +36 -0
  139. package/host-next/app/soma/route.ts +9 -0
  140. package/host-next/app/soma-runtime/[...file]/route.ts +21 -0
  141. package/host-next/app/soma-runtime/_shared/static-file.ts +89 -0
  142. package/host-next/bin/host-next.cjs +59 -0
  143. package/host-next/instrumentation.ts +13 -0
  144. package/host-next/next-env.d.ts +7 -0
  145. package/host-next/next.config.js +382 -0
  146. package/host-next/proxy.ts +43 -0
  147. package/host-next/src/shell-routes.cjs +51 -0
  148. package/host-next/src/workspace.ts +543 -0
  149. package/package.json +66 -41
  150. package/tsconfig.json +2 -1
  151. package/core/server/host/page-response-mode.cjs +0 -96
  152. package/core/server/host/page-response-request.ts +0 -33
  153. package/core/server/host/request-origin.ts +0 -18
  154. package/core/server/host/soma-request-hook-host.stub.ts +0 -4
  155. package/core/server/runtime-space/migrate-sources.ts +0 -124
  156. package/core/shared/source-compat.ts +0 -9
  157. package/dist/types/server/host/page-response-request.d.ts +0 -8
  158. package/dist/types/server/host/request-origin.d.ts +0 -1
  159. package/dist/types/server/host/soma-request-hook-host.stub.d.ts +0 -2
  160. package/dist/types/server/runtime-space/migrate-sources.d.ts +0 -19
  161. /package/dist/types/shared/{source-compat.d.ts → source-file-suffix.d.ts} +0 -0
@@ -0,0 +1,382 @@
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
+ const webpackCacheMode = readSomaWebpackCacheMode();
35
+
36
+ // 壳自有路由(app/ 枚举):经环境变量交给页面入口并入装配的 reservedRoutes(app/soma/_shared/host-prepare.ts)。
37
+ // next.config.js 的 __dirname 是 host-next 目录(工作区里的 next.config.js 只是转 require),app/ 与工作区里复制的 app/ 同源。
38
+ process.env.SOMA_SHELL_ROUTES = JSON.stringify(enumerateShellRoutes(path.join(__dirname, 'app')));
39
+
40
+ function readJson(filePath) {
41
+ try {
42
+ if (!fs.existsSync(filePath)) return null;
43
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * The generated Next workspace is intentionally isolated from a Host's
51
+ * node_modules. Resolve source-linked packages from their public exports map,
52
+ * never from a broad package-root alias: the latter makes unexported deep
53
+ * imports appear valid locally and fail after publication.
54
+ *
55
+ * Webpack aliases do not model package-export wildcards. Never map a wildcard
56
+ * to a directory-prefix alias: Webpack normalises `..` after that replacement,
57
+ * which can turn an exported namespace into an escape hatch. Instead, expand
58
+ * matching files into individual `$` exact aliases alongside concrete entries.
59
+ */
60
+ function isSafePackageChild(packageRoot, candidate) {
61
+ return candidate === packageRoot || candidate.startsWith(`${packageRoot}${path.sep}`);
62
+ }
63
+
64
+ function collectFiles(root) {
65
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];
66
+ const files = [];
67
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
68
+ const fullPath = path.join(root, entry.name);
69
+ if (entry.isDirectory()) files.push(...collectFiles(fullPath));
70
+ else if (entry.isFile()) files.push(fullPath);
71
+ }
72
+ return files;
73
+ }
74
+
75
+ function isSafeExportWildcardValue(value) {
76
+ return value.length > 0
77
+ && !path.isAbsolute(value)
78
+ && value.split(/[\\/]/).every((segment) => segment !== '' && segment !== '.' && segment !== '..');
79
+ }
80
+
81
+ function expandWildcardExportAliases(packageName, packageRoot, entry, target) {
82
+ if ((entry.match(/\*/g) ?? []).length !== 1 || (target.match(/\*/g) ?? []).length !== 1) return {};
83
+ const entryStar = entry.indexOf('*');
84
+ const targetStar = target.indexOf('*');
85
+ const entryPrefix = entry.slice(0, entryStar);
86
+ const entrySuffix = entry.slice(entryStar + 1);
87
+ const targetPrefix = target.slice(0, targetStar);
88
+ const targetSuffix = target.slice(targetStar + 1);
89
+ const sourceRoot = path.resolve(packageRoot, targetPrefix);
90
+ if (!isSafePackageChild(packageRoot, sourceRoot)) return {};
91
+
92
+ const aliases = {};
93
+ for (const filePath of collectFiles(sourceRoot)) {
94
+ const relative = path.relative(sourceRoot, filePath).split(path.sep).join('/');
95
+ if (!relative.endsWith(targetSuffix)) continue;
96
+ const wildcardValue = relative.slice(0, relative.length - targetSuffix.length);
97
+ if (!isSafeExportWildcardValue(wildcardValue)) continue;
98
+ const publicPath = `${entryPrefix.slice(2)}${wildcardValue}${entrySuffix}`;
99
+ if (!isSafeExportWildcardValue(publicPath)) continue;
100
+ aliases[`${packageName}/${publicPath}$`] = filePath;
101
+ }
102
+ return aliases;
103
+ }
104
+
105
+ function readPublicWebpackAliases(packageName, packageRoot) {
106
+ const exportsMap = readJson(path.join(packageRoot, 'package.json'))?.exports;
107
+ if (!exportsMap || typeof exportsMap !== 'object') return {};
108
+
109
+ const exactAliases = {};
110
+ const wildcardAliases = {};
111
+ for (const [entry, descriptor] of Object.entries(exportsMap)) {
112
+ if (entry !== '.' && !entry.startsWith('./')) continue;
113
+ const target = typeof descriptor === 'string'
114
+ ? descriptor
115
+ : descriptor?.import ?? descriptor?.default;
116
+ if (typeof target !== 'string' || !target.startsWith('./')) continue;
117
+
118
+ const isWildcard = entry.includes('*') || target.includes('*');
119
+ if (entry.includes('*') !== target.includes('*')) continue;
120
+ if (isWildcard) {
121
+ Object.assign(wildcardAliases, expandWildcardExportAliases(packageName, packageRoot, entry, target));
122
+ continue;
123
+ }
124
+
125
+ const resolved = path.resolve(packageRoot, target);
126
+ if (!isSafePackageChild(packageRoot, resolved) || !fs.existsSync(resolved)) continue;
127
+ const publicPath = entry === '.' ? '' : entry.slice(2);
128
+ const specifier = publicPath ? `${packageName}/${publicPath}` : packageName;
129
+ exactAliases[`${specifier}$`] = resolved;
130
+ }
131
+ // A concrete export wins if it overlaps an expanded wildcard pattern.
132
+ return { ...wildcardAliases, ...exactAliases };
133
+ }
134
+
135
+ function readCorePublicWebpackAliases() {
136
+ return readPublicWebpackAliases('soma-core', coreRoot);
137
+ }
138
+
139
+ function resolveSafeChildRoot(parent, relativePath) {
140
+ const trimmed = typeof relativePath === 'string' ? relativePath.trim() : '';
141
+ if (!trimmed) return parent;
142
+
143
+ const resolved = path.resolve(parent, trimmed);
144
+ if ((resolved === parent || resolved.startsWith(`${parent}${path.sep}`)) && fs.existsSync(resolved)) {
145
+ return resolved;
146
+ }
147
+ return parent;
148
+ }
149
+
150
+ // Host 源码根同取 core 的唯一实现(source-packages.cjs)。
151
+ const hostSourceRoot = getSomaHostSourceRoot(hostDir);
152
+ function runtimeWatchIgnoreDirectories(env = process.env) {
153
+ // runtime 根(唯一解析,含 prewarm/、static/、bindings/ 等全部子目录)+ 各目录环境变量。
154
+ // 复核结论(R-18):缺省根 <host>/.soma/runtime 与工作区 <host>/.soma/next 是同级目录,互不包含;
155
+ // 根被配到别处时仍由 resolveSomaRuntimeRoot 的结果覆盖,所以监听清单只需这一项加别名。
156
+ const { resolveSomaRuntimeRoot } = require(path.join(coreRoot, 'core/server/runtime-space/root.cjs'));
157
+ let runtimeRoot;
158
+ try {
159
+ runtimeRoot = resolveSomaRuntimeRoot(hostDir, env);
160
+ } catch {
161
+ runtimeRoot = undefined; // 越界由 core 启动期拒绝;这里只负责监听清单,不重复抛错
162
+ }
163
+ const directories = [
164
+ runtimeRoot,
165
+ env.SOMA_RUNTIME_DIR && path.resolve(hostDir, env.SOMA_RUNTIME_DIR),
166
+ env.SOMA_AI_METRICS_DIR,
167
+ env.SOMA_AI_FAILURE_DIR,
168
+ ].filter((value) => typeof value === 'string' && value.trim() !== '');
169
+ return [...new Set(directories.map((directory) => path.resolve(directory).replaceAll(path.sep, '/')))];
170
+ }
171
+
172
+ function escapeRegExp(value) {
173
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
174
+ }
175
+
176
+ function mergeWatchIgnored(existingIgnored) {
177
+ const directories = runtimeWatchIgnoreDirectories();
178
+ const patterns = directories.map((directory) => `${directory}/**`);
179
+ if (existingIgnored === undefined) return patterns;
180
+ if (existingIgnored instanceof RegExp) {
181
+ const runtimeSource = directories
182
+ .map((directory) => `${escapeRegExp(directory)}(?:[\\\\/]|$)`)
183
+ .join('|');
184
+ return new RegExp(`(?:${existingIgnored.source})|(?:${runtimeSource})`, existingIgnored.flags);
185
+ }
186
+ return [...(Array.isArray(existingIgnored) ? existingIgnored : [existingIgnored]), ...patterns];
187
+ }
188
+
189
+ function resolveOptionalHostSourceFile(relativePath, fallbackPath) {
190
+ const hostFile = path.resolve(hostSourceRoot, relativePath);
191
+ if (fs.existsSync(hostFile)) {
192
+ return hostFile;
193
+ }
194
+ return path.resolve(coreRoot, fallbackPath);
195
+ }
196
+
197
+ function readHostFileDependencyEntries() {
198
+ const packageJsonPath = path.join(hostDir, 'package.json');
199
+ if (!fs.existsSync(packageJsonPath)) {
200
+ return [];
201
+ }
202
+
203
+ try {
204
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
205
+ const dependencies = {
206
+ ...(packageJson.dependencies ?? {}),
207
+ ...(packageJson.devDependencies ?? {}),
208
+ };
209
+ return Object.entries(dependencies)
210
+ .filter(([, version]) => typeof version === 'string' && version.startsWith('file:'))
211
+ .map(([name, version]) => ({
212
+ name,
213
+ root: path.resolve(hostDir, String(version).slice('file:'.length)),
214
+ }))
215
+ .filter((entry) => fs.existsSync(entry.root));
216
+ } catch {
217
+ return [];
218
+ }
219
+ }
220
+
221
+ function readEnvTranspilePackages() {
222
+ return String(process.env.SOMA_TRANSPILE_PACKAGES ?? '')
223
+ .split(',')
224
+ .map((item) => item.trim())
225
+ .filter(Boolean);
226
+ }
227
+
228
+ // 源包名清单取自 core 的唯一实现(server/host/source-packages.cjs),壳里不再自带「哪些包是源包」的判定。
229
+ function readHostSourcePackageNames() {
230
+ return listSomaSourcePackageNames(hostDir);
231
+ }
232
+
233
+ const hostFileDependencyEntries = readHostFileDependencyEntries();
234
+ const transpilePackages = [
235
+ ...new Set([
236
+ 'soma-core',
237
+ ...hostFileDependencyEntries.map((entry) => entry.name),
238
+ ...readHostSourcePackageNames(),
239
+ ...readEnvTranspilePackages(),
240
+ ]),
241
+ ];
242
+
243
+ /**
244
+ * 构建期是否再跑一遍类型检查 / lint。
245
+ *
246
+ * 缺省跑(单机开发时这是最后一道拦截)。设 SOMA_BUILD_SKIP_CHECKS=1 可跳过——
247
+ * 两种场景需要它:
248
+ * 1. CI 里 `npm run verify` 已经按包跑过 `tsc --noEmit` 与 eslint,构建期重复一遍
249
+ * 只是把同一件事做两次;
250
+ * 2. **小内存机器**:实测本仓在 2GB 机器上做生产构建,编译阶段能过,
251
+ * 到"Linting and checking validity of types"时可用内存掉到 197MB,
252
+ * 构建 worker 直接被 SIGTERM(而 Next 只留下一句
253
+ * `build worker exited with code: null and signal: SIGTERM`,很容易被当成玄学)。
254
+ */
255
+ const skipBuildChecks = process.env.SOMA_BUILD_SKIP_CHECKS === '1';
256
+
257
+ /**
258
+ * dev 服务器允许的访问来源。
259
+ *
260
+ * Next 16 起 dev 资源(HMR 与按需 chunk)默认只认 `localhost`,从 `127.0.0.1` 打开同一台
261
+ * 机器上的同一个服务会被判为跨 origin 而拦截。症状很有欺骗性:页面本身 200,
262
+ * 但 `next/dynamic` 的 chunk 永远拿不到,整页停在 "Loading page…",看起来像 SOMA 没挂载。
263
+ * 回环地址与 localhost 指向同一主机,这里补齐;反代域名等额外来源用
264
+ * `SOMA_DEV_ORIGINS`(逗号分隔)追加,不放宽到通配。
265
+ */
266
+ const allowedDevOrigins = [
267
+ ...new Set([
268
+ 'localhost',
269
+ '127.0.0.1',
270
+ '[::1]',
271
+ ...String(process.env.SOMA_DEV_ORIGINS ?? '')
272
+ .split(',')
273
+ .map((item) => item.trim())
274
+ .filter(Boolean),
275
+ ]),
276
+ ];
277
+
278
+ const nextConfig = {
279
+ env: {
280
+ SOMA_SHELL_ROUTES: process.env.SOMA_SHELL_ROUTES,
281
+ },
282
+
283
+ allowedDevOrigins,
284
+ // 关掉 Next 开发浮层(<nextjs-portal>):它会压住控件、污染可用性门的截图与遮挡检查
285
+ devIndicators: false,
286
+
287
+ ...(skipBuildChecks
288
+ ? { typescript: { ignoreBuildErrors: true } }
289
+ : {}),
290
+
291
+ serverExternalPackages: ['jiti'],
292
+
293
+ experimental: {
294
+ externalDir: true,
295
+ // 低内存构建:并行 worker 是构建期内存的主要来源,小内存机器上把它压到 1
296
+ ...(skipBuildChecks ? { cpus: 1, workerThreads: false } : {}),
297
+ },
298
+
299
+ transpilePackages,
300
+
301
+ webpack: (config, { dev, isServer, webpack: webpackInstance }) => {
302
+ if (webpackCacheMode === 'memory' && dev) {
303
+ config.cache = { type: 'memory' };
304
+ }
305
+ if (dev) {
306
+ config.watchOptions = {
307
+ ...config.watchOptions,
308
+ ignored: mergeWatchIgnored(config.watchOptions?.ignored),
309
+ };
310
+ }
311
+ config.resolve.alias['@'] = coreRoot;
312
+ Object.assign(config.resolve.alias, readCorePublicWebpackAliases());
313
+ config.resolve.alias['@core'] = path.resolve(coreRoot, 'core');
314
+ for (const entry of hostFileDependencyEntries) {
315
+ // soma-core is resolved above from its own exports map. Other source
316
+ // linked packages get the same treatment instead of a broad root alias.
317
+ if (entry.name === 'soma-core') continue;
318
+ const packageJson = readJson(path.join(entry.root, 'package.json'));
319
+ if (packageJson?.soma?.configRoot) {
320
+ config.resolve.alias[`${entry.name}/config`] = resolveSafeChildRoot(
321
+ entry.root,
322
+ packageJson.soma.configRoot,
323
+ );
324
+ }
325
+ const publicAliases = readPublicWebpackAliases(entry.name, entry.root);
326
+ Object.assign(config.resolve.alias, publicAliases);
327
+ }
328
+ // 浏览器引导选项:只取 soma.app.ts(defineSomaApp 装配)的 host.bootstrap();没有 soma.app.ts 走桩(空选项)
329
+ config.resolve.alias['@soma-host/bootstrap/soma-bootstrap'] = path.resolve(
330
+ coreRoot,
331
+ fs.existsSync(path.resolve(hostSourceRoot, 'soma.app.ts'))
332
+ ? 'core/client/host-bridge/soma-bootstrap-from-app.ts'
333
+ : 'core/client/host-bridge/soma-bootstrap-host.stub.ts',
334
+ );
335
+ // soma.app.ts 用 `server: () => import('./soma.server')` 惰性交入服务端面(身份 / 虚拟页 / 请求钩子,含 fs 等);
336
+ // Next.js Client Component 的 SSR 与 Browser 编译层均不得跟进服务端面,统一用 IgnorePlugin 截断。
337
+ const hasHostDomainUi = fs.existsSync(path.resolve(hostSourceRoot, 'domain/ui'));
338
+ if (webpackInstance) {
339
+ config.plugins.push(new webpackInstance.IgnorePlugin({
340
+ checkResource(resource) {
341
+ if (/soma\.server/.test(resource)) return true;
342
+ if (!hasHostDomainUi && resource.startsWith('@soma-host/domain/ui')) return true;
343
+ return false;
344
+ },
345
+ }));
346
+ }
347
+ config.resolve.alias['@soma-host/bootstrap/soma-domain-loaders'] = resolveOptionalHostSourceFile(
348
+ 'bootstrap/soma-domain-loaders.ts',
349
+ 'core/client/host-bridge/soma-domain-loaders.stub.ts',
350
+ );
351
+ config.resolve.alias['@soma-host'] = hostSourceRoot;
352
+
353
+ config.plugins.push(new SomaManifestWebpackPlugin({ hostDir }));
354
+
355
+ config.module.rules.push(
356
+ {
357
+ test: /_(ui|event|style)\.ya?ml$/,
358
+ type: 'javascript/auto',
359
+ use: [
360
+ { loader: path.resolve(coreRoot, 'core/build/compiler/soma-webpack-loader.js') },
361
+ ],
362
+ },
363
+ {
364
+ test: /\.(config|locale(\.[a-zA-Z-]+)?)\.ya?ml$/,
365
+ type: 'javascript/auto',
366
+ use: [
367
+ { loader: path.resolve(coreRoot, 'core/build/compiler/soma-webpack-loader.js') },
368
+ ],
369
+ },
370
+ { test: /\.html$/, type: 'asset/source' },
371
+ {
372
+ test: /\.ya?ml$/,
373
+ exclude: /_(ui|event|style)\.ya?ml$|\.(config|locale(\.[a-zA-Z-]+)?)\.ya?ml$/,
374
+ type: 'asset/source',
375
+ },
376
+ { test: /\.md$/, type: 'asset/source' },
377
+ );
378
+ return config;
379
+ },
380
+ };
381
+
382
+ module.exports = nextConfig;
@@ -0,0 +1,43 @@
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
+ };
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+ // 壳路由枚举(需求单 R-18):从 `app/` 目录枚举壳自己占用的 URL,登记为宿主装配的 `reservedRoutes`。
3
+ //
4
+ // 规则(Next App Router 约定):
5
+ // · 含 `page.*` 或 `route.*` 的目录才是路由;
6
+ // · 路由组 `(x)` 不进 URL;`_x` 私有目录与 `@x` 并行槽位不是路由,整棵跳过;
7
+ // · 遇到动态段 `[x]` / `[...x]` / `[[...x]]` 就截到它之前(`app/api/[...path]` → `/api`);
8
+ // 截完是空(根 `/` 与根级 catch-all `[...path]`)的不登记——那是 SOMA 页面入口本身,不是壳占用的地址;
9
+ // · 结果去重、排序,形状符合 core 对 `reservedRoutes` 的要求(`/` 起首、无空白 / `?` / `#` / `//`、≤ 256)。
10
+ // CJS:next.config.js 直接 require;测试经 createRequire。
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+
15
+ const ROUTE_FILE = /^(page|route)\.(tsx|ts|jsx|js|mjs)$/;
16
+ const DYNAMIC_SEGMENT = /^\[.*\]$/;
17
+ const ROUTE_GROUP = /^\(.*\)$/;
18
+ const SHAPE_FORBIDDEN = /[\s?#]|\/\//;
19
+
20
+ function enumerateShellRoutes(appDir) {
21
+ const found = new Set();
22
+ if (!fs.existsSync(appDir) || !fs.statSync(appDir).isDirectory()) return [];
23
+
24
+ function walk(dir, segments, sawDynamic) {
25
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
26
+ if (entries.some((entry) => entry.isFile() && ROUTE_FILE.test(entry.name))) {
27
+ if (segments.length > 0) found.add('/' + segments.join('/'));
28
+ }
29
+ for (const entry of entries) {
30
+ if (!entry.isDirectory()) continue;
31
+ const name = entry.name;
32
+ if (name.startsWith('_') || name.startsWith('@')) continue;
33
+ const child = path.join(dir, name);
34
+ if (ROUTE_GROUP.test(name)) {
35
+ walk(child, segments, sawDynamic);
36
+ } else if (DYNAMIC_SEGMENT.test(name) || sawDynamic) {
37
+ // 动态段之下的路由都归它的静态前缀(已登记),只需继续看其子树里有没有路由文件以登记前缀本身
38
+ walk(child, segments, true);
39
+ } else {
40
+ walk(child, [...segments, name], false);
41
+ }
42
+ }
43
+ }
44
+ walk(appDir, [], false);
45
+
46
+ return [...found]
47
+ .filter((route) => route.length <= 256 && !SHAPE_FORBIDDEN.test(route))
48
+ .sort();
49
+ }
50
+
51
+ module.exports = { enumerateShellRoutes };