@openfairygui/backend 0.3.1 → 0.5.0-alpha.1

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.
@@ -1,4 +1,5 @@
1
1
  import { failure, success, type BackendContext } from './context.js';
2
+ import { enrichBackendDiagnostic } from '../diagnostics.js';
2
3
  import { createSessionNotFoundError } from './session-utils.js';
3
4
  import type {
4
5
  BackendEvent,
@@ -21,7 +22,7 @@ export class EventService {
21
22
  ...event,
22
23
  sequence: this.context.nextEventSequence(),
23
24
  timestamp: new Date().toISOString(),
24
- diagnostics: event.diagnostics ?? [],
25
+ diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId)),
25
26
  };
26
27
  const sessionId = event.sessionId;
27
28
  if (!sessionId) return emitted;
@@ -5,11 +5,52 @@ import type {
5
5
  BackendResult,
6
6
  BackendSessionSnapshot,
7
7
  GetProjectOutlineInput,
8
+ QueryEntityInput,
9
+ BackendEntitySnapshot,
10
+ BackendResourceSnapshot,
11
+ EntityQueryError,
8
12
  SessionNotFoundError,
13
+ ReadSessionStateInput,
14
+ ReadResourceBytesInput,
15
+ BackendSessionStateSnapshot,
16
+ BackendResourceBytesSnapshot,
17
+ SessionReadError,
18
+ SessionStaleReadError,
9
19
  } from '../runtime.js';
10
20
  import { createSessionNotFoundError, toSessionSnapshot } from './session-utils.js';
11
21
  import { validateProject } from '@openfairygui/functions';
12
22
  import type { ProjectValidationReport } from '@openfairygui/core';
23
+ import { BACKEND_ENTITY_QUERY_LIMITS, BACKEND_RESOURCE_QUERY_FIELDS, BACKEND_SESSION_READ_LIMITS } from '../runtime/contracts.js';
24
+
25
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
26
+ function queryResponseProblem(value: unknown, limits: { maxBytes: number; maxNodes: number; maxDepth: number } = BACKEND_ENTITY_QUERY_LIMITS): 'response_budget_exceeded' | 'non_json_value' | undefined {
27
+ const pending = [{ value, depth: 0 }];
28
+ let nodes = 0;
29
+ let stringUnits = 0;
30
+ while (pending.length) {
31
+ const { value, depth } = pending.pop()!;
32
+ if (++nodes > limits.maxNodes || depth > limits.maxDepth) return 'response_budget_exceeded';
33
+ if (typeof value === 'string' && (stringUnits += value.length) > limits.maxBytes) return 'response_budget_exceeded';
34
+ if (value === undefined || value === null || typeof value === 'string' || typeof value === 'boolean') continue;
35
+ if (typeof value === 'number') { if (!Number.isFinite(value)) return 'non_json_value'; continue; }
36
+ if (typeof value !== 'object' || (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) return 'non_json_value';
37
+ if (Array.isArray(value) && value.length + pending.length + nodes > limits.maxNodes) return 'response_budget_exceeded';
38
+ const entries = Object.entries(value);
39
+ if (entries.length + pending.length + nodes > limits.maxNodes) return 'response_budget_exceeded';
40
+ for (const [key, child] of entries) {
41
+ if (!Array.isArray(value) && (stringUnits += key.length) > limits.maxBytes) return 'response_budget_exceeded';
42
+ pending.push({ value: child, depth: depth + 1 });
43
+ }
44
+ }
45
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.maxBytes) return 'response_budget_exceeded';
46
+ return undefined;
47
+ }
48
+
49
+ function readFailure(startedAt: number, sessionId: string, reason: SessionReadError['reason'], revision?: number) {
50
+ return failure('read', startedAt, {
51
+ code: 'session_read_failed' as const, sessionId, reason, message: `Session read failed: ${reason}.`,
52
+ }, undefined, { sessionId, revision });
53
+ }
13
54
 
14
55
  function toProjectOutline(session: BackendSessionState): BackendProjectOutline {
15
56
  const project = session.project;
@@ -84,6 +125,133 @@ export class ReadService {
84
125
  });
85
126
  }
86
127
 
