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,66 @@
1
+ import type {
2
+ ChildProcess,
3
+ StdioOptions,
4
+ spawn,
5
+ spawnSync,
6
+ } from 'node:child_process';
7
+
8
+ export interface MockHostJournalRecord extends Record<string, unknown> {
9
+ sequence?: number;
10
+ pid?: number;
11
+ timestamp?: string;
12
+ scope?: string;
13
+ }
14
+
15
+ export interface MockHostOptions extends MockHostTerminationOptions {
16
+ hostRoot?: string;
17
+ mockCli: string;
18
+ command?: string;
19
+ commandArgs?: string[];
20
+ env?: NodeJS.ProcessEnv;
21
+ childEnvironment?: NodeJS.ProcessEnv;
22
+ prepareChildEnvironment?: (mockJournalFile: string) => NodeJS.ProcessEnv;
23
+ providerEnvironmentKeys?: string[];
24
+ readinessPath?: string;
25
+ readyAttempts?: number;
26
+ readyIntervalMs?: number;
27
+ nodeExecutable?: string;
28
+ spawnImpl?: typeof spawn;
29
+ stdio?: StdioOptions;
30
+ tempRoot?: string;
31
+ }
32
+
33
+ export interface MockHostHandle {
34
+ readonly baseUrl: string;
35
+ readonly port: number;
36
+ readonly mockJournalFile: string;
37
+ readonly mockTempDir: string;
38
+ readonly nextWorkspaceDir: string;
39
+ readonly child: ChildProcess;
40
+ readMockJournal(scope?: string): MockHostJournalRecord[];
41
+ getOutput(): string;
42
+ stop(): Promise<void>;
43
+ }
44
+
45
+ export interface MockHostTerminationOptions {
46
+ detached?: boolean;
47
+ killProcess?: typeof process.kill;
48
+ killWaitMs?: number;
49
+ platform?: NodeJS.Platform;
50
+ termGraceMs?: number;
51
+ windowsCommandRunner?: typeof spawnSync;
52
+ windowsTreeHasExited?: (child: ChildProcess) => boolean;
53
+ windowsTreeKill?: (pid: number, signal: NodeJS.Signals) => boolean | void;
54
+ }
55
+
56
+ export function readMockJournalFile(journalFile: string): MockHostJournalRecord[];
57
+ export function startMockHost(options: MockHostOptions): Promise<MockHostHandle>;
58
+ export function createMockHostChildEnvironment(
59
+ options: Pick<MockHostOptions, 'env'> | undefined,
60
+ mockJournalFile: string,
61
+ parentEnvironment?: NodeJS.ProcessEnv,
62
+ ): NodeJS.ProcessEnv;
63
+ export function terminateMockHostProcess(
64
+ child: ChildProcess,
65
+ options?: MockHostTerminationOptions,
66
+ ): Promise<void>;
@@ -0,0 +1,276 @@
1
+ import net from 'node:net';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import process from 'node:process';
6
+ import { spawn } from 'node:child_process';
7
+ import {
8
+ createMockHostChildEnvironment,
9
+ terminateMockHostProcess,
10
+ } from './host-runtime.mjs';
11
+ import { filterMockEnvironment } from '../node/environment-policy.mjs';
12
+
13
+ function listen(server, port = 0) {
14
+ return new Promise((resolve, reject) => {
15
+ const onError = (error) => {
16
+ server.off('listening', onListening);
17
+ reject(error);
18
+ };
19
+ const onListening = () => {
20
+ server.off('error', onError);
21
+ resolve(server.address().port);
22
+ };
23
+ server.once('error', onError);
24
+ server.once('listening', onListening);
25
+ server.listen(port, '127.0.0.1');
26
+ });
27
+ }
28
+
29
+ function close(server) {
30
+ return new Promise((resolve, reject) => {
31
+ if (!server?.listening) {
32
+ resolve();
33
+ return;
34
+ }
35
+ server.close((error) => (error ? reject(error) : resolve()));
36
+ });
37
+ }
38
+
39
+ function sleep(ms) {
40
+ return new Promise((resolve) => setTimeout(resolve, ms));
41
+ }
42
+
43
+ async function waitForReady(baseUrl, child, options = {}) {
44
+ const readinessPath = options.readinessPath || '/soma/page?path=%2F';
45
+ const attempts = options.readyAttempts ?? 80;
46
+ const intervalMs = options.readyIntervalMs ?? 250;
47
+ let lastError = null;
48
+ let spawnError = null;
49
+ const onChildError = (error) => {
50
+ spawnError = error;
51
+ };
52
+ child.on('error', onChildError);
53
+ try {
54
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
55
+ if (spawnError) throw spawnError;
56
+ if (child.exitCode !== null || child.signalCode !== null) {
57
+ throw new Error(
58
+ `SOMA app exited early (${child.exitCode ?? child.signalCode ?? 'unknown'}): ${lastError || ''}`,
59
+ );
60
+ }
61
+ try {
62
+ const response = await fetch(`${baseUrl}${readinessPath}`);
63
+ if (response.status === 200) return;
64
+ lastError = `HTTP ${response.status}`;
65
+ } catch (error) {
66
+ lastError = error;
67
+ }
68
+ await sleep(intervalMs);
69
+ }
70
+ throw new Error(`SOMA app did not become ready: ${lastError || 'timeout'}`);
71
+ } finally {
72
+ child.off('error', onChildError);
73
+ }
74
+ }
75
+
76
+ export function readMockJournalFile(journalFile) {
77
+ if (!fs.existsSync(journalFile)) return [];
78
+ const source = fs.readFileSync(journalFile, 'utf8');
79
+ const lines = source.split(/\r?\n/);
80
+ return lines.flatMap((line, index) => {
81
+ if (!line.trim()) return [];
82
+ try {
83
+ return [JSON.parse(line)];
84
+ } catch (error) {
85
+ const incompleteLastLine = index === lines.length - 1 && !source.endsWith('\n');
86
+ if (incompleteLastLine) return [];
87
+ throw new Error(`Invalid MSW journal JSON at ${journalFile}:${index + 1}`, { cause: error });
88
+ }
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Generic Mock Host test harness.
94
+ * Callers (upper frameworks) supply the Mock CLI path and optional env overlays.
95
+ * Core does not enable Mock itself; the CLI path is the enablement switch.
96
+ *
97
+ * @param {{
98
+ * hostRoot?: string,
99
+ * mockCli: string,
100
+ * command?: string,
101
+ * commandArgs?: string[],
102
+ * env?: NodeJS.ProcessEnv,
103
+ * childEnvironment?: NodeJS.ProcessEnv,
104
+ * prepareChildEnvironment?: (mockJournalFile: string) => NodeJS.ProcessEnv,
105
+ * providerEnvironmentKeys?: string[],
106
+ * readinessPath?: string,
107
+ * readyAttempts?: number,
108
+ * readyIntervalMs?: number,
109
+ * nodeExecutable?: string,
110
+ * spawnImpl?: typeof spawn,
111
+ * detached?: boolean,
112
+ * killProcess?: typeof process.kill,
113
+ * killWaitMs?: number,
114
+ * platform?: NodeJS.Platform,
115
+ * termGraceMs?: number,
116
+ * windowsCommandRunner?: typeof import('node:child_process').spawnSync,
117
+ * windowsTreeHasExited?: (child: import('node:child_process').ChildProcess) => boolean,
118
+ * windowsTreeKill?: (pid: number, signal: NodeJS.Signals) => boolean | void,
119
+ * stdio?: import('node:child_process').StdioOptions,
120
+ * tempRoot?: string,
121
+ * }} options
122
+ */
123
+ export async function startMockHost(options = {}) {
124
+ const hostRoot = path.resolve(options.hostRoot || process.cwd());
125
+ const mockCli = options.mockCli;
126
+ if (typeof mockCli !== 'string' || !mockCli.trim()) {
127
+ throw new TypeError('startMockHost requires options.mockCli (absolute path to Mock CLI)');
128
+ }
129
+
130
+ let mockTempDir = null;
131
+ let mockJournalFile = null;
132
+ let webProbe = null;
133
+ let webPort = null;
134
+ let child = null;
135
+ let output = '';
136
+ const terminationOptions = {
137
+ detached: options.detached ?? true,
138
+ killProcess: options.killProcess,
139
+ killWaitMs: options.killWaitMs,
140
+ platform: options.platform,
141
+ termGraceMs: options.termGraceMs,
142
+ windowsCommandRunner: options.windowsCommandRunner,
143
+ windowsTreeHasExited: options.windowsTreeHasExited,
144
+ windowsTreeKill: options.windowsTreeKill,
145
+ };
146
+
147
+ try {
148
+ const tempRoot = path.resolve(options.tempRoot || os.tmpdir());
149
+ mockTempDir = fs.mkdtempSync(path.join(tempRoot, 'soma-msw-'));
150
+ mockJournalFile = path.join(mockTempDir, 'journal.jsonl');
151
+ const nextWorkspaceDir = path.join(mockTempDir, 'next-workspace');
152
+ fs.writeFileSync(mockJournalFile, '', 'utf8');
153
+ webProbe = net.createServer();
154
+ try {
155
+ webPort = await listen(webProbe);
156
+ } finally {
157
+ await close(webProbe);
158
+ webProbe = null;
159
+ }
160
+
161
+ let childEnvironment;
162
+ if (typeof options.prepareChildEnvironment === 'function') {
163
+ childEnvironment = options.prepareChildEnvironment(mockJournalFile);
164
+ } else if (options.childEnvironment) {
165
+ childEnvironment = { ...options.childEnvironment };
166
+ } else {
167
+ childEnvironment = createMockHostChildEnvironment(options, mockJournalFile);
168
+ }
169
+ if (!childEnvironment || typeof childEnvironment !== 'object' || Array.isArray(childEnvironment)) {
170
+ throw new TypeError('Mock Host child environment must be an object');
171
+ }
172
+ childEnvironment = filterMockEnvironment(childEnvironment, {
173
+ providerEnvironmentKeys: options.providerEnvironmentKeys,
174
+ removeRuntimeHostDir: true,
175
+ });
176
+ if (!childEnvironment.SOMA_MOCK_JOURNAL_FILE) {
177
+ childEnvironment.SOMA_MOCK_JOURNAL_FILE = mockJournalFile;
178
+ }
179
+ childEnvironment.SOMA_NEXT_WORKSPACE_DIR = nextWorkspaceDir;
180
+
181
+ const command = options.command || 'dev';
182
+ const commandArgs = Array.isArray(options.commandArgs) ? options.commandArgs : ['--port', String(webPort)];
183
+ const spawnImpl = options.spawnImpl ?? spawn;
184
+ child = spawnImpl(options.nodeExecutable ?? process.execPath, [mockCli, command, ...commandArgs], {
185
+ cwd: hostRoot,
186
+ env: childEnvironment,
187
+ detached: terminationOptions.detached,
188
+ stdio: options.stdio ?? ['ignore', 'pipe', 'pipe'],
189
+ });
190
+ if (!child || typeof child.once !== 'function' || typeof child.kill !== 'function') {
191
+ throw new TypeError('Mock Host spawn implementation must return a ChildProcess');
192
+ }
193
+
194
+ if (child.stdout?.on) child.stdout.on('data', (chunk) => { output = `${output}${chunk}`.slice(-8000); });
195
+ if (child.stderr?.on) child.stderr.on('data', (chunk) => { output = `${output}${chunk}`.slice(-8000); });
196
+ await waitForReady(`http://127.0.0.1:${webPort}`, child, options);
197
+ } catch (error) {
198
+ const cleanupErrors = [];
199
+ if (webProbe) {
200
+ try {
201
+ await close(webProbe);
202
+ } catch (cleanupError) {
203
+ cleanupErrors.push(cleanupError);
204
+ }
205
+ }
206
+ if (child) {
207
+ try {
208
+ await terminateMockHostProcess(child, terminationOptions);
209
+ } catch (cleanupError) {
210
+ cleanupErrors.push(cleanupError);
211
+ }
212
+ }
213
+ if (mockTempDir) {
214
+ try {
215
+ fs.rmSync(mockTempDir, { recursive: true, force: true });
216
+ } catch (cleanupError) {
217
+ cleanupErrors.push(cleanupError);
218
+ }
219
+ }
220
+ const details = [
221
+ error instanceof Error ? error.message : String(error),
222
+ output,
223
+ ...cleanupErrors.map((cleanupError) =>
224
+ `Mock Host cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`),
225
+ ].filter(Boolean).join('\n');
226
+ throw new Error(details, { cause: error });
227
+ }
228
+
229
+ const readMockJournal = (scope) => {
230
+ const records = readMockJournalFile(mockJournalFile);
231
+ return scope ? records.filter((record) => record.scope === scope) : records;
232
+ };
233
+
234
+ let stopPromise;
235
+ return {
236
+ baseUrl: `http://127.0.0.1:${webPort}`,
237
+ port: webPort,
238
+ mockJournalFile,
239
+ mockTempDir,
240
+ nextWorkspaceDir: path.join(mockTempDir, 'next-workspace'),
241
+ child,
242
+ readMockJournal,
243
+ getOutput() {
244
+ return output;
245
+ },
246
+ async stop() {
247
+ if (!stopPromise) {
248
+ stopPromise = (async () => {
249
+ let terminationError;
250
+ let cleanupError;
251
+ try {
252
+ await terminateMockHostProcess(child, terminationOptions);
253
+ } catch (error) {
254
+ terminationError = error;
255
+ }
256
+ try {
257
+ fs.rmSync(mockTempDir, { recursive: true, force: true });
258
+ } catch (error) {
259
+ cleanupError = error;
260
+ }
261
+ if (terminationError && cleanupError) {
262
+ throw new AggregateError([terminationError, cleanupError], 'Mock Host termination and cleanup failed');
263
+ }
264
+ if (terminationError) throw terminationError;
265
+ if (cleanupError) throw cleanupError;
266
+ })();
267
+ }
268
+ await stopPromise;
269
+ },
270
+ };
271
+ }
272
+
273
+ export {
274
+ createMockHostChildEnvironment,
275
+ terminateMockHostProcess,
276
+ } from './host-runtime.mjs';
@@ -0,0 +1,48 @@
1
+ import process from 'node:process';
2
+ import {
3
+ PROCESS_KILL_WAIT_MS,
4
+ PROCESS_TERM_GRACE_MS,
5
+ childHasExited,
6
+ terminateMockChild,
7
+ } from '../node/process-lifecycle.mjs';
8
+ import { filterMockEnvironment } from '../node/environment-policy.mjs';
9
+
10
+ /**
11
+ * Terminate a Mock Host child process tree (TERM then KILL).
12
+ */
13
+ export async function terminateMockHostProcess(child, options = {}) {
14
+ return terminateMockChild(child, {
15
+ detached: options.detached ?? true,
16
+ killProcess: options.killProcess,
17
+ killWaitMs: options.killWaitMs ?? PROCESS_KILL_WAIT_MS,
18
+ platform: options.platform,
19
+ termGraceMs: options.termGraceMs ?? PROCESS_TERM_GRACE_MS,
20
+ windowsCommandRunner: options.windowsCommandRunner,
21
+ windowsTreeHasExited: options.windowsTreeHasExited,
22
+ windowsTreeKill: options.windowsTreeKill,
23
+ });
24
+ }
25
+
26
+ /**
27
+ * Build a clean Mock Host child environment.
28
+ * Inherited Mock keys are cleared first; options.env may set only Core's
29
+ * declared data-plane knobs and cannot reintroduce the control plane.
30
+ */
31
+ export function createMockHostChildEnvironment(options = {}, mockJournalFile, parentEnvironment = process.env) {
32
+ const environment = filterMockEnvironment(parentEnvironment, {
33
+ removeAllMockKeys: true,
34
+ removeRuntimeHostDir: true,
35
+ });
36
+ if (options.env && typeof options.env === 'object') {
37
+ Object.assign(environment, filterMockEnvironment(options.env, {
38
+ removeRuntimeHostDir: true,
39
+ }));
40
+ }
41
+ Object.assign(environment, {
42
+ SOMA_MOCK_JOURNAL_FILE: mockJournalFile,
43
+ NEXT_TELEMETRY_DISABLED: '1',
44
+ });
45
+ return environment;
46
+ }
47
+
48
+ export { childHasExited, PROCESS_KILL_WAIT_MS, PROCESS_TERM_GRACE_MS };
@@ -44,9 +44,13 @@ export function createDefaultRuntimeServices(options?: {
44
44
  config.load(options.appConfig as Record<string, unknown>);
45
45
  }
46
46
 
47
+ const router = new SomaRouter(options?.initialPath ?? '/');
47
48
  const http = new SomaHttpService({
48
49
  baseURL: String(config.get('apiBaseUrl') ?? '/api'),
49
50
  timeout: Number(config.get('requestTimeout') ?? 30000),
51
+ defaultHeaders: () => ({
52
+ 'x-soma-page-href': router.getCurrentPath().split('#')[0].split('?')[0] || '/',
53
+ }),
50
54
  });
51
55
 
52
56
  const storage: IStorageService =
@@ -79,7 +83,7 @@ export function createDefaultRuntimeServices(options?: {
79
83
  );
80
84
 
81
85
  return {
82
- router: new SomaRouter(options?.initialPath ?? '/'),
86
+ router,
83
87
  notify,
84
88
  logger: new ConsoleLogger(),
85
89
  http,
@@ -0,0 +1,152 @@
1
+ export type SomaJsonPrimitive = string | number | boolean | null;
2
+ export type SomaJsonValue =
3
+ | SomaJsonPrimitive
4
+ | SomaJsonValue[]
5
+ | { [key: string]: SomaJsonValue };
6
+
7
+ const OMIT = Symbol('soma-json-omit');
8
+ type VisitResult = SomaJsonValue | typeof OMIT;
9
+
10
+ export class SomaPageSerializationError extends Error {
11
+ readonly code: 'SOMA_PAGE_STATE_CIRCULAR' | 'SOMA_PAGE_STATE_UNSUPPORTED' | 'SOMA_PAGE_STATE_GETTER_FAILED';
12
+ readonly path: string;
13
+
14
+ constructor(
15
+ code: SomaPageSerializationError['code'],
16
+ path: string,
17
+ message: string,
18
+ ) {
19
+ super(message);
20
+ this.name = 'SomaPageSerializationError';
21
+ this.code = code;
22
+ this.path = path;
23
+ }
24
+ }
25
+
26
+ function propertyPath(parent: string, key: string): string {
27
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)
28
+ ? parent + '.' + key
29
+ : parent + '[' + JSON.stringify(key) + ']';
30
+ }
31
+
32
+ function readProperty(value: object, key: string, path: string): unknown {
33
+ try {
34
+ return (value as Record<string, unknown>)[key];
35
+ } catch (error) {
36
+ const detail = error instanceof Error ? error.message : String(error);
37
+ throw new SomaPageSerializationError(
38
+ 'SOMA_PAGE_STATE_GETTER_FAILED',
39
+ path,
40
+ 'Cannot read page state at ' + path + ': ' + detail,
41
+ );
42
+ }
43
+ }
44
+
45
+ function collectGetterNames(value: object): string[] {
46
+ const names = new Set<string>();
47
+ let prototype = Object.getPrototypeOf(value);
48
+ while (prototype && prototype !== Object.prototype) {
49
+ const descriptors = Object.getOwnPropertyDescriptors(prototype);
50
+ for (const [name, descriptor] of Object.entries(descriptors)) {
51
+ if (
52
+ name !== 'constructor'
53
+ && name !== 'toJSON'
54
+ && !name.startsWith('_')
55
+ && typeof descriptor.get === 'function'
56
+ ) {
57
+ names.add(name);
58
+ }
59
+ }
60
+ prototype = Object.getPrototypeOf(prototype);
61
+ }
62
+ return [...names];
63
+ }
64
+
65
+ function visit(value: unknown, path: string, ancestors: WeakSet<object>): VisitResult {
66
+ if (value === null) return null;
67
+ if (typeof value === 'string' || typeof value === 'boolean') return value;
68
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
69
+ if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol') {
70
+ return OMIT;
71
+ }
72
+ if (typeof value === 'bigint') {
73
+ throw new SomaPageSerializationError(
74
+ 'SOMA_PAGE_STATE_UNSUPPORTED',
75
+ path,
76
+ 'BigInt page state is not JSON serializable at ' + path,
77
+ );
78
+ }
79
+ if (typeof value !== 'object') {
80
+ throw new SomaPageSerializationError(
81
+ 'SOMA_PAGE_STATE_UNSUPPORTED',
82
+ path,
83
+ 'Unsupported page state at ' + path,
84
+ );
85
+ }
86
+ if (ancestors.has(value)) {
87
+ throw new SomaPageSerializationError(
88
+ 'SOMA_PAGE_STATE_CIRCULAR',
89
+ path,
90
+ 'Circular page state detected at ' + path,
91
+ );
92
+ }
93
+
94
+ ancestors.add(value);
95
+ try {
96
+ if (value instanceof Date) {
97
+ return Number.isNaN(value.getTime()) ? null : value.toISOString();
98
+ }
99
+
100
+ const toJSON = readProperty(value, 'toJSON', propertyPath(path, 'toJSON'));
101
+ if (typeof toJSON === 'function') {
102
+ let projected: unknown;
103
+ try {
104
+ projected = toJSON.call(value);
105
+ } catch (error) {
106
+ const detail = error instanceof Error ? error.message : String(error);
107
+ throw new SomaPageSerializationError(
108
+ 'SOMA_PAGE_STATE_GETTER_FAILED',
109
+ path,
110
+ 'Page toJSON failed at ' + path + ': ' + detail,
111
+ );
112
+ }
113
+ return visit(projected, path, ancestors);
114
+ }
115
+
116
+ if (Array.isArray(value)) {
117
+ return value.map((item, index) => {
118
+ const child = visit(item, path + '[' + index + ']', ancestors);
119
+ return child === OMIT ? null : child;
120
+ });
121
+ }
122
+
123
+ const result: Record<string, SomaJsonValue> = {};
124
+ const keys = new Set<string>([
125
+ ...Object.keys(value),
126
+ ...collectGetterNames(value),
127
+ ]);
128
+ for (const key of [...keys].sort()) {
129
+ if (key.startsWith('_') || key === 'toJSON') continue;
130
+ const childPath = propertyPath(path, key);
131
+ const child = visit(readProperty(value, key, childPath), childPath, ancestors);
132
+ if (child !== OMIT) {
133
+ result[key] = child;
134
+ }
135
+ }
136
+ return result;
137
+ } finally {
138
+ ancestors.delete(value);
139
+ }
140
+ }
141
+
142
+ export function serializeSomaPageState(root: unknown): SomaJsonValue {
143
+ const result = visit(root, '$', new WeakSet());
144
+ if (result === OMIT) {
145
+ throw new SomaPageSerializationError(
146
+ 'SOMA_PAGE_STATE_UNSUPPORTED',
147
+ '$',
148
+ 'Page state root must be JSON serializable',
149
+ );
150
+ }
151
+ return result;
152
+ }