soma-core 2.1.6 → 2.2.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 (70) 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/server/api/dispatch-service-api.ts +212 -0
  5. package/core/server/api/load-host-service.ts +230 -56
  6. package/core/server/api/service-path.ts +79 -14
  7. package/core/server/engines/style/candidate-guard.ts +57 -0
  8. package/core/server/engines/style/index.ts +1 -1
  9. package/core/server/engines/style/tailwind-adapter.ts +83 -16
  10. package/core/server/host/source-packages.cjs +98 -30
  11. package/core/server/host/source-packages.ts +12 -5
  12. package/core/server/index.ts +39 -17
  13. package/core/server/infra/cache/ServerFileCache.ts +138 -25
  14. package/core/server/node.ts +32 -8
  15. package/dist/cli/soma.js +68 -14
  16. package/dist/host-native/aot-builder.cjs +852 -0
  17. package/dist/host-native/native-server.cjs +15341 -0
  18. package/dist/types/server/api/dispatch-service-api.d.ts +18 -0
  19. package/dist/types/server/api/load-host-service.d.ts +7 -2
  20. package/dist/types/server/api/service-path.d.ts +21 -1
  21. package/dist/types/server/engines/style/candidate-guard.d.ts +10 -0
  22. package/dist/types/server/engines/style/index.d.ts +1 -1
  23. package/dist/types/server/engines/style/tailwind-adapter.d.ts +12 -0
  24. package/dist/types/server/host/source-packages.d.cts +13 -1
  25. package/dist/types/server/host/source-packages.d.ts +7 -4
  26. package/dist/types/server/index.d.ts +18 -17
  27. package/dist/types/server/infra/cache/ServerFileCache.d.ts +28 -5
  28. package/dist/types/server/node.d.ts +10 -7
  29. package/host-native/bin/host-native.cjs +204 -0
  30. package/host-native/client/browser-entry.ts +499 -0
  31. package/{host-next/app → host-native/client}/page-access.ts +12 -0
  32. package/host-native/client/router-bridge.ts +120 -0
  33. package/host-native/src/aot-builder.ts +486 -0
  34. package/host-native/src/csp-headers.ts +75 -0
  35. package/host-native/src/host-prepare.ts +123 -0
  36. package/{host-next/app/soma/manifest/route.ts → host-native/src/manifest-http.ts} +10 -10
  37. package/host-native/src/native-server.ts +691 -0
  38. package/host-native/src/page-http.ts +223 -0
  39. package/host-native/src/public-packages.cjs +167 -0
  40. package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts} +17 -19
  41. package/{host-next → host-native}/src/shell-routes.cjs +23 -13
  42. package/host-native/src/static-file.ts +172 -0
  43. package/host-native/src/workspace.ts +185 -0
  44. package/{host-next/app → host-native/styles}/globals.css +2 -2
  45. package/package.json +12 -31
  46. package/tsconfig.json +1 -1
  47. package/host-next/app/SomaPageClient.tsx +0 -359
  48. package/host-next/app/[...path]/page.tsx +0 -22
  49. package/host-next/app/api/[...path]/route.ts +0 -98
  50. package/host-next/app/components/SomaHostPage.tsx +0 -128
  51. package/host-next/app/components/SomaHydrationShell.tsx +0 -20
  52. package/host-next/app/components/SomaPageClientBoundary.tsx +0 -13
  53. package/host-next/app/components/SomaPageForbidden.tsx +0 -19
  54. package/host-next/app/favicon.ico/route.ts +0 -13
  55. package/host-next/app/layout.tsx +0 -27
  56. package/host-next/app/page.tsx +0 -9
  57. package/host-next/app/router-bridge.ts +0 -42
  58. package/host-next/app/soma/[...path]/route.ts +0 -9
  59. package/host-next/app/soma/_shared/host-prepare.ts +0 -33
  60. package/host-next/app/soma/_shared/page-http.ts +0 -86
  61. package/host-next/app/soma/page/route.ts +0 -36
  62. package/host-next/app/soma/route.ts +0 -9
  63. package/host-next/app/soma-runtime/[...file]/route.ts +0 -21
  64. package/host-next/app/soma-runtime/_shared/static-file.ts +0 -89
  65. package/host-next/bin/host-next.cjs +0 -60
  66. package/host-next/instrumentation.ts +0 -18
  67. package/host-next/next-env.d.ts +0 -7
  68. package/host-next/next.config.js +0 -410
  69. package/host-next/proxy.ts +0 -43
  70. package/host-next/src/workspace.ts +0 -543