128
+ public queryEntity(input: QueryEntityInput): BackendResult<BackendEntitySnapshot, SessionNotFoundError | EntityQueryError> {
129
+ const startedAt = Date.now();
130
+ const session = this.context.sessions.get(input.sessionId);
131
+ if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
132
+ const meta = { sessionId: session.sessionId, revision: session.revision };
133
+ const reject = (reason: EntityQueryError['reason']) => failure('read', startedAt, {
134
+ code: 'entity_query_failed' as const, sessionId: session.sessionId, reason,
135
+ message: `Entity query failed: ${reason}.`,
136
+ }, undefined, meta);
137
+ const target = input.target;
138
+ if (!target || typeof target !== 'object' || Array.isArray(target) || Object.keys(target).some((key) => key !== 'kind' && key !== 'selector')) return reject('invalid_query');
139
+ const respond = (entity: BackendEntitySnapshot['entity']) => {
140
+ const data = { ...meta, target, entity };
141
+ const problem = queryResponseProblem(data);
142
+ return problem ? reject(problem) : success('read', startedAt, structuredClone(data), meta);
143
+ };
144
+ if (target.kind === 'project') {
145
+ if (Object.hasOwn(target, 'selector')) return reject('invalid_query');
146
+ const { projectId, settings } = session.project;
147
+ return respond({ kind: 'project', properties: { projectId, settings } });
148
+ }
149
+ const keys = target.kind === 'package' ? ['packageId']
150
+ : target.kind === 'resource' ? ['packageId', 'resourceId']
151
+ : target.kind === 'component' ? ['packageId', 'componentResourceId']
152
+ : target.kind === 'displayNode' ? ['packageId', 'componentResourceId', 'displayNodeId']
153
+ : target.kind === 'controller' ? ['packageId', 'componentResourceId', 'controllerName']
154
+ : target.kind === 'transition' ? ['packageId', 'componentResourceId', 'transitionName'] : [];
155
+ const selector = target.selector as unknown as Record<string, unknown>;
156
+ if (!keys.length || !selector || typeof selector !== 'object' || Array.isArray(selector)
157
+ || Object.keys(selector).length !== keys.length
158
+ || keys.some((key) => !Object.hasOwn(selector, key) || typeof selector[key] !== 'string' || !(selector[key] as string).length || (selector[key] as string).length > 256)) return reject('invalid_query');
159
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
160
+ if (packages.length !== 1) return reject(packages.length ? 'ambiguous' : 'not_found');
161
+ if (target.kind === 'package') {
162
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
163
+ return respond({ kind: 'package', properties: { id, name, settings: { compressPNG, jpegQuality, publish } } });
164
+ }
165
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === 'resource' ? selector.resourceId : selector.componentResourceId));
166
+ if (resources.length !== 1) return reject(resources.length ? 'ambiguous' : 'not_found');
167
+ const resource = resources[0];
168
+ let entity: BackendEntitySnapshot['entity'];
169
+ if (target.kind === 'resource') {
170
+ const record = resource as unknown as Record<string, unknown>;
171
+ entity = { kind: 'resource', properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS
172
+ .filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]])) as BackendResourceSnapshot };
173
+ } else {
174
+ if (resource.kind !== 'component') return reject('not_found');
175
+ if (target.kind === 'component') {
176
+ const { size, properties, customData } = resource.component;
177
+ entity = { kind: 'component', properties: { size, properties, customData } };
178
+ } else if (target.kind === 'controller') {
179
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
180
+ if (controllers.length !== 1) return reject(controllers.length ? 'ambiguous' : 'not_found');
181
+ entity = { kind: 'controller', properties: controllers[0] };
182
+ } else if (target.kind === 'transition') {
183
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
184
+ if (transitions.length !== 1) return reject(transitions.length ? 'ambiguous' : 'not_found');
185
+ entity = { kind: 'transition', properties: transitions[0] };
186
+ } else {
187
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
188
+ if (nodes.length !== 1) return reject(nodes.length ? 'ambiguous' : 'not_found');
189
+ entity = { kind: 'displayNode', properties: nodes[0] };
190
+ }
191
+ }
192
+ return respond(entity);
193
+ }
194
+
195
+ private resolveReadSession(input: ReadSessionStateInput, startedAt: number): BackendResult<BackendSessionState, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
196
+ if (!input || typeof input.sessionId !== 'string' || !input.sessionId.length || input.sessionId.length > 256
197
+ || (input.expectedRevision !== undefined && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0))) {
198
+ return readFailure(startedAt, typeof input?.sessionId === 'string' ? input.sessionId : '', 'invalid_query');
199
+ }
200
+ const session = this.context.sessions.get(input.sessionId);
201
+ if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
202
+ const meta = { sessionId: session.sessionId, revision: session.revision };
203
+ if (input.expectedRevision !== undefined && input.expectedRevision !== session.revision) return failure('read', startedAt, {
204
+ code: 'stale_read', sessionId: session.sessionId, expectedRevision: input.expectedRevision, actualRevision: session.revision,
205
+ message: 'The session edit revision changed. Restart the model and resource read.',
206
+ }, undefined, meta);
207
+ return success('read', startedAt, session, meta);
208
+ }
209
+
210
+ public readSessionState(input: ReadSessionStateInput): BackendResult<BackendSessionStateSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
211
+ const startedAt = Date.now();
212
+ const resolved = this.resolveReadSession(input, startedAt);
213
+ if (!resolved.ok) return resolved;
214
+ const session = resolved.data;
215
+ const meta = { sessionId: session.sessionId, revision: session.revision };
216
+ // Capture synchronously: pending transactions have not committed; save bookkeeping may change without an edit revision.
217
+ const data: BackendSessionStateSnapshot = {
218
+ ...meta, dirty: session.dirty, lastSavedRevision: session.lastSavedRevision,
219
+ uamFidelity: session.uamFidelity, readComplete: session.readComplete, readDiagnostics: session.readDiagnostics,
220
+ project: { ...session.project, packages: session.project.packages.map((pkg) => ({
221
+ ...pkg, resources: pkg.resources.map((resource) => {
222
+ if (resource.kind === 'component') return resource;
223
+ const { sourceBytes: _sourceBytes, ...model } = resource;
224
+ return model;
225
+ }),
226
+ })) },
227
+ };
228
+ const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
229
+ return problem ? readFailure(startedAt, session.sessionId, problem, session.revision)
230
+ : success('read', startedAt, structuredClone(data), meta);
231
+ }
232
+
233
+ public readResourceBytes(input: ReadResourceBytesInput): BackendResult<BackendResourceBytesSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
234
+ const startedAt = Date.now();
235
+ const resolved = this.resolveReadSession(input, startedAt);
236
+ if (!resolved.ok) return resolved;
237
+ const session = resolved.data;
238
+ const reject = (reason: SessionReadError['reason']) => readFailure(startedAt, session.sessionId, reason, session.revision);
239
+ const selector = input.selector;
240
+ if (input.expectedRevision === undefined || !selector || typeof selector !== 'object' || Array.isArray(selector)
241
+ || Object.keys(selector).length !== 2 || ['packageId', 'resourceId'].some((key) => !Object.hasOwn(selector, key))
242
+ || [selector.packageId, selector.resourceId].some((value) => typeof value !== 'string' || !value.length || value.length > 256)) return reject('invalid_query');
243
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
244
+ if (packages.length !== 1) return reject(packages.length ? 'ambiguous' : 'not_found');
245
+ const resources = packages[0].resources.filter((resource) => resource.id === selector.resourceId);
246
+ if (resources.length !== 1) return reject(resources.length ? 'ambiguous' : 'not_found');
247
+ const resource = resources[0];
248
+ if (resource.kind === 'component') return reject('unsupported_resource');
249
+ if (!(resource.sourceBytes instanceof Uint8Array)) return reject('bytes_unavailable');
250
+ if (resource.sourceBytes.byteLength > BACKEND_SESSION_READ_LIMITS.resourceBytes) return reject('response_budget_exceeded');
251
+ const meta = { sessionId: session.sessionId, revision: session.revision };
252
+ return success('read', startedAt, { ...meta, selector: { ...selector }, sourceBytes: new Uint8Array(resource.sourceBytes) }, meta);
253
+ }
254
+
87
255
  public validateSession(
88
256
  input: { sessionId: string },
89
257
  ): BackendResult<ProjectValidationReport, SessionNotFoundError> {
@@ -100,7 +268,7 @@ export class ReadService {
100
268
  return success('read', startedAt, report, {
101
269
  sessionId: session.sessionId,
102
270
  revision: session.revision,
103
- diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({ code, message, severity, path })),
271
+ diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({ code, message, severity, path, owner: 'core.validation' })),
104
272
  });
