@openfairygui/backend 0.3.1 → 0.4.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.
@@ -5,11 +5,40 @@ import type {
5
5
  BackendResult,
6
6
  BackendSessionSnapshot,
7
7
  GetProjectOutlineInput,
8
+ QueryEntityInput,
9
+ BackendEntitySnapshot,
10
+ BackendResourceSnapshot,
11
+ EntityQueryError,
8
12
  SessionNotFoundError,
9
13
  } from '../runtime.js';
10
14
  import { createSessionNotFoundError, toSessionSnapshot } from './session-utils.js';
11
15
  import { validateProject } from '@openfairygui/functions';
12
16
  import type { ProjectValidationReport } from '@openfairygui/core';
17
+ import { BACKEND_ENTITY_QUERY_LIMITS, BACKEND_RESOURCE_QUERY_FIELDS } from '../runtime/contracts.js';
18
+
19
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
20
+ function queryResponseProblem(value: unknown): EntityQueryError['reason'] | undefined {
21
+ const pending = [{ value, depth: 0 }];
22
+ let nodes = 0;
23
+ let stringUnits = 0;
24
+ while (pending.length) {
25
+ const { value, depth } = pending.pop()!;
26
+ if (++nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes || depth > BACKEND_ENTITY_QUERY_LIMITS.maxDepth) return 'response_budget_exceeded';
27
+ if (typeof value === 'string' && (stringUnits += value.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return 'response_budget_exceeded';
28
+ if (value === undefined || value === null || typeof value === 'string' || typeof value === 'boolean') continue;
29
+ if (typeof value === 'number') { if (!Number.isFinite(value)) return 'non_json_value'; continue; }
30
+ if (typeof value !== 'object' || (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) return 'non_json_value';
31
+ if (Array.isArray(value) && value.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return 'response_budget_exceeded';
32
+ const entries = Object.entries(value);
33
+ if (entries.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return 'response_budget_exceeded';
34
+ for (const [key, child] of entries) {
35
+ if (!Array.isArray(value) && (stringUnits += key.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return 'response_budget_exceeded';
36
+ pending.push({ value: child, depth: depth + 1 });
37
+ }
38
+ }
39
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return 'response_budget_exceeded';
40
+ return undefined;
41
+ }
13
42
 
14
43
  function toProjectOutline(session: BackendSessionState): BackendProjectOutline {
15
44
  const project = session.project;
@@ -84,6 +113,73 @@ export class ReadService {
84
113
  });
85
114
  }
86
115
 
116
+ public queryEntity(input: QueryEntityInput): BackendResult<BackendEntitySnapshot, SessionNotFoundError | EntityQueryError> {
117
+ const startedAt = Date.now();
118
+ const session = this.context.sessions.get(input.sessionId);
119
+ if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
120
+ const meta = { sessionId: session.sessionId, revision: session.revision };
121
+ const reject = (reason: EntityQueryError['reason']) => failure('read', startedAt, {
122
+ code: 'entity_query_failed' as const, sessionId: session.sessionId, reason,
123
+ message: `Entity query failed: ${reason}.`,
124
+ }, undefined, meta);
125
+ const target = input.target;
126
+ if (!target || typeof target !== 'object' || Array.isArray(target) || Object.keys(target).some((key) => key !== 'kind' && key !== 'selector')) return reject('invalid_query');
127
+ const respond = (entity: BackendEntitySnapshot['entity']) => {
128
+ const data = { ...meta, target, entity };
129
+ const problem = queryResponseProblem(data);
130
+ return problem ? reject(problem) : success('read', startedAt, structuredClone(data), meta);
131
+ };
132
+ if (target.kind === 'project') {
133
+ if (Object.hasOwn(target, 'selector')) return reject('invalid_query');
134
+ const { projectId, settings } = session.project;
135
+ return respond({ kind: 'project', properties: { projectId, settings } });
136
+ }
137
+ const keys = target.kind === 'package' ? ['packageId']
138
+ : target.kind === 'resource' ? ['packageId', 'resourceId']
139
+ : target.kind === 'component' ? ['packageId', 'componentResourceId']
140
+ : target.kind === 'displayNode' ? ['packageId', 'componentResourceId', 'displayNodeId']
141
+ : target.kind === 'controller' ? ['packageId', 'componentResourceId', 'controllerName']
142
+ : target.kind === 'transition' ? ['packageId', 'componentResourceId', 'transitionName'] : [];
143
+ const selector = target.selector as unknown as Record<string, unknown>;
144
+ if (!keys.length || !selector || typeof selector !== 'object' || Array.isArray(selector)
145
+ || Object.keys(selector).length !== keys.length
146
+ || 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');
147
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
148
+ if (packages.length !== 1) return reject(packages.length ? 'ambiguous' : 'not_found');
149
+ if (target.kind === 'package') {
150
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
151
+ return respond({ kind: 'package', properties: { id, name, settings: { compressPNG, jpegQuality, publish } } });
152
+ }
153
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === 'resource' ? selector.resourceId : selector.componentResourceId));
154
+ if (resources.length !== 1) return reject(resources.length ? 'ambiguous' : 'not_found');
155
+ const resource = resources[0];
156
+ let entity: BackendEntitySnapshot['entity'];
157
+ if (target.kind === 'resource') {
158
+ const record = resource as unknown as Record<string, unknown>;
159
+ entity = { kind: 'resource', properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS
160
+ .filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]])) as BackendResourceSnapshot };
161
+ } else {
162
+ if (resource.kind !== 'component') return reject('not_found');
163
+ if (target.kind === 'component') {
164
+ const { size, properties, customData } = resource.component;
165
+ entity = { kind: 'component', properties: { size, properties, customData } };
166
+ } else if (target.kind === 'controller') {
167
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
168
+ if (controllers.length !== 1) return reject(controllers.length ? 'ambiguous' : 'not_found');
169
+ entity = { kind: 'controller', properties: controllers[0] };
170
+ } else if (target.kind === 'transition') {
171
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
172
+ if (transitions.length !== 1) return reject(transitions.length ? 'ambiguous' : 'not_found');
173
+ entity = { kind: 'transition', properties: transitions[0] };
174
+ } else {
175
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
176
+ if (nodes.length !== 1) return reject(nodes.length ? 'ambiguous' : 'not_found');
177
+ entity = { kind: 'displayNode', properties: nodes[0] };
178
+ }
179
+ }
180
+ return respond(entity);
181
+ }
182
+
87
183
  public validateSession(
88
184
  input: { sessionId: string },
89
185
  ): BackendResult<ProjectValidationReport, SessionNotFoundError> {
@@ -100,7 +196,7 @@ export class ReadService {
100
196
  return success('read', startedAt, report, {
101
197
  sessionId: session.sessionId,
102
198
  revision: session.revision,
103
- diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({ code, message, severity, path })),
199
+ diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({ code, message, severity, path, owner: 'core.validation' })),
104
200
  });
105
201
  }
106
202
  }
@@ -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
+ }