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
@@ -0,0 +1,185 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export const hostPackageRoot = path.resolve(__dirname, '..');
5
+ export const coreRoot = path.resolve(hostPackageRoot, '..');
6
+
7
+ function lstatIfPresent(filePath: string): fs.Stats | null {
8
+ try {
9
+ return fs.lstatSync(filePath);
10
+ } catch (error) {
11
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
12
+ throw error;
13
+ }
14
+ }
15
+
16
+ function rejectWorkspaceSymlink(filePath: string): fs.Stats | null {
17
+ const stat = lstatIfPresent(filePath);
18
+ if (stat?.isSymbolicLink()) {
19
+ throw new Error(`[soma] Refusing symbolic link inside the SOMA Next workspace: ${filePath}`);
20
+ }
21
+ return stat;
22
+ }
23
+
24
+ function canonicalizePotentialPath(filePath: string): string {
25
+ const missingSegments: string[] = [];
26
+ let existingPath = path.resolve(filePath);
27
+ while (!fs.existsSync(existingPath)) {
28
+ const parent = path.dirname(existingPath);
29
+ if (parent === existingPath) break;
30
+ missingSegments.unshift(path.basename(existingPath));
31
+ existingPath = parent;
32
+ }
33
+ const canonicalBase = fs.existsSync(existingPath)
34
+ ? fs.realpathSync(existingPath)
35
+ : existingPath;
36
+ return path.join(canonicalBase, ...missingSegments);
37
+ }
38
+
39
+ function pathsOverlap(left: string, right: string): boolean {
40
+ const contains = (parent: string, child: string) => (
41
+ child === parent || child.startsWith(`${parent}${path.sep}`)
42
+ );
43
+ return contains(left, right) || contains(right, left);
44
+ }
45
+
46
+ export function resolveRuntimeRootForGuard(hostDir: string, env: NodeJS.ProcessEnv = process.env): string | null {
47
+ try {
48
+ const { resolveSomaRuntimeRoot } = require(path.join(coreRoot, 'core/server/runtime-space/root.cjs')) as {
49
+ resolveSomaRuntimeRoot(hostDir: string, env?: NodeJS.ProcessEnv): string;
50
+ };
51
+ return canonicalizePotentialPath(resolveSomaRuntimeRoot(hostDir, env));
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ let protectedRuntimeRoot: string | null = null;
58
+
59
+ function removeManaged(target: string, options: fs.RmOptions): void {
60
+ if (protectedRuntimeRoot !== null && pathsOverlap(canonicalizePotentialPath(target), protectedRuntimeRoot)) {
61
+ throw new Error(`[soma] Refusing to remove ${target}: it overlaps the SOMA runtime root ${protectedRuntimeRoot}. Move SOMA_RUNTIME_DIR out of the Next workspace's framework-owned paths.`);
62
+ }
63
+ fs.rmSync(target, options);
64
+ }
65
+
66
+ const WORKSPACE_MANAGED_ENTRIES = ['app', 'core', 'public', 'node_modules', 'global.d.ts', 'proxy.ts', 'middleware.ts', 'instrumentation.ts', 'next.config.js', 'tsconfig.json', 'package.json'] as const;
67
+
68
+ export function assertRuntimeRootOutsideManaged(workspaceDir: string, runtimeRoot: string | null): void {
69
+ if (runtimeRoot === null) return;
70
+ const canonicalRuntimeRoot = canonicalizePotentialPath(runtimeRoot);
71
+ for (const name of WORKSPACE_MANAGED_ENTRIES) {
72
+ if (pathsOverlap(canonicalizePotentialPath(path.join(workspaceDir, name)), canonicalRuntimeRoot)) {
73
+ throw new Error(`[soma] SOMA runtime root ${runtimeRoot} overlaps the Next workspace path ${name}, which is rebuilt on every start. Set SOMA_RUNTIME_DIR to a directory outside the workspace's framework-owned paths (default: <host>/.soma/runtime).`);
74
+ }
75
+ }
76
+ }
77
+
78
+ function assertReusableWorkspaceDir(workspaceDir: string): void {
79
+ const workspaceStat = rejectWorkspaceSymlink(workspaceDir);
80
+ if (!workspaceStat) return;
81
+ if (!workspaceStat.isDirectory()) {
82
+ throw new Error('[soma] SOMA_NEXT_WORKSPACE_DIR must resolve to a directory.');
83
+ }
84
+ if (fs.readdirSync(workspaceDir).length === 0) return;
85
+
86
+ let markerName: unknown;
87
+ const markerPath = path.join(workspaceDir, 'package.json');
88
+ const markerStat = rejectWorkspaceSymlink(markerPath);
89
+ try {
90
+ if (!markerStat?.isFile()) throw new Error('workspace marker is not a file');
91
+ const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8')) as {
92
+ name?: unknown;
93
+ };
94
+ markerName = marker.name;
95
+ } catch {
96
+ markerName = undefined;
97
+ }
98
+ if (markerName !== 'soma-next-workspace') {
99
+ throw new Error(
100
+ '[soma] SOMA_NEXT_WORKSPACE_DIR points to a non-empty directory that is not a SOMA Next workspace.',
101
+ );
102
+ }
103
+ }
104
+
105
+ function assertDefaultWorkspacePath(hostDir: string, workspaceDir: string): void {
106
+ let current = path.resolve(hostDir);
107
+ for (const segment of ['.soma', 'next']) {
108
+ current = path.join(current, segment);
109
+ rejectWorkspaceSymlink(current);
110
+ }
111
+ const canonicalHostDir = canonicalizePotentialPath(hostDir);
112
+ const expectedWorkspaceDir = path.join(canonicalHostDir, '.soma', 'next');
113
+ if (canonicalizePotentialPath(workspaceDir) !== expectedWorkspaceDir) {
114
+ throw new Error('[soma] Default SOMA Next workspace escaped SOMA_HOST_DIR.');
115
+ }
116
+ }
117
+
118
+ function resolveNextWorkspaceDir(hostDir: string): string {
119
+ const configured = process.env.SOMA_NEXT_WORKSPACE_DIR;
120
+ const usesDefaultWorkspace = configured === undefined;
121
+ if (!usesDefaultWorkspace && !configured.trim()) {
122
+ throw new Error('[soma] SOMA_NEXT_WORKSPACE_DIR must be a non-empty path when set.');
123
+ }
124
+
125
+ const requestedWorkspaceDir = usesDefaultWorkspace
126
+ ? path.resolve(hostDir, '.soma', 'next')
127
+ : path.resolve(hostDir, configured);
128
+ if (usesDefaultWorkspace) {
129
+ assertDefaultWorkspacePath(hostDir, requestedWorkspaceDir);
130
+ } else {
131
+ rejectWorkspaceSymlink(requestedWorkspaceDir);
132
+ }
133
+ const workspaceDir = canonicalizePotentialPath(requestedWorkspaceDir);
134
+ const canonicalWorkspaceDir = canonicalizePotentialPath(workspaceDir);
135
+ const filesystemRoot = path.parse(canonicalWorkspaceDir).root;
136
+ const canonicalHostDir = canonicalizePotentialPath(hostDir);
137
+ const canonicalPackageRoots = [hostPackageRoot, coreRoot].map(canonicalizePotentialPath);
138
+ if (canonicalWorkspaceDir === filesystemRoot) {
139
+ throw new Error('[soma] SOMA Next workspace must not resolve to a filesystem root.');
140
+ }
141
+ if (!usesDefaultWorkspace && (
142
+ pathsOverlap(canonicalWorkspaceDir, canonicalHostDir)
143
+ || canonicalPackageRoots.some((root) => pathsOverlap(canonicalWorkspaceDir, root))
144
+ )) {
145
+ throw new Error(
146
+ '[soma] SOMA_NEXT_WORKSPACE_DIR must be isolated from SOMA_HOST_DIR and the soma-core package.',
147
+ );
148
+ }
149
+ assertReusableWorkspaceDir(workspaceDir);
150
+ return workspaceDir;
151
+ }
152
+
153
+ export function ensureNextWorkspace(hostDir: string): string {
154
+ const workspaceDir = resolveNextWorkspaceDir(hostDir);
155
+ const runtimeRoot = resolveRuntimeRootForGuard(hostDir);
156
+ assertRuntimeRootOutsideManaged(workspaceDir, runtimeRoot);
157
+ protectedRuntimeRoot = runtimeRoot;
158
+ fs.mkdirSync(workspaceDir, { recursive: true });
159
+
160
+ const pkgPath = path.join(workspaceDir, 'package.json');
161
+ fs.writeFileSync(
162
+ pkgPath,
163
+ JSON.stringify({ private: true, name: 'soma-next-workspace' }, null, 2) + '\n',
164
+ );
165
+
166
+ const appDir = path.join(workspaceDir, 'app');
167
+ if (fs.existsSync(appDir)) {
168
+ removeManaged(appDir, { recursive: true, force: true });
169
+ }
170
+ fs.mkdirSync(appDir, { recursive: true });
171
+
172
+ const tsconfigPath = path.join(workspaceDir, 'tsconfig.json');
173
+ fs.writeFileSync(
174
+ tsconfigPath,
175
+ JSON.stringify({
176
+ compilerOptions: {
177
+ target: 'ES2020',
178
+ module: 'esnext',
179
+ strict: true,
180
+ },
181
+ }, null, 2) + '\n',
182
+ );
183
+
184
+ return workspaceDir;
185
+ }
@@ -1,9 +1,9 @@
1
1
  /*
2
- * SOMA core shell styles.
2
+ * SOMA core native shell styles.
3
3
  *
4
4
  * This file deliberately contains no framework-specific utility compiler.
5
5
  * Business applications may add their own stylesheet/toolchain in their
6
- * owning Next host; SOMA's runtime and official components do not require it.
6
+ * owning host; SOMA's runtime and official components do not require it.
7
7
  */
8
8
  :root {
9
9
  color-scheme: light;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "soma-core",
3
- "version": "2.1.5",
4
- "description": "SOMA — Semantic Oriented Modular Architecture. A declarative frontend framework runtime with no UI framework dependency; the Next.js host shell ships in host-next/ (code-isolated from core/, next/react are optional peer dependencies).",
3
+ "version": "2.2.0",
4
+ "description": "SOMA — Semantic Oriented Modular Architecture. A declarative frontend framework runtime with no UI framework dependency; native host shell ships in host-native/.",
5
5
  "keywords": [
6
6
  "soma",
7
7
  "declarative-ui",
@@ -270,13 +270,10 @@
270
270
  "editor/",
271
271
  "dist/",
272
272
  "dist/vscode/",
273
- "host-next/bin/",
274
- "host-next/src/",
275
- "host-next/app/",
276
- "host-next/proxy.ts",
277
- "host-next/instrumentation.ts",
278
- "host-next/next.config.js",
279
- "host-next/next-env.d.ts",
273
+ "host-native/bin/",
274
+ "host-native/src/",
275
+ "host-native/client/",
276
+ "host-native/styles/",
280
277
  "tsconfig.json",
281
278
  "global.d.ts"
282
279
  ],
@@ -291,14 +288,14 @@
291
288
  "build:all": "npm run build:cli && npm run build:core-dist && npm run build:types",
292
289
  "package:vscode": "node scripts/package-vscode.mjs",
293
290
  "prepublishOnly": "npm run build:all",
294
- "test": "vitest run && npm run test:host-next",
291
+ "test": "vitest run && npm run test:host-native",
295
292
  "verify:client-boundary": "node scripts/verify-client-boundary.mjs",
296
293
  "verify:client-dep-graph": "node scripts/verify-client-dep-graph.mjs",
297
294
  "test:watch": "vitest",
298
- "typecheck": "tsc --noEmit && npm run typecheck:host-next",
299
- "test:host-next": "vitest run --root host-next",
300
- "typecheck:host-next": "tsc -p host-next/tsconfig.check.json",
301
- "verify:precompile": "node scripts/verify-precompile-fresh.mjs"
295
+ "typecheck": "tsc --noEmit && npm run typecheck:host-native",
296
+ "verify:precompile": "node scripts/verify-precompile-fresh.mjs",
297
+ "test:host-native": "vitest run --root host-native",
298
+ "typecheck:host-native": "tsc -p host-native/tsconfig.check.json"
302
299
  },
303
300
  "dependencies": {
304
301
  "@atlaskit/pragmatic-drag-and-drop": "1.8.1",
@@ -317,20 +314,18 @@
317
314
  "@zag-js/tree-view": "1.46.0",
318
315
  "@zag-js/vanilla": "1.46.0",
319
316
  "diff": "8.0.4",
317
+ "esbuild": "0.25.12",
320
318
  "jiti": "1.21.7",
321
319
  "js-yaml": "4.3.2",
322
320
  "parse5": "7.3.0",
323
321
  "qrcode-generator": "2.0.4",
324
322
  "server-only": "0.0.1",
325
- "soma-foundation": "^0.1.1",
323
+ "soma-foundation": "^0.1.2",
326
324
  "temporal-polyfill": "0.3.2"
327
325
  },
328
326
  "peerDependencies": {
329
327
  "echarts": "^6.0.0",
330
328
  "jsdom": "^26.1.0",
331
- "next": "16.4.1",
332
- "react": "18.3.1",
333
- "react-dom": "18.3.1",
334
329
  "tailwindcss": "^4.1.0"
335
330
  },
336
331
  "peerDependenciesMeta": {
@@ -340,15 +335,6 @@
340
335
  "jsdom": {
341
336
  "optional": true
342
337
  },
343
- "next": {
344
- "optional": true
345
- },
346
- "react": {
347
- "optional": true
348
- },
349
- "react-dom": {
350
- "optional": true
351
- },
352
338
  "tailwindcss": {
353
339
  "optional": true
354
340
  }
@@ -357,18 +343,13 @@
357
343
  "@types/dompurify": "3.0.5",
358
344
  "@types/js-yaml": "4.0.9",
359
345
  "@types/node": "20.19.40",
360
- "@types/react": "18.3.31",
361
- "@types/react-dom": "18.3.7",
362
346
  "@types/ws": "8.18.1",
363
347
  "@vitest/coverage-v8": "3.2.7",
364
348
  "dompurify": "3.4.17",
365
349
  "echarts": "6.1.0",
366
- "esbuild": "0.25.12",
367
350
  "jsdom": "26.1.0",
368
351
  "next": "16.4.1",
369
352
  "playwright": "1.62.1",
370
- "react": "18.3.1",
371
- "react-dom": "18.3.1",
372
353
  "reflect-metadata": "0.2.2",
373
354
  "tailwindcss": "4.3.3",
374
355
  "tsx": "4.23.13",
package/tsconfig.json CHANGED
@@ -36,6 +36,6 @@
36
36
  ],
37
37
  "exclude": [
38
38
  "node_modules",
39
- "host-next"
39
+ "host-native"
40
40
  ]
41
41
  }
