soma-core 2.2.5 → 2.2.6
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 +5 -6
- package/bin/soma.cjs +2 -2
- package/core/build/compiler/flat-page.ts +16 -0
- package/core/build/compiler/full-manifest-builder.ts +0 -3
- package/core/build/compiler/page-assets.ts +0 -1
- package/core/build/compiler/page-closure.ts +245 -0
- package/core/build/compiler/page-declaration-compiler.ts +2 -5
- package/core/build/compiler/soma-precompile.js +1848 -3244
- package/core/build/compiler/soma-precompile.ts +4 -7
- package/core/build/component-tree/artifact-codec.ts +4 -8
- package/core/build/lsp/soma-declaration.cjs +1 -1
- package/core/build/lsp/std-completion.generated.json +3 -3
- package/core/client/a11y/a11y-config.ts +2 -1
- package/core/client/a11y/dom-id.ts +1 -1
- package/core/client/base/SomaHttpClient.ts +11 -3
- package/core/client/base/SomaPageRootBase.ts +6 -0
- package/core/client/base/defineSomaView.ts +178 -0
- package/core/client/base/index.ts +13 -0
- package/core/client/base/view-context.ts +328 -0
- package/core/client/behavior/adapter-collection.ts +2 -2
- package/core/client/compiler/manifest-compiler.ts +5 -36
- package/core/client/component/component-definition.types.ts +2 -1
- package/core/client/component/component-manager.ts +110 -20
- package/core/client/component/structure-adapter.ts +3 -7
- package/core/client/container/SomaContainerAdapter.ts +9 -1
- package/core/client/data/data-object-resolver.ts +516 -181
- package/core/client/data/data-write-actions.ts +79 -15
- package/core/client/data/format-config.ts +3 -1
- package/core/client/data/region-scope-port.ts +11 -0
- package/core/client/engine/asset-resolver.ts +2 -5
- package/core/client/engine/dom-renderer.ts +7 -40
- package/core/client/engine/event-engine.ts +1 -105
- package/core/client/engine/property-watcher.ts +1 -1
- package/core/client/engine/reactive-proxy.ts +78 -17
- package/core/client/engine/runtime-builder.ts +0 -14
- package/core/client/engine/scope-resolver.ts +18 -0
- package/core/client/engine/soma-bootstrap.ts +385 -98
- package/core/client/engine/style-binder.ts +49 -106
- package/core/client/engine/timer-engine.ts +11 -1
- package/core/client/host-bridge/load-host-domain-class.ts +2 -1
- package/core/client/infra/http/SomaHttpService.ts +15 -4
- package/core/client/infra/i18n/pack-locales.ts +2 -2
- package/core/client/mount/domain-rule.ts +7 -3
- package/core/client/mount/mount-page.ts +38 -5
- package/core/client/mount/types.ts +2 -0
- package/core/client/parser/confirm-spec.ts +1 -1
- package/core/client/parser/data-config-parser.ts +27 -210
- package/core/client/parser/pipeline-parser.ts +14 -59
- package/core/client/parser/style-config-parser.ts +101 -95
- package/core/client/parser/timer-parser.ts +21 -0
- package/core/client/parser/ui-config-parser.ts +64 -12
- package/core/client/registry/declaration-renderer.ts +1 -1
- package/core/client/runtime/SomaRuntimeServices.ts +2 -1
- package/core/client/runtime/SomaSnapshotStore.ts +5 -0
- package/core/client/security/url-guard.ts +71 -11
- package/core/client/validation/async-check-registry.ts +2 -1
- package/core/client/validation/contract-validator.ts +2 -6
- package/core/client/validation/field-rules.ts +3 -13
- package/core/client/validation/object-rules.ts +2 -10
- package/core/index.ts +1 -35
- package/core/inspect/check-product.ts +5 -5
- package/core/inspect/runtime.ts +2 -1
- package/core/server/api/dispatch-service-api.ts +35 -36
- package/core/server/api/load-host-service.ts +5 -4
- package/core/server/compile-port.ts +1 -1
- package/core/server/host/app-config-composer.ts +2 -1
- package/core/server/host/host-assembly-entry.ts +1 -0
- package/core/server/host/host-assembly.ts +47 -3
- package/core/server/host/host-caller.ts +2 -1
- package/core/server/host/host-dir.ts +9 -0
- package/core/server/host/host-response-headers.ts +2 -1
- package/core/server/host/invoke-host-request-hook.ts +28 -4
- package/core/server/host/published-page-assets.ts +2 -1
- package/core/server/host/resolve-host-request-hook.ts +25 -7
- package/core/server/host/server-page-assets.ts +4 -4
- package/core/server/host/virtual-pages.ts +3 -2
- package/core/server/infra/cache/ServerFileCache.ts +79 -9
- package/core/server/registry/api-registry-store.ts +3 -1
- package/core/server/registry/declaration-precompiler.ts +0 -2
- package/core/server/registry/page-registry-repository.ts +2 -1
- package/core/server/registry/page-registry-store.ts +2 -1
- package/core/server/registry/registry-error.ts +6 -1
- package/core/server/registry/registry-file-lock.ts +296 -23
- package/core/server/registry/request-body-limit.ts +3 -2
- package/core/server/registry/validation/declaration-safety-scan.ts +151 -27
- package/core/server/runtime-space/access-gate.ts +21 -7
- package/core/server/runtime-space/bindings.ts +3 -6
- package/core/server/runtime-space/dynamic-pages.ts +181 -49
- package/core/server/runtime-space/errors.ts +3 -0
- package/core/server/runtime-space/inject.ts +74 -15
- package/core/server/runtime-space/page-grants.ts +7 -1
- package/core/server/runtime-space/resolve.ts +66 -19
- package/core/server/runtime-space/store.ts +32 -3
- package/core/server/runtime-space/submit-steps.ts +2 -1
- package/core/server/runtime-space/types.ts +3 -1
- package/core/shared/component-tree-errors.ts +2 -1
- package/core/shared/contract-a11y.ts +1 -1
- package/core/shared/contract-sections.ts +2 -2
- package/core/shared/core-diagnostic-codes.ts +8 -0
- package/core/shared/declaration-keys.ts +1 -1
- package/core/shared/engines/engine-error.ts +2 -1
- package/core/shared/generation-error.ts +2 -1
- package/core/shared/page-envelope.ts +1 -1
- package/core/shared/pure-binding.ts +88 -0
- package/core/shared/registry-generated/diagnostic-registry-index.ts +16 -19
- package/core/shared/registry-generated/diagnostic-registry.ts +135 -177
- package/core/shared/registry-generated/limits.ts +49 -13
- package/core/shared/registry-generated/std-grammar-completion.ts +0 -4
- package/core/shared/registry-generated/std-grammar-views.ts +40 -10
- package/core/shared/registry-generated/std-grammar.ts +42 -20
- package/core/shared/soma-error.ts +36 -0
- package/core/shared/types/compile-port.types.ts +1 -1
- package/core/shared/types/data-config.types.ts +17 -17
- package/core/shared/types/engine.types.ts +0 -3
- package/core/shared/types/event.types.ts +1 -11
- package/core/shared/types/generation-error.types.ts +5 -1
- package/core/shared/types/host-assembly.types.ts +7 -1
- package/core/shared/types/manifest.types.ts +0 -3
- package/core/shared/types/region-scope.types.ts +5 -1
- package/core/shared/types/scope-manifest.types.ts +0 -2
- package/core/shared/types/style-config.types.ts +21 -21
- package/core/shared/types/ui-config.types.ts +4 -5
- package/core/shared/types/watcher.types.ts +1 -1
- package/dist/browser/runtime-bundle.manifest.json +11 -13
- package/dist/browser/soma-runtime.js +2567 -2696
- package/dist/core/index.cjs +5446 -5486
- package/dist/host-native/aot-builder.cjs +46 -1
- package/dist/host-native/native-server.cjs +4879 -4505
- package/dist/lsp/component-tree.cjs +5814 -7042
- package/dist/types/build/compiler/full-manifest-builder.d.ts +0 -2
- package/dist/types/build/compiler/page-closure.d.ts +21 -0
- package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -4
- package/dist/types/build/compiler/soma-precompile.d.ts +1 -3
- package/dist/types/build/component-tree/artifact-codec.d.ts +0 -2
- package/dist/types/client/a11y/a11y-config.d.ts +2 -1
- package/dist/types/client/base/SomaHttpClient.d.ts +1 -1
- package/dist/types/client/base/SomaPageRootBase.d.ts +5 -0
- package/dist/types/client/base/defineSomaView.d.ts +46 -0
- package/dist/types/client/base/index.d.ts +2 -0
- package/dist/types/client/base/view-context.d.ts +136 -0
- package/dist/types/client/behavior/adapter-collection.d.ts +1 -1
- package/dist/types/client/compiler/manifest-compiler.d.ts +0 -3
- package/dist/types/client/component/component-definition.types.d.ts +2 -1
- package/dist/types/client/component/component-manager.d.ts +29 -0
- package/dist/types/client/data/data-object-resolver.d.ts +91 -31
- package/dist/types/client/data/format-config.d.ts +2 -1
- package/dist/types/client/engine/dom-renderer.d.ts +1 -2
- package/dist/types/client/engine/event-engine.d.ts +0 -7
- package/dist/types/client/engine/reactive-proxy.d.ts +11 -4
- package/dist/types/client/engine/runtime-builder.d.ts +0 -4
- package/dist/types/client/engine/soma-bootstrap.d.ts +44 -6
- package/dist/types/client/engine/style-binder.d.ts +8 -4
- package/dist/types/client/host-bridge/load-host-domain-class.d.ts +2 -1
- package/dist/types/client/mount/domain-rule.d.ts +2 -0
- package/dist/types/client/mount/mount-page.d.ts +2 -1
- package/dist/types/client/mount/types.d.ts +2 -0
- package/dist/types/client/parser/data-config-parser.d.ts +6 -5
- package/dist/types/client/parser/style-config-parser.d.ts +7 -3
- package/dist/types/client/parser/timer-parser.d.ts +5 -0
- package/dist/types/client/parser/ui-config-parser.d.ts +6 -2
- package/dist/types/client/runtime/SomaSnapshotStore.d.ts +2 -0
- package/dist/types/client/security/url-guard.d.ts +14 -0
- package/dist/types/client/validation/async-check-registry.d.ts +2 -1
- package/dist/types/client/validation/object-rules.d.ts +0 -5
- package/dist/types/index.d.ts +2 -7
- package/dist/types/inspect/runtime.d.ts +2 -1
- package/dist/types/server/api/dispatch-service-api.d.ts +5 -0
- package/dist/types/server/api/load-host-service.d.ts +1 -1
- package/dist/types/server/compile-port.d.ts +1 -1
- package/dist/types/server/host/host-assembly-entry.d.ts +1 -1
- package/dist/types/server/host/host-assembly.d.ts +2 -0
- package/dist/types/server/host/host-dir.d.ts +2 -0
- package/dist/types/server/host/invoke-host-request-hook.d.ts +10 -3
- package/dist/types/server/host/published-page-assets.d.ts +2 -1
- package/dist/types/server/host/resolve-host-request-hook.d.ts +18 -5
- package/dist/types/server/host/server-page-assets.d.ts +2 -1
- package/dist/types/server/infra/cache/ServerFileCache.d.ts +8 -0
- package/dist/types/server/registry/declaration-precompiler.d.ts +0 -1
- package/dist/types/server/registry/registry-error.d.ts +5 -1
- package/dist/types/server/registry/registry-file-lock.d.ts +30 -0
- package/dist/types/server/registry/request-body-limit.d.ts +3 -2
- package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +3 -0
- package/dist/types/server/runtime-space/access-gate.d.ts +7 -0
- package/dist/types/server/runtime-space/bindings.d.ts +3 -2
- package/dist/types/server/runtime-space/dynamic-pages.d.ts +6 -1
- package/dist/types/server/runtime-space/errors.d.ts +1 -1
- package/dist/types/server/runtime-space/resolve.d.ts +2 -0
- package/dist/types/server/runtime-space/store.d.ts +8 -1
- package/dist/types/server/runtime-space/submit-steps.d.ts +2 -1
- package/dist/types/server/runtime-space/types.d.ts +3 -1
- package/dist/types/shared/component-tree-errors.d.ts +2 -1
- package/dist/types/shared/core-diagnostic-codes.d.ts +1 -1
- package/dist/types/shared/declaration-keys.d.ts +1 -1
- package/dist/types/shared/engines/engine-error.d.ts +2 -1
- package/dist/types/shared/generation-error.d.ts +2 -1
- package/dist/types/shared/pure-binding.d.ts +48 -0
- package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +119 -158
- package/dist/types/shared/registry-generated/limits.d.ts +40 -10
- package/dist/types/shared/registry-generated/std-grammar-completion.d.ts +0 -30
- package/dist/types/shared/registry-generated/std-grammar-views.d.ts +97 -23
- package/dist/types/shared/registry-generated/std-grammar.d.ts +109 -241
- package/dist/types/shared/soma-error.d.ts +15 -0
- package/dist/types/shared/types/data-config.types.d.ts +14 -16
- package/dist/types/shared/types/engine.types.d.ts +0 -3
- package/dist/types/shared/types/event.types.d.ts +1 -7
- package/dist/types/shared/types/generation-error.types.d.ts +1 -1
- package/dist/types/shared/types/host-assembly.types.d.ts +2 -0
- package/dist/types/shared/types/manifest.types.d.ts +0 -3
- package/dist/types/shared/types/region-scope.types.d.ts +4 -1
- package/dist/types/shared/types/scope-manifest.types.d.ts +0 -2
- package/dist/types/shared/types/style-config.types.d.ts +17 -19
- package/dist/types/shared/types/ui-config.types.d.ts +4 -5
- package/host-native/bin/host-native.cjs +22 -1
- package/host-native/client/browser-entry.ts +21 -172
- package/host-native/src/aot-builder.ts +52 -0
- package/host-native/src/host-prepare.ts +39 -5
- package/host-native/src/manifest-http.ts +2 -3
- package/host-native/src/native-server.ts +812 -174
- package/host-native/src/page-http.ts +3 -3
- package/host-native/src/public-packages.cjs +0 -1
- package/host-native/src/registry-handler.ts +12 -5
- package/host-native/src/static-file.ts +203 -53
- package/package.json +3 -2
- package/core/client/engine/step-runner.ts +0 -212
- package/core/client/engine/trigger-engine.ts +0 -55
- package/core/client/format/zoned.ts +0 -10
- package/core/client/parser/step-parser.ts +0 -359
- package/core/client/parser/trigger-parser.ts +0 -90
- package/core/client/parser/value-lang.ts +0 -340
- package/core/client/time/instant.ts +0 -2
- package/core/shared/calc/coerce.ts +0 -2
- package/core/shared/calc/errors.ts +0 -40
- package/core/shared/calc/evaluator.ts +0 -113
- package/core/shared/calc/index.ts +0 -11
- package/core/shared/calc/lexer.ts +0 -189
- package/core/shared/calc/parser.ts +0 -193
- package/core/shared/calc/typer.ts +0 -171
- package/core/shared/date-parts.ts +0 -2
- package/core/shared/show-when.ts +0 -77
- package/core/shared/types/step.types.ts +0 -91
- package/core/shared/types/trigger.types.ts +0 -14
- package/dist/types/client/engine/step-runner.d.ts +0 -42
- package/dist/types/client/engine/trigger-engine.d.ts +0 -16
- package/dist/types/client/format/zoned.d.ts +0 -1
- package/dist/types/client/parser/step-parser.d.ts +0 -23
- package/dist/types/client/parser/trigger-parser.d.ts +0 -13
- package/dist/types/client/parser/value-lang.d.ts +0 -63
- package/dist/types/client/time/instant.d.ts +0 -1
- package/dist/types/shared/calc/coerce.d.ts +0 -1
- package/dist/types/shared/calc/errors.d.ts +0 -14
- package/dist/types/shared/calc/evaluator.d.ts +0 -2
- package/dist/types/shared/calc/index.d.ts +0 -6
- package/dist/types/shared/calc/lexer.d.ts +0 -19
- package/dist/types/shared/calc/parser.d.ts +0 -43
- package/dist/types/shared/calc/typer.d.ts +0 -11
- package/dist/types/shared/date-parts.d.ts +0 -1
- package/dist/types/shared/show-when.d.ts +0 -21
- package/dist/types/shared/types/step.types.d.ts +0 -76
- package/dist/types/shared/types/trigger.types.d.ts +0 -12
|
@@ -1,24 +1,24 @@
|
|
|
1
|
+
import net from 'node:net';
|
|
1
2
|
import http from 'node:http';
|
|
2
3
|
import fs from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
4
|
-
import { createHash } from 'node:crypto';
|
|
5
5
|
import zlib from 'node:zlib';
|
|
6
6
|
import { getSomaHostSourceRoot, getSomaHostApiRoot } from '../../core/server/host/source-packages.cjs';
|
|
7
7
|
import { resolveSomaRuntimeLayout } from '../../core/server/runtime-space/root';
|
|
8
8
|
import { loadPageByAddress } from '../../core/server/runtime-space';
|
|
9
9
|
import { readHostAppDisplayName } from '../../core/server/host/app-config-composer';
|
|
10
|
-
import { invokeHostRequestHook } from '../../core/server/host/invoke-host-request-hook';
|
|
10
|
+
import { invokeHostRequestHook, isSomaInternalRequestPath } from '../../core/server/host/invoke-host-request-hook';
|
|
11
11
|
import { dispatchHostServiceApiRequest } from '../../core/server/api/dispatch-service-api';
|
|
12
12
|
import { registerAotServiceResolver } from '../../core/server/api/load-host-service';
|
|
13
13
|
import { toPascalCase } from '../../core/server/api/service-path';
|
|
14
|
-
import { runHostStartup } from 'soma-core/server/host-assembly';
|
|
14
|
+
import { runHostStartup, loadHostAssembly } from 'soma-core/server/host-assembly';
|
|
15
15
|
import { clearTailwindCompilerCache } from 'soma-core/server/style-engine';
|
|
16
16
|
import { resolveHostResponseHeaders } from '../../core/server/host/host-response-headers';
|
|
17
17
|
import type { BrowserClientBuildResult, ServerAotManifest } from './aot-builder';
|
|
18
18
|
import { pageSuccessResponse, pageErrorResponse } from './page-http';
|
|
19
19
|
import { handleManifestGet } from './manifest-http';
|
|
20
|
-
import { prepareHostAssembly } from './host-prepare';
|
|
21
|
-
import { staticResponse } from './static-file';
|
|
20
|
+
import { prepareHostAssembly, invalidateHostPreparation, prewarmHostPages } from './host-prepare';
|
|
21
|
+
import { staticResponse, serveStaticFromRoot, isSafeSegments, acceptsGzip } from './static-file';
|
|
22
22
|
import {
|
|
23
23
|
applyHostAndCspHeaders,
|
|
24
24
|
createSomaCspHeader,
|
|
@@ -26,6 +26,38 @@ import {
|
|
|
26
26
|
resolveSomaCspOptionsFromEnv,
|
|
27
27
|
} from './csp-headers';
|
|
28
28
|
|
|
29
|
+
export class RequestBodyTooLargeError extends Error {
|
|
30
|
+
readonly status = 413;
|
|
31
|
+
constructor(readonly limitBytes: number, readonly seenBytes: number | null) {
|
|
32
|
+
const seen = seenBytes === null ? `exceeded ${limitBytes}` : `${seenBytes}`;
|
|
33
|
+
super(`Payload Too Large: ${seen} bytes / limit ${limitBytes} bytes`);
|
|
34
|
+
this.name = 'RequestBodyTooLargeError';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024; // 10MB
|
|
39
|
+
const API_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const;
|
|
40
|
+
const PAGE_ALLOW_METHODS = ['GET', 'HEAD'] as const;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 判定错误或请求状态是否为客户端主动中止 / 断连。
|
|
44
|
+
* 客户端断开连接时(如页面刷新、Tab 关闭、超时中止、socket 重置)不应当作服务器内部错误记录或回写。
|
|
45
|
+
*/
|
|
46
|
+
export function isClientAbortError(
|
|
47
|
+
_err: unknown,
|
|
48
|
+
res?: http.ServerResponse,
|
|
49
|
+
signal?: AbortSignal,
|
|
50
|
+
req?: http.IncomingMessage,
|
|
51
|
+
): boolean {
|
|
52
|
+
// 上游异常文案含 ECONNRESET/aborted 不代表当前客户端连接已断开;
|
|
53
|
+
// 仅以请求与响应的真实传输状态为准。
|
|
54
|
+
return signal?.aborted === true
|
|
55
|
+
|| req?.aborted === true
|
|
56
|
+
|| req?.socket?.destroyed === true
|
|
57
|
+
|| res?.destroyed === true
|
|
58
|
+
|| res?.socket?.destroyed === true;
|
|
59
|
+
}
|
|
60
|
+
|
|
29
61
|
export interface CreateNativeServerOptions {
|
|
30
62
|
readonly hostDir: string;
|
|
31
63
|
readonly webRoot?: string;
|
|
@@ -34,6 +66,7 @@ export interface CreateNativeServerOptions {
|
|
|
34
66
|
readonly hostname?: string;
|
|
35
67
|
readonly dev?: boolean;
|
|
36
68
|
readonly env?: NodeJS.ProcessEnv;
|
|
69
|
+
readonly maxBodyBytes?: number;
|
|
37
70
|
}
|
|
38
71
|
|
|
39
72
|
export interface NativeServerInstance {
|
|
@@ -44,6 +77,37 @@ export interface NativeServerInstance {
|
|
|
44
77
|
close(): Promise<void>;
|
|
45
78
|
}
|
|
46
79
|
|
|
80
|
+
function probeHostPort(port: number, host: string, timeoutMs = 150): Promise<boolean> {
|
|
81
|
+
return new Promise((resolve) => {
|
|
82
|
+
const socket = net.connect({ port, host });
|
|
83
|
+
let settled = false;
|
|
84
|
+
const finish = (inUse: boolean) => {
|
|
85
|
+
if (settled) return;
|
|
86
|
+
settled = true;
|
|
87
|
+
socket.destroy();
|
|
88
|
+
resolve(inUse);
|
|
89
|
+
};
|
|
90
|
+
socket.setTimeout(timeoutMs);
|
|
91
|
+
socket.once('connect', () => finish(true));
|
|
92
|
+
socket.once('timeout', () => finish(false));
|
|
93
|
+
socket.once('error', () => finish(false));
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function isPortInUse(port: number, hostname = '0.0.0.0'): Promise<boolean> {
|
|
98
|
+
if (!Number.isInteger(port) || port <= 0) return false;
|
|
99
|
+
const normalized = typeof hostname === 'string' ? hostname.trim() : '';
|
|
100
|
+
// 绑定 0.0.0.0 或 :: 或未指定时探测 127.0.0.1 与 ::1;绑定到具体地址时只探测该地址
|
|
101
|
+
const hosts =
|
|
102
|
+
!normalized || normalized === '0.0.0.0' || normalized === '::'
|
|
103
|
+
? ['127.0.0.1', '::1']
|
|
104
|
+
: [normalized];
|
|
105
|
+
for (const h of hosts) {
|
|
106
|
+
if (await probeHostPort(port, h)) return true;
|
|
107
|
+
}
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
|
|
47
111
|
function escapeHtml(str: string): string {
|
|
48
112
|
return str
|
|
49
113
|
.replace(/&/g, '&')
|
|
@@ -96,10 +160,129 @@ function installAotManifest(manifestPath: string, hostDir: string): void {
|
|
|
96
160
|
}
|
|
97
161
|
}
|
|
98
162
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
163
|
+
function checkContentLength(req: http.IncomingMessage, maxBytes: number): void {
|
|
164
|
+
const raw = req.headers['content-length'];
|
|
165
|
+
if (raw !== undefined && raw !== null && raw !== '') {
|
|
166
|
+
const declared = Number(raw);
|
|
167
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
168
|
+
throw new RequestBodyTooLargeError(maxBytes, declared);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function readIncomingRequestBody(
|
|
174
|
+
req: http.IncomingMessage,
|
|
175
|
+
maxBodyBytes: number,
|
|
176
|
+
signal?: AbortSignal,
|
|
177
|
+
): Promise<Uint8Array> {
|
|
178
|
+
try {
|
|
179
|
+
checkContentLength(req, maxBodyBytes);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
return Promise.reject(error);
|
|
182
|
+
}
|
|
183
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
184
|
+
if (method === 'GET' || method === 'HEAD' || req.readableEnded) return Promise.resolve(new Uint8Array());
|
|
185
|
+
|
|
186
|
+
return new Promise<Uint8Array>((resolve, reject) => {
|
|
187
|
+
const chunks: Buffer[] = [];
|
|
188
|
+
let totalLength = 0;
|
|
189
|
+
let settled = false;
|
|
190
|
+
const cleanup = () => {
|
|
191
|
+
req.off('data', onData);
|
|
192
|
+
req.off('end', onEnd);
|
|
193
|
+
req.off('aborted', onAborted);
|
|
194
|
+
req.off('close', onClose);
|
|
195
|
+
req.off('error', onError);
|
|
196
|
+
signal?.removeEventListener('abort', onSignalAbort);
|
|
197
|
+
};
|
|
198
|
+
const finish = (error?: unknown, bytes?: Uint8Array) => {
|
|
199
|
+
if (settled) return;
|
|
200
|
+
settled = true;
|
|
201
|
+
cleanup();
|
|
202
|
+
if (error !== undefined) reject(error);
|
|
203
|
+
else resolve(bytes ?? new Uint8Array());
|
|
204
|
+
};
|
|
205
|
+
const onData = (chunk: Buffer | string) => {
|
|
206
|
+
if (signal?.aborted) {
|
|
207
|
+
req.pause();
|
|
208
|
+
finish(signal.reason ?? new Error('Request aborted by client'));
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
212
|
+
totalLength += bytes.byteLength;
|
|
213
|
+
if (totalLength > maxBodyBytes) {
|
|
214
|
+
req.pause();
|
|
215
|
+
finish(new RequestBodyTooLargeError(maxBodyBytes, totalLength));
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
chunks.push(bytes);
|
|
219
|
+
};
|
|
220
|
+
const onEnd = () => finish(undefined, Buffer.concat(chunks, totalLength));
|
|
221
|
+
const onAborted = () => finish(new Error('Request body connection aborted'));
|
|
222
|
+
const onClose = () => {
|
|
223
|
+
if (!req.complete || req.aborted) finish(new Error('Request body connection closed before completion'));
|
|
224
|
+
};
|
|
225
|
+
const onError = (error: Error) => finish(error);
|
|
226
|
+
const onSignalAbort = () => {
|
|
227
|
+
req.pause();
|
|
228
|
+
finish(signal?.reason ?? new Error('Request body read aborted'));
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
if (signal?.aborted) {
|
|
232
|
+
onSignalAbort();
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
// A completed zero-byte request may have emitted end before the hook asked
|
|
236
|
+
// for the body; non-empty buffered input is still consumed by the listeners.
|
|
237
|
+
if (req.complete && req.readableLength === 0) {
|
|
238
|
+
finish(undefined, new Uint8Array());
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
req.on('data', onData);
|
|
242
|
+
req.once('end', onEnd);
|
|
243
|
+
req.once('aborted', onAborted);
|
|
244
|
+
req.once('close', onClose);
|
|
245
|
+
req.once('error', onError);
|
|
246
|
+
signal?.addEventListener('abort', onSignalAbort, { once: true });
|
|
247
|
+
if (signal?.aborted) onSignalAbort();
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function createRequestBodyReader(
|
|
252
|
+
req: http.IncomingMessage,
|
|
253
|
+
maxBodyBytes: number,
|
|
254
|
+
signal?: AbortSignal,
|
|
255
|
+
): {
|
|
256
|
+
readBody: () => Promise<Uint8Array>;
|
|
257
|
+
readRawBody: () => Promise<Uint8Array>;
|
|
258
|
+
assertWithinLimit: () => void;
|
|
259
|
+
} {
|
|
260
|
+
let bodyPromise: Promise<Uint8Array> | undefined;
|
|
261
|
+
let bodyLimitError: RequestBodyTooLargeError | undefined;
|
|
262
|
+
const readRawBody = (): Promise<Uint8Array> => {
|
|
263
|
+
bodyPromise ??= readIncomingRequestBody(req, maxBodyBytes, signal).catch((error: unknown) => {
|
|
264
|
+
if (error instanceof RequestBodyTooLargeError) bodyLimitError = error;
|
|
265
|
+
throw error;
|
|
266
|
+
});
|
|
267
|
+
return bodyPromise;
|
|
268
|
+
};
|
|
269
|
+
return {
|
|
270
|
+
readRawBody,
|
|
271
|
+
assertWithinLimit() {
|
|
272
|
+
if (bodyLimitError) throw bodyLimitError;
|
|
273
|
+
},
|
|
274
|
+
async readBody() {
|
|
275
|
+
// Buffer.slice() 是视图而非副本;显式构造 Uint8Array,防止钩子改写内部缓存。
|
|
276
|
+
return new Uint8Array(await readRawBody());
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function createHeaderOnlyWebRequest(
|
|
282
|
+
req: http.IncomingMessage,
|
|
283
|
+
origin: string,
|
|
284
|
+
signal?: AbortSignal,
|
|
285
|
+
): Request {
|
|
103
286
|
const url = new URL(req.url || '/', origin);
|
|
104
287
|
const method = (req.method || 'GET').toUpperCase();
|
|
105
288
|
const headers = new Headers();
|
|
@@ -113,34 +296,141 @@ async function toWebRequest(req: http.IncomingMessage, origin: string): Promise<
|
|
|
113
296
|
}
|
|
114
297
|
}
|
|
115
298
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
299
|
+
return new Request(url.toString(), {
|
|
300
|
+
method,
|
|
301
|
+
headers,
|
|
302
|
+
signal,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const HOOK_BODY_MEMBERS: ReadonlySet<string> = new Set([
|
|
307
|
+
'body', 'text', 'json', 'arrayBuffer', 'formData', 'blob', 'bytes',
|
|
308
|
+
]);
|
|
121
309
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
310
|
+
/**
|
|
311
|
+
* 与响应体 / 实体语义绑定的头:钩子拒绝复制时跳过、500 分支清除,共用这一个基础集合。
|
|
312
|
+
* 两处的差别:500 清头集合在它之上还清 `cache-control` / `expires` / `vary` / `location`;钩子拒绝时的跳过集合只在它之上加 `connection`,
|
|
313
|
+
* 不跳过 `location` / `cache-control` 等(照常复制),`set-cookie` 因在基础集合里被跳过,改由 `copyHookResponseHeaders` 的多值复制单独处理。
|
|
314
|
+
*/
|
|
315
|
+
const ENTITY_BOUND_HEADERS: readonly string[] = [
|
|
316
|
+
'content-length', 'content-encoding', 'transfer-encoding', 'content-type', 'content-range', 'accept-ranges',
|
|
317
|
+
'etag', 'last-modified', 'content-language', 'content-md5', 'content-disposition', 'set-cookie',
|
|
318
|
+
];
|
|
319
|
+
|
|
320
|
+
/** 500 分支要清掉的头:实体头 + 缓存 / 重定向语义头。 */
|
|
321
|
+
const STALE_ENTITY_HEADERS: readonly string[] = [
|
|
322
|
+
...ENTITY_BOUND_HEADERS, 'cache-control', 'expires', 'vary', 'location',
|
|
323
|
+
];
|
|
324
|
+
|
|
325
|
+
/** 请求确有(未读取的)请求体:有非 0 content-length 或 transfer-encoding。 */
|
|
326
|
+
function requestHasBody(req: http.IncomingMessage): boolean {
|
|
327
|
+
if (req.headers['transfer-encoding'] !== undefined) return true;
|
|
328
|
+
const cl = req.headers['content-length'];
|
|
329
|
+
if (typeof cl !== 'string' || cl.trim() === '') return false;
|
|
330
|
+
const n = Number(cl);
|
|
331
|
+
return !Number.isFinite(n) || n !== 0;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* 开发态告警:钩子拿到的 request 只有头视图,读其请求体成员会得到空内容。
|
|
336
|
+
* 仅 dev + 非 GET/HEAD + 确有 body 时包 Proxy;其余行为与原对象一致。
|
|
337
|
+
*/
|
|
338
|
+
function guardHookRequestBody(
|
|
339
|
+
request: Request,
|
|
340
|
+
req: http.IncomingMessage,
|
|
341
|
+
dev: boolean,
|
|
342
|
+
warned: Set<string>,
|
|
343
|
+
): Request {
|
|
344
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
345
|
+
if (!dev || method === 'GET' || method === 'HEAD' || !requestHasBody(req)) return request;
|
|
346
|
+
return new Proxy(request, {
|
|
347
|
+
get(target, prop) {
|
|
348
|
+
if (typeof prop === 'string' && HOOK_BODY_MEMBERS.has(prop) && !warned.has(prop)) {
|
|
349
|
+
warned.add(prop);
|
|
350
|
+
console.warn(`请求钩子读取了 request 的请求体成员 ${prop}:传给钩子的 request 不含请求体,请改用 await context.readBody()`);
|
|
351
|
+
}
|
|
352
|
+
const value = Reflect.get(target, prop, target);
|
|
353
|
+
return typeof value === 'function' && prop !== 'constructor' ? value.bind(target) : value;
|
|
354
|
+
},
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** 把钩子响应头复制到 res(跳过由本处自行决定的头;多值 Set-Cookie 逐条设置)。 */
|
|
359
|
+
function copyHookResponseHeaders(hookRes: Response, res: http.ServerResponse): void {
|
|
360
|
+
const skip = new Set<string>([...ENTITY_BOUND_HEADERS, 'connection']);
|
|
361
|
+
hookRes.headers.forEach((value, name) => {
|
|
362
|
+
if (!skip.has(name.toLowerCase())) res.setHeader(name, value);
|
|
363
|
+
});
|
|
364
|
+
const cookies = typeof hookRes.headers.getSetCookie === 'function' ? hookRes.headers.getSetCookie() : [];
|
|
365
|
+
if (cookies.length > 0) res.setHeader('Set-Cookie', cookies);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function createStaticLookupRequest(
|
|
369
|
+
req: http.IncomingMessage,
|
|
370
|
+
method: string,
|
|
371
|
+
): { readonly method: string; readonly headers: { get(name: string): string | null } } {
|
|
372
|
+
return {
|
|
373
|
+
method,
|
|
374
|
+
headers: {
|
|
375
|
+
get(name: string) {
|
|
376
|
+
const v = req.headers[name.toLowerCase()];
|
|
377
|
+
return Array.isArray(v) ? v.join(', ') : v || null;
|
|
378
|
+
},
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* 将 Node IncomingMessage 转换为标准 Request 对象
|
|
385
|
+
*/
|
|
386
|
+
async function toWebRequest(
|
|
387
|
+
req: http.IncomingMessage,
|
|
388
|
+
origin: string,
|
|
389
|
+
maxBodyBytes: number = DEFAULT_MAX_BODY_BYTES,
|
|
390
|
+
signal?: AbortSignal,
|
|
391
|
+
baseHeaders?: Headers,
|
|
392
|
+
bodyBytes?: Uint8Array,
|
|
393
|
+
): Promise<Request> {
|
|
394
|
+
const url = new URL(req.url || '/', origin);
|
|
395
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
396
|
+
const headers = baseHeaders ? new Headers(baseHeaders) : new Headers();
|
|
397
|
+
|
|
398
|
+
if (!baseHeaders) {
|
|
399
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
400
|
+
if (value === undefined) continue;
|
|
401
|
+
if (Array.isArray(value)) {
|
|
402
|
+
for (const v of value) headers.append(key, v);
|
|
403
|
+
} else {
|
|
404
|
+
headers.set(key, value);
|
|
127
405
|
}
|
|
128
|
-
chunks.push(buf);
|
|
129
406
|
}
|
|
130
|
-
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
let body: Uint8Array | null = null;
|
|
410
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
411
|
+
checkContentLength(req, maxBodyBytes);
|
|
412
|
+
body = bodyBytes ?? new Uint8Array();
|
|
413
|
+
if (body.byteLength > maxBodyBytes) {
|
|
414
|
+
throw new RequestBodyTooLargeError(maxBodyBytes, body.byteLength);
|
|
415
|
+
}
|
|
131
416
|
}
|
|
132
417
|
|
|
133
418
|
return new Request(url.toString(), {
|
|
134
419
|
method,
|
|
135
420
|
headers,
|
|
136
|
-
|
|
421
|
+
signal,
|
|
422
|
+
...(body && body.byteLength > 0 ? { body: Buffer.from(body) as unknown as BodyInit, duplex: 'half' as any } : {}),
|
|
137
423
|
});
|
|
138
424
|
}
|
|
139
425
|
|
|
140
426
|
/**
|
|
141
427
|
* 将标准 Web Response 写入 Node ServerResponse
|
|
142
428
|
*/
|
|
143
|
-
async function sendWebResponse(
|
|
429
|
+
async function sendWebResponse(
|
|
430
|
+
webRes: Response,
|
|
431
|
+
res: http.ServerResponse,
|
|
432
|
+
method?: string,
|
|
433
|
+
): Promise<void> {
|
|
144
434
|
res.statusCode = webRes.status;
|
|
145
435
|
|
|
146
436
|
if (typeof (webRes.headers as any).getSetCookie === 'function') {
|
|
@@ -155,14 +445,112 @@ async function sendWebResponse(webRes: Response, res: http.ServerResponse): Prom
|
|
|
155
445
|
res.setHeader(key, value);
|
|
156
446
|
}
|
|
157
447
|
|
|
158
|
-
if (webRes.body) {
|
|
159
|
-
const arrayBuffer = await webRes.arrayBuffer();
|
|
160
|
-
res.end(Buffer.from(arrayBuffer));
|
|
161
|
-
} else {
|
|
448
|
+
if (!webRes.body || method === 'HEAD') {
|
|
162
449
|
res.end();
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const reader = webRes.body.getReader();
|
|
454
|
+
let closed = false;
|
|
455
|
+
let cancelPromise: Promise<void> | undefined;
|
|
456
|
+
const cancelReader = () => {
|
|
457
|
+
cancelPromise ??= reader.cancel().then(() => {}, () => {});
|
|
458
|
+
return cancelPromise;
|
|
459
|
+
};
|
|
460
|
+
const onClose = () => {
|
|
461
|
+
if (res.writableEnded || closed) return;
|
|
462
|
+
closed = true;
|
|
463
|
+
void cancelReader();
|
|
464
|
+
};
|
|
465
|
+
const waitForDrainOrClose = (): Promise<boolean> => new Promise((resolve) => {
|
|
466
|
+
let settled = false;
|
|
467
|
+
const finish = (wasClosed: boolean) => {
|
|
468
|
+
if (settled) return;
|
|
469
|
+
settled = true;
|
|
470
|
+
res.off('drain', onDrain);
|
|
471
|
+
res.off('close', onDrainClose);
|
|
472
|
+
resolve(wasClosed);
|
|
473
|
+
};
|
|
474
|
+
const onDrain = () => finish(false);
|
|
475
|
+
const onDrainClose = () => finish(true);
|
|
476
|
+
if (res.destroyed && !res.writableEnded && !closed) onClose();
|
|
477
|
+
if (closed || res.destroyed || res.writableEnded) {
|
|
478
|
+
finish(true);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
res.once('drain', onDrain);
|
|
482
|
+
res.once('close', onDrainClose);
|
|
483
|
+
if (res.destroyed && !res.writableEnded && !closed) onClose();
|
|
484
|
+
if (closed || res.destroyed) finish(true);
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
res.once('close', onClose);
|
|
488
|
+
if (res.destroyed) onClose();
|
|
489
|
+
try {
|
|
490
|
+
while (true) {
|
|
491
|
+
if (closed || res.destroyed || res.writableEnded) return;
|
|
492
|
+
// `reader.cancel()` 会解除待处理的 read;其底层取消 Promise 可能不结束,不能等待它。
|
|
493
|
+
const { done, value } = await reader.read();
|
|
494
|
+
if (done) break;
|
|
495
|
+
if (value && value.byteLength > 0) {
|
|
496
|
+
const ok = res.write(value);
|
|
497
|
+
if (typeof (res as any).flush === 'function') {
|
|
498
|
+
(res as any).flush();
|
|
499
|
+
}
|
|
500
|
+
if (!ok && !res.destroyed && !res.writableEnded) {
|
|
501
|
+
if (await waitForDrainOrClose()) return;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if (!res.writableEnded && !res.destroyed) res.end();
|
|
506
|
+
} catch (err) {
|
|
507
|
+
if (closed || res.destroyed) return;
|
|
508
|
+
void cancelReader();
|
|
509
|
+
// 让外层请求边界在仍可写时生成通用 500;已发出头后由外层统一关闭连接。
|
|
510
|
+
throw err;
|
|
511
|
+
} finally {
|
|
512
|
+
res.off('close', onClose);
|
|
513
|
+
try { reader.releaseLock(); } catch {}
|
|
163
514
|
}
|
|
164
515
|
}
|
|
165
516
|
|
|
517
|
+
async function sendEarlyResponseAndClose(
|
|
518
|
+
webRes: Response,
|
|
519
|
+
res: http.ServerResponse,
|
|
520
|
+
method?: string,
|
|
521
|
+
): Promise<void> {
|
|
522
|
+
if (res.destroyed || res.writableEnded) return;
|
|
523
|
+
res.shouldKeepAlive = false;
|
|
524
|
+
if (!res.headersSent) res.setHeader('Connection', 'close');
|
|
525
|
+
// 先完整写出拒绝响应,再由 Node 按 Connection: close 关闭该连接;不排空无限请求体。
|
|
526
|
+
await sendWebResponse(webRes, res, method);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** 装配可选字段 `documentHead` 的形状:静态片段,或按请求上下文(CSP nonce)生成片段的函数 */
|
|
530
|
+
export type DocumentHeadSource = string | ((ctx: { readonly nonce?: string }) => string);
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* 按形状从已加载的 Host 装配读取可选 `documentHead`(类型契约之外的方言中性扩展口)。
|
|
534
|
+
* 无装配或未写该字段 → undefined;写了但不是字符串 / 函数 → 当场抛错,避免静默吞掉装配错误。
|
|
535
|
+
*/
|
|
536
|
+
export function readDocumentHeadSource(assembly: unknown): DocumentHeadSource | undefined {
|
|
537
|
+
if (assembly === null || typeof assembly !== 'object') return undefined;
|
|
538
|
+
const value = (assembly as Record<string, unknown>).documentHead;
|
|
539
|
+
if (value === undefined) return undefined;
|
|
540
|
+
if (typeof value === 'string' || typeof value === 'function') return value as DocumentHeadSource;
|
|
541
|
+
throw new Error('soma.app.ts 的 Host 装配的 documentHead 必须是字符串或返回字符串的函数');
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** 求出要插入 `<head>` 的片段:原样插入(片段自身负责转义与 nonce),末尾补换行缩进;无片段返回空串 */
|
|
545
|
+
export function renderDocumentHead(source: DocumentHeadSource | undefined, nonce: string | undefined): string {
|
|
546
|
+
if (source === undefined) return '';
|
|
547
|
+
const snippet = typeof source === 'function' ? source(nonce === undefined ? {} : { nonce }) : source;
|
|
548
|
+
if (typeof snippet !== 'string') {
|
|
549
|
+
throw new Error('soma.app.ts 的 Host 装配的 documentHead() 必须返回字符串');
|
|
550
|
+
}
|
|
551
|
+
return snippet === '' ? '' : `${snippet}\n `;
|
|
552
|
+
}
|
|
553
|
+
|
|
166
554
|
export async function createNativeServer(
|
|
167
555
|
options: CreateNativeServerOptions,
|
|
168
556
|
): Promise<NativeServerInstance> {
|
|
@@ -179,6 +567,7 @@ export async function createNativeServer(
|
|
|
179
567
|
const webRoot = path.resolve(options.webRoot || getSomaHostSourceRoot(hostDir, env));
|
|
180
568
|
const apiRoot = path.resolve(options.apiRoot || getSomaHostApiRoot(hostDir, env));
|
|
181
569
|
const dev = Boolean(options.dev);
|
|
570
|
+
const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
182
571
|
const runtimeLayout = resolveSomaRuntimeLayout(hostDir, env);
|
|
183
572
|
|
|
184
573
|
// 1. 若存在 AOT 服务清单,立即登记 AOT 解析器
|
|
@@ -186,6 +575,8 @@ export async function createNativeServer(
|
|
|
186
575
|
installAotManifest(aotManifestPath, hostDir);
|
|
187
576
|
|
|
188
577
|
await runHostStartup(hostDir);
|
|
578
|
+
// 装配的可选文档头片段(方言中性):按形状读取,插到外壳 <head> 末尾
|
|
579
|
+
let documentHeadSource = readDocumentHeadSource(await loadHostAssembly(hostDir));
|
|
189
580
|
|
|
190
581
|
// 2. 准备客户端产物(生产态优先直接读取预编译清单,零 esbuild 驻留)
|
|
191
582
|
const clientManifestPath = path.join(runtimeLayout.dirs.static, 'client', 'client-manifest.json');
|
|
@@ -220,7 +611,8 @@ export async function createNativeServer(
|
|
|
220
611
|
const key = `${titleText}\0${clientBuild.entryUrl}\0${clientBuild.cssText.length}\0${dev ? '1' : '0'}`;
|
|
221
612
|
if (cachedStaticShell && cachedStaticShell.key === key) return cachedStaticShell;
|
|
222
613
|
const devSse = dev ? '<script>window.__SOMA_DEV_SSE__ = true;</script>\n ' : '';
|
|
223
|
-
const
|
|
614
|
+
const extraHead = renderDocumentHead(documentHeadSource, undefined);
|
|
615
|
+
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(titleText)}</title>\n <style>${clientBuild.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="${clientBuild.entryUrl}"></script>\n</body>\n</html>`;
|
|
224
616
|
const utf8 = Buffer.from(html, 'utf8');
|
|
225
617
|
const gzip = zlib.gzipSync(utf8);
|
|
226
618
|
cachedStaticShell = { key, utf8, gzip };
|
|
@@ -252,13 +644,50 @@ export async function createNativeServer(
|
|
|
252
644
|
}
|
|
253
645
|
}
|
|
254
646
|
|
|
255
|
-
// 4.
|
|
647
|
+
// 4. 开发态监听前端目录;同宿主刷新串行执行,运行中的变更合并为下一轮。
|
|
256
648
|
let fsWatcher: fs.FSWatcher | null = null;
|
|
649
|
+
let watcherClosed = false;
|
|
650
|
+
let debounceTimer: NodeJS.Timeout | null = null;
|
|
651
|
+
let refreshPending = false;
|
|
652
|
+
let refreshNeedsTailwindClear = false;
|
|
653
|
+
let refreshTask: Promise<void> | null = null;
|
|
654
|
+
|
|
655
|
+
const drainDevRefreshQueue = (): Promise<void> => {
|
|
656
|
+
if (refreshTask) return refreshTask;
|
|
657
|
+
if (watcherClosed || !refreshPending) return Promise.resolve();
|
|
658
|
+
const task = (async () => {
|
|
659
|
+
while (refreshPending && !watcherClosed) {
|
|
660
|
+
const clearTailwind = refreshNeedsTailwindClear;
|
|
661
|
+
refreshPending = false;
|
|
662
|
+
refreshNeedsTailwindClear = false;
|
|
663
|
+
try {
|
|
664
|
+
if (clearTailwind) clearTailwindCompilerCache();
|
|
665
|
+
await invalidateHostPreparation(hostDir);
|
|
666
|
+
if (watcherClosed) break;
|
|
667
|
+
await prewarmHostPages(hostDir, env);
|
|
668
|
+
if (watcherClosed) break;
|
|
669
|
+
documentHeadSource = readDocumentHeadSource(await loadHostAssembly(hostDir));
|
|
670
|
+
cachedStaticShell = null;
|
|
671
|
+
await clientBuild.rebuild();
|
|
672
|
+
// 有更新排队或仍在 debounce 时不向浏览器发送中间代通知。
|
|
673
|
+
if (!watcherClosed && !refreshPending && debounceTimer === null) broadcastHmr('reload');
|
|
674
|
+
} catch (error) {
|
|
675
|
+
// 单轮失败只记录本轮;队列仍会继续执行合并后的下一代。
|
|
676
|
+
console.error('[soma-native][dev-rebuild-error]', error);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
})();
|
|
680
|
+
refreshTask = task.finally(() => {
|
|
681
|
+
refreshTask = null;
|
|
682
|
+
if (refreshPending && !watcherClosed) void drainDevRefreshQueue();
|
|
683
|
+
});
|
|
684
|
+
return refreshTask;
|
|
685
|
+
};
|
|
686
|
+
|
|
257
687
|
if (dev) {
|
|
258
688
|
try {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
if (!filename) return;
|
|
689
|
+
fsWatcher = fs.watch(webRoot, { recursive: true }, (_event, filename) => {
|
|
690
|
+
if (watcherClosed || !filename) return;
|
|
262
691
|
const norm = filename.replace(/\\/g, '/');
|
|
263
692
|
if (
|
|
264
693
|
norm.startsWith('.') ||
|
|
@@ -268,35 +697,90 @@ export async function createNativeServer(
|
|
|
268
697
|
) {
|
|
269
698
|
return;
|
|
270
699
|
}
|
|
271
|
-
//
|
|
700
|
+
// 仅当 apiRoot 与 webRoot 不同且位于其下时,才跳过后端文件变动(默认布局二者相同,不能丢事件)
|
|
272
701
|
const full = path.join(webRoot, filename);
|
|
273
|
-
if (full.startsWith(apiRoot + path.sep)) return;
|
|
702
|
+
if (apiRoot !== webRoot && full.startsWith(apiRoot + path.sep)) return;
|
|
274
703
|
|
|
704
|
+
refreshNeedsTailwindClear ||= /\.(?:css|ya?ml)$/i.test(norm);
|
|
275
705
|
if (debounceTimer) clearTimeout(debounceTimer);
|
|
276
|
-
debounceTimer = setTimeout(
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
await clientBuild.rebuild();
|
|
282
|
-
broadcastHmr('reload');
|
|
283
|
-
} catch (e) {
|
|
284
|
-
console.error('[soma-native][dev-rebuild-error]', e);
|
|
285
|
-
}
|
|
706
|
+
debounceTimer = setTimeout(() => {
|
|
707
|
+
debounceTimer = null;
|
|
708
|
+
if (watcherClosed) return;
|
|
709
|
+
refreshPending = true;
|
|
710
|
+
void drainDevRefreshQueue();
|
|
286
711
|
}, 100);
|
|
287
712
|
});
|
|
288
|
-
} catch {
|
|
289
|
-
// 平台不支持 recursive watch
|
|
713
|
+
} catch (error) {
|
|
714
|
+
// 平台不支持 recursive watch 时降级,但不能静默
|
|
715
|
+
console.warn('[soma-native] 热更新不可用:文件监听启动失败', error instanceof Error ? error.message : error);
|
|
290
716
|
}
|
|
291
717
|
}
|
|
292
718
|
|
|
293
719
|
// 5. 纯 node:http 服务器主调度
|
|
720
|
+
const warnedHookBodyMembers = new Set<string>();
|
|
294
721
|
const server = http.createServer(async (req, res) => {
|
|
722
|
+
const abortController = new AbortController();
|
|
723
|
+
res.on('close', () => {
|
|
724
|
+
if (!res.writableEnded) {
|
|
725
|
+
abortController.abort();
|
|
726
|
+
}
|
|
727
|
+
});
|
|
728
|
+
|
|
295
729
|
try {
|
|
296
730
|
const origin = `http://${req.headers.host || 'localhost'}`;
|
|
297
|
-
|
|
731
|
+
let url: URL;
|
|
732
|
+
try {
|
|
733
|
+
url = new URL(req.url || '/', origin);
|
|
734
|
+
} catch {
|
|
735
|
+
// Host 或请求目标非法属于客户端错误,不记为服务端错误
|
|
736
|
+
res.shouldKeepAlive = false;
|
|
737
|
+
res.statusCode = 400;
|
|
738
|
+
res.setHeader('Connection', 'close');
|
|
739
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
740
|
+
res.end('Bad Request');
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
298
743
|
const pathname = url.pathname;
|
|
299
744
|
const method = (req.method || 'GET').toUpperCase();
|
|
745
|
+
const isApiPath = pathname === '/api' || pathname.startsWith('/api/');
|
|
746
|
+
const isSomaInternalPath = pathname === '/soma' || pathname.startsWith('/soma/');
|
|
747
|
+
const allowedMethods = isApiPath
|
|
748
|
+
? API_ALLOW_METHODS
|
|
749
|
+
: isSomaInternalPath
|
|
750
|
+
? (['GET'] as const)
|
|
751
|
+
: PAGE_ALLOW_METHODS;
|
|
752
|
+
if (!(allowedMethods as readonly string[]).includes(method)) {
|
|
753
|
+
let methodNotAllowed = new Response('Method Not Allowed', {
|
|
754
|
+
status: 405,
|
|
755
|
+
headers: {
|
|
756
|
+
allow: allowedMethods.join(', '),
|
|
757
|
+
'cache-control': 'no-store',
|
|
758
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
759
|
+
},
|
|
760
|
+
});
|
|
761
|
+
methodNotAllowed = await applyHostAndCspHeaders(methodNotAllowed, { method, pathname }, env);
|
|
762
|
+
await sendEarlyResponseAndClose(methodNotAllowed, res, method);
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// 全局前置安全拦截:只拦截编码路径穿越(%2e%2e, %2e., .%2e, %2f%2e)与控制字符(\0-\x1f)
|
|
767
|
+
const rawUrl = req.url || '/';
|
|
768
|
+
const rawPathOnly = rawUrl.split('?')[0].split('#')[0];
|
|
769
|
+
const hasEncodedTraversal = /%2e%2e|%2e\.|%2f%2e|\.%2e/i.test(rawPathOnly);
|
|
770
|
+
const hasControlChars = /[\x00-\x1f]/.test(rawPathOnly);
|
|
771
|
+
if (hasEncodedTraversal || hasControlChars) {
|
|
772
|
+
let notFoundRes = new Response('Not found', {
|
|
773
|
+
status: 404,
|
|
774
|
+
headers: {
|
|
775
|
+
'cache-control': 'no-store',
|
|
776
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
777
|
+
'x-content-type-options': 'nosniff',
|
|
778
|
+
},
|
|
779
|
+
});
|
|
780
|
+
notFoundRes = await applyHostAndCspHeaders(notFoundRes, { method, pathname }, env);
|
|
781
|
+
await sendWebResponse(notFoundRes, res, method);
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
300
784
|
|
|
301
785
|
// ==========================================
|
|
302
786
|
// 分支 A: 静态极速通道
|
|
@@ -320,118 +804,54 @@ export async function createNativeServer(
|
|
|
320
804
|
|
|
321
805
|
// A.2: 客户端 JS/CSS 分片直出
|
|
322
806
|
if (pathname.startsWith('/_soma/client/')) {
|
|
323
|
-
const
|
|
324
|
-
const
|
|
325
|
-
const
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
} catch {
|
|
330
|
-
res.statusCode = 404;
|
|
331
|
-
res.end('File not found');
|
|
807
|
+
const subSegments = pathname.slice('/_soma/client/'.length).split('/').filter(Boolean);
|
|
808
|
+
const staticReq = createStaticLookupRequest(req, method);
|
|
809
|
+
const clientStaticDir = path.resolve(runtimeLayout.dirs.static, 'client');
|
|
810
|
+
const clientRes = serveStaticFromRoot(clientStaticDir, subSegments, staticReq, true);
|
|
811
|
+
if (clientRes) {
|
|
812
|
+
await sendWebResponse(clientRes, res, method);
|
|
332
813
|
return;
|
|
333
814
|
}
|
|
334
815
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
return;
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
const isHashed = /[-.](?:[0-9a-f]{8,}|[0-9A-Z]{8})\.[a-z0-9]+$/.test(subfile);
|
|
349
|
-
const etag = `W/"${createHash('sha1').update(`${stat.size}:${stat.mtimeMs}`).digest('hex').slice(0, 20)}"`;
|
|
350
|
-
const ifNoneMatch = req.headers['if-none-match'];
|
|
351
|
-
|
|
352
|
-
if (ifNoneMatch && ifNoneMatch.includes(etag)) {
|
|
353
|
-
res.statusCode = 304;
|
|
354
|
-
res.end();
|
|
355
|
-
return;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
const ext = path.extname(realFile).toLowerCase();
|
|
359
|
-
let contentType = 'application/octet-stream';
|
|
360
|
-
if (ext === '.js' || ext === '.mjs') contentType = 'text/javascript; charset=utf-8';
|
|
361
|
-
else if (ext === '.css') contentType = 'text/css; charset=utf-8';
|
|
362
|
-
else if (ext === '.json' || ext === '.map') contentType = 'application/json; charset=utf-8';
|
|
363
|
-
|
|
364
|
-
res.setHeader('Content-Type', contentType);
|
|
365
|
-
res.setHeader(
|
|
366
|
-
'Cache-Control',
|
|
367
|
-
isHashed ? 'public, max-age=31536000, immutable' : 'public, max-age=300, must-revalidate',
|
|
368
|
-
);
|
|
369
|
-
res.setHeader('ETag', etag);
|
|
370
|
-
|
|
371
|
-
if (method === 'HEAD') {
|
|
372
|
-
res.statusCode = 200;
|
|
373
|
-
res.end();
|
|
374
|
-
return;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
const content = fs.readFileSync(realFile);
|
|
378
|
-
res.statusCode = 200;
|
|
379
|
-
res.end(content);
|
|
816
|
+
let notFoundRes = new Response('File not found', {
|
|
817
|
+
status: 404,
|
|
818
|
+
headers: {
|
|
819
|
+
'cache-control': 'no-store',
|
|
820
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
821
|
+
'x-content-type-options': 'nosniff',
|
|
822
|
+
},
|
|
823
|
+
});
|
|
824
|
+
notFoundRes = await applyHostAndCspHeaders(notFoundRes, { method, pathname }, env);
|
|
825
|
+
await sendWebResponse(notFoundRes, res, method);
|
|
380
826
|
return;
|
|
381
827
|
}
|
|
382
828
|
|
|
383
829
|
// A.3: /soma-runtime/* 核心静态资源
|
|
384
830
|
if (pathname.startsWith('/soma-runtime/')) {
|
|
385
831
|
const segments = pathname.slice('/soma-runtime/'.length).split('/').filter(Boolean);
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
headers: {
|
|
389
|
-
get(name: string) {
|
|
390
|
-
const v = req.headers[name.toLowerCase()];
|
|
391
|
-
return Array.isArray(v) ? v.join(', ') : v || null;
|
|
392
|
-
},
|
|
393
|
-
},
|
|
394
|
-
};
|
|
395
|
-
const staticRes = staticResponse(segments, standardReq, env);
|
|
832
|
+
const staticReq = createStaticLookupRequest(req, method);
|
|
833
|
+
const staticRes = staticResponse(segments, staticReq, env);
|
|
396
834
|
await sendWebResponse(staticRes, res);
|
|
397
835
|
return;
|
|
398
836
|
}
|
|
399
837
|
|
|
400
838
|
// A.4: public/* 宿主静态文件直出
|
|
401
839
|
const publicDir = path.resolve(webRoot, 'public');
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
let ctype = 'application/octet-stream';
|
|
411
|
-
if (ext === '.ico') ctype = 'image/x-icon';
|
|
412
|
-
else if (ext === '.svg') ctype = 'image/svg+xml';
|
|
413
|
-
else if (ext === '.png') ctype = 'image/png';
|
|
414
|
-
else if (ext === '.jpg' || ext === '.jpeg') ctype = 'image/jpeg';
|
|
415
|
-
else if (ext === '.txt') ctype = 'text/plain; charset=utf-8';
|
|
416
|
-
|
|
417
|
-
res.statusCode = 200;
|
|
418
|
-
res.setHeader('Content-Type', ctype);
|
|
419
|
-
res.setHeader('Content-Length', stat.size);
|
|
420
|
-
if (method === 'HEAD') {
|
|
421
|
-
res.end();
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
res.end(fs.readFileSync(realTarget));
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
} catch {}
|
|
840
|
+
const publicSegments = pathname.split('/').filter(Boolean);
|
|
841
|
+
if (fs.existsSync(publicDir) && publicSegments.length > 0) {
|
|
842
|
+
const staticReq = createStaticLookupRequest(req, method);
|
|
843
|
+
const publicRes = serveStaticFromRoot(publicDir, publicSegments, staticReq);
|
|
844
|
+
if (publicRes) {
|
|
845
|
+
await sendWebResponse(publicRes, res, method);
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
428
848
|
}
|
|
429
849
|
|
|
430
850
|
// ==========================================
|
|
431
851
|
// 分支 B: SOMA 内部数据接口 (/soma/*)
|
|
432
852
|
// ==========================================
|
|
433
853
|
if (pathname.startsWith('/soma/') || pathname === '/soma') {
|
|
434
|
-
const webReq =
|
|
854
|
+
const webReq = createHeaderOnlyWebRequest(req, origin, abortController.signal);
|
|
435
855
|
|
|
436
856
|
// B.1: GET /soma/page
|
|
437
857
|
if (pathname === '/soma/page' && method === 'GET') {
|
|
@@ -439,48 +859,130 @@ export async function createNativeServer(
|
|
|
439
859
|
let assembly: any = null;
|
|
440
860
|
try {
|
|
441
861
|
assembly = await prepareHostAssembly(hostDir);
|
|
442
|
-
const hookRejected = await invokeHostRequestHook(
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
862
|
+
const hookRejected = await invokeHostRequestHook(
|
|
863
|
+
webReq,
|
|
864
|
+
{
|
|
865
|
+
kind: 'page',
|
|
866
|
+
path: pagePath,
|
|
867
|
+
pageHref: pagePath,
|
|
868
|
+
},
|
|
869
|
+
undefined,
|
|
870
|
+
{ hostDir },
|
|
871
|
+
);
|
|
447
872
|
if (hookRejected) {
|
|
448
873
|
const hooked = await applyHostAndCspHeaders(hookRejected, { method: 'GET', pathname }, env);
|
|
449
|
-
await
|
|
874
|
+
await sendEarlyResponseAndClose(hooked, res, method);
|
|
450
875
|
return;
|
|
451
876
|
}
|
|
452
877
|
const page = await loadPageByAddress(pagePath, webReq, { hostDir });
|
|
453
878
|
const pageRecord = page as unknown as {
|
|
454
|
-
binding?: { digest?: string; generation?: number };
|
|
879
|
+
binding?: { digest?: string; generation?: number; kind?: string };
|
|
455
880
|
nav?: unknown;
|
|
456
881
|
params?: unknown;
|
|
457
882
|
query?: unknown;
|
|
458
883
|
};
|
|
459
|
-
const
|
|
884
|
+
const isPrefix = pageRecord.binding?.kind === 'prefix';
|
|
885
|
+
const cacheKey = dev || isPrefix || page.cacheable === false
|
|
886
|
+
? undefined
|
|
887
|
+
: `page:${hostDir}:${pagePath}:${pageRecord.binding?.digest ?? ''}:${pageRecord.binding?.generation ?? 0}:${JSON.stringify([pageRecord.nav ?? null, pageRecord.params ?? null, pageRecord.query ?? null])}`;
|
|
460
888
|
let response = pageSuccessResponse(page, page, webReq, cacheKey);
|
|
461
889
|
response = await applyHostAndCspHeaders(response, { method: 'GET', pathname }, env);
|
|
462
|
-
await sendWebResponse(response, res);
|
|
890
|
+
await sendWebResponse(response, res, method);
|
|
463
891
|
return;
|
|
464
892
|
} catch (error) {
|
|
465
893
|
let response = pageErrorResponse(error, assembly);
|
|
466
894
|
response = await applyHostAndCspHeaders(response, { method: 'GET', pathname }, env);
|
|
467
|
-
await sendWebResponse(response, res);
|
|
895
|
+
await sendWebResponse(response, res, method);
|
|
468
896
|
return;
|
|
469
897
|
}
|
|
470
898
|
}
|
|
471
899
|
|
|
472
900
|
// B.2: GET /soma/manifest
|
|
473
901
|
if (pathname === '/soma/manifest' && method === 'GET') {
|
|
474
|
-
|
|
902
|
+
await prepareHostAssembly(hostDir);
|
|
903
|
+
|
|
904
|
+
const isIndex = url.searchParams.get('index') === '1';
|
|
905
|
+
if (isIndex && !dev) {
|
|
906
|
+
let forbiddenRes = Response.json(
|
|
907
|
+
{ error: 'Manifest index is disabled in production' },
|
|
908
|
+
{ status: 403 },
|
|
909
|
+
);
|
|
910
|
+
forbiddenRes = await applyHostAndCspHeaders(forbiddenRes, { method: 'GET', pathname }, env);
|
|
911
|
+
await sendWebResponse(forbiddenRes, res, method);
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
if (isIndex) {
|
|
916
|
+
// 开发态 index=1 也必须先跑钩子(context.path 用 '/')
|
|
917
|
+
const hookRejected = await invokeHostRequestHook(
|
|
918
|
+
webReq,
|
|
919
|
+
{
|
|
920
|
+
kind: 'page',
|
|
921
|
+
path: '/',
|
|
922
|
+
pageHref: '/',
|
|
923
|
+
},
|
|
924
|
+
undefined,
|
|
925
|
+
{ hostDir },
|
|
926
|
+
);
|
|
927
|
+
if (hookRejected) {
|
|
928
|
+
const hooked = await applyHostAndCspHeaders(hookRejected, { method: 'GET', pathname }, env);
|
|
929
|
+
await sendEarlyResponseAndClose(hooked, res, method);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
let response = await handleManifestGet(webReq, { hostDir });
|
|
933
|
+
response = await applyHostAndCspHeaders(response, { method: 'GET', pathname }, env);
|
|
934
|
+
await sendWebResponse(response, res, method);
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
// 缺 path(且非开发态 index=1)返回 400
|
|
939
|
+
const rawPath = url.searchParams.get('path');
|
|
940
|
+
if (!rawPath) {
|
|
941
|
+
let badReqRes = Response.json(
|
|
942
|
+
{ error: 'Missing path parameter' },
|
|
943
|
+
{ status: 400 },
|
|
944
|
+
);
|
|
945
|
+
badReqRes = await applyHostAndCspHeaders(badReqRes, { method: 'GET', pathname }, env);
|
|
946
|
+
await sendWebResponse(badReqRes, res, method);
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// path 自身落在 /soma 保留命名空间时返回 400
|
|
951
|
+
if (isSomaInternalRequestPath(rawPath)) {
|
|
952
|
+
let badReqRes = Response.json(
|
|
953
|
+
{ error: 'Path cannot be in reserved /soma namespace' },
|
|
954
|
+
{ status: 400 },
|
|
955
|
+
);
|
|
956
|
+
badReqRes = await applyHostAndCspHeaders(badReqRes, { method: 'GET', pathname }, env);
|
|
957
|
+
await sendWebResponse(badReqRes, res, method);
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
const hookRejected = await invokeHostRequestHook(
|
|
962
|
+
webReq,
|
|
963
|
+
{
|
|
964
|
+
kind: 'page',
|
|
965
|
+
path: rawPath,
|
|
966
|
+
pageHref: rawPath,
|
|
967
|
+
},
|
|
968
|
+
undefined,
|
|
969
|
+
{ hostDir },
|
|
970
|
+
);
|
|
971
|
+
if (hookRejected) {
|
|
972
|
+
const hooked = await applyHostAndCspHeaders(hookRejected, { method: 'GET', pathname }, env);
|
|
973
|
+
await sendEarlyResponseAndClose(hooked, res, method);
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
let response = await handleManifestGet(webReq, { hostDir });
|
|
475
977
|
response = await applyHostAndCspHeaders(response, { method: 'GET', pathname }, env);
|
|
476
|
-
await sendWebResponse(response, res);
|
|
978
|
+
await sendWebResponse(response, res, method);
|
|
477
979
|
return;
|
|
478
980
|
}
|
|
479
981
|
|
|
480
982
|
// B.3: 未知内部端点 404
|
|
481
983
|
let notFoundRes = Response.json({ error: 'SOMA internal endpoint not found' }, { status: 404 });
|
|
482
984
|
notFoundRes = await applyHostAndCspHeaders(notFoundRes, { method, pathname }, env);
|
|
483
|
-
await sendWebResponse(notFoundRes, res);
|
|
985
|
+
await sendWebResponse(notFoundRes, res, method);
|
|
484
986
|
return;
|
|
485
987
|
}
|
|
486
988
|
|
|
@@ -488,18 +990,62 @@ export async function createNativeServer(
|
|
|
488
990
|
// 分支 C: 后端业务接口 (/api/*)
|
|
489
991
|
// ==========================================
|
|
490
992
|
if (pathname.startsWith('/api/') || pathname === '/api') {
|
|
491
|
-
|
|
993
|
+
checkContentLength(req, maxBodyBytes);
|
|
994
|
+
|
|
995
|
+
// 1. 先用不消费 req 流的轻量 Request 跑鉴权;需要签名时由钩子显式惰性读取。
|
|
996
|
+
const bodyReader = createRequestBodyReader(req, maxBodyBytes, abortController.signal);
|
|
997
|
+
const headerReq = createHeaderOnlyWebRequest(req, origin, abortController.signal);
|
|
998
|
+
const hookRejected = await invokeHostRequestHook(
|
|
999
|
+
guardHookRequestBody(headerReq, req, dev, warnedHookBodyMembers),
|
|
1000
|
+
{
|
|
1001
|
+
kind: 'api',
|
|
1002
|
+
path: pathname,
|
|
1003
|
+
readBody: bodyReader.readBody,
|
|
1004
|
+
},
|
|
1005
|
+
undefined,
|
|
1006
|
+
{ hostDir },
|
|
1007
|
+
);
|
|
1008
|
+
bodyReader.assertWithinLimit();
|
|
1009
|
+
if (hookRejected) {
|
|
1010
|
+
const hooked = await applyHostAndCspHeaders(hookRejected, { method, pathname }, env);
|
|
1011
|
+
await sendEarlyResponseAndClose(hooked, res, method);
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// 2. 钩子放行后复用其惰性缓存的原始字节与改写后的 headers,不二次读取 socket。
|
|
1016
|
+
const bodyBytes = await bodyReader.readRawBody();
|
|
1017
|
+
const webReq = await toWebRequest(req, origin, maxBodyBytes, abortController.signal, headerReq.headers, bodyBytes);
|
|
492
1018
|
const segments = pathname.slice('/api'.length).split('/').filter(Boolean);
|
|
493
|
-
let apiRes = await dispatchHostServiceApiRequest(webReq, {
|
|
1019
|
+
let apiRes = await dispatchHostServiceApiRequest(webReq, {
|
|
1020
|
+
segments,
|
|
1021
|
+
hostDir,
|
|
1022
|
+
requestHookHandled: true,
|
|
1023
|
+
});
|
|
494
1024
|
apiRes = await applyHostAndCspHeaders(apiRes, { method, pathname }, env);
|
|
495
|
-
await sendWebResponse(apiRes, res);
|
|
1025
|
+
await sendWebResponse(apiRes, res, method);
|
|
496
1026
|
return;
|
|
497
1027
|
}
|
|
498
1028
|
|
|
499
1029
|
// ==========================================
|
|
500
1030
|
// 分支 D: 前端页面 HTML 极速外壳 (GET / HEAD)
|
|
501
1031
|
// ==========================================
|
|
502
|
-
|
|
1032
|
+
// 页面路由安全拦截:点起首隐藏文件段或不安全段(如 /.env, /.git/config)不可进入前端 SPA 外壳,统一 404 拒绝
|
|
1033
|
+
const pathSegments = pathname.split('/').filter(Boolean);
|
|
1034
|
+
if (pathSegments.length > 0 && !isSafeSegments(pathSegments)) {
|
|
1035
|
+
let notFoundRes = new Response('Not found', {
|
|
1036
|
+
status: 404,
|
|
1037
|
+
headers: {
|
|
1038
|
+
'cache-control': 'no-store',
|
|
1039
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
1040
|
+
'x-content-type-options': 'nosniff',
|
|
1041
|
+
},
|
|
1042
|
+
});
|
|
1043
|
+
notFoundRes = await applyHostAndCspHeaders(notFoundRes, { method, pathname }, env);
|
|
1044
|
+
await sendWebResponse(notFoundRes, res, method);
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
const headerReq = createHeaderOnlyWebRequest(req, origin, abortController.signal);
|
|
503
1049
|
const csp = createSomaCspHeader(resolveSomaCspOptionsFromEnv(env));
|
|
504
1050
|
const verifiedNonce = await readCspNonceMeta(csp?.nonce, env as Record<string, string | undefined>);
|
|
505
1051
|
const nonceAttr = verifiedNonce ? ` nonce="${escapeHtml(verifiedNonce)}"` : '';
|
|
@@ -511,18 +1057,32 @@ export async function createNativeServer(
|
|
|
511
1057
|
}
|
|
512
1058
|
};
|
|
513
1059
|
|
|
1060
|
+
await prepareHostAssembly(hostDir);
|
|
514
1061
|
// 跑 Host 请求钩子
|
|
515
|
-
const rejected = await invokeHostRequestHook(
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
1062
|
+
const rejected = await invokeHostRequestHook(
|
|
1063
|
+
guardHookRequestBody(headerReq, req, dev, warnedHookBodyMembers),
|
|
1064
|
+
{
|
|
1065
|
+
kind: 'page',
|
|
1066
|
+
path: pathname,
|
|
1067
|
+
pageHref: pathname,
|
|
1068
|
+
},
|
|
1069
|
+
undefined,
|
|
1070
|
+
{ hostDir },
|
|
1071
|
+
);
|
|
520
1072
|
|
|
521
1073
|
if (rejected) {
|
|
1074
|
+
// 仅当请求带有未读取的请求体时才强制关闭连接(否则残留字节会污染 keep-alive)
|
|
1075
|
+
const unreadBody = requestHasBody(req);
|
|
1076
|
+
if (unreadBody) {
|
|
1077
|
+
res.shouldKeepAlive = false;
|
|
1078
|
+
if (!res.headersSent) res.setHeader('Connection', 'close');
|
|
1079
|
+
}
|
|
1080
|
+
const sendRejection = (webRes: Response) =>
|
|
1081
|
+
unreadBody ? sendEarlyResponseAndClose(webRes, res, method) : sendWebResponse(webRes, res, method);
|
|
522
1082
|
// 重定向(经可写克隆合并宿主头与 CSP,并完整保留 Set-Cookie 等头)
|
|
523
1083
|
if (rejected.status >= 300 && rejected.status < 400 && rejected.headers.get('location')) {
|
|
524
1084
|
const hooked = await applyHostAndCspHeaders(rejected, { method, pathname }, env);
|
|
525
|
-
await
|
|
1085
|
+
await sendRejection(hooked);
|
|
526
1086
|
return;
|
|
527
1087
|
}
|
|
528
1088
|
|
|
@@ -535,7 +1095,7 @@ export async function createNativeServer(
|
|
|
535
1095
|
(rejected.ok || !acceptHeader.includes('text/html'))
|
|
536
1096
|
) {
|
|
537
1097
|
const hooked = await applyHostAndCspHeaders(rejected, { method, pathname }, env);
|
|
538
|
-
await
|
|
1098
|
+
await sendRejection(hooked);
|
|
539
1099
|
return;
|
|
540
1100
|
}
|
|
541
1101
|
|
|
@@ -544,20 +1104,22 @@ export async function createNativeServer(
|
|
|
544
1104
|
const rawHtml = await rejected.text();
|
|
545
1105
|
const inner = extractHtmlBodyInner(rawHtml);
|
|
546
1106
|
const html = `<!DOCTYPE html><html><head><meta charset="utf-8">${cspMeta}</head><body><div data-soma-request-rejected="${rejected.status}" data-soma-rejection-html="1">${inner}</div></body></html>`;
|
|
1107
|
+
copyHookResponseHeaders(rejected, res);
|
|
547
1108
|
res.statusCode = rejected.status;
|
|
548
1109
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
549
1110
|
if (csp) res.setHeader(csp.name, csp.value);
|
|
550
|
-
res.end(html);
|
|
1111
|
+
if (method === 'HEAD') res.end(); else res.end(html);
|
|
551
1112
|
return;
|
|
552
1113
|
}
|
|
553
1114
|
|
|
554
1115
|
// JSON/文本拒绝
|
|
555
1116
|
const message = await readRejectedMessage(rejected);
|
|
556
1117
|
const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Request Rejected</title>${cspMeta}<style${nonceAttr}>${clientBuild.cssText}</style></head><body><main class="soma-request-rejected" data-soma-request-rejected="${rejected.status}"><section class="soma-request-rejected__panel"><p class="soma-request-rejected__eyebrow">HTTP ${rejected.status}</p><h1 class="soma-request-rejected__title">Request rejected</h1><p class="soma-request-rejected__message">${escapeHtml(message)}</p></section></main></body></html>`;
|
|
1118
|
+
copyHookResponseHeaders(rejected, res);
|
|
557
1119
|
res.statusCode = rejected.status;
|
|
558
1120
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
559
1121
|
if (csp) res.setHeader(csp.name, csp.value);
|
|
560
|
-
res.end(html);
|
|
1122
|
+
if (method === 'HEAD') res.end(); else res.end(html);
|
|
561
1123
|
return;
|
|
562
1124
|
}
|
|
563
1125
|
|
|
@@ -569,7 +1131,7 @@ export async function createNativeServer(
|
|
|
569
1131
|
res.statusCode = 200;
|
|
570
1132
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
571
1133
|
const ae = req.headers['accept-encoding'];
|
|
572
|
-
if (
|
|
1134
|
+
if (acceptsGzip(ae) && prebuilt.utf8.length >= 1024) {
|
|
573
1135
|
res.setHeader('Content-Encoding', 'gzip');
|
|
574
1136
|
res.setHeader('Vary', 'Accept-Encoding');
|
|
575
1137
|
res.setHeader('Content-Length', prebuilt.gzip.length);
|
|
@@ -585,6 +1147,7 @@ export async function createNativeServer(
|
|
|
585
1147
|
const devSseScript = dev
|
|
586
1148
|
? `<script${nonceAttr}>window.__SOMA_DEV_SSE__ = true;</script>\n`
|
|
587
1149
|
: '';
|
|
1150
|
+
const extraHeadSnippet = renderDocumentHead(documentHeadSource, verifiedNonce || undefined);
|
|
588
1151
|
|
|
589
1152
|
const htmlDocument = `<!DOCTYPE html>
|
|
590
1153
|
<html lang="en">
|
|
@@ -601,7 +1164,7 @@ export async function createNativeServer(
|
|
|
601
1164
|
}
|
|
602
1165
|
} catch (_) {}
|
|
603
1166
|
</script>
|
|
604
|
-
${devSseScript}</head>
|
|
1167
|
+
${extraHeadSnippet}${devSseScript}</head>
|
|
605
1168
|
<body>
|
|
606
1169
|
<div id="soma-app-root">
|
|
607
1170
|
<div class="soma-hydration-shell">
|
|
@@ -618,8 +1181,7 @@ export async function createNativeServer(
|
|
|
618
1181
|
|
|
619
1182
|
const acceptEncoding = req.headers['accept-encoding'];
|
|
620
1183
|
if (
|
|
621
|
-
acceptEncoding &&
|
|
622
|
-
(acceptEncoding.includes('gzip') || acceptEncoding.includes('*')) &&
|
|
1184
|
+
acceptsGzip(acceptEncoding) &&
|
|
623
1185
|
htmlDocument.length >= 1024
|
|
624
1186
|
) {
|
|
625
1187
|
try {
|
|
@@ -644,27 +1206,68 @@ export async function createNativeServer(
|
|
|
644
1206
|
}
|
|
645
1207
|
res.end(htmlBuf);
|
|
646
1208
|
} catch (err: unknown) {
|
|
1209
|
+
if (isClientAbortError(err, res, abortController.signal, req)) return;
|
|
1210
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
1211
|
+
if (!res.headersSent) {
|
|
1212
|
+
await sendEarlyResponseAndClose(
|
|
1213
|
+
Response.json({ error: 'Payload Too Large' }, { status: 413 }),
|
|
1214
|
+
res,
|
|
1215
|
+
(req.method || 'GET').toUpperCase(),
|
|
1216
|
+
);
|
|
1217
|
+
} else if (!res.writableEnded && !res.destroyed) {
|
|
1218
|
+
res.destroy();
|
|
1219
|
+
}
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
647
1222
|
const message = err instanceof Error ? err.stack || err.message : String(err);
|
|
648
1223
|
console.error('[soma-native][server-error]', message);
|
|
649
1224
|
if (!res.headersSent) {
|
|
1225
|
+
res.shouldKeepAlive = false;
|
|
650
1226
|
res.statusCode = 500;
|
|
1227
|
+
// 只清与已作废响应体 / 缓存语义相关的头;安全头等保留
|
|
1228
|
+
for (const name of STALE_ENTITY_HEADERS) res.removeHeader(name);
|
|
1229
|
+
res.setHeader('Connection', 'close');
|
|
1230
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
651
1231
|
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
652
1232
|
res.end('Internal Server Error');
|
|
1233
|
+
} else if (!res.writableEnded && !res.destroyed) {
|
|
1234
|
+
res.destroy();
|
|
653
1235
|
}
|
|
654
1236
|
}
|
|
655
1237
|
});
|
|
656
1238
|
|
|
1239
|
+
// CONNECT 不会进入 createServer(requestListener),Node 会单独发出 connect 事件。
|
|
1240
|
+
server.on('connect', (_req, socket) => {
|
|
1241
|
+
if (socket.destroyed) return;
|
|
1242
|
+
const response = [
|
|
1243
|
+
'HTTP/1.1 405 Method Not Allowed',
|
|
1244
|
+
`Allow: ${API_ALLOW_METHODS.join(', ')}`,
|
|
1245
|
+
'Connection: close',
|
|
1246
|
+
'Content-Length: 0',
|
|
1247
|
+
'',
|
|
1248
|
+
'',
|
|
1249
|
+
].join('\r\n');
|
|
1250
|
+
socket.end(response);
|
|
1251
|
+
});
|
|
1252
|
+
|
|
657
1253
|
server.keepAliveTimeout = 65_000;
|
|
658
1254
|
server.headersTimeout = 66_000;
|
|
659
1255
|
|
|
660
1256
|
const port = options.port ?? (process.env.PORT ? parseInt(process.env.PORT, 10) : 3000);
|
|
661
|
-
const hostname = options.hostname ?? process.env.
|
|
1257
|
+
const hostname = options.hostname ?? (options.env ? (options.env.SOMA_HOST ?? options.env.HOST) : undefined) ?? process.env.SOMA_HOST ?? process.env.HOST ?? '0.0.0.0';
|
|
662
1258
|
|
|
663
1259
|
return {
|
|
664
1260
|
server,
|
|
665
1261
|
port,
|
|
666
1262
|
url: `http://${hostname === '0.0.0.0' ? 'localhost' : hostname}:${port}`,
|
|
667
|
-
start() {
|
|
1263
|
+
async start() {
|
|
1264
|
+
if (port > 0 && (await isPortInUse(port, hostname))) {
|
|
1265
|
+
const msg = `[soma-native][server] 端口 ${port} 已被其他进程占用,请使用 --port 指定其他端口`;
|
|
1266
|
+
console.error(msg);
|
|
1267
|
+
const err = new Error(msg) as NodeJS.ErrnoException;
|
|
1268
|
+
err.code = 'EADDRINUSE';
|
|
1269
|
+
throw err;
|
|
1270
|
+
}
|
|
668
1271
|
return new Promise((resolve, reject) => {
|
|
669
1272
|
server.listen(port, hostname, () => {
|
|
670
1273
|
const addr = server.address();
|
|
@@ -672,10 +1275,20 @@ export async function createNativeServer(
|
|
|
672
1275
|
const url = `http://${hostname === '0.0.0.0' ? 'localhost' : hostname}:${actualPort}`;
|
|
673
1276
|
resolve({ url, port: actualPort });
|
|
674
1277
|
});
|
|
675
|
-
server.once('error',
|
|
1278
|
+
server.once('error', (err: NodeJS.ErrnoException) => {
|
|
1279
|
+
if (err && err.code === 'EADDRINUSE') {
|
|
1280
|
+
console.error(`[soma-native][server] 端口 ${port} 已被其他进程占用,请使用 --port 指定其他端口`);
|
|
1281
|
+
}
|
|
1282
|
+
reject(err);
|
|
1283
|
+
});
|
|
676
1284
|
});
|
|
677
1285
|
},
|
|
678
1286
|
async close() {
|
|
1287
|
+
watcherClosed = true;
|
|
1288
|
+
if (debounceTimer) clearTimeout(debounceTimer);
|
|
1289
|
+
debounceTimer = null;
|
|
1290
|
+
refreshPending = false;
|
|
1291
|
+
refreshNeedsTailwindClear = false;
|
|
679
1292
|
if (hmrHeartbeatTimer) clearInterval(hmrHeartbeatTimer);
|
|
680
1293
|
for (const client of sseClients) {
|
|
681
1294
|
try {
|
|
@@ -688,15 +1301,40 @@ export async function createNativeServer(
|
|
|
688
1301
|
fsWatcher.close();
|
|
689
1302
|
} catch {}
|
|
690
1303
|
}
|
|
1304
|
+
await refreshTask?.catch(() => {});
|
|
691
1305
|
await clientBuild.dispose();
|
|
692
1306
|
if (prevWebDir !== undefined) process.env.SOMA_WEB_DIR = prevWebDir;
|
|
693
1307
|
else delete process.env.SOMA_WEB_DIR;
|
|
694
1308
|
if (prevApiDir !== undefined) process.env.SOMA_API_DIR = prevApiDir;
|
|
695
1309
|
else delete process.env.SOMA_API_DIR;
|
|
696
|
-
|
|
697
|
-
if (
|
|
1310
|
+
|
|
1311
|
+
if (!server.listening) return;
|
|
1312
|
+
|
|
1313
|
+
if (typeof server.closeIdleConnections === 'function') {
|
|
1314
|
+
server.closeIdleConnections();
|
|
1315
|
+
}
|
|
1316
|
+
|
|
698
1317
|
await new Promise<void>((resolve) => {
|
|
699
|
-
|
|
1318
|
+
let settled = false;
|
|
1319
|
+
const finish = () => {
|
|
1320
|
+
if (settled) return;
|
|
1321
|
+
settled = true;
|
|
1322
|
+
resolve();
|
|
1323
|
+
};
|
|
1324
|
+
|
|
1325
|
+
const graceTimer = setTimeout(() => {
|
|
1326
|
+
if (typeof server.closeAllConnections === 'function') {
|
|
1327
|
+
server.closeAllConnections();
|
|
1328
|
+
}
|
|
1329
|
+
}, 2000);
|
|
1330
|
+
if (typeof graceTimer.unref === 'function') {
|
|
1331
|
+
graceTimer.unref();
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
server.close(() => {
|
|
1335
|
+
clearTimeout(graceTimer);
|
|
1336
|
+
finish();
|
|
1337
|
+
});
|
|
700
1338
|
});
|
|
701
1339
|
},
|
|
702
1340
|
};
|