soma-core 2.1.6 → 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.
- package/README.md +2 -2
- package/bin/soma.cjs +1 -1
- package/bin/soma.ts +64 -15
- package/core/server/api/dispatch-service-api.ts +212 -0
- package/core/server/api/load-host-service.ts +230 -56
- package/core/server/api/service-path.ts +78 -14
- package/core/server/engines/style/candidate-guard.ts +57 -0
- package/core/server/engines/style/index.ts +1 -1
- package/core/server/engines/style/tailwind-adapter.ts +83 -16
- package/core/server/host/source-packages.cjs +96 -30
- package/core/server/host/source-packages.ts +12 -5
- package/core/server/index.ts +39 -17
- package/core/server/infra/cache/ServerFileCache.ts +138 -25
- package/core/server/node.ts +32 -8
- package/dist/cli/soma.js +68 -14
- package/dist/host-native/aot-builder.cjs +850 -0
- package/dist/host-native/native-server.cjs +15338 -0
- package/dist/types/server/api/dispatch-service-api.d.ts +18 -0
- package/dist/types/server/api/load-host-service.d.ts +7 -2
- package/dist/types/server/api/service-path.d.ts +21 -1
- package/dist/types/server/engines/style/candidate-guard.d.ts +10 -0
- package/dist/types/server/engines/style/index.d.ts +1 -1
- package/dist/types/server/engines/style/tailwind-adapter.d.ts +12 -0
- package/dist/types/server/host/source-packages.d.cts +13 -1
- package/dist/types/server/host/source-packages.d.ts +7 -4
- package/dist/types/server/index.d.ts +18 -17
- package/dist/types/server/infra/cache/ServerFileCache.d.ts +28 -5
- package/dist/types/server/node.d.ts +10 -7
- package/host-native/bin/host-native.cjs +204 -0
- package/host-native/client/browser-entry.ts +499 -0
- package/{host-next/app → host-native/client}/page-access.ts +12 -0
- package/host-native/client/router-bridge.ts +120 -0
- package/host-native/src/aot-builder.ts +486 -0
- package/host-native/src/csp-headers.ts +75 -0
- package/host-native/src/host-prepare.ts +123 -0
- package/{host-next/app/soma/manifest/route.ts → host-native/src/manifest-http.ts} +10 -10
- package/host-native/src/native-server.ts +691 -0
- package/host-native/src/page-http.ts +223 -0
- package/host-native/src/public-packages.cjs +167 -0
- package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts} +17 -19
- package/{host-next → host-native}/src/shell-routes.cjs +23 -13
- package/host-native/src/static-file.ts +172 -0
- package/host-native/src/workspace.ts +185 -0
- package/{host-next/app → host-native/styles}/globals.css +2 -2
- package/package.json +12 -31
- package/tsconfig.json +1 -1
- package/host-next/app/SomaPageClient.tsx +0 -359
- package/host-next/app/[...path]/page.tsx +0 -22
- package/host-next/app/api/[...path]/route.ts +0 -98
- package/host-next/app/components/SomaHostPage.tsx +0 -128
- package/host-next/app/components/SomaHydrationShell.tsx +0 -20
- package/host-next/app/components/SomaPageClientBoundary.tsx +0 -13
- package/host-next/app/components/SomaPageForbidden.tsx +0 -19
- package/host-next/app/favicon.ico/route.ts +0 -13
- package/host-next/app/layout.tsx +0 -27
- package/host-next/app/page.tsx +0 -9
- package/host-next/app/router-bridge.ts +0 -42
- package/host-next/app/soma/[...path]/route.ts +0 -9
- package/host-next/app/soma/_shared/host-prepare.ts +0 -33
- package/host-next/app/soma/_shared/page-http.ts +0 -86
- package/host-next/app/soma/page/route.ts +0 -36
- package/host-next/app/soma/route.ts +0 -9
- package/host-next/app/soma-runtime/[...file]/route.ts +0 -21
- package/host-next/app/soma-runtime/_shared/static-file.ts +0 -89
- package/host-next/bin/host-next.cjs +0 -60
- package/host-next/instrumentation.ts +0 -18
- package/host-next/next-env.d.ts +0 -7
- package/host-next/next.config.js +0 -410
- package/host-next/proxy.ts +0 -43
- package/host-next/src/workspace.ts +0 -543
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path, { join, normalize, resolve } from "node:path";
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* 将 kebab-case / snake_case 转为 PascalCase
|
|
@@ -8,32 +9,95 @@ export function toPascalCase(str: string): string {
|
|
|
8
9
|
return str
|
|
9
10
|
.split(/[-_]/)
|
|
10
11
|
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
|
11
|
-
.join(
|
|
12
|
+
.join("");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 校验服务路由片段的安全与合法性,并将末段解析为 PascalCase 类名。
|
|
17
|
+
* 拒收:空片段、"." / ".."、以 "_" 起头的私有模块、含 "/" / "\\" / "\0" 的穿越字符。
|
|
18
|
+
*/
|
|
19
|
+
export function validateServiceSegments(segments: readonly string[]): { dirSegments: string[]; className: string } | null {
|
|
20
|
+
if (!segments || segments.length === 0) return null;
|
|
21
|
+
|
|
22
|
+
for (const segment of segments) {
|
|
23
|
+
if (!segment || typeof segment !== "string" || segment.startsWith("_")) return null;
|
|
24
|
+
if (segment === "." || segment === "..") return null;
|
|
25
|
+
if (segment.includes("/") || segment.includes("\\") || segment.includes("\0")) return null;
|
|
26
|
+
const normalized = normalize(segment);
|
|
27
|
+
if (normalized === "." || normalized.startsWith("..") || normalized.includes("\0")) return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const last = segments[segments.length - 1];
|
|
31
|
+
const className = toPascalCase(last);
|
|
32
|
+
if (!className) return null;
|
|
33
|
+
const dirSegments = segments.slice(0, -1);
|
|
34
|
+
return { dirSegments, className };
|
|
12
35
|
}
|
|
13
36
|
|
|
14
37
|
/**
|
|
15
38
|
* 从 /api/{...path} 片段解析宿主服务文件绝对路径。
|
|
16
39
|
*
|
|
17
40
|
* 规则(与文档 12.4 一致):
|
|
18
|
-
* - ["
|
|
41
|
+
* - ["products"] → {host}/api/service/Products.ts
|
|
19
42
|
* - ["user", "profile"] → {host}/api/service/user/Profile.ts
|
|
20
43
|
*/
|
|
21
44
|
export function resolveServiceFilePath(hostDir: string, segments: string[]): string | null {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
for (const segment of segments) {
|
|
25
|
-
if (!segment || segment.startsWith('_')) return null;
|
|
26
|
-
const normalized = normalize(segment);
|
|
27
|
-
if (normalized.startsWith('..') || normalized.includes('\0')) return null;
|
|
28
|
-
}
|
|
45
|
+
const validated = validateServiceSegments(segments);
|
|
46
|
+
if (!validated) return null;
|
|
29
47
|
|
|
30
|
-
const fileName = `${
|
|
31
|
-
const
|
|
32
|
-
const filePath = join(hostDir, 'api', 'service', ...dirs, fileName);
|
|
48
|
+
const fileName = `${validated.className}.ts`;
|
|
49
|
+
const filePath = join(hostDir, "api", "service", ...validated.dirSegments, fileName);
|
|
33
50
|
|
|
34
51
|
const resolved = resolve(filePath);
|
|
35
|
-
const serviceRoot = resolve(hostDir,
|
|
52
|
+
const serviceRoot = resolve(hostDir, "api", "service");
|
|
36
53
|
if (!resolved.startsWith(serviceRoot)) return null;
|
|
37
54
|
|
|
38
55
|
return resolved;
|
|
39
56
|
}
|
|
57
|
+
|
|
58
|
+
export interface ResolveHostServiceCandidateOptions {
|
|
59
|
+
readonly allowDirectRoot?: boolean;
|
|
60
|
+
readonly extensions?: readonly string[];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const DEFAULT_SERVICE_EXTENSIONS: readonly string[] = [".ts", ".js", ".mjs", ".cjs"];
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 在给定后端根 apiRoot 下按顺序探测真实存在的服务文件(默认后缀顺序 [".ts", ".js", ".mjs", ".cjs"]):
|
|
67
|
+
* 1) <apiRoot>/api/service/<...dirSegments>/<ClassName><ext>
|
|
68
|
+
* 2) <apiRoot>/service/<...dirSegments>/<ClassName><ext>
|
|
69
|
+
* 3) 当 options?.allowDirectRoot === true 时额外探测 <apiRoot>/<...dirSegments>/<ClassName><ext>
|
|
70
|
+
* 每一步都必须校验 resolved.startsWith(normalizedAllowedBase + path.sep) 且 fs.statSync(resolved, { throwIfNoEntry: false })?.isFile() === true
|
|
71
|
+
*/
|
|
72
|
+
export function resolveHostServiceCandidate(
|
|
73
|
+
apiRoot: string,
|
|
74
|
+
segments: string[],
|
|
75
|
+
options?: ResolveHostServiceCandidateOptions,
|
|
76
|
+
): string | null {
|
|
77
|
+
const validated = validateServiceSegments(segments);
|
|
78
|
+
if (!validated) return null;
|
|
79
|
+
|
|
80
|
+
const normalizedApiRoot = resolve(apiRoot);
|
|
81
|
+
const extensions = options?.extensions ?? DEFAULT_SERVICE_EXTENSIONS;
|
|
82
|
+
const { dirSegments, className } = validated;
|
|
83
|
+
|
|
84
|
+
const candidateBases = [
|
|
85
|
+
join(normalizedApiRoot, "api", "service"),
|
|
86
|
+
join(normalizedApiRoot, "service"),
|
|
87
|
+
...(options?.allowDirectRoot ? [normalizedApiRoot] : []),
|
|
88
|
+
];
|
|
89
|
+
|
|
90
|
+
for (const base of candidateBases) {
|
|
91
|
+
const normalizedAllowedBase = resolve(base);
|
|
92
|
+
for (const ext of extensions) {
|
|
93
|
+
const fileName = `${className}${ext}`;
|
|
94
|
+
const resolved = resolve(normalizedAllowedBase, ...dirSegments, fileName);
|
|
95
|
+
if (resolved.startsWith(normalizedAllowedBase + path.sep)) {
|
|
96
|
+
const stat = fs.statSync(resolved, { throwIfNoEntry: false });
|
|
97
|
+
if (stat?.isFile()) return resolved;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
@@ -57,3 +57,60 @@ export function hasRuleForCandidate(css: string, candidate: string): boolean {
|
|
|
57
57
|
from = at + needle.length;
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
|
+
|
|
61
|
+
function decodeCssEscape(escaped: string): string {
|
|
62
|
+
return escaped.replace(/\\(?:([0-9a-fA-F]{1,6})[ \t\r\n\f]?|([\s\S]))/g, (_match, hex, char) => {
|
|
63
|
+
if (hex !== undefined) {
|
|
64
|
+
const code = parseInt(hex, 16);
|
|
65
|
+
return code === 0 ? '�' : String.fromCodePoint(code);
|
|
66
|
+
}
|
|
67
|
+
return char;
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const CLASS_SELECTOR_RE = /\.((?:[a-zA-Z_]|[^\x00-\x7f]|-(?![0-9])|\\(?:[0-9a-fA-F]{1,6}[ \t\r\n\f]?|[\s\S]))(?:[a-zA-Z0-9_-]|[^\x00-\x7f]|\\(?:[0-9a-fA-F]{1,6}[ \t\r\n\f]?|[\s\S]))*)/g;
|
|
72
|
+
|
|
73
|
+
/** 从 CSS 选择器片段单遍提取所有类名(已解码转义) */
|
|
74
|
+
export function extractClassesFromCss(css: string): Set<string> {
|
|
75
|
+
const classes = new Set<string>();
|
|
76
|
+
const clean = css.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
77
|
+
let segStart = 0;
|
|
78
|
+
for (let i = 0; i < clean.length; i++) {
|
|
79
|
+
const ch = clean[i];
|
|
80
|
+
if (ch === '{') {
|
|
81
|
+
const seg = clean.slice(segStart, i);
|
|
82
|
+
CLASS_SELECTOR_RE.lastIndex = 0;
|
|
83
|
+
let m: RegExpExecArray | null;
|
|
84
|
+
while ((m = CLASS_SELECTOR_RE.exec(seg)) !== null) {
|
|
85
|
+
classes.add(decodeCssEscape(m[1]));
|
|
86
|
+
}
|
|
87
|
+
segStart = i + 1;
|
|
88
|
+
} else if (ch === '}' || ch === ';') {
|
|
89
|
+
segStart = i + 1;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return classes;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 批量判定编译产物中是否包含指定候选类的规则。
|
|
97
|
+
* O(1) 查表命中 99.9% 候选类,未命中时回退 hasRuleForCandidate 兜底复杂选择器,结果逐字等价。
|
|
98
|
+
*/
|
|
99
|
+
export function partitionCompiledCandidates(
|
|
100
|
+
css: string,
|
|
101
|
+
candidates: readonly string[],
|
|
102
|
+
): { matched: string[]; unmatched: string[] } {
|
|
103
|
+
const classSet = extractClassesFromCss(css);
|
|
104
|
+
const matched: string[] = [];
|
|
105
|
+
const unmatched: string[] = [];
|
|
106
|
+
for (const candidate of candidates) {
|
|
107
|
+
if (classSet.has(candidate)) {
|
|
108
|
+
matched.push(candidate);
|
|
109
|
+
} else if (hasRuleForCandidate(css, candidate)) {
|
|
110
|
+
matched.push(candidate);
|
|
111
|
+
} else {
|
|
112
|
+
unmatched.push(candidate);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { matched, unmatched };
|
|
116
|
+
}
|
|
@@ -22,7 +22,7 @@ export type {
|
|
|
22
22
|
} from '../../../shared/engines/style/style-engine.types';
|
|
23
23
|
export { assertStyleEngineAdapter, assertThemeCss } from './port';
|
|
24
24
|
export { guardCandidates } from './candidate-guard';
|
|
25
|
-
export { createTailwindAdapter } from './tailwind-adapter';
|
|
25
|
+
export { createTailwindAdapter, clearTailwindCompilerCache } from './tailwind-adapter';
|
|
26
26
|
|
|
27
27
|
export interface StyleEnginePortOptions { readonly telemetry?: EngineLoadTelemetry }
|
|
28
28
|
|
|
@@ -12,15 +12,31 @@ import type {
|
|
|
12
12
|
StyleCompileResult,
|
|
13
13
|
} from '../../../shared/engines/style/style-engine.types';
|
|
14
14
|
import { loadEngineModule, type EngineLoadTelemetry } from '../../../client/engines/load';
|
|
15
|
-
import { guardCandidates,
|
|
15
|
+
import { guardCandidates, partitionCompiledCandidates } from './candidate-guard';
|
|
16
16
|
import { assertThemeCss } from './port';
|
|
17
17
|
|
|
18
|
-
interface TailwindCompiler { build(candidates: string[]): string }
|
|
19
|
-
interface TailwindModule { compile(css: string): Promise<TailwindCompiler> }
|
|
18
|
+
export interface TailwindCompiler { build(candidates: string[]): string }
|
|
19
|
+
export interface TailwindModule { compile(css: string, options?: { base?: string }): Promise<TailwindCompiler> }
|
|
20
20
|
|
|
21
|
-
export interface TailwindAdapterOptions {
|
|
21
|
+
export interface TailwindAdapterOptions {
|
|
22
|
+
readonly telemetry?: EngineLoadTelemetry;
|
|
23
|
+
readonly base?: string;
|
|
24
|
+
readonly loadTailwind?: () => Promise<TailwindModule>;
|
|
25
|
+
}
|
|
22
26
|
|
|
23
27
|
const UTILITIES_DIRECTIVE = /@tailwind\s+utilities\b/;
|
|
28
|
+
const MAX_COMPILER_CACHE = 16;
|
|
29
|
+
|
|
30
|
+
const defaultCompilerCache = new Map<string, Promise<TailwindCompiler>>();
|
|
31
|
+
let defaultTailwindModulePromise: Promise<TailwindModule> | null = null;
|
|
32
|
+
let customCompilerCaches = new WeakMap<object, Map<string, Promise<TailwindCompiler>>>();
|
|
33
|
+
|
|
34
|
+
/** 清除 Tailwind 编译器与模块缓存(供内部测试重置) */
|
|
35
|
+
export function clearTailwindCompilerCache(): void {
|
|
36
|
+
defaultCompilerCache.clear();
|
|
37
|
+
defaultTailwindModulePromise = null;
|
|
38
|
+
customCompilerCaches = new WeakMap();
|
|
39
|
+
}
|
|
24
40
|
|
|
25
41
|
function withUtilities(themeCss: string): string {
|
|
26
42
|
return UTILITIES_DIRECTIVE.test(themeCss) ? themeCss : `${themeCss}\n@tailwind utilities;\n`;
|
|
@@ -31,24 +47,74 @@ function digestOf(css: string): string {
|
|
|
31
47
|
}
|
|
32
48
|
|
|
33
49
|
export function createTailwindAdapter(adapterOptions: TailwindAdapterOptions = {}): SomaStyleEngine {
|
|
34
|
-
const load = (): Promise<TailwindModule> =>
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
50
|
+
const load = (): Promise<TailwindModule> => {
|
|
51
|
+
if (adapterOptions.loadTailwind !== undefined) {
|
|
52
|
+
return adapterOptions.loadTailwind();
|
|
53
|
+
}
|
|
54
|
+
if (!defaultTailwindModulePromise) {
|
|
55
|
+
defaultTailwindModulePromise = loadEngineModule<TailwindModule>(
|
|
56
|
+
'tailwindcss',
|
|
57
|
+
() => import('tailwindcss') as unknown as Promise<TailwindModule>,
|
|
58
|
+
{ telemetry: adapterOptions.telemetry },
|
|
59
|
+
).catch((cause) => {
|
|
60
|
+
defaultTailwindModulePromise = null;
|
|
61
|
+
throw cause;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return defaultTailwindModulePromise;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const getCompilerCache = (): Map<string, Promise<TailwindCompiler>> => {
|
|
68
|
+
if (adapterOptions.loadTailwind !== undefined) {
|
|
69
|
+
let m = customCompilerCaches.get(adapterOptions.loadTailwind);
|
|
70
|
+
if (!m) {
|
|
71
|
+
m = new Map<string, Promise<TailwindCompiler>>();
|
|
72
|
+
customCompilerCaches.set(adapterOptions.loadTailwind, m);
|
|
73
|
+
}
|
|
74
|
+
return m;
|
|
75
|
+
}
|
|
76
|
+
return defaultCompilerCache;
|
|
77
|
+
};
|
|
38
78
|
|
|
39
79
|
return {
|
|
40
80
|
id: 'tailwind',
|
|
41
81
|
async compile(input: StyleCompileInput): Promise<StyleCompileResult> {
|
|
42
82
|
assertThemeCss(input.themeCss);
|
|
43
83
|
const guarded = guardCandidates(input.candidates, input.allow);
|
|
44
|
-
const
|
|
84
|
+
const cssWithUtils = withUtilities(input.themeCss);
|
|
85
|
+
const cacheKey = createHash('sha256')
|
|
86
|
+
.update(cssWithUtils + '\0' + (adapterOptions.base ?? ''))
|
|
87
|
+
.digest('hex');
|
|
88
|
+
|
|
89
|
+
const compilerCache = getCompilerCache();
|
|
90
|
+
let compilerPromise = compilerCache.get(cacheKey);
|
|
91
|
+
if (compilerPromise !== undefined) {
|
|
92
|
+
compilerCache.delete(cacheKey);
|
|
93
|
+
compilerCache.set(cacheKey, compilerPromise);
|
|
94
|
+
} else {
|
|
95
|
+
while (compilerCache.size >= MAX_COMPILER_CACHE) {
|
|
96
|
+
const oldest = compilerCache.keys().next().value;
|
|
97
|
+
if (oldest !== undefined) compilerCache.delete(oldest);
|
|
98
|
+
else break;
|
|
99
|
+
}
|
|
100
|
+
compilerPromise = (async () => {
|
|
101
|
+
const lib = await load();
|
|
102
|
+
const compileOptions = adapterOptions.base !== undefined ? { base: adapterOptions.base } : undefined;
|
|
103
|
+
return compileOptions ? lib.compile(cssWithUtils, compileOptions) : lib.compile(cssWithUtils);
|
|
104
|
+
})().catch((cause) => {
|
|
105
|
+
compilerCache.delete(cacheKey);
|
|
106
|
+
throw cause;
|
|
107
|
+
});
|
|
108
|
+
compilerCache.set(cacheKey, compilerPromise);
|
|
109
|
+
}
|
|
45
110
|
|
|
46
111
|
let compiler: TailwindCompiler;
|
|
47
112
|
try {
|
|
48
|
-
compiler = await
|
|
113
|
+
compiler = await compilerPromise;
|
|
49
114
|
} catch (cause) {
|
|
50
115
|
throw new SomaEngineError('CORE-STYLE-ENGINE-THEME', 'style', '主题 CSS 编译失败', { cause });
|
|
51
116
|
}
|
|
117
|
+
|
|
52
118
|
let css: string;
|
|
53
119
|
try {
|
|
54
120
|
css = compiler.build([...guarded.accepted]);
|
|
@@ -56,12 +122,13 @@ export function createTailwindAdapter(adapterOptions: TailwindAdapterOptions = {
|
|
|
56
122
|
throw new SomaEngineError('CORE-STYLE-ENGINE-COMPILE', 'style', '样式表编译失败', { cause });
|
|
57
123
|
}
|
|
58
124
|
|
|
59
|
-
const
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
125
|
+
const { matched, unmatched } = partitionCompiledCandidates(css, guarded.accepted);
|
|
126
|
+
const accepted: string[] = matched;
|
|
127
|
+
const rejected: StyleCompileRejection[] = [
|
|
128
|
+
...guarded.rejected,
|
|
129
|
+
...unmatched.map((candidate) => ({ candidate, reason: 'no-rule' as const })),
|
|
130
|
+
];
|
|
131
|
+
|
|
65
132
|
return { css, accepted, rejected, digest: digestOf(css) };
|
|
66
133
|
},
|
|
67
134
|
};
|
|
@@ -5,33 +5,42 @@
|
|
|
5
5
|
// `scripts/verify-single-impl.mjs` 的 S1-d 对「别处再写一份源包判定」报红。
|
|
6
6
|
//
|
|
7
7
|
// 纪律(AD-34):这里只有 Host 与源包两种来源类别,不出现任何产生方的名字。
|
|
8
|
-
const fs = require(
|
|
9
|
-
const path = require(
|
|
8
|
+
const fs = require("node:fs");
|
|
9
|
+
const path = require("node:path");
|
|
10
10
|
|
|
11
11
|
/** @typedef {Readonly<Record<string, string | undefined>>} SomaEnv */
|
|
12
|
-
const { getSomaHostConfigRoot } = require(
|
|
12
|
+
const { getSomaHostConfigRoot } = require("./host-config-paths.cjs");
|
|
13
13
|
|
|
14
14
|
/** 环境变量:显式声明的源包名(逗号分隔),不论其 package.json 怎么写都当源包 */
|
|
15
|
-
const SOMA_SOURCE_PACKAGES_ENV =
|
|
15
|
+
const SOMA_SOURCE_PACKAGES_ENV = "SOMA_SOURCE_PACKAGES";
|
|
16
|
+
|
|
17
|
+
const MAX_ASSET_SOURCE_CACHE = 64;
|
|
18
|
+
/** @typedef {{ type: "host" | "package"; name: string; assetRoot: string; codeRoot: string; apiRoot: string; configRoot: string; packageName?: string }} SomaAssetSourceItem */
|
|
19
|
+
/** @type {Map<string, SomaAssetSourceItem[]>} */
|
|
20
|
+
const assetSourcesCache = new Map();
|
|
21
|
+
|
|
22
|
+
function clearSomaAssetSourcesCache() {
|
|
23
|
+
assetSourcesCache.clear();
|
|
24
|
+
}
|
|
16
25
|
|
|
17
26
|
function readJson(filePath) {
|
|
18
27
|
try {
|
|
19
28
|
if (!fs.existsSync(filePath)) return null;
|
|
20
|
-
return JSON.parse(fs.readFileSync(filePath,
|
|
29
|
+
return JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
21
30
|
} catch {
|
|
22
31
|
return null;
|
|
23
32
|
}
|
|
24
33
|
}
|
|
25
34
|
|
|
26
35
|
function packagePathInNodeModules(hostDir, packageName) {
|
|
27
|
-
return path.join(hostDir,
|
|
36
|
+
return path.join(hostDir, "node_modules", ...packageName.split("/"));
|
|
28
37
|
}
|
|
29
38
|
|
|
30
39
|
function resolvePackageRoot(hostDir, packageName, version) {
|
|
31
40
|
const nodeModulesPath = packagePathInNodeModules(hostDir, packageName);
|
|
32
41
|
if (fs.existsSync(nodeModulesPath)) return nodeModulesPath;
|
|
33
|
-
if (typeof version ===
|
|
34
|
-
const fileRoot = path.resolve(hostDir, version.slice(
|
|
42
|
+
if (typeof version === "string" && version.startsWith("file:")) {
|
|
43
|
+
const fileRoot = path.resolve(hostDir, version.slice("file:".length));
|
|
35
44
|
if (fs.existsSync(fileRoot)) return fileRoot;
|
|
36
45
|
}
|
|
37
46
|
return null;
|
|
@@ -39,14 +48,14 @@ function resolvePackageRoot(hostDir, packageName, version) {
|
|
|
39
48
|
|
|
40
49
|
/** @param {SomaEnv} [env] */
|
|
41
50
|
function readExplicitSourcePackages(env = process.env) {
|
|
42
|
-
return String(env[SOMA_SOURCE_PACKAGES_ENV] ??
|
|
43
|
-
.split(
|
|
51
|
+
return String(env?.[SOMA_SOURCE_PACKAGES_ENV] ?? "")
|
|
52
|
+
.split(",")
|
|
44
53
|
.map((item) => item.trim())
|
|
45
54
|
.filter(Boolean);
|
|
46
55
|
}
|
|
47
56
|
|
|
48
57
|
function readHostDependencies(hostDir) {
|
|
49
|
-
const packageJson = readJson(path.join(hostDir,
|
|
58
|
+
const packageJson = readJson(path.join(hostDir, "package.json"));
|
|
50
59
|
return {
|
|
51
60
|
...(packageJson?.dependencies ?? {}),
|
|
52
61
|
...(packageJson?.devDependencies ?? {}),
|
|
@@ -56,7 +65,7 @@ function readHostDependencies(hostDir) {
|
|
|
56
65
|
/** 子路径必须落在 parent 内且存在,否则回落 parent(越界不报错、不跟随) */
|
|
57
66
|
function resolveSafeChildRoot(parent, relativePath) {
|
|
58
67
|
const normalizedParent = path.resolve(parent);
|
|
59
|
-
const trimmed = typeof relativePath ===
|
|
68
|
+
const trimmed = typeof relativePath === "string" ? relativePath.trim() : "";
|
|
60
69
|
if (!trimmed) return normalizedParent;
|
|
61
70
|
const resolved = path.resolve(normalizedParent, trimmed);
|
|
62
71
|
if (resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)) {
|
|
@@ -65,29 +74,66 @@ function resolveSafeChildRoot(parent, relativePath) {
|
|
|
65
74
|
return normalizedParent;
|
|
66
75
|
}
|
|
67
76
|
|
|
68
|
-
|
|
77
|
+
/** 解析显式外部/同级/子目录路径(仅用于宿主自身 hostDir,第三方包不走此函数) */
|
|
78
|
+
function resolveExplicitHostPath(baseDir, rawPath, options = {}) {
|
|
79
|
+
if (typeof rawPath !== "string") return null;
|
|
80
|
+
const trimmed = rawPath.trim();
|
|
81
|
+
if (!trimmed || trimmed.includes("\0")) return null;
|
|
82
|
+
const resolved = path.resolve(baseDir, trimmed);
|
|
83
|
+
if (resolved === path.parse(resolved).root) return null;
|
|
84
|
+
if (options.requireExists && !fs.existsSync(resolved)) return null;
|
|
85
|
+
return resolved;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function getSomaHostSourceRoot(hostDir, env = process.env) {
|
|
69
89
|
const normalizedHostDir = path.resolve(hostDir);
|
|
70
|
-
|
|
90
|
+
if (env && typeof env.SOMA_WEB_DIR === "string" && env.SOMA_WEB_DIR.trim()) {
|
|
91
|
+
const explicit = resolveExplicitHostPath(normalizedHostDir, env.SOMA_WEB_DIR, { requireExists: false });
|
|
92
|
+
if (explicit) return explicit;
|
|
93
|
+
}
|
|
94
|
+
const packageJson = readJson(path.join(normalizedHostDir, "package.json"));
|
|
95
|
+
if (typeof packageJson?.soma?.webRoot === "string" && packageJson.soma.webRoot.trim()) {
|
|
96
|
+
const explicit = resolveExplicitHostPath(normalizedHostDir, packageJson.soma.webRoot, { requireExists: true });
|
|
97
|
+
if (explicit) return explicit;
|
|
98
|
+
}
|
|
71
99
|
return resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot);
|
|
72
100
|
}
|
|
73
101
|
|
|
102
|
+
function getSomaHostApiRoot(hostDir, env = process.env) {
|
|
103
|
+
const normalizedHostDir = path.resolve(hostDir);
|
|
104
|
+
if (env && typeof env.SOMA_API_DIR === "string" && env.SOMA_API_DIR.trim()) {
|
|
105
|
+
const explicit = resolveExplicitHostPath(normalizedHostDir, env.SOMA_API_DIR, { requireExists: false });
|
|
106
|
+
if (explicit) return explicit;
|
|
107
|
+
}
|
|
108
|
+
const packageJson = readJson(path.join(normalizedHostDir, "package.json"));
|
|
109
|
+
const candidate = typeof packageJson?.soma?.apiRoot === "string" && packageJson.soma.apiRoot.trim()
|
|
110
|
+
? packageJson.soma.apiRoot
|
|
111
|
+
: (typeof packageJson?.soma?.serviceRoot === "string" && packageJson.soma.serviceRoot.trim() ? packageJson.soma.serviceRoot : null);
|
|
112
|
+
if (candidate) {
|
|
113
|
+
const explicit = resolveExplicitHostPath(normalizedHostDir, candidate, { requireExists: true });
|
|
114
|
+
if (explicit) return explicit;
|
|
115
|
+
}
|
|
116
|
+
return getSomaHostSourceRoot(normalizedHostDir, env);
|
|
117
|
+
}
|
|
118
|
+
|
|
74
119
|
/** 源包判定:显式声明(环境变量)或 `package.json` 的 `soma.source === true` */
|
|
75
120
|
function isSomaSourcePackage(packageRoot, explicit) {
|
|
76
121
|
if (explicit) return true;
|
|
77
|
-
const packageJson = readJson(path.join(packageRoot,
|
|
122
|
+
const packageJson = readJson(path.join(packageRoot, "package.json"));
|
|
78
123
|
return packageJson?.soma?.source === true;
|
|
79
124
|
}
|
|
80
125
|
|
|
81
126
|
function toPackageSource(packageName, packageRoot) {
|
|
82
|
-
const packageJson = readJson(path.join(packageRoot,
|
|
127
|
+
const packageJson = readJson(path.join(packageRoot, "package.json"));
|
|
83
128
|
const codeRoot = resolveSafeChildRoot(packageRoot, packageJson?.soma?.hostRoot);
|
|
84
129
|
const configRoot = resolveSafeChildRoot(packageRoot, packageJson?.soma?.configRoot);
|
|
85
130
|
return {
|
|
86
|
-
type:
|
|
131
|
+
type: "package",
|
|
87
132
|
name: packageName,
|
|
88
133
|
packageName,
|
|
89
134
|
assetRoot: codeRoot,
|
|
90
135
|
codeRoot,
|
|
136
|
+
apiRoot: codeRoot,
|
|
91
137
|
configRoot,
|
|
92
138
|
};
|
|
93
139
|
}
|
|
@@ -96,17 +142,29 @@ function toPackageSource(packageName, packageRoot) {
|
|
|
96
142
|
/** @param {SomaEnv} [env] */
|
|
97
143
|
function getSomaAssetSources(hostDir, env = process.env) {
|
|
98
144
|
const normalizedHostDir = path.resolve(hostDir);
|
|
99
|
-
|
|
145
|
+
|
|
146
|
+
const pkgStat = fs.statSync(path.join(normalizedHostDir, "package.json"), { throwIfNoEntry: false });
|
|
147
|
+
const pkgStatKey = pkgStat ? `${pkgStat.mtimeMs}:${pkgStat.size}` : "none";
|
|
148
|
+
const cacheKey = `${normalizedHostDir}\0${env?.[SOMA_SOURCE_PACKAGES_ENV] ?? ""}\0${env?.SOMA_WEB_DIR ?? ""}\0${env?.SOMA_API_DIR ?? ""}\0${pkgStatKey}`;
|
|
149
|
+
|
|
150
|
+
const cached = assetSourcesCache.get(cacheKey);
|
|
151
|
+
if (cached) {
|
|
152
|
+
return cached.slice();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const hostSourceRoot = getSomaHostSourceRoot(normalizedHostDir, env);
|
|
156
|
+
const hostApiRoot = getSomaHostApiRoot(normalizedHostDir, env);
|
|
100
157
|
const dependencies = readHostDependencies(normalizedHostDir);
|
|
101
158
|
const explicitPackages = new Set(readExplicitSourcePackages(env));
|
|
102
159
|
const packageNames = new Set([...Object.keys(dependencies), ...explicitPackages]);
|
|
103
160
|
|
|
104
161
|
const sources = [
|
|
105
162
|
{
|
|
106
|
-
type:
|
|
107
|
-
name:
|
|
163
|
+
type: "host",
|
|
164
|
+
name: "host",
|
|
108
165
|
assetRoot: hostSourceRoot,
|
|
109
166
|
codeRoot: hostSourceRoot,
|
|
167
|
+
apiRoot: hostApiRoot,
|
|
110
168
|
configRoot: getSomaHostConfigRoot(normalizedHostDir),
|
|
111
169
|
},
|
|
112
170
|
];
|
|
@@ -116,32 +174,38 @@ function getSomaAssetSources(hostDir, env = process.env) {
|
|
|
116
174
|
if (!packageRoot || !isSomaSourcePackage(packageRoot, explicitPackages.has(packageName))) continue;
|
|
117
175
|
sources.push(toPackageSource(packageName, packageRoot));
|
|
118
176
|
}
|
|
119
|
-
|
|
177
|
+
|
|
178
|
+
if (assetSourcesCache.size >= MAX_ASSET_SOURCE_CACHE) {
|
|
179
|
+
assetSourcesCache.delete(assetSourcesCache.keys().next().value);
|
|
180
|
+
}
|
|
181
|
+
assetSourcesCache.set(cacheKey, sources);
|
|
182
|
+
|
|
183
|
+
return sources.slice();
|
|
120
184
|
}
|
|
121
185
|
|
|
122
186
|
/** 源包名清单(next.config 的 transpilePackages 用) */
|
|
123
187
|
/** @param {SomaEnv} [env] */
|
|
124
188
|
function listSomaSourcePackageNames(hostDir, env = process.env) {
|
|
125
189
|
return getSomaAssetSources(hostDir, env)
|
|
126
|
-
.filter((source) => source.type ===
|
|
190
|
+
.filter((source) => source.type === "package")
|
|
127
191
|
.map((source) => source.packageName);
|
|
128
192
|
}
|
|
129
193
|
|
|
130
194
|
/** 覆盖顺序:源包在前、Host 在后(同名页面与片段由 Host 覆盖) */
|
|
131
195
|
function orderSourcesForOverride(sources) {
|
|
132
196
|
return [
|
|
133
|
-
...sources.filter((source) => source.type ===
|
|
134
|
-
...sources.filter((source) => source.type ===
|
|
197
|
+
...sources.filter((source) => source.type === "package"),
|
|
198
|
+
...sources.filter((source) => source.type === "host"),
|
|
135
199
|
];
|
|
136
200
|
}
|
|
137
201
|
|
|
138
|
-
function collectHtmlFiles(dir, prefix =
|
|
202
|
+
function collectHtmlFiles(dir, prefix = "", acc = []) {
|
|
139
203
|
if (!fs.existsSync(dir)) return acc;
|
|
140
204
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
141
205
|
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
142
206
|
const full = path.join(dir, entry.name);
|
|
143
207
|
if (entry.isDirectory()) collectHtmlFiles(full, rel, acc);
|
|
144
|
-
else if (entry.name.endsWith(
|
|
208
|
+
else if (entry.name.endsWith(".html")) acc.push(rel);
|
|
145
209
|
}
|
|
146
210
|
return acc;
|
|
147
211
|
}
|
|
@@ -150,7 +214,7 @@ function collectHtmlFiles(dir, prefix = '', acc = []) {
|
|
|
150
214
|
function collectPageEntries(sources) {
|
|
151
215
|
const byHtmlFile = new Map();
|
|
152
216
|
for (const source of orderSourcesForOverride(sources)) {
|
|
153
|
-
const htmlRoot = path.join(source.assetRoot,
|
|
217
|
+
const htmlRoot = path.join(source.assetRoot, "html");
|
|
154
218
|
for (const htmlFile of collectHtmlFiles(htmlRoot).sort()) {
|
|
155
219
|
byHtmlFile.set(htmlFile, { source, htmlFile });
|
|
156
220
|
}
|
|
@@ -162,11 +226,11 @@ function collectPageEntries(sources) {
|
|
|
162
226
|
function collectIncludes(sources) {
|
|
163
227
|
const includes = {};
|
|
164
228
|
for (const source of orderSourcesForOverride(sources)) {
|
|
165
|
-
const sharedDir = path.join(source.assetRoot,
|
|
229
|
+
const sharedDir = path.join(source.assetRoot, "html", "shared");
|
|
166
230
|
if (!fs.existsSync(sharedDir)) continue;
|
|
167
231
|
for (const entry of fs.readdirSync(sharedDir, { withFileTypes: true })) {
|
|
168
|
-
if (!entry.isFile() || !entry.name.endsWith(
|
|
169
|
-
includes[`shared/${entry.name}`] = fs.readFileSync(path.join(sharedDir, entry.name),
|
|
232
|
+
if (!entry.isFile() || !entry.name.endsWith(".html")) continue;
|
|
233
|
+
includes[`shared/${entry.name}`] = fs.readFileSync(path.join(sharedDir, entry.name), "utf8");
|
|
170
234
|
}
|
|
171
235
|
}
|
|
172
236
|
return includes;
|
|
@@ -175,6 +239,8 @@ function collectIncludes(sources) {
|
|
|
175
239
|
module.exports = {
|
|
176
240
|
SOMA_SOURCE_PACKAGES_ENV,
|
|
177
241
|
getSomaHostSourceRoot,
|
|
242
|
+
getSomaHostApiRoot,
|
|
243
|
+
clearSomaAssetSourcesCache,
|
|
178
244
|
getSomaAssetSources,
|
|
179
245
|
listSomaSourcePackageNames,
|
|
180
246
|
orderSourcesForOverride,
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import * as impl from
|
|
1
|
+
import * as impl from "./source-packages.cjs";
|
|
2
2
|
|
|
3
3
|
export interface SomaAssetSource {
|
|
4
|
-
type:
|
|
4
|
+
type: "host" | "package";
|
|
5
5
|
name: string;
|
|
6
6
|
assetRoot: string;
|
|
7
7
|
codeRoot: string;
|
|
8
|
+
apiRoot: string;
|
|
8
9
|
configRoot: string;
|
|
9
10
|
packageName?: string;
|
|
10
11
|
}
|
|
@@ -16,11 +17,17 @@ export {
|
|
|
16
17
|
resolveAppConfigPath,
|
|
17
18
|
resolveHostAppConfigPath,
|
|
18
19
|
resolveHostConfigRoot,
|
|
19
|
-
} from
|
|
20
|
-
export type { SomaEnvName } from
|
|
20
|
+
} from "./host-config-paths";
|
|
21
|
+
export type { SomaEnvName } from "./host-config-paths";
|
|
21
22
|
|
|
22
23
|
/** 实现只有 `source-packages.cjs` 一份(RT3 单实现);这里只补类型再导出,不另写第二份。 */
|
|
23
|
-
export const getSomaHostSourceRoot: (hostDir: string) => string =
|
|
24
|
+
export const getSomaHostSourceRoot: (hostDir: string, env?: Readonly<Record<string, string | undefined>>) => string =
|
|
25
|
+
impl.getSomaHostSourceRoot;
|
|
26
|
+
|
|
27
|
+
export const getSomaHostApiRoot: (hostDir: string, env?: Readonly<Record<string, string | undefined>>) => string =
|
|
28
|
+
impl.getSomaHostApiRoot;
|
|
29
|
+
|
|
30
|
+
export const clearSomaAssetSourcesCache: () => void = impl.clearSomaAssetSourcesCache;
|
|
24
31
|
|
|
25
32
|
/** Host 自己 + 全部源包;Host 恒在第一位 */
|
|
26
33
|
export const getSomaAssetSources: (hostDir: string, env?: Readonly<Record<string, string | undefined>>) => SomaAssetSource[] =
|