@@ -1,359 +0,0 @@
1
- 'use client';
2
-
3
- import { useCallback, useEffect, useRef, useState } from 'react';
4
- import { usePathname, useRouter, useSearchParams } from 'next/navigation';
5
- import { SomaHydrationShell } from './components/SomaHydrationShell';
6
- import { SomaPageForbidden } from './components/SomaPageForbidden';
7
- import { PageAccessError, readPageAccessError, loginRedirectTarget } from './page-access';
8
- import { createNextNavigate, pendingNavigateInfo, type SomaShellNavigate } from './router-bridge';
9
- import type {
10
- ComponentTreeRuntimeEnvelope,
11
- SomaBootstrap as SomaBootstrapType,
12
- SomaPageAssets,
13
- SomaRuntimeServices,
14
- } from 'soma-core/runtime';
15
- import { assertRuntimeArtifact, maybeStartBootTimings, readBootTimings } from 'soma-core/runtime';
16
- import { loadHostDomainClass, resolveHostBootstrapOptions } from 'soma-core/host-bridge';
17
-
18
- const isDev = process.env.NODE_ENV !== 'production';
19
-
20
- export default function SomaEntry() {
21
- const pathname = usePathname();
22
- const searchParams = useSearchParams();
23
- const router = useRouter();
24
- // core 带来的落历史方式:replace → router.replace(不入历史),否则 push
25
- const navigate = useCallback<SomaShellNavigate>((url, info) => {
26
- createNextNavigate(router)(url, info);
27
- }, [router]);
28
- const routerPath = searchParams.toString()
29
- ? `${pathname}?${searchParams.toString()}`
30
- : pathname;
31
- return (
32
- <SomaPageRenderer
33
- pagePath={pathname}
34
- routerPath={routerPath}
35
- onNavigate={navigate}
36
- />
37
- );
38
- }
39
-
40
- function urlPathToPageBase(urlPath: string): string {
41
- const clean = urlPath.replace(/^\//, '').replace(/\.html$/i, '');
42
- return clean || 'index';
43
- }
44
-
45
- type PagePayload = ComponentTreeRuntimeEnvelope & {
46
- base: string;
47
- sourcePackage?: string | null;
48
- html: string;
49
- ui: string;
50
- event: string;
51
- styleYaml?: string;
52
- dataYaml?: string;
53
- includes?: Record<string, string>;
54
- localeYaml: string;
55
- appConfigYaml: string;
56
- /** 编译样式片与暗色首帧载体(KC2):服务端页面外壳读 colorScheme,浏览器只装载 compiledStyles */
57
- compiledStyles?: SomaPageAssets['compiledStyles'];
58
- colorScheme?: SomaPageAssets['colorScheme'];
59
- /** 取页响应带来的路由上下文(E3 / E4):每次取页都以最新响应为准,不进资产缓存 */
60
- params?: SomaPageAssets['pageParams'];
61
- query?: SomaPageAssets['pageQuery'];
62
- queryContract?: SomaPageAssets['queryContract'];
63
- nav?: SomaPageAssets['nav'];
64
- };
65
-
66
- type PrecompiledAssets = Pick<
67
- SomaPageAssets,
68
- 'html' | 'sourceMarkup' | 'artifact' | 'uiConfig' | 'eventConfig' | 'triggerConfig' | 'timerConfig' | 'styleConfig' | 'locale' | 'appConfig' | 'dataConfig' | 'compiledStyles'
69
- >;
70
-
71
- const pageAssetCache = new Map<string, PagePayload>();
72
-
73
- async function loadPrecompiledFromManifest(path: string, current: ComponentTreeRuntimeEnvelope): Promise<PrecompiledAssets | null> {
74
- try {
75
- const res = await fetch(`/soma/manifest?path=${encodeURIComponent(path)}`);
76
- if (!res.ok) return null;
77
- const data: PrecompiledAssets & {
78
- triggers?: SomaPageAssets['triggerConfig']; timers?: SomaPageAssets['timerConfig'];
79
- } = await res.json();
80
- assertRuntimeArtifact(data);
81
- if ((data.sourceMarkup ?? 'legacy-html') !== (current.sourceMarkup ?? 'legacy-html')) return null;
82
- if (current.sourceMarkup === 'component-tree'
83
- && data.artifact?.artifactDigest !== current.artifact?.artifactDigest) return null;
84
- if (typeof data.html !== 'string') return null;
85
- return {
86
- sourceMarkup: data.sourceMarkup,
87
- html: data.html,
88
- artifact: data.artifact,
89
- uiConfig: data.uiConfig,
90
- eventConfig: data.eventConfig,
91
- triggerConfig: data.triggers ?? [],
92
- timerConfig: data.timers ?? [],
93
- styleConfig: data.styleConfig,
94
- locale: data.locale ?? {},
95
- appConfig: data.appConfig ?? null,
96
- dataConfig: data.dataConfig ?? undefined,
97
- ...(data.compiledStyles !== undefined ? { compiledStyles: data.compiledStyles } : {}),
98
- };
99
- } catch {
100
- return null;
101
- }
102
- }
103
-
104
- function SomaPageRenderer({
105
- pagePath,
106
- routerPath,
107
- onNavigate,
108
- }: {
109
- pagePath: string;
110
- routerPath: string;
111
- onNavigate: SomaShellNavigate;
112
- }) {
113
- const containerRef = useRef<HTMLDivElement>(null);
114
- const bootstrapRef = useRef<SomaBootstrapType | null>(null);
115
- const routerBridgeRef = useRef<(() => void) | null>(null);
116
- const [error, setError] = useState<string | null>(null);
117
- const [mounting, setMounting] = useState(true);
118
- const [forbidden, setForbidden] = useState<{ textKey: string | undefined } | null>(null);
119
-
120
- useEffect(() => {
121
- if (!containerRef.current) return;
122
-
123
- let cancelled = false;
124
-
125
- const mountInto = async (
126
- DomainClass: new () => any,
127
- SomaBootstrapCtor: new (...args: any[]) => SomaBootstrapType,
128
- assets: Omit<SomaPageAssets, 'html' | 'includes' | 'DomainClass'>,
129
- html: string,
130
- includes?: Record<string, string>,
131
- ) => {
132
- await bootstrapRef.current?.unmount();
133
-
134
- const getServices = () =>
135
- bootstrapRef.current?.getDomainInstance()?._services as SomaRuntimeServices | undefined;
136
-
137
- // 分片重试退避缺省值取 soma-design 真源(经 foundation 投影),core 里不写数字(层标准 D22)
138
- const { designChunkLoadBackoffMs } = await import('soma-foundation/layout');
139
- const hostBootstrapOptions = await resolveHostBootstrapOptions(getServices, { chunkLoadBackoffMs: designChunkLoadBackoffMs() });
140
-
141
- const bs = new SomaBootstrapCtor(hostBootstrapOptions);
142
- bootstrapRef.current = bs;
143
-
144
- await bs.mount(containerRef.current!, {
145
- html,
146
- includes,
147
- DomainClass,
148
- ...assets,
149
- });
150
-
151
- await bs.whenSettled();
152
- if (cancelled) return;
153
- if (typeof window !== 'undefined') {
154
- window.__SOMA_DIAGNOSTICS__ = {
155
- isSettled: () => bs.isSettled(),
156
- getDomainValue: (path: string) => bs.getDomainValue(path),
157
- getRegisteredSomaIds: () => bs.getRegisteredSomaIds(),
158
- // 只读 CSP nonce 链:响应头 nonce → meta → 运行期注入的样式元素。
159
- // 浏览器插入后会抹掉 nonce 内容属性,这里读 IDL 属性。
160
- getCspNonceChain: () => ({
161
- meta: document.querySelector('meta[name="csp-nonce"]')?.getAttribute('content')?.trim() ?? '',
162
- styles: Array.from(document.head.querySelectorAll('style'))
163
- .map((style) => (style as HTMLStyleElement).nonce ?? '')
164
- .filter(Boolean),
165
- }),
166
- };
167
- window.__SOMA_READY__ = bs.isInitialized();
168
- }
169
-
170
- routerBridgeRef.current?.();
171
- const domain = bs.getDomainInstance() as {
172
- _services?: {
173
- router: {
174
- getCurrentPath: () => string;
175
- getHistory?: () => readonly string[];
176
- onNavigate: (cb: (p: string, info?: { readonly replace?: boolean }) => void) => () => void;
177
- };
178
- };
179
- } | null;
180
- if (domain?._services?.router) {
181
- const somaRouter = domain._services.router;
182
- routerBridgeRef.current = somaRouter.onNavigate((nextPath, info) => {
183
- if (nextPath !== routerPath) {
184
- onNavigate(nextPath, info);
185
- }
186
- });
187
- // onMount 里触发的 navigate 发生在桥接注册之前,此处补同步到 Next 路由(落历史方式按内存路由轨迹推断)
188
- const pending = somaRouter.getCurrentPath();
189
- if (pending !== routerPath) {
190
- onNavigate(pending, pendingNavigateInfo(somaRouter));
191
- }
192
- }
193
-
194
- if (isDev && typeof window !== 'undefined') {
195
- window.__SOMA__ = {
196
- getDiagnosticsSnapshot: () => bs.getDiagnosticsSnapshot(),
197
- getTelemetrySnapshot: () => bs.getTelemetrySnapshot(),
198
- // 首屏三段:E2E/手工排查从这里读,不必自己去翻 performance 时间线
199
- getBootTimings: () => readBootTimings(),
200
- getDomainInstance: () => bs.getDomainInstance(),
201
- captureSnapshot: () => bs.captureSnapshot(),
202
- restoreSnapshot: (id: number) => bs.restoreSnapshot(id),
203
- setLocale: (locale: string) => bs.setLocale(locale),
204
- };
205
- }
206
- };
207
-
208
- const run = async () => {
209
- try {
210
- // 首屏三段打点的起点:放在页面资产拉取之前,段一才量得到网络那一截。
211
- // 未开启(globalThis.__SOMA_BOOT_TIMINGS__ 未置真)时只是一次布尔判断。
212
- maybeStartBootTimings();
213
- setError(null);
214
- setForbidden(null);
215
- setMounting(true);
216
-
217
- const { SomaBootstrap } = await import('soma-core/runtime');
218
-
219
- const res = await fetch(`/soma/page?path=${encodeURIComponent(pagePath)}`);
220
- if (!res.ok) throw await readPageAccessError(res);
221
- const data: PagePayload = await res.json();
222
- assertRuntimeArtifact(data);
223
- if (cancelled) return;
224
-
225
- const base = (data.base as string) || urlPathToPageBase(pagePath);
226
- const sourcePackage = typeof data.sourcePackage === 'string' ? data.sourcePackage : null;
227
- const DomainClass = await loadHostDomainClass({ base, sourcePackage });
228
- const routeAssets = {
229
- routerPath,
230
- ...(data.params !== undefined ? { pageParams: data.params } : {}),
231
- ...(data.query !== undefined ? { pageQuery: data.query } : {}),
232
- ...(data.queryContract !== undefined ? { queryContract: data.queryContract } : {}),
233
- ...(data.nav !== undefined ? { nav: data.nav } : {}),
234
- };
235
-
236
- if (!isDev) {
237
- const precompiled = await loadPrecompiledFromManifest(pagePath, data);
238
- if (precompiled) {
239
- await mountInto(
240
- DomainClass,
241
- SomaBootstrap,
242
- { ...precompiled, ...routeAssets },
243
- precompiled.html,
244
- );
245
- return;
246
- }
247
-
248
- const cached = pageAssetCache.get(routerPath);
249
- if (cached && (cached.sourceMarkup ?? 'legacy-html') === (data.sourceMarkup ?? 'legacy-html')
250
- && (data.sourceMarkup !== 'component-tree' || cached.artifact?.artifactDigest === data.artifact?.artifactDigest)) {
251
- const CachedClass = await loadHostDomainClass({
252
- base: cached.base,
253
- sourcePackage: cached.sourcePackage,
254
- });
255
- await mountInto(CachedClass, SomaBootstrap, {
256
- uiYaml: cached.ui,
257
- eventYaml: cached.event,
258
- styleYaml: cached.styleYaml,
259
- dataYaml: cached.dataYaml,
260
- locale: cached.localeYaml ?? '',
261
- appConfigYaml: cached.appConfigYaml ?? '',
262
- sourceMarkup: cached.sourceMarkup,
263
- artifact: cached.artifact,
264
- ...(cached.compiledStyles !== undefined ? { compiledStyles: cached.compiledStyles } : {}),
265
- ...routeAssets,
266
- }, cached.html, cached.includes);
267
- return;
268
- }
269
- }
270
-
271
- const payload: PagePayload = {
272
- base,
273
- sourcePackage,
274
- sourceMarkup: data.sourceMarkup,
275
- artifact: data.artifact,
276
- html: data.html,
277
- ui: data.ui,
278
- event: data.event,
279
- styleYaml: data.styleYaml ?? '',
280
- dataYaml: typeof data.dataYaml === 'string' ? data.dataYaml : undefined,
281
- includes: data.includes,
282
- localeYaml: data.localeYaml ?? '',
283
- appConfigYaml: data.appConfigYaml ?? '',
284
- compiledStyles: data.compiledStyles,
285
- colorScheme: data.colorScheme,
286
- };
287
-
288
- if (!isDev) {
289
- pageAssetCache.set(routerPath, payload);
290
- }
291
-
292
- await mountInto(DomainClass, SomaBootstrap, {
293
- uiYaml: payload.ui,
294
- eventYaml: payload.event,
295
- styleYaml: payload.styleYaml,
296
- dataYaml: payload.dataYaml,
297
- locale: payload.localeYaml ?? '',
298
- appConfigYaml: payload.appConfigYaml ?? '',
299
- sourceMarkup: payload.sourceMarkup,
300
- artifact: payload.artifact,
301
- ...(payload.compiledStyles !== undefined ? { compiledStyles: payload.compiledStyles } : {}),
302
- ...routeAssets,
303
- }, payload.html, payload.includes);
304
- } catch (err: any) {
305
- if (cancelled) return;
306
- if (err instanceof PageAccessError && err.status === 401) {
307
- // 未登录:跳 Host 约定的登录页(响应带路径),带回跳地址;已在登录页上时不再跳,避免循环
308
- const target = loginRedirectTarget(err.loginPath, pagePath, routerPath);
309
- if (target !== null) {
310
- window.location.assign(target);
311
- return;
312
- }
313
- }
314
- if (err instanceof PageAccessError && err.status === 403) {
315
- setForbidden({ textKey: err.textKey });
316
- return;
317
- }
318
- setError(err?.message ?? String(err));
319
- } finally {
320
- if (!cancelled) setMounting(false);
321
- }
322
- };
323
-
324
- void run();
325
-
326
- return () => {
327
- cancelled = true;
328
- routerBridgeRef.current?.();
329
- routerBridgeRef.current = null;
330
- if (typeof window !== 'undefined') {
331
- delete window.__SOMA__;
332
- delete window.__SOMA_READY__;
333
- delete window.__SOMA_DIAGNOSTICS__;
334
- }
335
- void bootstrapRef.current?.unmount();
336
- bootstrapRef.current = null;
337
- };
338
- }, [pagePath, routerPath, onNavigate]);
339
-
340
- if (forbidden) {
341
- return <SomaPageForbidden textKey={forbidden.textKey} />;
342
- }
343
-
344
- if (error) {
345
- return (
346
- <div className="soma-page-error">
347
- <p className="soma-page-error__title">Page failed to load</p>
348
- <p className="soma-page-error__message">{error}</p>
349
- </div>
350
- );
351
- }
352
-
353
- return (
354
- <>
355
- {mounting && !error ? <SomaHydrationShell /> : null}
356
- <div ref={containerRef} className={mounting && !error ? 'soma-hidden' : undefined} />
357
- </>
358
- );
359
- }