@@ -0,0 +1,486 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import esbuild, { type BuildContext, type Plugin } from 'esbuild';
5
+ import { readAllSomaPublicAliases } from './public-packages.cjs';
6
+ import { toPascalCase } from '../../core/server/api/service-path';
7
+ import { getSomaHostSourceRoot, getSomaHostApiRoot } from '../../core/server/host/source-packages.cjs';
8
+
9
+ export interface BuildBrowserClientOptions {
10
+ readonly hostDir: string;
11
+ readonly webRoot?: string;
12
+ readonly outDir: string;
13
+ readonly dev: boolean;
14
+ readonly env?: NodeJS.ProcessEnv;
15
+ }
16
+
17
+ export interface BrowserClientBuildResult {
18
+ readonly entryUrl: string;
19
+ readonly cssUrl: string;
20
+ readonly cssText: string;
21
+ rebuild(): Promise<void>;
22
+ dispose(): Promise<void>;
23
+ }
24
+
25
+ export interface BuildServerAotOptions {
26
+ readonly hostDir: string;
27
+ readonly webRoot?: string;
28
+ readonly apiRoot?: string;
29
+ readonly outDir: string;
30
+ readonly env?: NodeJS.ProcessEnv;
31
+ }
32
+
33
+ export interface ServerAotManifest {
34
+ readonly hostDir: string;
35
+ readonly webRoot: string;
36
+ readonly apiRoot: string;
37
+ readonly builtAt: string;
38
+ readonly routes: Record<string, string>;
39
+ readonly hostAppCompiledPath?: string;
40
+ }
41
+
42
+
43
+ function resolveModuleFile(baseDir: string, subpath: string): string {
44
+ const target = subpath ? path.resolve(baseDir, subpath) : path.resolve(baseDir);
45
+ for (const ext of ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']) {
46
+ const candidate = target + ext;
47
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
48
+ return candidate;
49
+ }
50
+ }
51
+ if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
52
+ for (const index of ['index.ts', 'index.tsx', 'index.js', 'index.mjs', 'index.cjs']) {
53
+ const candidate = path.join(target, index);
54
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
55
+ return candidate;
56
+ }
57
+ }
58
+ }
59
+ return target;
60
+ }
61
+
62
+ const coreRoot = path.resolve(__dirname, '../..');
63
+ const hostNativeRoot = path.join(coreRoot, 'host-native');
64
+ const repoRoot = path.resolve(coreRoot, '..');
65
+
66
+ /**
67
+ * 客户端专属 esbuild 插件:
68
+ * 1. 严禁 import 'server-only';
69
+ * 2. 映射 @soma-host/* 虚拟/可选模块;
70
+ * 3. 映射 soma-* 公开子路径。
71
+ */
72
+ function createBrowserClientPlugin(options: {
73
+ hostDir: string;
74
+ webRoot: string;
75
+ }): Plugin {
76
+ const { hostDir, webRoot } = options;
77
+ const publicAliases = readAllSomaPublicAliases(hostDir, repoRoot, [webRoot, coreRoot]) as Record<string, string>;
78
+
79
+ return {
80
+ name: 'soma-browser-client-plugin',
81
+ setup(build) {
82
+ // 1. 硬拦截 server-only
83
+ build.onResolve({ filter: /^server-only$/ }, (args) => {
84
+ throw new Error(
85
+ `[soma] Client bundle must not import 'server-only'! Boundary violation detected from ${args.importer}`,
86
+ );
87
+ });
88
+
89
+ // 2. @soma-host/bootstrap/soma-bootstrap
90
+ build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-bootstrap$/ }, () => {
91
+ const candidateHostFile = path.resolve(webRoot, 'bootstrap/soma-bootstrap');
92
+ for (const ext of ['.ts', '.js', '.mjs']) {
93
+ if (fs.existsSync(candidateHostFile + ext)) {
94
+ return { path: candidateHostFile + ext };
95
+ }
96
+ }
97
+ if (fs.existsSync(path.resolve(webRoot, 'soma.app.ts'))) {
98
+ return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-from-app.ts') };
99
+ }
100
+ return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-host.stub.ts') };
101
+ });
102
+
103
+ // 3. @soma-host/bootstrap/soma-domain-loaders
104
+ build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-domain-loaders$/ }, () => {
105
+ const candidateLoader = path.resolve(webRoot, 'bootstrap/soma-domain-loaders');
106
+ for (const ext of ['.ts', '.js', '.mjs']) {
107
+ if (fs.existsSync(candidateLoader + ext)) {
108
+ return { path: candidateLoader + ext };
109
+ }
110
+ }
111
+ return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-domain-loaders.stub.ts') };
112
+ });
113
+
114
+ // 4. @soma-host/domain/ui/*Class.ts 按需动态分片加载或缺失抛错
115
+ build.onResolve({ filter: /^@soma-host\/domain\/ui\/.*Class\.ts$/ }, (args) => {
116
+ const baseName = path.basename(args.path);
117
+ const diskFile = path.resolve(webRoot, 'domain/ui', baseName);
118
+ if (fs.existsSync(diskFile)) {
119
+ return { path: diskFile };
120
+ }
121
+ return {
122
+ path: args.path,
123
+ namespace: 'soma-absent-domain',
124
+ };
125
+ });
126
+
127
+ build.onLoad({ filter: /.*/, namespace: 'soma-absent-domain' }, (args) => {
128
+ return {
129
+ contents: `
130
+ const err = new Error("Cannot find module '${args.path}'");
131
+ err.code = "MODULE_NOT_FOUND";
132
+ throw err;
133
+ `,
134
+ loader: 'js',
135
+ };
136
+ });
137
+
138
+ // 5. 其他 @soma-host/* 解析到 webRoot
139
+ build.onResolve({ filter: /^@soma-host(?:\/.*)?$/ }, (args) => {
140
+ const subpath = args.path.replace(/^@soma-host\/?/, '');
141
+ const target = path.resolve(webRoot, subpath);
142
+ for (const ext of ['', '.ts', '.tsx', '.js', '.jsx', '.mjs']) {
143
+ if (fs.existsSync(target + ext) && fs.statSync(target + ext).isFile()) {
144
+ return { path: target + ext };
145
+ }
146
+ }
147
+ if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
148
+ for (const index of ['index.ts', 'index.tsx', 'index.js', 'index.jsx']) {
149
+ if (fs.existsSync(path.join(target, index))) {
150
+ return { path: path.join(target, index) };
151
+ }
152
+ }
153
+ }
154
+ return { path: target };
155
+ });
156
+
157
+ // 6. 拦截内部 engine 模块私有深导入(RT4 守卫)
158
+ build.onResolve({ filter: /core\/client\/engine\// }, (args) => {
159
+ if (!args.importer.includes('soma-core')) {
160
+ throw new Error(
161
+ `[soma] Deep import forbidden: '${args.path}' from '${args.importer}'. Import from 'soma-core/runtime' instead.`,
162
+ );
163
+ }
164
+ return undefined;
165
+ });
166
+
167
+ // 7. soma-* 公开子路径解析
168
+ build.onResolve({ filter: /^soma-[a-z0-9-]+(?:\/.*)?$/ }, (args) => {
169
+ const direct = publicAliases[args.path];
170
+ if (direct && fs.existsSync(direct)) {
171
+ return { path: direct };
172
+ }
173
+ return undefined;
174
+ });
175
+ },
176
+ };
177
+ }
178
+
179
+ /**
180
+ * 客户端 AOT 预编译打包:输出浏览器 ESM 分片与 globals.css
181
+ */
182
+ export async function buildBrowserClient(
183
+ options: BuildBrowserClientOptions,
184
+ ): Promise<BrowserClientBuildResult> {
185
+ const hostDir = path.resolve(options.hostDir);
186
+ const webRoot = path.resolve(options.webRoot || getSomaHostSourceRoot(hostDir, options.env));
187
+ const outDir = path.resolve(options.outDir);
188
+ const clientOutDir = path.join(outDir, 'client');
189
+ fs.mkdirSync(clientOutDir, { recursive: true });
190
+
191
+ const clientEntry = path.join(hostNativeRoot, 'client/browser-entry.ts');
192
+ const plugin = createBrowserClientPlugin({ hostDir, webRoot });
193
+
194
+ // 编译并输出 CSS
195
+ const cssSourcePath = path.join(hostNativeRoot, 'styles/globals.css');
196
+ let rawCss = '';
197
+ try {
198
+ rawCss = fs.readFileSync(cssSourcePath, 'utf8');
199
+ } catch {
200
+ rawCss = '/* soma globals */\n';
201
+ }
202
+
203
+ let finalCss = rawCss;
204
+ if (!options.dev) {
205
+ const minifiedCss = await esbuild.transform(rawCss, {
206
+ loader: 'css',
207
+ minify: true,
208
+ });
209
+ finalCss = minifiedCss.code;
210
+ }
211
+
212
+ let cssFileName = 'globals.css';
213
+ if (!options.dev) {
214
+ const hash = createHash('sha256').update(finalCss).digest('hex').slice(0, 8);
215
+ cssFileName = `globals-${hash}.css`;
216
+ }
217
+ fs.writeFileSync(path.join(clientOutDir, cssFileName), finalCss, 'utf8');
218
+ const cssUrl = `/_soma/client/${cssFileName}`;
219
+
220
+ const buildOptions: esbuild.BuildOptions = {
221
+ entryPoints: {
222
+ 'browser-entry': clientEntry,
223
+ },
224
+ outdir: clientOutDir,
225
+ bundle: true,
226
+ format: 'esm',
227
+ splitting: true,
228
+ platform: 'browser',
229
+ target: ['es2022'],
230
+ minify: !options.dev,
231
+ sourcemap: options.dev ? 'inline' : false,
232
+ entryNames: options.dev ? '[name]' : '[name]-[hash]',
233
+ chunkNames: options.dev ? 'chunks/[name]' : 'chunks/[name]-[hash]',
234
+ nodePaths: [path.join(webRoot, 'node_modules'), path.join(hostDir, 'node_modules'), path.join(coreRoot, 'node_modules')].filter((d) => fs.existsSync(d)),
235
+ plugins: [plugin],
236
+ define: {
237
+ 'process.env.NODE_ENV': JSON.stringify(options.dev ? 'development' : 'production'),
238
+ },
239
+ };
240
+
241
+ let ctx: BuildContext | null = null;
242
+ let entryUrl = '/_soma/client/browser-entry.js';
243
+
244
+ if (options.dev) {
245
+ ctx = await esbuild.context(buildOptions);
246
+ await ctx.rebuild();
247
+ entryUrl = '/_soma/client/browser-entry.js';
248
+ } else {
249
+ const result = await esbuild.build({
250
+ ...buildOptions,
251
+ metafile: true,
252
+ });
253
+ if (result.metafile) {
254
+ for (const [outputPath, meta] of Object.entries(result.metafile.outputs)) {
255
+ if (
256
+ meta.entryPoint &&
257
+ (meta.entryPoint.endsWith('browser-entry.ts') || path.basename(outputPath).startsWith('browser-entry')) &&
258
+ outputPath.endsWith('.js')
259
+ ) {
260
+ const fileName = path.basename(outputPath);
261
+ entryUrl = `/_soma/client/${fileName}`;
262
+ break;
263
+ }
264
+ }
265
+ }
266
+ }
267
+
268
+ if (!options.dev) {
269
+ fs.writeFileSync(
270
+ path.join(clientOutDir, 'client-manifest.json'),
271
+ JSON.stringify({ entryUrl, cssUrl, cssText: finalCss }, null, 2) + '\n',
272
+ 'utf8',
273
+ );
274
+ }
275
+
276
+ return {
277
+ entryUrl,
278
+ cssUrl,
279
+ cssText: finalCss,
280
+ rebuild: async () => {
281
+ if (ctx) {
282
+ await ctx.rebuild();
283
+ }
284
+ },
285
+ dispose: async () => {
286
+ if (ctx) {
287
+ await ctx.dispose();
288
+ }
289
+ },
290
+ };
291
+ }
292
+
293
+ /**
294
+ * 后端 AOT 预编译:扫描后端服务源文件及 soma.app.ts,内联编译成 Node CJS 极速产物并生成 aot-manifest.json
295
+ */
296
+ export async function buildServerAot(
297
+ options: BuildServerAotOptions,
298
+ ): Promise<ServerAotManifest> {
299
+ const hostDir = path.resolve(options.hostDir);
300
+ const webRoot = path.resolve(options.webRoot || getSomaHostSourceRoot(hostDir, options.env));
301
+ const apiRoot = path.resolve(options.apiRoot || getSomaHostApiRoot(hostDir, options.env));
302
+ const outDir = path.resolve(options.outDir);
303
+ const aotServerDir = path.join(outDir, 'aot-server');
304
+ fs.mkdirSync(aotServerDir, { recursive: true });
305
+
306
+ const serviceFiles = scanServiceFiles(apiRoot, webRoot);
307
+ const entryPoints: Record<string, string> = {};
308
+ const routes: Record<string, string> = {};
309
+
310
+ for (const item of serviceFiles) {
311
+ const entryName = `services/${item.routeKey.replace(/\//g, '_')}`;
312
+ entryPoints[entryName] = item.filePath;
313
+ routes[item.routeKey] = `${entryName}.cjs`;
314
+
315
+ // 支持不同大小写路由键
316
+ const segments = item.routeKey.split('/');
317
+ const pascalKey = segments.slice(0, -1).concat(toPascalCase(segments[segments.length - 1])).join('/');
318
+ if (pascalKey !== item.routeKey) {
319
+ routes[pascalKey] = `${entryName}.cjs`;
320
+ }
321
+ const lowerKey = item.routeKey.toLowerCase();
322
+ if (lowerKey !== item.routeKey) {
323
+ routes[lowerKey] = `${entryName}.cjs`;
324
+ }
325
+ }
326
+
327
+ // 扫描 soma.app.ts
328
+ let hostAppCompiledPath: string | undefined;
329
+ const hostAppPath = path.resolve(webRoot, 'soma.app.ts');
330
+ if (fs.existsSync(hostAppPath)) {
331
+ entryPoints['host-app'] = hostAppPath;
332
+ hostAppCompiledPath = 'host-app.cjs';
333
+ }
334
+
335
+ if (Object.keys(entryPoints).length > 0) {
336
+ await esbuild.build({
337
+ entryPoints,
338
+ outdir: aotServerDir,
339
+ bundle: true,
340
+ platform: 'node',
341
+ format: 'cjs',
342
+ target: 'node20',
343
+ packages: 'external',
344
+ nodePaths: [path.join(apiRoot, 'node_modules'), path.join(webRoot, 'node_modules'), path.join(hostDir, 'node_modules'), path.join(coreRoot, 'node_modules')].filter((d) => fs.existsSync(d)),
345
+ outExtension: { '.js': '.cjs' },
346
+ plugins: [
347
+ {
348
+ name: 'soma-server-aot-plugin',
349
+ setup(build) {
350
+ const publicAliases = readAllSomaPublicAliases(hostDir, repoRoot, [webRoot, apiRoot, coreRoot]) as Record<string, string>;
351
+ build.onResolve({ filter: /^server-only$/ }, () => {
352
+ return { path: path.resolve(coreRoot, 'core/server/host/server-only-noop.cjs') };
353
+ });
354
+ build.onResolve({ filter: /^@core(?:\/.*)?$/ }, (args) => {
355
+ const subpath = args.path.replace(/^@core\/?/, '');
356
+ return { path: resolveModuleFile(path.resolve(coreRoot, 'core'), subpath) };
357
+ });
358
+ build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-bootstrap$/ }, () => {
359
+ const candidateHostFile = path.resolve(webRoot, 'bootstrap/soma-bootstrap');
360
+ for (const ext of ['.ts', '.js', '.mjs']) {
361
+ if (fs.existsSync(candidateHostFile + ext)) {
362
+ return { path: candidateHostFile + ext };
363
+ }
364
+ }
365
+ if (fs.existsSync(path.resolve(webRoot, 'soma.app.ts'))) {
366
+ return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-from-app.ts') };
367
+ }
368
+ return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-host.stub.ts') };
369
+ });
370
+ build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-domain-loaders$/ }, () => {
371
+ const candidateLoader = path.resolve(webRoot, 'bootstrap/soma-domain-loaders');
372
+ for (const ext of ['.ts', '.js', '.mjs']) {
373
+ if (fs.existsSync(candidateLoader + ext)) {
374
+ return { path: candidateLoader + ext };
375
+ }
376
+ }
377
+ return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-domain-loaders.stub.ts') };
378
+ });
379
+ build.onResolve({ filter: /^@soma-host\/domain\/ui\/.*Class\.ts$/ }, (args) => {
380
+ const baseName = path.basename(args.path);
381
+ const diskFile = path.resolve(webRoot, 'domain/ui', baseName);
382
+ if (fs.existsSync(diskFile)) {
383
+ return { path: diskFile };
384
+ }
385
+ return { path: args.path, namespace: 'soma-absent-domain' };
386
+ });
387
+ build.onLoad({ filter: /.*/, namespace: 'soma-absent-domain' }, (args) => ({
388
+ contents: `const err = new Error("Cannot find module '${args.path}'"); err.code = "MODULE_NOT_FOUND"; throw err;`,
389
+ loader: 'js',
390
+ }));
391
+ build.onResolve({ filter: /^@soma-host(?:\/.*)?$/ }, (args) => {
392
+ const subpath = args.path.replace(/^@soma-host\/?/, '');
393
+ return { path: resolveModuleFile(webRoot, subpath) };
394
+ });
395
+ build.onResolve({ filter: /^@soma-api(?:\/.*)?$/ }, (args) => {
396
+ const subpath = args.path.replace(/^@soma-api\/?/, '');
397
+ return { path: resolveModuleFile(apiRoot, subpath) };
398
+ });
399
+ build.onResolve({ filter: /^soma-[a-z0-9-]+(?:\/.*)?$/ }, (args) => {
400
+ const direct = publicAliases[args.path];
401
+ if (direct && fs.existsSync(direct)) {
402
+ return { path: direct };
403
+ }
404
+ return undefined;
405
+ });
406
+ },
407
+ },
408
+ ],
409
+ });
410
+ }
411
+
412
+ const manifest: ServerAotManifest = {
413
+ hostDir,
414
+ webRoot,
415
+ apiRoot,
416
+ builtAt: new Date().toISOString(),
417
+ routes,
418
+ ...(hostAppCompiledPath ? { hostAppCompiledPath } : {}),
419
+ };
420
+
421
+ const manifestPath = path.join(aotServerDir, 'aot-manifest.json');
422
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
423
+
424
+ return manifest;
425
+ }
426
+
427
+ interface ScannedServiceItem {
428
+ readonly routeKey: string;
429
+ readonly filePath: string;
430
+ }
431
+
432
+ function scanServiceFiles(apiRoot: string, webRoot: string): ScannedServiceItem[] {
433
+ const items: ScannedServiceItem[] = [];
434
+ const scannedPaths = new Set<string>();
435
+
436
+ const baseCandidates = [
437
+ { base: path.join(apiRoot, 'api', 'service'), isDirect: false },
438
+ { base: path.join(apiRoot, 'service'), isDirect: false },
439
+ ];
440
+ if (apiRoot !== webRoot) {
441
+ baseCandidates.push({ base: apiRoot, isDirect: true });
442
+ }
443
+
444
+ for (const { base, isDirect } of baseCandidates) {
445
+ if (!fs.existsSync(base)) continue;
446
+ walk(base, base, isDirect);
447
+ }
448
+
449
+ function walk(currentDir: string, baseDir: string, isDirect: boolean) {
450
+ let entries: fs.Dirent[] = [];
451
+ try {
452
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
453
+ } catch {
454
+ return;
455
+ }
456
+
457
+ for (const entry of entries) {
458
+ const name = entry.name;
459
+ if (name.startsWith('.') || name.startsWith('_')) continue;
460
+ if (name === 'node_modules' || name === 'dist' || name === '.soma' || name === '.next') continue;
461
+
462
+ const fullPath = path.join(currentDir, name);
463
+ if (entry.isDirectory()) {
464
+ walk(fullPath, baseDir, isDirect);
465
+ } else if (entry.isFile()) {
466
+ if (!/\.(?:ts|js|mjs|cjs)$/.test(name)) continue;
467
+ if (name.endsWith('.d.ts') || name.includes('.test.') || name.includes('.spec.')) continue;
468
+
469
+ if (scannedPaths.has(fullPath)) continue;
470
+ scannedPaths.add(fullPath);
471
+
472
+ const rel = path.relative(baseDir, fullPath).replace(/\\/g, '/');
473
+ const segments = rel.replace(/\.[^.]+$/, '').split('/');
474
+ // 末段类名转换:如果文件名是 PascalCase(如 Hello),转成 kebab/camel(如 hello)
475
+ const last = segments[segments.length - 1];
476
+ const lowerLast = last.charAt(0).toLowerCase() + last.slice(1);
477
+ segments[segments.length - 1] = lowerLast;
478
+
479
+ const routeKey = segments.join('/');
480
+ items.push({ routeKey, filePath: fullPath });
481
+ }
482
+ }
483
+ }
484
+
485
+ return items;
486
+ }
@@ -0,0 +1,75 @@
1
+ import {
2
+ createSomaCspHeader,
3
+ resolveSomaCspOptionsFromEnv,
4
+ SOMA_CSP_NONCE_HEADER,
5
+ } from '../../core/server/host/content-security-policy';
6
+ import { resolveHostResponseHeaders } from '../../core/server/host/host-response-headers';
7
+ import { somaCspNonceMetadataAsync } from '../../core/server/host/csp-nonce-metadata';
8
+
9
+ export { createSomaCspHeader, resolveSomaCspOptionsFromEnv, SOMA_CSP_NONCE_HEADER };
10
+
11
+ /**
12
+ * 为响应追加 Host 装配自定义头与 SOMA CSP 安全头
13
+ */
14
+ export async function applyHostAndCspHeaders(
15
+ response: Response,
16
+ options: { readonly method: string; readonly pathname: string },
17
+ env: Readonly<Record<string, string | undefined>> = process.env,
18
+ ): Promise<Response> {
19
+ const csp = createSomaCspHeader(resolveSomaCspOptionsFromEnv(env));
20
+ if (csp) {
21
+ response.headers.set(csp.name, csp.value);
22
+ }
23
+
24
+ const extra = await resolveHostResponseHeaders({
25
+ method: options.method,
26
+ pathname: options.pathname,
27
+ });
28
+ if (extra !== undefined) {
29
+ for (const [name, value] of Object.entries(extra)) {
30
+ response.headers.set(name, value);
31
+ }
32
+ }
33
+
34
+ return response;
35
+ }
36
+
37
+ /**
38
+ * 宿主 CSP 中间件(纯原生 Web Request / Response 实现,兼容测试与服务层)
39
+ */
40
+ export async function proxy(
41
+ request: { readonly url: string; readonly method?: string; readonly headers?: HeadersInit },
42
+ env: Readonly<Record<string, string | undefined>> = process.env,
43
+ ): Promise<Response> {
44
+ const csp = createSomaCspHeader(resolveSomaCspOptionsFromEnv(env));
45
+ const responseHeaders = new Headers();
46
+
47
+ if (csp) {
48
+ responseHeaders.set(csp.name, csp.value);
49
+ // 供请求层及测试使用的规范回显头
50
+ responseHeaders.set('x-middleware-request-content-security-policy', csp.value);
51
+ if (csp.nonce) {
52
+ responseHeaders.set(`x-middleware-request-${SOMA_CSP_NONCE_HEADER}`, csp.nonce);
53
+ }
54
+ }
55
+
56
+ const response = new Response(null, { status: 200, headers: responseHeaders });
57
+ const url = new URL(request.url);
58
+ const extra = await resolveHostResponseHeaders({
59
+ method: request.method || 'GET',
60
+ pathname: url.pathname,
61
+ });
62
+ if (extra !== undefined) {
63
+ for (const [name, value] of Object.entries(extra)) {
64
+ response.headers.set(name, value);
65
+ }
66
+ }
67
+ return response;
68
+ }
69
+
70
+ export async function readCspNonceMeta(nonce: string | undefined, env: Record<string, string | undefined> = process.env): Promise<string | undefined> {
71
+ const meta = await somaCspNonceMetadataAsync(async () => ({
72
+ get: (name: string) => (name === SOMA_CSP_NONCE_HEADER ? (nonce ?? null) : null),
73
+ }), env);
74
+ return meta.other?.['csp-nonce'];
75
+ }
@@ -0,0 +1,123 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { assertReservedRoutesShape, loadHostAssembly, registerShellRoutes as registerCoreShellRoutes } from 'soma-core/server/host-assembly';
4
+ import { precompileAll, precompilePage } from '../../core/build/compiler/full-manifest-builder';
5
+ import { addressOfPageBase } from '../../core/build/compiler/page-base-resolver';
6
+ import { loadPageMarkupConfig } from '../../core/server/host/page-markup-config';
7
+ import { resolveHostTreeCompileContext } from '../../core/server/host/resolve-host-tree-context';
8
+ import { runPrewarm, computePrewarmInputsDigest } from '../../core/server/runtime-space/prewarm';
9
+ import { resolveAppConfigPath, resolveHostAppConfigPath } from '../../core/server/host/host-config-paths.cjs';
10
+ import { getSomaAssetSources, collectPageEntries, collectIncludes } from '../../core/server/host/source-packages';
11
+
12
+ export const SOMA_SHELL_ROUTES_ENV = 'SOMA_SHELL_ROUTES';
13
+
14
+ let lastRaw: string | undefined;
15
+ let lastParsed: readonly string[] = [];
16
+
17
+ export function readShellRoutesFromEnv(env: Readonly<Record<string, string | undefined>> = process.env): readonly string[] {
18
+ const raw = env[SOMA_SHELL_ROUTES_ENV];
19
+ if (!raw) return [];
20
+ if (raw === lastRaw) return lastParsed;
21
+
22
+ try {
23
+ const parsed: unknown = JSON.parse(raw);
24
+ assertReservedRoutesShape(parsed);
25
+ const result = Array.isArray(parsed) ? (parsed as string[]) : [];
26
+ lastRaw = raw;
27
+ lastParsed = result;
28
+ return result;
29
+ } catch {
30
+ return [];
31
+ }
32
+ }
33
+
34
+ /** 登记壳路由(转调 core 登记口);环境里没有时什么也不做。返回登记后 core 已知的壳路由 */
35
+ export function registerShellRoutes(shellRoutes: readonly string[] = readShellRoutesFromEnv()): readonly string[] {
36
+ return shellRoutes.length === 0 ? [] : registerCoreShellRoutes(shellRoutes);
37
+ }
38
+
39
+ export async function prepareHostAssembly(hostDir: string | undefined) {
40
+ if (!hostDir) return null;
41
+ const assembly = await loadHostAssembly(hostDir);
42
+ registerShellRoutes();
43
+ return assembly;
44
+ }
45
+
46
+ function readFileOrEmpty(filePath: string): string {
47
+ return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
48
+ }
49
+
50
+ /**
51
+ * 构建期 / 开发期全量页面预热:统一处理原生四件套静态页与方言装配 prewarm() 钩子。
52
+ */
53
+ export async function prewarmHostPages(hostDir: string, env: NodeJS.ProcessEnv = process.env) {
54
+ const resolvedHostDir = path.resolve(hostDir);
55
+ const host = await prepareHostAssembly(resolvedHostDir);
56
+ const sources = getSomaAssetSources(resolvedHostDir, env);
57
+ const pageEntries = collectPageEntries(sources);
58
+ const includes = collectIncludes(sources);
59
+ const htmlFiles = pageEntries.map((entry: { htmlFile: string }) => entry.htmlFile);
60
+ const hostConfigRoot = sources.find((source: { type: string }) => source.type === 'host')?.configRoot ?? resolvedHostDir;
61
+ const hostAppConfigPath = resolveHostAppConfigPath(resolvedHostDir);
62
+ const localeYaml = readFileOrEmpty(path.join(hostConfigRoot, 'locale.yaml'));
63
+ const appConfigYaml = hostAppConfigPath ? readFileOrEmpty(hostAppConfigPath) : '';
64
+
65
+ const shell = precompileAll({ htmlFiles, localeYaml, appConfigYaml, pages: [] });
66
+ const hasIncludes = Object.keys(includes).length > 0;
67
+
68
+ const pages = pageEntries
69
+ .filter(({ htmlFile }: { htmlFile: string }) => !htmlFile.startsWith('shared/') && !htmlFile.startsWith('system/'))
70
+ .map(({ source, htmlFile }: { source: { configRoot: string; assetRoot: string }; htmlFile: string }) => {
71
+ const base = htmlFile.replace(/\.html$/, '');
72
+ const sourceAppConfigPath = resolveAppConfigPath(source.configRoot);
73
+ const uiDir = path.join(source.assetRoot, 'ui');
74
+ const metadata = loadPageMarkupConfig(source.configRoot, base);
75
+ const html = fs.readFileSync(path.join(source.assetRoot, 'html', htmlFile), 'utf8');
76
+ const uiYaml = readFileOrEmpty(path.join(uiDir, `${base}_ui.yaml`));
77
+ const eventYaml = readFileOrEmpty(path.join(source.assetRoot, 'event', `${base}_event.yaml`));
78
+ const styleYaml = readFileOrEmpty(path.join(source.assetRoot, 'style', `${base}_style.yaml`));
79
+ const compileInput = {
80
+ path: `/${base}`,
81
+ html,
82
+ uiYaml,
83
+ ...(eventYaml.trim() ? { eventYaml } : {}),
84
+ ...(styleYaml.trim() ? { styleYaml } : {}),
85
+ ...metadata,
86
+ treeContext: metadata.markup === 'component-tree'
87
+ ? resolveHostTreeCompileContext(resolvedHostDir, { pageBase: base })
88
+ : undefined,
89
+ ...(hasIncludes ? { includes } : {}),
90
+ appConfigYaml: sourceAppConfigPath
91
+ ? readFileOrEmpty(sourceAppConfigPath)
92
+ : (hostAppConfigPath ? readFileOrEmpty(hostAppConfigPath) : ''),
93
+ };
94
+ return {
95
+ address: addressOfPageBase(base),
96
+ page: {
97
+ format: 1 as const,
98
+ html,
99
+ uiYaml,
100
+ ...(eventYaml.trim() ? { eventYaml } : {}),
101
+ ...(styleYaml.trim() ? { styleYaml } : {}),
102
+ ...(localeYaml ? { locale: localeYaml } : {}),
103
+ ...(hasIncludes ? { includes } : {}),
104
+ },
105
+ inputsDigest: computePrewarmInputsDigest({
106
+ path: compileInput.path,
107
+ metadata,
108
+ appConfigYaml: compileInput.appConfigYaml,
109
+ hostAppConfigYaml: appConfigYaml,
110
+ treeContext: compileInput.treeContext ?? null,
111
+ compilerIdentity: null,
112
+ }),
113
+ compile: () => precompilePage(compileInput, { hostAppConfig: shell.appConfig }),
114
+ };
115
+ });
116
+
117
+ return runPrewarm({
118
+ hostDir: resolvedHostDir,
119
+ pages,
120
+ meta: { routes: shell.routes, locale: shell.locale, appConfig: shell.appConfig },
121
+ ...(host && typeof host.prewarm === 'function' ? { hook: () => host.prewarm!() } : {}),
122
+ });
123
+ }