soma-core 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/app/SomaPageClient.tsx +8 -45
  2. package/app/[...path]/page.tsx +21 -0
  3. package/app/api/[...path]/route.ts +86 -77
  4. package/app/components/SomaHostPage.tsx +133 -0
  5. package/app/components/SomaHydrationShell.tsx +1 -1
  6. package/app/layout.tsx +10 -6
  7. package/app/page.tsx +7 -18
  8. package/app/soma/[...path]/route.ts +9 -0
  9. package/app/{api/soma-manifest → soma/manifest}/route.ts +3 -3
  10. package/app/soma/page/route.ts +29 -0
  11. package/app/soma/page-object/route.ts +158 -0
  12. package/app/soma/route.ts +9 -0
  13. package/bin/soma-mock.mjs +38 -0
  14. package/core/base/SomaHttpClient.ts +5 -3
  15. package/core/compiler/full-manifest-builder.ts +84 -69
  16. package/core/compiler/host-config-sync.cjs +32 -6
  17. package/core/compiler/soma-manifest-webpack-plugin.js +41 -7
  18. package/core/engine/soma-headless-page.ts +86 -0
  19. package/core/host/app-config-composer.ts +90 -0
  20. package/core/host/host-config-paths.cjs +100 -0
  21. package/core/host/host-config-paths.ts +132 -0
  22. package/core/host/invoke-host-request-hook.ts +37 -0
  23. package/core/host/load-host-domain-class.ts +87 -0
  24. package/core/host/page-response-mode.cjs +96 -0
  25. package/core/host/page-response-request.ts +35 -0
  26. package/core/host/request-origin.ts +18 -0
  27. package/core/host/resolve-host-request-hook.ts +29 -0
  28. package/core/host/server-page-assets.ts +193 -0
  29. package/core/host/soma-domain-loaders.stub.ts +6 -0
  30. package/core/host/soma-domain-loaders.ts +69 -0
  31. package/core/host/soma-request-hook-host.stub.ts +4 -0
  32. package/core/host/source-packages.ts +46 -5
  33. package/core/index.ts +22 -0
  34. package/core/infra/http/SomaHttpService.ts +23 -14
  35. package/core/infra/http/soma-server-request-context.ts +126 -0
  36. package/core/mock/node/catch-all.mjs +35 -0
  37. package/core/mock/node/cli.d.mts +58 -0
  38. package/core/mock/node/cli.mjs +243 -0
  39. package/core/mock/node/context.mjs +167 -0
  40. package/core/mock/node/environment-policy.mjs +52 -0
  41. package/core/mock/node/plugin-loader.mjs +212 -0
  42. package/core/mock/node/preload.mjs +91 -0
  43. package/core/mock/node/process-lifecycle.mjs +236 -0
  44. package/core/mock/node/public.d.mts +110 -0
  45. package/core/mock/node/public.mjs +4 -0
  46. package/core/mock/node/registry.mjs +336 -0
  47. package/core/mock/node/schema-generator.mjs +1310 -0
  48. package/core/mock/testing/host-harness.d.mts +66 -0
  49. package/core/mock/testing/host-harness.mjs +276 -0
  50. package/core/mock/testing/host-runtime.mjs +48 -0
  51. package/core/runtime/SomaRuntimeServices.ts +5 -1
  52. package/core/runtime/serialize-page-state.ts +152 -0
  53. package/dist/cli/soma.js +374 -3
  54. package/dist/core/index.cjs +2861 -2388
  55. package/dist/tsconfig.types.tsbuildinfo +1 -1
  56. package/dist/types/base/SomaHttpClient.d.ts +2 -0
  57. package/dist/types/compiler/full-manifest-builder.d.ts +2 -0
  58. package/dist/types/engine/soma-headless-page.d.ts +10 -0
  59. package/dist/types/host/app-config-composer.d.ts +6 -0
  60. package/dist/types/host/host-config-paths.d.ts +23 -0
  61. package/dist/types/host/invoke-host-request-hook.d.ts +8 -0
  62. package/dist/types/host/load-host-domain-class.d.ts +12 -0
  63. package/dist/types/host/page-response-request.d.ts +9 -0
  64. package/dist/types/host/request-origin.d.ts +1 -0
  65. package/dist/types/host/resolve-host-request-hook.d.ts +16 -0
  66. package/dist/types/host/server-page-assets.d.ts +29 -0
  67. package/dist/types/host/soma-domain-loaders.d.ts +19 -0
  68. package/dist/types/host/soma-domain-loaders.stub.d.ts +4 -0
  69. package/dist/types/host/soma-request-hook-host.stub.d.ts +2 -0
  70. package/dist/types/host/source-packages.d.ts +4 -0
  71. package/dist/types/index.d.ts +3 -0
  72. package/dist/types/infra/http/SomaHttpService.d.ts +2 -0
  73. package/dist/types/infra/http/soma-server-request-context.d.ts +5 -0
  74. package/dist/types/runtime/serialize-page-state.d.ts +10 -0
  75. package/docs//351/241/265/351/235/242JSON/346/250/241/345/274/217/346/216/245/345/205/245/346/214/207/345/215/227.md +141 -0
  76. package/global.d.ts +67 -26
  77. package/middleware.ts +33 -0
  78. package/next.config.js +109 -23
  79. package/package.json +39 -9
  80. package/tsconfig.json +1 -5
  81. package/app/api/page/route.ts +0 -119
  82. package/app/loading.tsx +0 -5