105
273
  }
106
274
  }
@@ -1,3 +1,4 @@
1
+ import { capturedDirectoriesEqual, capturedFilesEqual, createCaptureFileSystem } from './capture-project.js';
1
2
  import { type FileSystem, ProjectReader, ProjectWriter } from '@openfairygui/core/project-io';
2
3
  import {
3
4
  liftDocumentToUamProject,
@@ -88,71 +89,6 @@ function createProjectReaderFileSystem(
88
89
  };
89
90
  }
90
91
 
91
- function createCaptureFileSystem(
92
- files: Map<string, string | Uint8Array>,
93
- directories: Set<string>,
94
- ): FileSystem {
95
- const normalize = (filePath: string): string => filePath.replace(/\\/g, '/').replace(/\/+/g, '/');
96
- return {
97
- async readFile(filePath: string): Promise<string> {
98
- const value = files.get(normalize(filePath));
99
- if (typeof value !== 'string') throw new Error(`Captured text file was not found: ${filePath}`);
100
- return value;
101
- },
102
- async readFileRaw(filePath: string): Promise<Uint8Array> {
103
- const value = files.get(normalize(filePath));
104
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
105
- return value.slice();
106
- },
107
- async writeFile(filePath: string, content: string): Promise<void> {
108
- files.set(normalize(filePath), content);
109
- },
110
- async writeFileRaw(filePath: string, data: Uint8Array): Promise<void> {
111
- files.set(normalize(filePath), data.slice());
112
- },
113
- async mkdir(dirPath: string): Promise<void> {
114
- directories.add(normalize(dirPath));
115
- },
116
- async readdir(): Promise<string[]> {
117
- return [];
118
- },
119
- async exists(filePath: string): Promise<boolean> {
120
- return files.has(normalize(filePath));
121
- },
122
- join(...paths: string[]): string {
123
- return normalize(paths.filter(Boolean).join('/'));
124
- },
125
- dirname(filePath: string): string {
126
- const normalized = normalize(filePath);
127
- const separator = normalized.lastIndexOf('/');
128
- return separator < 0 ? '' : normalized.slice(0, separator);
129
- },
130
- async unlink(filePath: string): Promise<void> {
131
- files.delete(normalize(filePath));
132
- },
133
- };
134
- }
135
-
136
- function capturedFilesEqual(left: Map<string, string | Uint8Array>, right: Map<string, string | Uint8Array>): boolean {
137
- if (left.size !== right.size) return false;
138
- for (const [filePath, leftValue] of left) {
139
- const rightValue = right.get(filePath);
140
- if (typeof leftValue === 'string') {
141
- if (leftValue !== rightValue) return false;
142
- continue;
143
- }
144
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
145
- for (let index = 0; index < leftValue.length; index += 1) {
146
- if (leftValue[index] !== rightValue[index]) return false;
147
- }
148
- }
149
- return true;
150
- }
151
-
152
- function capturedDirectoriesEqual(left: Set<string>, right: Set<string>): boolean {
153
- return left.size === right.size && [...left].every((directory) => right.has(directory));
154
- }
155
-
156
92
  async function hasFullUamFidelity(
157
93
  document: Awaited<ReturnType<ProjectReader['read']>>,
158
94
  project: UamProject,
@@ -0,0 +1,114 @@
1
+ import { materializeUamProject, type UamProject } from '@openfairygui/core/uam';
2
+ import { BACKEND_TRANSACTION_PREVIEW_LIMITS, type BackendTransactionEntityChange, type BackendTransactionPreview } from '../runtime/contracts.js';
3
+ import { captureProject } from './capture-project.js';
4
+ import type { BackendSessionState } from './context.js';
5
+
6
+ type Entity = { target: BackendTransactionEntityChange['target']; properties: Record<string, unknown> };
7
+
8
+ /** Keep child identities/order on their parent, and compare each child's own properties separately. */
9
+ function entities(project: UamProject): Map<string, Entity> {
10
+ const result = new Map<string, Entity>();
11
+ function add(target: Entity['target'], properties: object): void {
12
+ const key = JSON.stringify(target);
13
+ if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
14
+ result.set(key, { target, properties: properties as Entity['properties'] });
15
+ }
16
+ const { packages, ...properties } = project;
17
+ add({ kind: 'project' }, { ...properties, packages: packages.map((pkg) => pkg.id) });
18
+ for (const { resources, ...pkg } of packages) {
19
+ const packageId = pkg.id;
20
+ add({ kind: 'package', selector: { packageId } }, { ...pkg, resources: resources.map((resource) => resource.id) });
21
+ for (const resource of resources) {
22
+ const resourceTarget = { kind: 'resource' as const, selector: { packageId, resourceId: resource.id } };
23
+ if (resource.kind !== 'component') { add(resourceTarget, resource); continue; }
24
+ const { component, ...resourceProperties } = resource;
25
+ add(resourceTarget, resourceProperties);
26
+ const { displayList, controllers, transitions, ...componentProperties } = component;
27
+ const selector = { packageId, componentResourceId: resource.id };
28
+ add({ kind: 'component', selector }, {
29
+ ...componentProperties, displayList: displayList.map((node) => node.id),
30
+ controllers: controllers.map((controller) => controller.name), transitions: transitions.map((transition) => transition.name),
31
+ });
32
+ for (const node of displayList) add({ kind: 'displayNode', selector: { ...selector, displayNodeId: node.id } }, node);
33
+ for (const controller of controllers) add({ kind: 'controller', selector: { ...selector, controllerName: controller.name } }, controller);
34
+ for (const transition of transitions) add({ kind: 'transition', selector: { ...selector, transitionName: transition.name } }, transition);
35
+ }
36
+ }
37
+ return result;
38
+ }
39
+
40
+ function equal(left: unknown, right: unknown, depth = 0): boolean {
41
+ if (left === right) return true;
42
+ if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false;
43
+ if (left instanceof Uint8Array || right instanceof Uint8Array) {
44
+ return left instanceof Uint8Array && right instanceof Uint8Array && left.length === right.length
45
+ && left.every((value, index) => value === right[index]);
46
+ }
47
+ if (depth > 128) throw new Error('Preview property comparison exceeds the supported nesting depth.');
48
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
49
+ if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
50
+ const a = left as Record<string, unknown>, b = right as Record<string, unknown>;
51
+ const keys = Object.keys(a);
52
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
53
+ }
54
+
55
+ export class PreviewBudgetError extends Error {}
56
+
57
+ /** No host filesystem, cache, event or session mutation is involved in the projection. */
58
+ export async function previewTransactionImpact(
59
+ session: BackendSessionState,
60
+ project: UamProject,
61
+ fileSystemAvailable: boolean,
62
+ ): Promise<BackendTransactionPreview> {
63
+ const impact: BackendTransactionPreview['impact'] = { entities: [], files: [] };
64
+ const before = entities(session.project), after = entities(project);
65
+ let entries = 0, bytes = 0;
66
+ const encoder = new TextEncoder();
67
+ function count(value: unknown): void {
68
+ bytes += encoder.encode(JSON.stringify(value)).byteLength;
69
+ if (++entries > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxEntries || bytes > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) {
70
+ throw new PreviewBudgetError('The complete transaction impact exceeds the preview response budget.');
71
+ }
72
+ }
73
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
74
+ const previous = before.get(key), next = after.get(key);
75
+ const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])]
76
+ .filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
77
+ if (!fields.length && previous && next) continue;
78
+ const change: BackendTransactionEntityChange = {
79
+ target: (next ?? previous)!.target, change: !previous ? 'added' : !next ? 'removed' : 'updated', fields,
80
+ };
81
+ count(change); impact.entities.push(change);
82
+ }
83
+ const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, '/').split('/').at(-1)! : 'Project.fairy';
84
+ // ponytail: two full in-memory serializations reuse the writer; add writer-level incremental planning only if measured cost requires it.
85
+ const [previousFiles, nextFiles] = await Promise.all([
86
+ captureProject(materializeUamProject(session.project), fairyFileName),
87
+ captureProject(materializeUamProject(project), fairyFileName),
88
+ ]);
89
+ for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
90
+ const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
91
+ if (equal(previous, next)) continue;
92
+ const change = { path, kind: 'file' as const, change: previous === undefined ? 'added' as const : next === undefined ? 'removed' as const : 'updated' as const };
93
+ count(change); impact.files.push(change);
94
+ }
95
+ for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
96
+ if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
97
+ const change = { path, kind: 'directory' as const, change: nextFiles.directories.has(path) ? 'added' as const : 'removed' as const };
98
+ count(change); impact.files.push(change);
99
+ }
100
+ impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
101
+ const preview: BackendTransactionPreview = {
102
+ sessionId: session.sessionId, baseRevision: session.revision, projectedRevision: session.revision + 1,
103
+ mode: 'execute-and-discard', impact,
104
+ persistence: {
105
+ requiredAfterApply: true, fileSystemAvailable, uamFidelity: session.uamFidelity, writeVerified: false,
106
+ nextAction: session.uamFidelity === 'unsupported' || !fileSystemAvailable ? 'host-action'
107
+ : session.fileSystem ? 'saveSession' : 'materializeSession',
108
+ },
109
+ };
110
+ if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) {
111
+ throw new PreviewBudgetError('The complete transaction preview exceeds the response byte budget.');
112
+ }
113
+ return preview;
114
+ }