soma-core 2.2.9 → 2.2.11
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 +8 -19
- package/bin/service-codegen.cjs +2 -3
- package/bin/soma.cjs +2 -2
- package/core/build/compiler/soma-precompile.js +19 -6
- package/core/client/data/region-scope-port.ts +8 -3
- package/core/client/engine/event-engine.ts +1 -1
- package/core/client/engine/soma-bootstrap.ts +9 -0
- package/core/client/engines/diff/code.ts +205 -0
- package/core/client/engines/diff/index.ts +27 -1
- package/core/client/engines/diff/port.ts +75 -0
- package/core/client/parser/confirm-spec.ts +10 -4
- package/core/client/parser/ui-config-parser.ts +14 -2
- package/core/index.ts +1 -1
- package/core/server/api/load-host-service.ts +0 -1
- package/core/server/host/source-packages.cjs +3 -0
- package/core/shared/registry-generated/diagnostic-registry-index.ts +16 -0
- package/core/shared/registry-generated/diagnostic-registry.ts +130 -0
- package/core/shared/registry-generated/limits.ts +6 -2
- package/core/shared/registry-generated/std-grammar-views.ts +1 -1
- package/core/shared/registry-generated/std-grammar.ts +1 -1
- package/core/shared/types/region-scope.types.ts +6 -0
- package/dist/browser/runtime-bundle.manifest.json +12 -12
- package/dist/browser/soma-runtime.js +752 -489
- package/dist/core/index.cjs +752 -489
- package/dist/host-native/aot-builder.cjs +366 -226
- package/dist/host-native/native-server.cjs +131 -56
- package/dist/lsp/component-tree.cjs +23 -10
- package/dist/types/client/data/region-scope-port.d.ts +1 -1
- package/dist/types/client/engine/soma-bootstrap.d.ts +5 -0
- package/dist/types/client/engines/diff/code.d.ts +27 -0
- package/dist/types/client/engines/diff/index.d.ts +2 -1
- package/dist/types/client/engines/diff/port.d.ts +77 -0
- package/dist/types/client/parser/confirm-spec.d.ts +1 -1
- package/dist/types/server/host/source-packages.d.cts +5 -0
- package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +113 -1
- package/dist/types/shared/registry-generated/limits.d.ts +4 -0
- package/dist/types/shared/registry-generated/std-grammar-views.d.ts +1 -1
- package/dist/types/shared/registry-generated/std-grammar.d.ts +1 -1
- package/dist/types/shared/types/region-scope.types.d.ts +6 -0
- package/host-native/bin/host-native.cjs +1 -1
- package/host-native/client/browser-entry.ts +12 -1
- package/host-native/client/first-frame.ts +8 -0
- package/host-native/client/router-bridge.ts +8 -2
- package/host-native/src/aot-builder.ts +173 -93
- package/host-native/src/native-server.ts +131 -25
- package/host-native/src/public-packages.cjs +156 -50
- package/host-native/styles/globals.css +28 -2
- package/package.json +2 -2
- package/dist/core/adaptive-pure.cjs +0 -41
- package/dist/core/theme-pure.cjs +0 -38
- package/dist/preview-export.cjs +0 -3401
|
@@ -2,7 +2,7 @@ import fs from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
4
|
import esbuild, { type BuildContext, type Plugin } from 'esbuild';
|
|
5
|
-
import { readAllSomaPublicAliases } from './public-packages.cjs';
|
|
5
|
+
import { readAllSomaPublicAliases, createPublicAliasesFilter } from './public-packages.cjs';
|
|
6
6
|
import { collectDevChunks, outputsRelativeTo, releaseDevChunks } from './dev-chunk-gc';
|
|
7
7
|
import { toPascalCase } from '../../core/server/api/service-path';
|
|
8
8
|
import { getSomaHostSourceRoot, getSomaHostApiRoot } from '../../core/server/host/source-packages.cjs';
|
|
@@ -39,9 +39,27 @@ export interface BrowserClientBuildResult {
|
|
|
39
39
|
readonly cssUrl: string;
|
|
40
40
|
readonly cssText: string;
|
|
41
41
|
rebuild(): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* 开发态:这批改动(绝对路径)会不会改变客户端包(clientBuildAffectedBy)。缺省(生产清单、首轮构建前)视为会。
|
|
44
|
+
* 宿主刷新队列据此跳过只改页面资产(html / yaml 等,不进客户端包)时的整包重建。
|
|
45
|
+
*/
|
|
46
|
+
affectedBy?(changedFiles: readonly string[]): boolean;
|
|
42
47
|
dispose(): Promise<void>;
|
|
43
48
|
}
|
|
44
49
|
|
|
50
|
+
/** esbuild 能当模块加载的扩展名:新增 / 删除这类文件可能改变插件的解析结果(bootstrap、domain/ui/*Class.ts、@soma-host/* 的存在性判断),即使它还不在上次的输入里 */
|
|
51
|
+
const CLIENT_MODULE_EXT = /\.(?:[cm]?[jt]sx?|json|css)$/i;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 开发态按需重建的判据(纯函数):inputs = 上次构建 metafile 的输入(绝对路径;null = 还不知道)。
|
|
55
|
+
* 改动里有任一文件是上次的输入、或是可当模块加载的扩展名 → 需要重建;改动集为空(来源不明)也重建。
|
|
56
|
+
* 只改页面资产(四件套 html / yaml、kit 页面 yaml、文档、图片)且它们不在输入里 → 不重建:页面由预热与 Registry 出,客户端包不变。
|
|
57
|
+
*/
|
|
58
|
+
export function clientBuildAffectedBy(inputs: ReadonlySet<string> | null, changedFiles: readonly string[]): boolean {
|
|
59
|
+
if (inputs === null || changedFiles.length === 0) return true;
|
|
60
|
+
return changedFiles.some((file) => inputs.has(path.resolve(file)) || CLIENT_MODULE_EXT.test(file));
|
|
61
|
+
}
|
|
62
|
+
|
|
45
63
|
export interface BuildServerAotOptions {
|
|
46
64
|
readonly hostDir: string;
|
|
47
65
|
readonly webRoot?: string;
|
|
@@ -87,14 +105,16 @@ const repoRoot = path.resolve(coreRoot, '..');
|
|
|
87
105
|
* 客户端专属 esbuild 插件:
|
|
88
106
|
* 1. 严禁 import 'server-only';
|
|
89
107
|
* 2. 映射 @soma-host/* 虚拟/可选模块;
|
|
90
|
-
* 3. 映射 soma-*
|
|
108
|
+
* 3. 映射 soma-* 及 soma.source 源包公开子路径。
|
|
91
109
|
*/
|
|
92
110
|
function createBrowserClientPlugin(options: {
|
|
93
111
|
hostDir: string;
|
|
94
112
|
webRoot: string;
|
|
113
|
+
env?: NodeJS.ProcessEnv;
|
|
95
114
|
}): Plugin {
|
|
96
|
-
const { hostDir, webRoot } = options;
|
|
97
|
-
const publicAliases = readAllSomaPublicAliases(hostDir, repoRoot, [webRoot, coreRoot]) as Record<string, string>;
|
|
115
|
+
const { hostDir, webRoot, env } = options;
|
|
116
|
+
const publicAliases = readAllSomaPublicAliases(hostDir, repoRoot, [webRoot, coreRoot], env) as Record<string, string>;
|
|
117
|
+
const publicFilter = createPublicAliasesFilter(publicAliases);
|
|
98
118
|
|
|
99
119
|
return {
|
|
100
120
|
name: 'soma-browser-client-plugin',
|
|
@@ -175,7 +195,7 @@ function createBrowserClientPlugin(options: {
|
|
|
175
195
|
});
|
|
176
196
|
|
|
177
197
|
// 5b. 源码根别名(soma.sourceRoots)
|
|
178
|
-
registerSourceRootResolve(build, hostDir);
|
|
198
|
+
registerSourceRootResolve(build, hostDir, env);
|
|
179
199
|
|
|
180
200
|
// 6. 拦截内部 engine 模块私有深导入(RT4 守卫)
|
|
181
201
|
build.onResolve({ filter: /core\/client\/engine\// }, (args) => {
|
|
@@ -187,14 +207,16 @@ function createBrowserClientPlugin(options: {
|
|
|
187
207
|
return undefined;
|
|
188
208
|
});
|
|
189
209
|
|
|
190
|
-
// 7. soma-*
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
210
|
+
// 7. soma-* 与 soma.source 源包公开子路径解析
|
|
211
|
+
if (publicFilter) {
|
|
212
|
+
build.onResolve({ filter: publicFilter }, (args) => {
|
|
213
|
+
const direct = publicAliases[args.path];
|
|
214
|
+
if (direct && fs.existsSync(direct)) {
|
|
215
|
+
return { path: direct };
|
|
216
|
+
}
|
|
217
|
+
return undefined;
|
|
218
|
+
});
|
|
219
|
+
}
|
|
198
220
|
|
|
199
221
|
// 8. 可选 peer 依赖 echarts:仅当包 `echarts` 本身无法解析(未安装)时才回落轻量无头桩模块,
|
|
200
222
|
// 防未装 echarts 的应用在 soma dev / build 时崩溃;已安装 echarts 但某个子路径解析失败(版本不符、路径写错)
|
|
@@ -264,7 +286,7 @@ export async function buildBrowserClient(
|
|
|
264
286
|
fs.mkdirSync(clientOutDir, { recursive: true });
|
|
265
287
|
|
|
266
288
|
const clientEntry = path.join(hostNativeRoot, 'client/browser-entry.ts');
|
|
267
|
-
const plugin = createBrowserClientPlugin({ hostDir, webRoot });
|
|
289
|
+
const plugin = createBrowserClientPlugin({ hostDir, webRoot, env: options.env });
|
|
268
290
|
|
|
269
291
|
// 编译并输出 CSS
|
|
270
292
|
const cssSourcePath = path.join(hostNativeRoot, 'styles/globals.css');
|
|
@@ -316,11 +338,16 @@ export async function buildBrowserClient(
|
|
|
316
338
|
let ctx: BuildContext | null = null;
|
|
317
339
|
let entryUrl = '/_soma/client/browser-entry.js';
|
|
318
340
|
|
|
319
|
-
// 开发态每次构建后按进程登记回收旧分片(dev-chunk-gc.ts):旧实现从不清理,chunks/
|
|
341
|
+
// 开发态每次构建后按进程登记回收旧分片(dev-chunk-gc.ts):旧实现从不清理,chunks/ 会无限增长;
|
|
342
|
+
// 同一份 metafile 的输入集记下来,供按需重建判据(clientBuildAffectedBy)用
|
|
343
|
+
let devInputs: Set<string> | null = null;
|
|
320
344
|
const devRebuild = async (): Promise<void> => {
|
|
321
345
|
if (!ctx) return;
|
|
322
346
|
const result = await ctx.rebuild();
|
|
323
|
-
if (result.metafile)
|
|
347
|
+
if (result.metafile) {
|
|
348
|
+
collectDevChunks(clientOutDir, outputsRelativeTo(clientOutDir, Object.keys(result.metafile.outputs)));
|
|
349
|
+
devInputs = new Set(Object.keys(result.metafile.inputs).map((file) => path.resolve(file)));
|
|
350
|
+
}
|
|
324
351
|
};
|
|
325
352
|
|
|
326
353
|
if (options.dev) {
|
|
@@ -362,6 +389,7 @@ export async function buildBrowserClient(
|
|
|
362
389
|
rebuild: async () => {
|
|
363
390
|
await devRebuild();
|
|
364
391
|
},
|
|
392
|
+
affectedBy: (changedFiles) => clientBuildAffectedBy(devInputs, changedFiles),
|
|
365
393
|
dispose: async () => {
|
|
366
394
|
if (ctx) {
|
|
367
395
|
await ctx.dispose();
|
|
@@ -371,8 +399,20 @@ export async function buildBrowserClient(
|
|
|
371
399
|
};
|
|
372
400
|
}
|
|
373
401
|
|
|
402
|
+
/** 将公开包说明符映射为无冲突的共享 AOT 预编译文件名(不含 .cjs 后缀) */
|
|
403
|
+
function sharedPackageSlug(specifier: string): string {
|
|
404
|
+
const safe = specifier
|
|
405
|
+
.replace(/^@/, '')
|
|
406
|
+
.replace(/[^a-zA-Z0-9_-]+/g, '__')
|
|
407
|
+
.replace(/^_+|_+$/g, '');
|
|
408
|
+
const hash = createHash('sha256').update(specifier).digest('hex').slice(0, 8);
|
|
409
|
+
return `${safe || 'pkg'}-${hash}`;
|
|
410
|
+
}
|
|
411
|
+
|
|
374
412
|
/**
|
|
375
|
-
* 后端 AOT 预编译:扫描后端服务源文件及 soma.app.ts,内联编译成 Node CJS 极速产物并生成 aot-manifest.json
|
|
413
|
+
* 后端 AOT 预编译:扫描后端服务源文件及 soma.app.ts,内联编译成 Node CJS 极速产物并生成 aot-manifest.json。
|
|
414
|
+
* 被引用的 soma-* / soma.source 源包出口统一预编译一次到 `aot-server/_packages/*.cjs`,各服务通过相对 require 共享同一份实例,
|
|
415
|
+
* 既彻底避免 Node 24 拒绝在 node_modules 下剥离 .ts 类型(ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING),又避免多服务重复内联导致的体积膨胀与单例分裂。
|
|
376
416
|
*/
|
|
377
417
|
export async function buildServerAot(
|
|
378
418
|
options: BuildServerAotOptions,
|
|
@@ -382,15 +422,17 @@ export async function buildServerAot(
|
|
|
382
422
|
const apiRoot = path.resolve(options.apiRoot || getSomaHostApiRoot(hostDir, options.env));
|
|
383
423
|
const outDir = path.resolve(options.outDir);
|
|
384
424
|
const aotServerDir = path.join(outDir, 'aot-server');
|
|
425
|
+
const sharedPackagesDir = path.join(aotServerDir, '_packages');
|
|
385
426
|
fs.mkdirSync(aotServerDir, { recursive: true });
|
|
427
|
+
fs.rmSync(sharedPackagesDir, { recursive: true, force: true });
|
|
386
428
|
|
|
387
429
|
const serviceFiles = scanServiceFiles(apiRoot, webRoot);
|
|
388
|
-
const
|
|
430
|
+
const serviceEntryPoints: Record<string, string> = {};
|
|
389
431
|
const routes: Record<string, string> = {};
|
|
390
432
|
|
|
391
433
|
for (const item of serviceFiles) {
|
|
392
434
|
const entryName = `services/${item.routeKey.replace(/\//g, '_')}`;
|
|
393
|
-
|
|
435
|
+
serviceEntryPoints[entryName] = item.filePath;
|
|
394
436
|
routes[item.routeKey] = `${entryName}.cjs`;
|
|
395
437
|
|
|
396
438
|
// 支持不同大小写路由键
|
|
@@ -409,85 +451,123 @@ export async function buildServerAot(
|
|
|
409
451
|
let hostAppCompiledPath: string | undefined;
|
|
410
452
|
const hostAppPath = path.resolve(webRoot, 'soma.app.ts');
|
|
411
453
|
if (fs.existsSync(hostAppPath)) {
|
|
412
|
-
entryPoints['host-app'] = hostAppPath;
|
|
413
454
|
hostAppCompiledPath = 'host-app.cjs';
|
|
414
455
|
}
|
|
415
456
|
|
|
416
|
-
|
|
457
|
+
const publicAliases = readAllSomaPublicAliases(hostDir, repoRoot, [webRoot, apiRoot, coreRoot], options.env) as Record<string, string>;
|
|
458
|
+
const publicFilter = createPublicAliasesFilter(publicAliases);
|
|
459
|
+
const sharedEntries = new Map<string, string>();
|
|
460
|
+
const nodePaths = [
|
|
461
|
+
path.join(apiRoot, 'node_modules'),
|
|
462
|
+
path.join(webRoot, 'node_modules'),
|
|
463
|
+
path.join(hostDir, 'node_modules'),
|
|
464
|
+
path.join(coreRoot, 'node_modules'),
|
|
465
|
+
].filter((d) => fs.existsSync(d));
|
|
466
|
+
|
|
467
|
+
const createServerAotPlugin = (mode: { sharedOutPrefix: string } | { inlinePublic: true }): Plugin => ({
|
|
468
|
+
name: 'soma-server-aot-plugin',
|
|
469
|
+
setup(build) {
|
|
470
|
+
build.onResolve({ filter: /^server-only$/ }, () => {
|
|
471
|
+
return { path: path.resolve(coreRoot, 'core/server/host/server-only-noop.cjs') };
|
|
472
|
+
});
|
|
473
|
+
build.onResolve({ filter: /^@core(?:\/.*)?$/ }, (args) => {
|
|
474
|
+
const subpath = args.path.replace(/^@core\/?/, '');
|
|
475
|
+
return { path: resolveModuleFile(path.resolve(coreRoot, 'core'), subpath) };
|
|
476
|
+
});
|
|
477
|
+
build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-bootstrap$/ }, () => {
|
|
478
|
+
const candidateHostFile = path.resolve(webRoot, 'bootstrap/soma-bootstrap');
|
|
479
|
+
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
480
|
+
if (fs.existsSync(candidateHostFile + ext)) {
|
|
481
|
+
return { path: candidateHostFile + ext };
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
if (fs.existsSync(path.resolve(webRoot, 'soma.app.ts'))) {
|
|
485
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-from-app.ts') };
|
|
486
|
+
}
|
|
487
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-host.stub.ts') };
|
|
488
|
+
});
|
|
489
|
+
build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-domain-loaders$/ }, () => {
|
|
490
|
+
const candidateLoader = path.resolve(webRoot, 'bootstrap/soma-domain-loaders');
|
|
491
|
+
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
492
|
+
if (fs.existsSync(candidateLoader + ext)) {
|
|
493
|
+
return { path: candidateLoader + ext };
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-domain-loaders.stub.ts') };
|
|
497
|
+
});
|
|
498
|
+
build.onResolve({ filter: /^@soma-host\/domain\/ui\/.*Class\.ts$/ }, (args) => {
|
|
499
|
+
const baseName = path.basename(args.path);
|
|
500
|
+
const diskFile = path.resolve(webRoot, 'domain/ui', baseName);
|
|
501
|
+
if (fs.existsSync(diskFile)) {
|
|
502
|
+
return { path: diskFile };
|
|
503
|
+
}
|
|
504
|
+
return { path: args.path, namespace: 'soma-absent-domain' };
|
|
505
|
+
});
|
|
506
|
+
build.onLoad({ filter: /.*/, namespace: 'soma-absent-domain' }, (args) => ({
|
|
507
|
+
contents: `const err = new Error("Cannot find module '${args.path}'"); err.code = "MODULE_NOT_FOUND"; throw err;`,
|
|
508
|
+
loader: 'js',
|
|
509
|
+
}));
|
|
510
|
+
build.onResolve({ filter: /^@soma-host(?:\/.*)?$/ }, (args) => {
|
|
511
|
+
const subpath = args.path.replace(/^@soma-host\/?/, '');
|
|
512
|
+
return { path: resolveModuleFile(webRoot, subpath) };
|
|
513
|
+
});
|
|
514
|
+
registerSourceRootResolve(build, hostDir, options.env);
|
|
515
|
+
build.onResolve({ filter: /^@soma-api(?:\/.*)?$/ }, (args) => {
|
|
516
|
+
const subpath = args.path.replace(/^@soma-api\/?/, '');
|
|
517
|
+
return { path: resolveModuleFile(apiRoot, subpath) };
|
|
518
|
+
});
|
|
519
|
+
if (publicFilter) {
|
|
520
|
+
build.onResolve({ filter: publicFilter }, (args) => {
|
|
521
|
+
const direct = publicAliases[args.path];
|
|
522
|
+
if (!direct || !fs.existsSync(direct)) {
|
|
523
|
+
return undefined;
|
|
524
|
+
}
|
|
525
|
+
if ('inlinePublic' in mode) {
|
|
526
|
+
return { path: direct };
|
|
527
|
+
}
|
|
528
|
+
const slug = sharedPackageSlug(args.path);
|
|
529
|
+
sharedEntries.set(slug, direct);
|
|
530
|
+
return { path: `${mode.sharedOutPrefix}_packages/${slug}.cjs`, external: true };
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
},
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
const baseServerBuildOptions: Omit<esbuild.BuildOptions, 'entryPoints' | 'outdir' | 'plugins'> = {
|
|
537
|
+
bundle: true,
|
|
538
|
+
platform: 'node',
|
|
539
|
+
format: 'cjs',
|
|
540
|
+
target: 'node20',
|
|
541
|
+
packages: 'external',
|
|
542
|
+
nodePaths,
|
|
543
|
+
outExtension: { '.js': '.cjs' },
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
if (Object.keys(serviceEntryPoints).length > 0) {
|
|
417
547
|
await esbuild.build({
|
|
418
|
-
|
|
548
|
+
...baseServerBuildOptions,
|
|
549
|
+
entryPoints: serviceEntryPoints,
|
|
419
550
|
outdir: aotServerDir,
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
const candidateHostFile = path.resolve(webRoot, 'bootstrap/soma-bootstrap');
|
|
441
|
-
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
442
|
-
if (fs.existsSync(candidateHostFile + ext)) {
|
|
443
|
-
return { path: candidateHostFile + ext };
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
if (fs.existsSync(path.resolve(webRoot, 'soma.app.ts'))) {
|
|
447
|
-
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-from-app.ts') };
|
|
448
|
-
}
|
|
449
|
-
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-bootstrap-host.stub.ts') };
|
|
450
|
-
});
|
|
451
|
-
build.onResolve({ filter: /^@soma-host\/bootstrap\/soma-domain-loaders$/ }, () => {
|
|
452
|
-
const candidateLoader = path.resolve(webRoot, 'bootstrap/soma-domain-loaders');
|
|
453
|
-
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
454
|
-
if (fs.existsSync(candidateLoader + ext)) {
|
|
455
|
-
return { path: candidateLoader + ext };
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
return { path: path.resolve(coreRoot, 'core/client/host-bridge/soma-domain-loaders.stub.ts') };
|
|
459
|
-
});
|
|
460
|
-
build.onResolve({ filter: /^@soma-host\/domain\/ui\/.*Class\.ts$/ }, (args) => {
|
|
461
|
-
const baseName = path.basename(args.path);
|
|
462
|
-
const diskFile = path.resolve(webRoot, 'domain/ui', baseName);
|
|
463
|
-
if (fs.existsSync(diskFile)) {
|
|
464
|
-
return { path: diskFile };
|
|
465
|
-
}
|
|
466
|
-
return { path: args.path, namespace: 'soma-absent-domain' };
|
|
467
|
-
});
|
|
468
|
-
build.onLoad({ filter: /.*/, namespace: 'soma-absent-domain' }, (args) => ({
|
|
469
|
-
contents: `const err = new Error("Cannot find module '${args.path}'"); err.code = "MODULE_NOT_FOUND"; throw err;`,
|
|
470
|
-
loader: 'js',
|
|
471
|
-
}));
|
|
472
|
-
build.onResolve({ filter: /^@soma-host(?:\/.*)?$/ }, (args) => {
|
|
473
|
-
const subpath = args.path.replace(/^@soma-host\/?/, '');
|
|
474
|
-
return { path: resolveModuleFile(webRoot, subpath) };
|
|
475
|
-
});
|
|
476
|
-
registerSourceRootResolve(build, hostDir, options.env);
|
|
477
|
-
build.onResolve({ filter: /^@soma-api(?:\/.*)?$/ }, (args) => {
|
|
478
|
-
const subpath = args.path.replace(/^@soma-api\/?/, '');
|
|
479
|
-
return { path: resolveModuleFile(apiRoot, subpath) };
|
|
480
|
-
});
|
|
481
|
-
build.onResolve({ filter: /^soma-[a-z0-9-]+(?:\/.*)?$/ }, (args) => {
|
|
482
|
-
const direct = publicAliases[args.path];
|
|
483
|
-
if (direct && fs.existsSync(direct)) {
|
|
484
|
-
return { path: direct };
|
|
485
|
-
}
|
|
486
|
-
return undefined;
|
|
487
|
-
});
|
|
488
|
-
},
|
|
489
|
-
},
|
|
490
|
-
],
|
|
551
|
+
plugins: [createServerAotPlugin({ sharedOutPrefix: '../' })],
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
if (hostAppCompiledPath) {
|
|
556
|
+
await esbuild.build({
|
|
557
|
+
...baseServerBuildOptions,
|
|
558
|
+
entryPoints: { 'host-app': hostAppPath },
|
|
559
|
+
outdir: aotServerDir,
|
|
560
|
+
plugins: [createServerAotPlugin({ sharedOutPrefix: './' })],
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
if (sharedEntries.size > 0) {
|
|
565
|
+
fs.mkdirSync(sharedPackagesDir, { recursive: true });
|
|
566
|
+
await esbuild.build({
|
|
567
|
+
...baseServerBuildOptions,
|
|
568
|
+
entryPoints: Object.fromEntries(sharedEntries),
|
|
569
|
+
outdir: sharedPackagesDir,
|
|
570
|
+
plugins: [createServerAotPlugin({ inlinePublic: true })],
|
|
491
571
|
});
|
|
492
572
|
}
|
|
493
573
|
|
|
@@ -527,12 +527,17 @@ async function sendEarlyResponseAndClose(
|
|
|
527
527
|
await sendWebResponse(webRes, res, method);
|
|
528
528
|
}
|
|
529
529
|
|
|
530
|
-
/**
|
|
530
|
+
/**
|
|
531
|
+
* 装配可选字段 `documentHead` 的形状:静态片段,或按请求上下文(CSP nonce)生成片段的函数。
|
|
532
|
+
* 契约:`documentHead` 函数须为无副作用纯函数,相同输入返回稳定字符串以便命中静态壳缓存;
|
|
533
|
+
* 启动期与开发态重载期会以 `{}` 预求值一次,返回非字符串或抛错时立即快失败。
|
|
534
|
+
*/
|
|
531
535
|
export type DocumentHeadSource = string | ((ctx: { readonly nonce?: string }) => string);
|
|
532
536
|
|
|
533
537
|
/**
|
|
534
538
|
* 按形状从已加载的 Host 装配读取可选 `documentHead`(类型契约之外的方言中性扩展口)。
|
|
535
539
|
* 无装配或未写该字段 → undefined;写了但不是字符串 / 函数 → 当场抛错,避免静默吞掉装配错误。
|
|
540
|
+
* `documentHead` 函数须为无副作用纯函数,相同输入返回稳定字符串以便命中静态壳缓存。
|
|
536
541
|
*/
|
|
537
542
|
export function readDocumentHeadSource(assembly: unknown): DocumentHeadSource | undefined {
|
|
538
543
|
if (assembly === null || typeof assembly !== 'object') return undefined;
|
|
@@ -542,16 +547,98 @@ export function readDocumentHeadSource(assembly: unknown): DocumentHeadSource |
|
|
|
542
547
|
throw new Error('soma.app.ts 的 Host 装配的 documentHead 必须是字符串或返回字符串的函数');
|
|
543
548
|
}
|
|
544
549
|
|
|
545
|
-
|
|
546
|
-
export function renderDocumentHead(source: DocumentHeadSource | undefined, nonce: string | undefined): string {
|
|
550
|
+
function evalDocumentHeadSnippet(source: DocumentHeadSource | undefined, nonce: string | undefined): string {
|
|
547
551
|
if (source === undefined) return '';
|
|
548
552
|
const snippet = typeof source === 'function' ? source(nonce === undefined ? {} : { nonce }) : source;
|
|
549
553
|
if (typeof snippet !== 'string') {
|
|
550
554
|
throw new Error('soma.app.ts 的 Host 装配的 documentHead() 必须返回字符串');
|
|
551
555
|
}
|
|
556
|
+
return snippet;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** 求出要插入 `<head>` 的片段:原样插入(片段自身负责转义与 nonce),末尾补换行缩进;无片段返回空串 */
|
|
560
|
+
export function renderDocumentHead(source: DocumentHeadSource | undefined, nonce: string | undefined): string {
|
|
561
|
+
const snippet = evalDocumentHeadSnippet(source, nonce);
|
|
552
562
|
return snippet === '' ? '' : `${snippet}\n `;
|
|
553
563
|
}
|
|
554
564
|
|
|
565
|
+
export interface StaticShellInputs {
|
|
566
|
+
readonly title: string;
|
|
567
|
+
readonly entryUrl: string;
|
|
568
|
+
readonly cssText: string;
|
|
569
|
+
readonly dev: boolean;
|
|
570
|
+
readonly documentHeadSource: DocumentHeadSource | undefined;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export interface StaticShellCacheEntry {
|
|
574
|
+
readonly head: string;
|
|
575
|
+
readonly title: string;
|
|
576
|
+
readonly entryUrl: string;
|
|
577
|
+
readonly cssText: string;
|
|
578
|
+
readonly dev: boolean;
|
|
579
|
+
readonly html: string;
|
|
580
|
+
readonly utf8: Buffer;
|
|
581
|
+
readonly gzip: Buffer;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
export interface StaticShellCache {
|
|
585
|
+
get(inputs: StaticShellInputs): StaticShellCacheEntry;
|
|
586
|
+
clear(): void;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
const LAYER_ORDER_STYLE_RE = /<style\b[^>]*\bdata-soma-kit-layer-order\b[^>]*>[\s\S]*?<\/style>/gi;
|
|
590
|
+
|
|
591
|
+
/** V4-L1-6:将 documentHead 中携带 data-soma-kit-layer-order 的首行层序声明提前至 <style>${cssText}</style> 之前,确保 CSSOM 全局层序在任何样式表之前生效;其余脚本/样式仍留原位 */
|
|
592
|
+
export function splitLayerOrderHead(head: string): { readonly layerOrder: string; readonly rest: string } {
|
|
593
|
+
if (!head.includes('data-soma-kit-layer-order')) return { layerOrder: '', rest: head };
|
|
594
|
+
const extracted: string[] = [];
|
|
595
|
+
const rest = head
|
|
596
|
+
.replace(LAYER_ORDER_STYLE_RE, (m) => {
|
|
597
|
+
extracted.push(m.trim());
|
|
598
|
+
return '';
|
|
599
|
+
})
|
|
600
|
+
.replace(/\n{2,}/g, '\n')
|
|
601
|
+
.trim();
|
|
602
|
+
return { layerOrder: extracted.join('\n '), rest };
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* 预构建静态 HTML 外壳缓冲缓存(仅用于无 CSP 场景;CSP 开启时每次必须按请求 nonce 新鲜生成)。
|
|
607
|
+
* 每次读取都会实时求值 `documentHead` 片段,并与全部注入外壳的字段逐项比对:
|
|
608
|
+
* 全部一致时零重建、零压缩直接复用缓存;任一项变化时立即重建并刷新缓存。
|
|
609
|
+
*/
|
|
610
|
+
export function createStaticShellCache(): StaticShellCache {
|
|
611
|
+
let cachedStaticShell: StaticShellCacheEntry | null = null;
|
|
612
|
+
return {
|
|
613
|
+
get(inputs: StaticShellInputs): StaticShellCacheEntry {
|
|
614
|
+
const { title, entryUrl, cssText, dev, documentHeadSource } = inputs;
|
|
615
|
+
const head = evalDocumentHeadSnippet(documentHeadSource, undefined);
|
|
616
|
+
if (
|
|
617
|
+
cachedStaticShell !== null
|
|
618
|
+
&& cachedStaticShell.head === head
|
|
619
|
+
&& cachedStaticShell.title === title
|
|
620
|
+
&& cachedStaticShell.entryUrl === entryUrl
|
|
621
|
+
&& cachedStaticShell.cssText === cssText
|
|
622
|
+
&& cachedStaticShell.dev === dev
|
|
623
|
+
) {
|
|
624
|
+
return cachedStaticShell;
|
|
625
|
+
}
|
|
626
|
+
const { layerOrder, rest } = splitLayerOrderHead(head);
|
|
627
|
+
const layerOrderHead = layerOrder === '' ? '' : `${layerOrder}\n `;
|
|
628
|
+
const devSse = dev ? '<script>window.__SOMA_DEV_SSE__ = true;</script>\n ' : '';
|
|
629
|
+
const extraHead = rest === '' ? '' : `${rest}\n `;
|
|
630
|
+
const html = `<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>${escapeHtml(title)}</title>\n ${layerOrderHead}<style>${cssText}</style>\n <script>\n try {\n const theme = localStorage.getItem('soma-theme');\n if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {\n document.documentElement.setAttribute('data-theme', 'dark');\n }\n } catch (_) {}\n </script>\n ${extraHead}${devSse}</head>\n<body>\n <div id="soma-app-root">\n <div class="soma-hydration-shell">\n <div class="soma-hydration-shell__bar"></div>\n </div>\n </div>\n <script type="module" src="${entryUrl}"></script>\n</body>\n</html>`;
|
|
631
|
+
const utf8 = Buffer.from(html, 'utf8');
|
|
632
|
+
const gzip = zlib.gzipSync(utf8);
|
|
633
|
+
cachedStaticShell = { head, title, entryUrl, cssText, dev, html, utf8, gzip };
|
|
634
|
+
return cachedStaticShell;
|
|
635
|
+
},
|
|
636
|
+
clear(): void {
|
|
637
|
+
cachedStaticShell = null;
|
|
638
|
+
},
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
|
|
555
642
|
export async function createNativeServer(
|
|
556
643
|
options: CreateNativeServerOptions,
|
|
557
644
|
): Promise<NativeServerInstance> {
|
|
@@ -576,8 +663,9 @@ export async function createNativeServer(
|
|
|
576
663
|
installAotManifest(aotManifestPath, hostDir);
|
|
577
664
|
|
|
578
665
|
await runHostStartup(hostDir);
|
|
579
|
-
//
|
|
666
|
+
// 装配的可选文档头片段(方言中性):按形状读取并做启动期快失败预求值,插到外壳 <head> 末尾
|
|
580
667
|
let documentHeadSource = readDocumentHeadSource(await loadHostAssembly(hostDir));
|
|
668
|
+
evalDocumentHeadSnippet(documentHeadSource, undefined);
|
|
581
669
|
|
|
582
670
|
// 2. 准备客户端产物(生产态优先直接读取预编译清单,零 esbuild 驻留)
|
|
583
671
|
const clientManifestPath = path.join(runtimeLayout.dirs.static, 'client', 'client-manifest.json');
|
|
@@ -606,18 +694,19 @@ export async function createNativeServer(
|
|
|
606
694
|
});
|
|
607
695
|
}
|
|
608
696
|
|
|
609
|
-
// 预构建静态 HTML 外壳缓冲(CSP
|
|
610
|
-
|
|
611
|
-
function getStaticShellBuffers(
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
697
|
+
// 预构建静态 HTML 外壳缓冲(CSP 关闭时零字符串拼接、零实时压缩直出;每次校验 documentHead 与全部外壳输入)
|
|
698
|
+
const staticShellCache = createStaticShellCache();
|
|
699
|
+
function getStaticShellBuffers(
|
|
700
|
+
titleText: string,
|
|
701
|
+
headSource: DocumentHeadSource | undefined = documentHeadSource,
|
|
702
|
+
): StaticShellCacheEntry {
|
|
703
|
+
return staticShellCache.get({
|
|
704
|
+
title: titleText,
|
|
705
|
+
entryUrl: clientBuild.entryUrl,
|
|
706
|
+
cssText: clientBuild.cssText,
|
|
707
|
+
dev,
|
|
708
|
+
documentHeadSource: headSource,
|
|
709
|
+
});
|
|
621
710
|
}
|
|
622
711
|
|
|
623
712
|
// 3. SSE 热更新客户端集合
|
|
@@ -651,6 +740,8 @@ export async function createNativeServer(
|
|
|
651
740
|
let debounceTimer: NodeJS.Timeout | null = null;
|
|
652
741
|
let refreshPending = false;
|
|
653
742
|
let refreshNeedsTailwindClear = false;
|
|
743
|
+
/** 自上一轮成功刷新以来改过的文件(绝对路径):决定这一轮要不要重建客户端包(clientBuild.affectedBy);本轮失败时并回下一轮 */
|
|
744
|
+
const refreshChanged = new Set<string>();
|
|
654
745
|
let refreshTask: Promise<void> | null = null;
|
|
655
746
|
|
|
656
747
|
const drainDevRefreshQueue = (): Promise<void> => {
|
|
@@ -659,6 +750,8 @@ export async function createNativeServer(
|
|
|
659
750
|
const task = (async () => {
|
|
660
751
|
while (refreshPending && !watcherClosed) {
|
|
661
752
|
const clearTailwind = refreshNeedsTailwindClear;
|
|
753
|
+
const changed = [...refreshChanged];
|
|
754
|
+
refreshChanged.clear();
|
|
662
755
|
refreshPending = false;
|
|
663
756
|
refreshNeedsTailwindClear = false;
|
|
664
757
|
try {
|
|
@@ -667,13 +760,17 @@ export async function createNativeServer(
|
|
|
667
760
|
if (watcherClosed) break;
|
|
668
761
|
await prewarmHostPages(hostDir, env);
|
|
669
762
|
if (watcherClosed) break;
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
763
|
+
const nextDocumentHeadSource = readDocumentHeadSource(await loadHostAssembly(hostDir));
|
|
764
|
+
evalDocumentHeadSnippet(nextDocumentHeadSource, undefined);
|
|
765
|
+
documentHeadSource = nextDocumentHeadSource;
|
|
766
|
+
staticShellCache.clear();
|
|
767
|
+
// 只改页面资产(不在客户端包输入里的 html / yaml 等)时不重建客户端包:页面由上面的预热出,整包重建只会拖慢 reload
|
|
768
|
+
if (clientBuild.affectedBy?.(changed) !== false) await clientBuild.rebuild();
|
|
673
769
|
// 有更新排队或仍在 debounce 时不向浏览器发送中间代通知。
|
|
674
770
|
if (!watcherClosed && !refreshPending && debounceTimer === null) broadcastHmr('reload');
|
|
675
771
|
} catch (error) {
|
|
676
|
-
//
|
|
772
|
+
// 单轮失败只记录本轮;队列仍会继续执行合并后的下一代(本轮的改动并回去,下一轮照样据此判要不要重建)。
|
|
773
|
+
for (const file of changed) refreshChanged.add(file);
|
|
677
774
|
console.error('[soma-native][dev-rebuild-error]', error);
|
|
678
775
|
}
|
|
679
776
|
}
|
|
@@ -712,6 +809,7 @@ export async function createNativeServer(
|
|
|
712
809
|
if (apiRoot !== webRoot && full.startsWith(apiRoot + path.sep)) return;
|
|
713
810
|
|
|
714
811
|
refreshNeedsTailwindClear ||= /\.(?:css|ya?ml)$/i.test(norm);
|
|
812
|
+
refreshChanged.add(full);
|
|
715
813
|
if (debounceTimer) clearTimeout(debounceTimer);
|
|
716
814
|
debounceTimer = setTimeout(() => {
|
|
717
815
|
debounceTimer = null;
|
|
@@ -1073,7 +1171,7 @@ export async function createNativeServer(
|
|
|
1073
1171
|
}
|
|
1074
1172
|
};
|
|
1075
1173
|
|
|
1076
|
-
await prepareHostAssembly(hostDir);
|
|
1174
|
+
const assembly = await prepareHostAssembly(hostDir);
|
|
1077
1175
|
// 跑 Host 请求钩子
|
|
1078
1176
|
const rejected = await invokeHostRequestHook(
|
|
1079
1177
|
guardHookRequestBody(headerReq, req, dev, warnedHookBodyMembers),
|
|
@@ -1140,10 +1238,15 @@ export async function createNativeServer(
|
|
|
1140
1238
|
}
|
|
1141
1239
|
|
|
1142
1240
|
applyExtraResHeaders();
|
|
1241
|
+
const currentDocumentHeadSource = readDocumentHeadSource(assembly);
|
|
1242
|
+
if (currentDocumentHeadSource !== documentHeadSource) {
|
|
1243
|
+
evalDocumentHeadSnippet(currentDocumentHeadSource, undefined);
|
|
1244
|
+
documentHeadSource = currentDocumentHeadSource;
|
|
1245
|
+
}
|
|
1143
1246
|
// 正常 HTML 外壳(CSP 关闭时直接走预压缩内存 Buffer 快速通道)
|
|
1144
1247
|
const title = readHostAppDisplayName() || 'SOMA';
|
|
1145
1248
|
if (!csp) {
|
|
1146
|
-
const prebuilt = getStaticShellBuffers(title);
|
|
1249
|
+
const prebuilt = getStaticShellBuffers(title, currentDocumentHeadSource);
|
|
1147
1250
|
res.statusCode = 200;
|
|
1148
1251
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
1149
1252
|
const ae = req.headers['accept-encoding'];
|
|
@@ -1163,7 +1266,10 @@ export async function createNativeServer(
|
|
|
1163
1266
|
const devSseScript = dev
|
|
1164
1267
|
? `<script${nonceAttr}>window.__SOMA_DEV_SSE__ = true;</script>\n`
|
|
1165
1268
|
: '';
|
|
1166
|
-
const extraHeadSnippet = renderDocumentHead(
|
|
1269
|
+
const extraHeadSnippet = renderDocumentHead(currentDocumentHeadSource, verifiedNonce || undefined);
|
|
1270
|
+
const { layerOrder: cspLayerOrder, rest: cspRestHead } = splitLayerOrderHead(extraHeadSnippet);
|
|
1271
|
+
const cspLayerOrderHead = cspLayerOrder === '' ? '' : `${cspLayerOrder}\n `;
|
|
1272
|
+
const cspExtraHead = cspRestHead === '' ? '' : `${cspRestHead}\n `;
|
|
1167
1273
|
|
|
1168
1274
|
const htmlDocument = `<!DOCTYPE html>
|
|
1169
1275
|
<html lang="en">
|
|
@@ -1171,7 +1277,7 @@ export async function createNativeServer(
|
|
|
1171
1277
|
<meta charset="utf-8">
|
|
1172
1278
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1173
1279
|
${cspMeta} <title>${escapeHtml(title)}</title>
|
|
1174
|
-
<style${nonceAttr}>${clientBuild.cssText}</style>
|
|
1280
|
+
${cspLayerOrderHead}<style${nonceAttr}>${clientBuild.cssText}</style>
|
|
1175
1281
|
<script${nonceAttr}>
|
|
1176
1282
|
try {
|
|
1177
1283
|
const theme = localStorage.getItem('soma-theme');
|
|
@@ -1180,7 +1286,7 @@ export async function createNativeServer(
|
|
|
1180
1286
|
}
|
|
1181
1287
|
} catch (_) {}
|
|
1182
1288
|
</script>
|
|
1183
|
-
${
|
|
1289
|
+
${cspExtraHead}${devSseScript}</head>
|
|
1184
1290
|
<body>
|
|
1185
1291
|
<div id="soma-app-root">
|
|
1186
1292
|
<div class="soma-hydration-shell">
|