@@ -0,0 +1,90 @@
1
+ import fs from 'node:fs';
2
+ import yaml from 'js-yaml';
3
+ import { resolveHostAppConfigPath } from './host-config-paths';
4
+
5
+ type AppConfigRecord = Record<string, unknown>;
6
+
7
+ const UNSAFE_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
8
+
9
+ function isRecord(value: unknown): value is AppConfigRecord {
10
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
11
+ }
12
+
13
+ function cloneValue(value: unknown): unknown {
14
+ if (Array.isArray(value)) {
15
+ return value.map((item) => cloneValue(item));
16
+ }
17
+ if (!isRecord(value)) {
18
+ return value;
19
+ }
20
+ const result: AppConfigRecord = {};
21
+ for (const [key, child] of Object.entries(value)) {
22
+ if (!UNSAFE_KEYS.has(key)) {
23
+ result[key] = cloneValue(child);
24
+ }
25
+ }
26
+ return result;
27
+ }
28
+
29
+ function mergeRecords(defaults: AppConfigRecord, host: AppConfigRecord): AppConfigRecord {
30
+ const result = cloneValue(defaults) as AppConfigRecord;
31
+ for (const [key, hostValue] of Object.entries(host)) {
32
+ if (UNSAFE_KEYS.has(key)) {
33
+ continue;
34
+ }
35
+ const defaultValue = result[key];
36
+ result[key] = isRecord(defaultValue) && isRecord(hostValue)
37
+ ? mergeRecords(defaultValue, hostValue)
38
+ : cloneValue(hostValue);
39
+ }
40
+ return result;
41
+ }
42
+
43
+ export function parseAppConfigYaml(source: string): unknown {
44
+ return source.trim() ? yaml.load(source) ?? {} : {};
45
+ }
46
+
47
+ /** Source packages provide defaults; the Host remains the final App-config owner. */
48
+ export function mergeSourcePackageAppConfig(
49
+ sourcePackageConfig: unknown,
50
+ hostConfig: unknown,
51
+ ): unknown {
52
+ if (isRecord(sourcePackageConfig) && isRecord(hostConfig)) {
53
+ return mergeRecords(sourcePackageConfig, hostConfig);
54
+ }
55
+ if (hostConfig !== undefined && hostConfig !== null) {
56
+ return cloneValue(hostConfig);
57
+ }
58
+ return cloneValue(sourcePackageConfig ?? {});
59
+ }
60
+
61
+ export function composeAppConfigYaml(
62
+ sourcePackageConfigYaml: string,
63
+ hostConfigYaml: string,
64
+ ): string {
65
+ const merged = mergeSourcePackageAppConfig(
66
+ parseAppConfigYaml(sourcePackageConfigYaml),
67
+ parseAppConfigYaml(hostConfigYaml),
68
+ );
69
+ return yaml.dump(merged, { noRefs: true, lineWidth: -1 });
70
+ }
71
+
72
+ /** Browser metadata uses the Host App's displayName, never a source-package brand. */
73
+ export function readHostAppDisplayName(hostDir = process.env.SOMA_HOST_DIR): string {
74
+ if (!hostDir) {
75
+ return '';
76
+ }
77
+ const configPath = resolveHostAppConfigPath(hostDir);
78
+ if (!configPath) {
79
+ return '';
80
+ }
81
+ try {
82
+ const config = parseAppConfigYaml(fs.readFileSync(configPath, 'utf8'));
83
+ if (!isRecord(config) || typeof config.displayName !== 'string') {
84
+ return '';
85
+ }
86
+ return config.displayName.trim();
87
+ } catch {
88
+ return '';
89
+ }
90
+ }
@@ -0,0 +1,100 @@
1
+ /** CJS mirror of host-config-paths.ts for next.config.js / webpack plugin. */
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+
5
+ function readJson(filePath) {
6
+ try {
7
+ if (!fs.existsSync(filePath)) return null;
8
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ function resolveSafeChildRoot(parent, relativePath, options = {}) {
15
+ const trimmed = typeof relativePath === 'string' ? relativePath.trim() : '';
16
+ if (!trimmed) return parent;
17
+
18
+ const resolved = path.resolve(parent, trimmed);
19
+ const normalizedParent = path.resolve(parent);
20
+ if (resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)) {
21
+ if (options.requireExists && !fs.existsSync(resolved)) {
22
+ return normalizedParent;
23
+ }
24
+ return resolved;
25
+ }
26
+ return options.fallback ?? normalizedParent;
27
+ }
28
+
29
+ function normalizeSomaEnv(raw) {
30
+ const value = String(raw ?? '').trim().toLowerCase();
31
+ if (!value) return 'test';
32
+ if (
33
+ ['test', 'testing', 'dev', 'development', 'local', 'qa', 'staging', 'pre', 'prepub', 'uat']
34
+ .includes(value)
35
+ ) {
36
+ return 'test';
37
+ }
38
+ return 'prod';
39
+ }
40
+
41
+ /** Priority: SOMA_ENV → APP_ENV → NODE_ENV (framework-neutral only). */
42
+ function readSomaEnv(env = process.env) {
43
+ return normalizeSomaEnv(env.SOMA_ENV ?? env.APP_ENV ?? env.NODE_ENV);
44
+ }
45
+
46
+ function resolveHostConfigRoot(hostDir) {
47
+ const normalizedHostDir = path.resolve(hostDir);
48
+ const packageJson = readJson(path.join(normalizedHostDir, 'package.json'));
49
+ const configured = packageJson?.soma?.configRoot?.trim();
50
+ if (configured) {
51
+ return resolveSafeChildRoot(normalizedHostDir, configured, {
52
+ fallback: path.join(normalizedHostDir, 'config'),
53
+ });
54
+ }
55
+
56
+ const hostSourceRoot = resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot, {
57
+ requireExists: true,
58
+ });
59
+ const candidates = [
60
+ path.join(normalizedHostDir, 'config'),
61
+ path.join(hostSourceRoot, 'config'),
62
+ ];
63
+ for (const candidate of candidates) {
64
+ if (fs.existsSync(candidate)) {
65
+ return candidate;
66
+ }
67
+ }
68
+ return path.join(hostSourceRoot, 'config');
69
+ }
70
+
71
+ function getSomaHostConfigRoot(hostDir) {
72
+ return resolveHostConfigRoot(hostDir);
73
+ }
74
+
75
+ function resolveAppConfigPath(configRoot, envName) {
76
+ const env = envName ?? readSomaEnv();
77
+ const candidates = [
78
+ path.join(configRoot, `app.config.${env}.yaml`),
79
+ path.join(configRoot, 'app.config.yaml'),
80
+ ];
81
+ for (const candidate of candidates) {
82
+ if (fs.existsSync(candidate)) {
83
+ return candidate;
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function resolveHostAppConfigPath(hostDir, envName) {
90
+ return resolveAppConfigPath(resolveHostConfigRoot(hostDir), envName);
91
+ }
92
+
93
+ module.exports = {
94
+ normalizeSomaEnv,
95
+ readSomaEnv,
96
+ resolveHostConfigRoot,
97
+ getSomaHostConfigRoot,
98
+ resolveAppConfigPath,
99
+ resolveHostAppConfigPath,
100
+ };
@@ -0,0 +1,132 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export type SomaEnvName = 'test' | 'prod';
5
+
6
+ interface PackageJson {
7
+ soma?: {
8
+ hostRoot?: string;
9
+ configRoot?: string;
10
+ };
11
+ }
12
+
13
+ function readJson<T>(filePath: string): T | null {
14
+ try {
15
+ if (!fs.existsSync(filePath)) {
16
+ return null;
17
+ }
18
+ return JSON.parse(fs.readFileSync(filePath, 'utf8')) as T;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ function resolveSafeChildRoot(
25
+ parent: string,
26
+ relativePath: string | undefined,
27
+ options: { requireExists?: boolean; fallback?: string } = {},
28
+ ): string {
29
+ const trimmed = relativePath?.trim();
30
+ if (!trimmed) {
31
+ return parent;
32
+ }
33
+
34
+ const resolved = path.resolve(parent, trimmed);
35
+ const normalizedParent = path.resolve(parent);
36
+ if (resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)) {
37
+ if (options.requireExists && !fs.existsSync(resolved)) {
38
+ return normalizedParent;
39
+ }
40
+ return resolved;
41
+ }
42
+
43
+ return options.fallback ?? normalizedParent;
44
+ }
45
+
46
+ export function normalizeSomaEnv(raw?: string): SomaEnvName {
47
+ const value = String(raw ?? '').trim().toLowerCase();
48
+ if (!value) {
49
+ return 'test';
50
+ }
51
+ // 不区分 dev / test:同属测试环境配置族
52
+ if (
53
+ ['test', 'testing', 'dev', 'development', 'local', 'qa', 'staging', 'pre', 'prepub', 'uat']
54
+ .includes(value)
55
+ ) {
56
+ return 'test';
57
+ }
58
+ return 'prod';
59
+ }
60
+
61
+ /**
62
+ * Resolve SOMA env from framework-neutral variables only.
63
+ * Priority: SOMA_ENV → APP_ENV → NODE_ENV.
64
+ */
65
+ export function readSomaEnv(env: NodeJS.ProcessEnv = process.env): SomaEnvName {
66
+ return normalizeSomaEnv(env.SOMA_ENV ?? env.APP_ENV ?? env.NODE_ENV);
67
+ }
68
+
69
+ /**
70
+ * Resolve the Host config directory.
71
+ * Prefer package.json `soma.configRoot` (relative to Host root, not hostRoot).
72
+ * Fallback: `<hostDir>/config`, then `<hostRoot>/config`.
73
+ */
74
+ export function resolveHostConfigRoot(hostDir: string): string {
75
+ const normalizedHostDir = path.resolve(hostDir);
76
+ const packageJson = readJson<PackageJson>(path.join(normalizedHostDir, 'package.json'));
77
+ const configured = packageJson?.soma?.configRoot?.trim();
78
+ if (configured) {
79
+ return resolveSafeChildRoot(normalizedHostDir, configured, {
80
+ fallback: path.join(normalizedHostDir, 'config'),
81
+ });
82
+ }
83
+
84
+ const hostSourceRoot = resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot, {
85
+ requireExists: true,
86
+ });
87
+ const candidates = [
88
+ path.join(normalizedHostDir, 'config'),
89
+ path.join(hostSourceRoot, 'config'),
90
+ ];
91
+ for (const candidate of candidates) {
92
+ if (fs.existsSync(candidate)) {
93
+ return candidate;
94
+ }
95
+ }
96
+ return path.join(hostSourceRoot, 'config');
97
+ }
98
+
99
+ export function getSomaHostConfigRoot(hostDir: string): string {
100
+ return resolveHostConfigRoot(hostDir);
101
+ }
102
+
103
+ /**
104
+ * Resolve an app config file inside an already-resolved config root with
105
+ * env-specific priority:
106
+ * `app.config.<env>.yaml` → `app.config.yaml`.
107
+ * Never falls back across environments (e.g. prod must not load test yaml).
108
+ */
109
+ export function resolveAppConfigPath(
110
+ configRoot: string,
111
+ envName?: SomaEnvName,
112
+ ): string | null {
113
+ const env = envName ?? readSomaEnv();
114
+ const candidates = [
115
+ path.join(configRoot, `app.config.${env}.yaml`),
116
+ path.join(configRoot, 'app.config.yaml'),
117
+ ];
118
+ for (const candidate of candidates) {
119
+ if (fs.existsSync(candidate)) {
120
+ return candidate;
121
+ }
122
+ }
123
+ return null;
124
+ }
125
+
126
+ /** Resolve the Host app config from its package-level configRoot contract. */
127
+ export function resolveHostAppConfigPath(
128
+ hostDir: string,
129
+ envName?: SomaEnvName,
130
+ ): string | null {
131
+ return resolveAppConfigPath(resolveHostConfigRoot(hostDir), envName);
132
+ }
@@ -0,0 +1,37 @@
1
+ import {
2
+ resolveHostRequestHook,
3
+ type SomaHostRequestContext,
4
+ type SomaRequestHook,
5
+ } from './resolve-host-request-hook';
6
+
7
+ export type SomaRequestHookResolver = () => Promise<SomaRequestHook | null>;
8
+
9
+ function requestPathname(path: string): string {
10
+ try {
11
+ return new URL(path, 'http://soma.local').pathname;
12
+ } catch {
13
+ return path.split('?')[0].split('#')[0] || '/';
14
+ }
15
+ }
16
+
17
+ export function isSomaInternalRequestPath(path: string): boolean {
18
+ const pathname = requestPathname(path);
19
+ return pathname === '/soma' || pathname.startsWith('/soma/');
20
+ }
21
+
22
+ /**
23
+ * Calls the Host extension exactly once for Host-owned page/API requests.
24
+ * SOMA's reserved /soma namespace never reaches the Host extension.
25
+ */
26
+ export async function invokeHostRequestHook(
27
+ request: Request,
28
+ context: SomaHostRequestContext,
29
+ resolveHook: SomaRequestHookResolver = resolveHostRequestHook,
30
+ ): Promise<Response | undefined> {
31
+ if (isSomaInternalRequestPath(context.path)) {
32
+ return undefined;
33
+ }
34
+
35
+ const hook = await resolveHook();
36
+ return hook?.(request, context);
37
+ }
@@ -0,0 +1,87 @@
1
+ import { SomaLocaleOnlyPageRoot } from '../base/SomaLocaleOnlyPageRoot';
2
+ import type { SomaPageRoot } from '../types/domain.types';
3
+ import {
4
+ loadSomaDomainModuleFromRegistry,
5
+ type SomaDomainLoadContext,
6
+ type SomaDomainLoaderModule,
7
+ type SomaDomainModule,
8
+ } from './soma-domain-loaders';
9
+
10
+ export type SomaDomainConstructor = new () => SomaPageRoot;
11
+
12
+ export class SomaDomainLoadError extends Error {
13
+ readonly code = 'SOMA_DOMAIN_LOAD_FAILED';
14
+ readonly context: SomaDomainLoadContext;
15
+
16
+ constructor(context: SomaDomainLoadContext, message: string) {
17
+ super(message);
18
+ this.name = 'SomaDomainLoadError';
19
+ this.context = context;
20
+ }
21
+ }
22
+
23
+ export function resolveSomaDomainConstructor(
24
+ module: SomaDomainModule,
25
+ label: string,
26
+ ): SomaDomainConstructor {
27
+ if (typeof module.default === 'function') {
28
+ return module.default as SomaDomainConstructor;
29
+ }
30
+ const constructor = Object.values(module).find(
31
+ (value): value is SomaDomainConstructor => typeof value === 'function',
32
+ );
33
+ if (constructor) return constructor;
34
+ throw new SomaDomainLoadError(
35
+ { base: label },
36
+ 'Domain class missing: ' + label,
37
+ );
38
+ }
39
+
40
+ export async function loadHostDomainClass(
41
+ context: SomaDomainLoadContext,
42
+ options: { allowLocaleOnlyFallback?: boolean } = {},
43
+ ): Promise<SomaDomainConstructor> {
44
+ let registryFailure: unknown;
45
+ try {
46
+ const registry = await import('@soma-host/bootstrap/soma-domain-loaders')
47
+ .catch(() => null) as SomaDomainLoaderModule | null;
48
+ const module = await loadSomaDomainModuleFromRegistry(registry, context);
49
+ if (module) {
50
+ const label = (context.sourcePackage ?? 'host') + ':' + context.base + 'Class';
51
+ return resolveSomaDomainConstructor(module, label);
52
+ }
53
+ } catch (error) {
54
+ registryFailure = error;
55
+ if (context.sourcePackage) {
56
+ throw error;
57
+ }
58
+ }
59
+
60
+ if (context.sourcePackage) {
61
+ throw new SomaDomainLoadError(
62
+ context,
63
+ 'Domain class missing: ' + context.sourcePackage + ':' + context.base + 'Class',
64
+ );
65
+ }
66
+
67
+ try {
68
+ const module = await import(
69
+ /* webpackInclude: /\/domain\/ui\/.*Class\.ts$/ */
70
+ `@soma-host/domain/ui/${context.base}Class.ts`
71
+ ) as SomaDomainModule;
72
+ return resolveSomaDomainConstructor(module, context.base + 'Class');
73
+ } catch (error) {
74
+ if (options.allowLocaleOnlyFallback !== false) {
75
+ return SomaLocaleOnlyPageRoot;
76
+ }
77
+ const detail = error instanceof Error
78
+ ? error.message
79
+ : registryFailure instanceof Error
80
+ ? registryFailure.message
81
+ : String(error);
82
+ throw new SomaDomainLoadError(
83
+ context,
84
+ 'Domain class missing: ' + context.base + 'Class (' + detail + ')',
85
+ );
86
+ }
87
+ }
@@ -0,0 +1,96 @@
1
+ const fs = require('node:fs');
2
+ const yaml = require('js-yaml');
3
+ const {
4
+ readSomaEnv,
5
+ resolveHostAppConfigPath,
6
+ } = require('./host-config-paths.cjs');
7
+
8
+ const PAGE_RESPONSE_MODES = new Set(['html', 'json']);
9
+
10
+ class SomaPageResponseModeConfigError extends Error {
11
+ constructor(code, message, configPath) {
12
+ super(message);
13
+ this.name = 'SomaPageResponseModeConfigError';
14
+ this.code = code;
15
+ this.configPath = configPath;
16
+ }
17
+ }
18
+
19
+ function isRecord(value) {
20
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
21
+ }
22
+
23
+ function readSomaPageResponseMode(hostDir, env = process.env) {
24
+ const environment = readSomaEnv(env);
25
+ const configPath = resolveHostAppConfigPath(hostDir, environment);
26
+ if (!configPath) {
27
+ return { mode: 'html', environment, configPath: null };
28
+ }
29
+
30
+ let document;
31
+ try {
32
+ document = yaml.load(fs.readFileSync(configPath, 'utf8')) ?? {};
33
+ } catch (error) {
34
+ const detail = error instanceof Error ? error.message : String(error);
35
+ throw new SomaPageResponseModeConfigError(
36
+ 'SOMA_PAGE_RESPONSE_CONFIG_INVALID',
37
+ 'Cannot read App config for page response mode: ' + detail,
38
+ configPath,
39
+ );
40
+ }
41
+
42
+ if (!isRecord(document)) {
43
+ throw new SomaPageResponseModeConfigError(
44
+ 'SOMA_PAGE_RESPONSE_CONFIG_INVALID',
45
+ 'App config must be a YAML object: ' + configPath,
46
+ configPath,
47
+ );
48
+ }
49
+
50
+ const somaConfig = document.soma;
51
+ if (somaConfig === undefined || somaConfig === null) {
52
+ return { mode: 'html', environment, configPath };
53
+ }
54
+ if (!isRecord(somaConfig)) {
55
+ throw new SomaPageResponseModeConfigError(
56
+ 'SOMA_PAGE_RESPONSE_CONFIG_INVALID',
57
+ 'App config field "soma" must be an object: ' + configPath,
58
+ configPath,
59
+ );
60
+ }
61
+
62
+ const rawMode = somaConfig.pageResponseMode;
63
+ if (rawMode === undefined || rawMode === null || rawMode === '') {
64
+ return { mode: 'html', environment, configPath };
65
+ }
66
+ if (typeof rawMode !== 'string') {
67
+ throw new SomaPageResponseModeConfigError(
68
+ 'SOMA_PAGE_RESPONSE_MODE_INVALID',
69
+ 'App config field "soma.pageResponseMode" must be "html" or "json": ' + configPath,
70
+ configPath,
71
+ );
72
+ }
73
+
74
+ const mode = rawMode.trim().toLowerCase();
75
+ if (!PAGE_RESPONSE_MODES.has(mode)) {
76
+ throw new SomaPageResponseModeConfigError(
77
+ 'SOMA_PAGE_RESPONSE_MODE_INVALID',
78
+ 'Unsupported soma.pageResponseMode "' + rawMode + '"; expected "html" or "json": ' + configPath,
79
+ configPath,
80
+ );
81
+ }
82
+ if (mode === 'json' && environment !== 'test') {
83
+ throw new SomaPageResponseModeConfigError(
84
+ 'SOMA_PAGE_RESPONSE_MODE_PRODUCTION_FORBIDDEN',
85
+ 'soma.pageResponseMode=json is test-only and cannot run in production: ' + configPath,
86
+ configPath,
87
+ );
88
+ }
89
+
90
+ return { mode, environment, configPath };
91
+ }
92
+
93
+ module.exports = {
94
+ SomaPageResponseModeConfigError,
95
+ readSomaPageResponseMode,
96
+ };
@@ -0,0 +1,35 @@
1
+ export type SomaPageResponseMode = 'html' | 'json';
2
+
3
+ export const SOMA_PAGE_REQUEST_URL_HEADER = 'x-soma-page-request-url';
4
+
5
+ export function isJsonPageResponseMode(mode: string | undefined): boolean {
6
+ return mode?.trim().toLowerCase() === 'json';
7
+ }
8
+
9
+ export function isSomaPageRequestPath(pathname: string): boolean {
10
+ const normalized = pathname.startsWith('/') ? pathname : '/' + pathname;
11
+ const firstSegment = normalized.split('/').filter(Boolean)[0] ?? '';
12
+ if (firstSegment === 'api' || firstSegment === 'soma' || firstSegment === '_next') {
13
+ return false;
14
+ }
15
+
16
+ const lastSegment = normalized.split('/').filter(Boolean).at(-1) ?? '';
17
+ if (lastSegment === 'favicon.ico') {
18
+ return false;
19
+ }
20
+ const extension = lastSegment.match(/\.([^./]+)$/)?.[1]?.toLowerCase();
21
+ return !extension || extension === 'html';
22
+ }
23
+
24
+ export function shouldUseJsonPageResponse(options: {
25
+ mode: string | undefined;
26
+ method: string;
27
+ pathname: string;
28
+ }): boolean {
29
+ const method = options.method.toUpperCase();
30
+ return (
31
+ isJsonPageResponseMode(options.mode)
32
+ && (method === 'GET' || method === 'HEAD')
33
+ && isSomaPageRequestPath(options.pathname)
34
+ );
35
+ }
@@ -0,0 +1,18 @@
1
+ function firstForwardedValue(value: string | null): string {
2
+ return value?.split(',')[0]?.trim() ?? '';
3
+ }
4
+
5
+ export function resolveSomaRequestOrigin(requestHeaders: Headers): string {
6
+ const host = firstForwardedValue(requestHeaders.get('x-forwarded-host'))
7
+ || firstForwardedValue(requestHeaders.get('host'))
8
+ || 'localhost';
9
+ const closingBracket = host.indexOf(']');
10
+ const hostname = (host.startsWith('[') && closingBracket > 0
11
+ ? host.slice(1, closingBracket)
12
+ : host.split(':')[0]).toLowerCase();
13
+ const forwardedProtocol = firstForwardedValue(requestHeaders.get('x-forwarded-proto'));
14
+ const protocol = forwardedProtocol === 'http' || forwardedProtocol === 'https'
15
+ ? forwardedProtocol
16
+ : (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' ? 'http' : 'https');
17
+ return protocol + '://' + host;
18
+ }
@@ -0,0 +1,29 @@
1
+ export type SomaHostRequestKind = 'page' | 'api';
2
+
3
+ export interface SomaHostRequestContext {
4
+ kind: SomaHostRequestKind;
5
+ path: string;
6
+ pageHref?: string;
7
+ }
8
+
9
+ /**
10
+ * Generic server ingress extension. soma-core does not know authentication,
11
+ * authorization, Admin, or any business application.
12
+ */
13
+ export type SomaRequestHook = (
14
+ request: Request,
15
+ context: SomaHostRequestContext,
16
+ ) => Response | undefined | Promise<Response | undefined>;
17
+
18
+ export interface SomaRequestHookModule {
19
+ somaRequestHook?: SomaRequestHook;
20
+ handleSomaRequest?: SomaRequestHook;
21
+ }
22
+
23
+ export async function resolveHostRequestHook(): Promise<SomaRequestHook | null> {
24
+ const module = await import(
25
+ /* webpackInclude: /\/bootstrap\/soma-request-hook\.ts$/ */
26
+ '@soma-host/bootstrap/soma-request-hook'
27
+ ) as SomaRequestHookModule;
28
+ return module.somaRequestHook ?? module.handleSomaRequest ?? null;
29
+ }