@openfairygui/backend 0.7.1 → 0.8.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.
@@ -1,11 +1,11 @@
1
- import { r as enrichBackendDiagnostic } from "./diagnostics-DTnLXQGs.mjs";
1
+ import { r as enrichBackendDiagnostic } from "./diagnostics-By8Kxj6K.mjs";
2
2
  import { UAM_SUPPORTED_MATERIALIZATION_SCOPE, UAM_SUPPORTED_TRANSACTION_SCOPE, commitUamProjectSourcePaths, liftDocumentToUamProject, materializeUamProject, normalizeUamProject, staleBranchDirectories, staleResourceFolders, staleSourceFiles, validateUamProject } from "@openfairygui/core/uam";
3
3
  import { applyUamTransactionAppAsync } from "@openfairygui/functions/uam";
4
4
  import { ProjectReader, ProjectWriter } from "@openfairygui/core/project-io";
5
5
  import { validateProject } from "@openfairygui/functions";
6
6
  //#region src/contracts.ts
7
7
  const BACKEND_CONTRACT_VERSION = "3.0.0";
8
- const BACKEND_CAPABILITY_SCHEMA_VERSION = 15;
8
+ const BACKEND_CAPABILITY_SCHEMA_VERSION = 16;
9
9
  const BACKEND_COMPATIBILITY_POLICY = {
10
10
  incompatibleChange: "requires contractVersion bump",
11
11
  capabilitySchemaChange: "requires capabilitySchemaVersion bump",
@@ -153,7 +153,7 @@ function createMeta(stage, startedAt, options) {
153
153
  diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
154
154
  stage,
155
155
  contractVersion: BACKEND_CONTRACT_VERSION,
156
- capabilitySchemaVersion: 15
156
+ capabilitySchemaVersion: 16
157
157
  };
158
158
  }
159
159
  function success(stage, startedAt, data, options) {
@@ -185,6 +185,7 @@ function toSessionSnapshot(session, capabilities) {
185
185
  lastSavedRevision: session.lastSavedRevision,
186
186
  dirty: session.dirty,
187
187
  uamFidelity: session.uamFidelity,
188
+ ...session.uamFidelity === "unsupported" && session.uamFidelityReport ? { uamFidelityReport: cloneReadData(session.uamFidelityReport) } : {},
188
189
  lockHeld: session.lockHeld,
189
190
  capabilities: cloneReadData(capabilities)
190
191
  };
@@ -213,6 +214,30 @@ const BACKEND_ENTITY_QUERY_LIMITS = {
213
214
  maxDepth: 32,
214
215
  maxNodes: 1e5
215
216
  };
217
+ const BACKEND_DISPLAY_NODE_QUERY_LIMITS = {
218
+ maxBytes: 262144,
219
+ maxDepth: 32,
220
+ maxNodes: 1e5,
221
+ defaultLimit: 50,
222
+ maxLimit: 200
223
+ };
224
+ const BACKEND_DISPLAY_NODE_FILTER_FIELDS = [
225
+ "kind",
226
+ "name",
227
+ "nameContains",
228
+ "text",
229
+ "textContains",
230
+ "title",
231
+ "titleContains",
232
+ "group",
233
+ "resourceId",
234
+ "url",
235
+ "visible",
236
+ "locked",
237
+ "touchable",
238
+ "hasGears",
239
+ "hasRelations"
240
+ ];
216
241
  const BACKEND_SESSION_READ_LIMITS = {
217
242
  model: {
218
243
  maxBytes: 4194304,
@@ -300,22 +325,6 @@ function createCaptureFileSystem(files, directories) {
300
325
  }
301
326
  };
302
327
  }
303
- function capturedFilesEqual(left, right) {
304
- if (left.size !== right.size) return false;
305
- for (const [filePath, leftValue] of left) {
306
- const rightValue = right.get(filePath);
307
- if (typeof leftValue === "string") {
308
- if (leftValue !== rightValue) return false;
309
- continue;
310
- }
311
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
312
- for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
313
- }
314
- return true;
315
- }
316
- function capturedDirectoriesEqual(left, right) {
317
- return left.size === right.size && [...left].every((directory) => right.has(directory));
318
- }
319
328
  /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
320
329
  async function captureProject(document, fairyFileName) {
321
330
  const files = /* @__PURE__ */ new Map();
@@ -719,6 +728,180 @@ async function writeSessionProject(input) {
719
728
  throw error;
720
729
  }
721
730
  }
731
+ function boundText(value, maxChars) {
732
+ const normalized = value.replace(/\r/g, "").trim();
733
+ if (normalized.length <= maxChars) return normalized;
734
+ return `${normalized.slice(0, Math.max(0, maxChars - 3))}...`;
735
+ }
736
+ function bytesEqual(left, right) {
737
+ if (left.length !== right.length) return false;
738
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
739
+ return true;
740
+ }
741
+ function firstTextLineDiff(source, materialized) {
742
+ const sourceLines = source.split("\n");
743
+ const materializedLines = materialized.split("\n");
744
+ const limit = Math.max(sourceLines.length, materializedLines.length);
745
+ for (let index = 0; index < limit; index += 1) {
746
+ const left = sourceLines[index] ?? "";
747
+ const right = materializedLines[index] ?? "";
748
+ if (left !== right) return {
749
+ line: index + 1,
750
+ sourceExcerpt: boundText(left, 240),
751
+ materializedExcerpt: boundText(right, 240)
752
+ };
753
+ }
754
+ return {
755
+ line: 1,
756
+ sourceExcerpt: boundText(sourceLines[0] ?? "", 240),
757
+ materializedExcerpt: boundText(materializedLines[0] ?? "", 240)
758
+ };
759
+ }
760
+ function diffCapturedProjects(sourceFiles, sourceDirectories, materializedFiles, materializedDirectories, maxDiffs = 50) {
761
+ const allDiffs = [];
762
+ const filePaths = [...new Set([...sourceFiles.keys(), ...materializedFiles.keys()])].sort((left, right) => left.localeCompare(right));
763
+ for (const filePath of filePaths) {
764
+ const left = sourceFiles.get(filePath);
765
+ const right = materializedFiles.get(filePath);
766
+ if (left === void 0) {
767
+ allDiffs.push({
768
+ path: filePath,
769
+ kind: "file",
770
+ change: "extra"
771
+ });
772
+ continue;
773
+ }
774
+ if (right === void 0) {
775
+ allDiffs.push({
776
+ path: filePath,
777
+ kind: "file",
778
+ change: "missing"
779
+ });
780
+ continue;
781
+ }
782
+ if (typeof left === "string" && typeof right === "string") {
783
+ if (left !== right) {
784
+ const diff = firstTextLineDiff(left, right);
785
+ allDiffs.push({
786
+ path: filePath,
787
+ kind: "file",
788
+ change: "modified",
789
+ line: diff.line,
790
+ sourceExcerpt: diff.sourceExcerpt,
791
+ materializedExcerpt: diff.materializedExcerpt
792
+ });
793
+ }
794
+ continue;
795
+ }
796
+ if (left instanceof Uint8Array && right instanceof Uint8Array) {
797
+ if (!bytesEqual(left, right)) allDiffs.push({
798
+ path: filePath,
799
+ kind: "file",
800
+ change: "modified"
801
+ });
802
+ continue;
803
+ }
804
+ allDiffs.push({
805
+ path: filePath,
806
+ kind: "file",
807
+ change: "type_mismatch"
808
+ });
809
+ }
810
+ const directories = [...new Set([...sourceDirectories, ...materializedDirectories])].sort((left, right) => left.localeCompare(right));
811
+ for (const directory of directories) {
812
+ const inSource = sourceDirectories.has(directory);
813
+ const inMaterialized = materializedDirectories.has(directory);
814
+ if (inSource && !inMaterialized) allDiffs.push({
815
+ path: directory,
816
+ kind: "directory",
817
+ change: "missing"
818
+ });
819
+ else if (!inSource && inMaterialized) allDiffs.push({
820
+ path: directory,
821
+ kind: "directory",
822
+ change: "extra"
823
+ });
824
+ }
825
+ allDiffs.sort((left, right) => left.path === right.path ? left.kind.localeCompare(right.kind) : left.path.localeCompare(right.path));
826
+ const limit = Math.max(0, maxDiffs);
827
+ return {
828
+ totalDiffCount: allDiffs.length,
829
+ diffs: allDiffs.slice(0, limit),
830
+ truncated: allDiffs.length > limit
831
+ };
832
+ }
833
+ async function evaluateUamFidelity(document, project, options) {
834
+ if (options?.readComplete === false) {
835
+ const detail = options.readDiagnostics?.[0]?.message;
836
+ return {
837
+ uamFidelity: "unsupported",
838
+ report: {
839
+ reason: "incomplete_read",
840
+ ...detail ? { errorMessage: boundText(detail, 512) } : {},
841
+ totalDiffCount: 0,
842
+ diffs: [],
843
+ truncated: false
844
+ }
845
+ };
846
+ }
847
+ const fairyFileName = options?.fairyFileName || "Project.fairy";
848
+ const sourceFiles = /* @__PURE__ */ new Map();
849
+ const materializedFiles = /* @__PURE__ */ new Map();
850
+ const sourceDirectories = /* @__PURE__ */ new Set();
851
+ const materializedDirectories = /* @__PURE__ */ new Set();
852
+ try {
853
+ await Promise.all([new ProjectWriter(createCaptureFileSystem(sourceFiles, sourceDirectories)).write(document, fairyFileName), new ProjectWriter(createCaptureFileSystem(materializedFiles, materializedDirectories)).write(materializeUamProject(project), fairyFileName)]);
854
+ } catch (error) {
855
+ const message = error instanceof Error ? error.message : String(error);
856
+ return {
857
+ uamFidelity: "unsupported",
858
+ report: {
859
+ reason: "materialize_failed",
860
+ ...message ? { errorMessage: boundText(message, 512) } : {},
861
+ totalDiffCount: 0,
862
+ diffs: [],
863
+ truncated: false
864
+ }
865
+ };
866
+ }
867
+ const comparison = diffCapturedProjects(sourceFiles, sourceDirectories, materializedFiles, materializedDirectories, options?.maxDiffs);
868
+ if (comparison.totalDiffCount === 0) return { uamFidelity: "full" };
869
+ return {
870
+ uamFidelity: "unsupported",
871
+ report: {
872
+ reason: "round_trip_mismatch",
873
+ totalDiffCount: comparison.totalDiffCount,
874
+ diffs: comparison.diffs,
875
+ truncated: comparison.truncated
876
+ }
877
+ };
878
+ }
879
+ function formatUamFidelityUnsupportedMessage(report) {
880
+ if (!report) return "The source project contains formal properties that the current UAM cannot preserve.";
881
+ if (report.reason === "incomplete_read") return report.errorMessage ? `The source project read was incomplete, so UAM fidelity cannot be verified: ${report.errorMessage}` : "The source project read was incomplete, so UAM fidelity cannot be verified.";
882
+ if (report.reason === "materialize_failed") return report.errorMessage ? `The source project could not be materialized through the current UAM: ${report.errorMessage}` : "The source project could not be materialized through the current UAM.";
883
+ const first = report.diffs[0];
884
+ const firstLocation = first ? `, first: ${first.path}${first.line !== void 0 ? `:${first.line}` : ""} [${first.change}]` : "";
885
+ return `The source project contains formal properties that the current UAM cannot preserve (${report.totalDiffCount} difference(s)${firstLocation}).`;
886
+ }
887
+ function formatDiffDiagnosticMessage(entry) {
888
+ if (entry.kind === "directory") return `UAM round-trip directory ${entry.change}: ${entry.path}`;
889
+ if (entry.change === "modified" && entry.line !== void 0) return `UAM round-trip modified ${entry.path} at line ${entry.line} (source: ${entry.sourceExcerpt ?? ""}; materialized: ${entry.materializedExcerpt ?? ""}).`;
890
+ return `UAM round-trip file ${entry.change}: ${entry.path}`;
891
+ }
892
+ function createUamFidelityDiagnostics(report, fallbackMessage) {
893
+ if (report?.reason === "round_trip_mismatch" && report.diffs.length > 0) return report.diffs.map((entry) => ({
894
+ code: "uam_fidelity_unsupported",
895
+ severity: "error",
896
+ path: entry.path,
897
+ message: formatDiffDiagnosticMessage(entry)
898
+ }));
899
+ return [{
900
+ code: "uam_fidelity_unsupported",
901
+ severity: "error",
902
+ message: fallbackMessage
903
+ }];
904
+ }
722
905
  //#endregion
723
906
  //#region src/services/persistence-service.ts
724
907
  function createCapabilityUnavailableError$1(message) {
@@ -730,11 +913,13 @@ function createCapabilityUnavailableError$1(message) {
730
913
  };
731
914
  }
732
915
  function createUamFidelityUnsupportedError(session) {
916
+ const report = session.uamFidelityReport;
733
917
  return {
734
918
  code: "uam_fidelity_unsupported",
735
- message: "The source project contains formal properties that the current UAM cannot preserve.",
919
+ message: formatUamFidelityUnsupportedMessage(report),
736
920
  sessionId: session.sessionId,
737
- canonicalPathKey: session.canonicalPathKey
921
+ canonicalPathKey: session.canonicalPathKey,
922
+ ...report ? { fidelityReport: structuredClone(report) } : {}
738
923
  };
739
924
  }
740
925
  function validationDiagnostics(sessionProject) {
@@ -826,10 +1011,14 @@ var PersistenceService = class {
826
1011
  sessionId: session.sessionId,
827
1012
  revision: session.revision
828
1013
  });
829
- if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
830
- sessionId: session.sessionId,
831
- revision: session.revision
832
- });
1014
+ if (session.uamFidelity === "unsupported") {
1015
+ const error = createUamFidelityUnsupportedError(session);
1016
+ return failure("authoring", startedAt, error, toSessionSnapshot(session, this.context.capabilities), {
1017
+ sessionId: session.sessionId,
1018
+ revision: session.revision,
1019
+ diagnostics: createUamFidelityDiagnostics(session.uamFidelityReport, error.message)
1020
+ });
1021
+ }
833
1022
  const committedPaths = [];
834
1023
  const failedPaths = [];
835
1024
  this.eventService.emit({
@@ -922,10 +1111,14 @@ var PersistenceService = class {
922
1111
  sessionId: session.sessionId,
923
1112
  revision: session.revision
924
1113
  });
925
- if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
926
- sessionId: session.sessionId,
927
- revision: session.revision
928
- });
1114
+ if (session.uamFidelity === "unsupported") {
1115
+ const error = createUamFidelityUnsupportedError(session);
1116
+ return failure("authoring", startedAt, error, toSessionSnapshot(session, this.context.capabilities), {
1117
+ sessionId: session.sessionId,
1118
+ revision: session.revision,
1119
+ diagnostics: createUamFidelityDiagnostics(session.uamFidelityReport, error.message)
1120
+ });
1121
+ }
929
1122
  const diagnostics = validationDiagnostics(session.project);
930
1123
  if (diagnostics.length > 0) return failure("authoring", startedAt, {
931
1124
  code: "materialize_validation_failed",
@@ -1308,6 +1501,167 @@ var EventService = class {
1308
1501
  };
1309
1502
  //#endregion
1310
1503
  //#region src/services/read-service.ts
1504
+ const DISPLAY_NODE_KINDS = new Set([
1505
+ "image",
1506
+ "text",
1507
+ "richText",
1508
+ "textInput",
1509
+ "component",
1510
+ "list",
1511
+ "tree",
1512
+ "graph",
1513
+ "group",
1514
+ "loader",
1515
+ "loader3D",
1516
+ "movieClip",
1517
+ "button",
1518
+ "label",
1519
+ "comboBox",
1520
+ "progressBar",
1521
+ "slider",
1522
+ "scrollBar"
1523
+ ]);
1524
+ const DISPLAY_NODE_FILTER_KEY_SET = new Set(BACKEND_DISPLAY_NODE_FILTER_FIELDS);
1525
+ const DISPLAY_NODE_FILTER_EXACT_STRINGS = [
1526
+ "name",
1527
+ "text",
1528
+ "title",
1529
+ "group",
1530
+ "url"
1531
+ ];
1532
+ const DISPLAY_NODE_FILTER_CONTAINS_STRINGS = [
1533
+ "nameContains",
1534
+ "textContains",
1535
+ "titleContains"
1536
+ ];
1537
+ const DISPLAY_NODE_FILTER_BOOLEANS = [
1538
+ "visible",
1539
+ "locked",
1540
+ "touchable",
1541
+ "hasGears",
1542
+ "hasRelations"
1543
+ ];
1544
+ const DISPLAY_NODE_QUERY_INPUT_KEYS = new Set([
1545
+ "sessionId",
1546
+ "selector",
1547
+ "filter",
1548
+ "limit"
1549
+ ]);
1550
+ function isPlainRecord(value) {
1551
+ return typeof value === "object" && value !== null && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1552
+ }
1553
+ function isValidDisplayNodeFilter(value) {
1554
+ if (!isPlainRecord(value)) return false;
1555
+ for (const key of Object.keys(value)) if (!DISPLAY_NODE_FILTER_KEY_SET.has(key)) return false;
1556
+ if (value.kind !== void 0 && (typeof value.kind !== "string" || !DISPLAY_NODE_KINDS.has(value.kind))) return false;
1557
+ for (const key of DISPLAY_NODE_FILTER_EXACT_STRINGS) {
1558
+ const entry = value[key];
1559
+ if (entry !== void 0 && (typeof entry !== "string" || entry.length > 1024)) return false;
1560
+ }
1561
+ for (const key of DISPLAY_NODE_FILTER_CONTAINS_STRINGS) {
1562
+ const entry = value[key];
1563
+ if (entry !== void 0 && (typeof entry !== "string" || !entry.length || entry.length > 1024)) return false;
1564
+ }
1565
+ if (value.resourceId !== void 0 && (typeof value.resourceId !== "string" || !value.resourceId.length || value.resourceId.length > 256)) return false;
1566
+ for (const key of DISPLAY_NODE_FILTER_BOOLEANS) {
1567
+ const entry = value[key];
1568
+ if (entry !== void 0 && typeof entry !== "boolean") return false;
1569
+ }
1570
+ return true;
1571
+ }
1572
+ function displayNodeText(node) {
1573
+ if (node.kind === "text" || node.kind === "richText" || node.kind === "textInput") return node.text;
1574
+ }
1575
+ function displayNodeTitle(node) {
1576
+ if (node.kind === "button" || node.kind === "label" || node.kind === "comboBox") return node.title;
1577
+ if (node.kind === "component" && node.instanceProperties && "title" in node.instanceProperties && typeof node.instanceProperties.title === "string") return node.instanceProperties.title;
1578
+ }
1579
+ function displayNodeGroup(node) {
1580
+ return "group" in node ? node.group : void 0;
1581
+ }
1582
+ function displayNodeResource(node) {
1583
+ if (node.kind === "image" || node.kind === "component" || node.kind === "movieClip") return {
1584
+ ...node.resource.packageId !== void 0 ? { packageId: node.resource.packageId } : {},
1585
+ resourceId: node.resource.resourceId
1586
+ };
1587
+ if ("src" in node && typeof node.src === "string" && node.src.length > 0) {
1588
+ const packageId = "packageId" in node && typeof node.packageId === "string" && node.packageId.length > 0 ? node.packageId : void 0;
1589
+ return {
1590
+ ...packageId !== void 0 ? { packageId } : {},
1591
+ resourceId: node.src
1592
+ };
1593
+ }
1594
+ }
1595
+ function displayNodeUrl(node) {
1596
+ if (node.kind === "loader" || node.kind === "loader3D") return node.url;
1597
+ }
1598
+ function matchesDisplayNodeFilter(node, filter) {
1599
+ if (!filter) return true;
1600
+ if (filter.kind !== void 0 && node.kind !== filter.kind) return false;
1601
+ if (filter.name !== void 0 && node.name !== filter.name) return false;
1602
+ if (filter.nameContains !== void 0 && !node.name.includes(filter.nameContains)) return false;
1603
+ if (filter.text !== void 0 || filter.textContains !== void 0) {
1604
+ const text = displayNodeText(node);
1605
+ if (typeof text !== "string") return false;
1606
+ if (filter.text !== void 0 && text !== filter.text) return false;
1607
+ if (filter.textContains !== void 0 && !text.includes(filter.textContains)) return false;
1608
+ }
1609
+ if (filter.title !== void 0 || filter.titleContains !== void 0) {
1610
+ const title = displayNodeTitle(node);
1611
+ if (typeof title !== "string") return false;
1612
+ if (filter.title !== void 0 && title !== filter.title) return false;
1613
+ if (filter.titleContains !== void 0 && !title.includes(filter.titleContains)) return false;
1614
+ }
1615
+ if (filter.group !== void 0) {
1616
+ const group = displayNodeGroup(node);
1617
+ if (group === void 0 || group !== filter.group) return false;
1618
+ }
1619
+ if (filter.resourceId !== void 0) {
1620
+ const resource = displayNodeResource(node);
1621
+ if (!resource || resource.resourceId !== filter.resourceId) return false;
1622
+ }
1623
+ if (filter.url !== void 0) {
1624
+ const url = displayNodeUrl(node);
1625
+ if (typeof url !== "string" || url !== filter.url) return false;
1626
+ }
1627
+ if (filter.visible !== void 0 && node.visible !== filter.visible) return false;
1628
+ if (filter.locked !== void 0 && node.locked !== filter.locked) return false;
1629
+ if (filter.touchable !== void 0 && node.touchable !== filter.touchable) return false;
1630
+ if (filter.hasGears !== void 0 && node.gears.length > 0 !== filter.hasGears) return false;
1631
+ if (filter.hasRelations !== void 0 && node.relations.length > 0 !== filter.hasRelations) return false;
1632
+ return true;
1633
+ }
1634
+ function toDisplayNodeCandidate(node, index) {
1635
+ const group = displayNodeGroup(node);
1636
+ const text = displayNodeText(node);
1637
+ const title = displayNodeTitle(node);
1638
+ const resource = displayNodeResource(node);
1639
+ const url = displayNodeUrl(node);
1640
+ return {
1641
+ id: node.id,
1642
+ name: node.name,
1643
+ kind: node.kind,
1644
+ index,
1645
+ position: {
1646
+ x: node.position.x,
1647
+ y: node.position.y
1648
+ },
1649
+ size: {
1650
+ width: node.size.width,
1651
+ height: node.size.height
1652
+ },
1653
+ visible: node.visible,
1654
+ locked: node.locked,
1655
+ touchable: node.touchable,
1656
+ ...group !== void 0 && group.length > 0 ? { group } : {},
1657
+ ...text !== void 0 ? { text } : {},
1658
+ ...title !== void 0 ? { title } : {},
1659
+ ...resource !== void 0 ? { resource } : {},
1660
+ ...url !== void 0 ? { url } : {},
1661
+ gearCount: node.gears.length,
1662
+ relationCount: node.relations.length
1663
+ };
1664
+ }
1311
1665
  /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
1312
1666
  function queryResponseProblem(value, limits = BACKEND_ENTITY_QUERY_LIMITS) {
1313
1667
  const pending = [{
@@ -1533,6 +1887,53 @@ var ReadService = class {
1533
1887
  }
1534
1888
  return respond(entity);
1535
1889
  }
1890
+ queryDisplayNodes(input) {
1891
+ const startedAt = Date.now();
1892
+ const sessionId = typeof input?.sessionId === "string" ? input.sessionId : "";
1893
+ const session = this.getSessionState(sessionId);
1894
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(sessionId));
1895
+ const meta = {
1896
+ sessionId: session.sessionId,
1897
+ revision: session.revision
1898
+ };
1899
+ const reject = (reason) => failure("read", startedAt, {
1900
+ code: "entity_query_failed",
1901
+ sessionId: session.sessionId,
1902
+ reason,
1903
+ message: `Display node query failed: ${reason}.`
1904
+ }, void 0, meta);
1905
+ if (!isPlainRecord(input) || Object.keys(input).some((key) => !DISPLAY_NODE_QUERY_INPUT_KEYS.has(key))) return reject("invalid_query");
1906
+ const selector = input.selector;
1907
+ if (!isPlainRecord(selector) || Object.keys(selector).length !== 2 || ["packageId", "componentResourceId"].some((key) => !Object.hasOwn(selector, key) || typeof selector[key] !== "string" || !selector[key].length || selector[key].length > 256)) return reject("invalid_query");
1908
+ const limit = input.limit ?? BACKEND_DISPLAY_NODE_QUERY_LIMITS.defaultLimit;
1909
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > BACKEND_DISPLAY_NODE_QUERY_LIMITS.maxLimit) return reject("invalid_query");
1910
+ if (input.filter !== void 0 && !isValidDisplayNodeFilter(input.filter)) return reject("invalid_query");
1911
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
1912
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
1913
+ const resources = packages[0].resources.filter((resource) => resource.id === selector.componentResourceId);
1914
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
1915
+ const resource = resources[0];
1916
+ if (resource.kind !== "component") return reject("not_found");
1917
+ let totalMatched = 0;
1918
+ const nodes = [];
1919
+ for (const [index, node] of resource.component.displayList.entries()) {
1920
+ if (!matchesDisplayNodeFilter(node, input.filter)) continue;
1921
+ totalMatched += 1;
1922
+ if (nodes.length < limit) nodes.push(toDisplayNodeCandidate(node, index));
1923
+ }
1924
+ const data = {
1925
+ ...meta,
1926
+ selector: {
1927
+ packageId: selector.packageId,
1928
+ componentResourceId: selector.componentResourceId
1929
+ },
1930
+ totalMatched,
1931
+ truncated: totalMatched > nodes.length,
1932
+ nodes
1933
+ };
1934
+ const problem = queryResponseProblem(data, BACKEND_DISPLAY_NODE_QUERY_LIMITS);
1935
+ return problem ? reject(problem) : success("read", startedAt, structuredClone(data), meta);
1936
+ }
1536
1937
  resolveReadSession(input, startedAt) {
1537
1938
  if (!input || typeof input.sessionId !== "string" || !input.sessionId.length || input.sessionId.length > 256 || input.expectedRevision !== void 0 && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0)) return readFailure(startedAt, typeof input?.sessionId === "string" ? input.sessionId : "", "invalid_query");
1538
1939
  const session = this.getSessionState(input.sessionId);
@@ -1564,6 +1965,7 @@ var ReadService = class {
1564
1965
  dirty: session.dirty,
1565
1966
  lastSavedRevision: session.lastSavedRevision,
1566
1967
  uamFidelity: session.uamFidelity,
1968
+ ...session.uamFidelity === "unsupported" && session.uamFidelityReport ? { uamFidelityReport: session.uamFidelityReport } : {},
1567
1969
  readComplete: session.readComplete,
1568
1970
  readDiagnostics: session.readDiagnostics,
1569
1971
  project: {
@@ -1686,17 +2088,8 @@ function createProjectReaderFileSystem(fileSystem, projectRoot) {
1686
2088
  }
1687
2089
  };
1688
2090
  }
1689
- async function hasFullUamFidelity(document, project) {
1690
- const sourceFiles = /* @__PURE__ */ new Map();
1691
- const materializedFiles = /* @__PURE__ */ new Map();
1692
- const sourceDirectories = /* @__PURE__ */ new Set();
1693
- const materializedDirectories = /* @__PURE__ */ new Set();
1694
- try {
1695
- await Promise.all([new ProjectWriter(createCaptureFileSystem(sourceFiles, sourceDirectories)).write(document, "Project.fairy"), new ProjectWriter(createCaptureFileSystem(materializedFiles, materializedDirectories)).write(materializeUamProject(project), "Project.fairy")]);
1696
- } catch {
1697
- return false;
1698
- }
1699
- return capturedFilesEqual(sourceFiles, materializedFiles) && capturedDirectoriesEqual(sourceDirectories, materializedDirectories);
2091
+ function extractFairyFileName(fairyPath) {
2092
+ return fairyPath.replace(/\\/g, "/").split("/").at(-1) || "Project.fairy";
1700
2093
  }
1701
2094
  var RuntimeService = class {
1702
2095
  constructor(context, cacheService, eventService, sessionOperations) {
@@ -1767,6 +2160,11 @@ var RuntimeService = class {
1767
2160
  if (!read.document) throw createProjectReadFailure(read.diagnostics[0]?.message);
1768
2161
  const document = read.document;
1769
2162
  const project = liftDocumentToUamProject(document);
2163
+ const fidelity = await evaluateUamFidelity(document, project, {
2164
+ readComplete: read.complete,
2165
+ readDiagnostics: read.diagnostics,
2166
+ fairyFileName: extractFairyFileName(fairyPath)
2167
+ });
1770
2168
  const session = {
1771
2169
  sessionId,
1772
2170
  fairyPath,
@@ -1778,7 +2176,8 @@ var RuntimeService = class {
1778
2176
  project,
1779
2177
  readDiagnostics: read.diagnostics,
1780
2178
  readComplete: read.complete,
1781
- uamFidelity: read.complete && await hasFullUamFidelity(document, project) ? "full" : "unsupported",
2179
+ uamFidelity: fidelity.uamFidelity,
2180
+ ...fidelity.uamFidelity === "unsupported" ? { uamFidelityReport: fidelity.report } : {},
1782
2181
  revision: 0,
1783
2182
  lastSavedRevision: 0,
1784
2183
  pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
@@ -1943,6 +2342,7 @@ const BACKEND_METHODS = [
1943
2342
  "getSession",
1944
2343
  "getProjectOutline",
1945
2344
  "queryEntity",
2345
+ "queryDisplayNodes",
1946
2346
  "readSessionState",
1947
2347
  "readResourceBytes",
1948
2348
  "validateSession",
@@ -1965,7 +2365,7 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
1965
2365
  function createCapabilities(atomicSave = false, caseSensitivePaths = false, maxSessions = 32, idleSessionTimeoutMs = 30 * 6e4) {
1966
2366
  return {
1967
2367
  contractVersion: BACKEND_CONTRACT_VERSION,
1968
- capabilitySchemaVersion: 15,
2368
+ capabilitySchemaVersion: 16,
1969
2369
  transactionKernelOwner: "@openfairygui/core",
1970
2370
  appSeamOwner: "@openfairygui/functions",
1971
2371
  runtimeOwner: "@openfairygui/backend",
@@ -1988,6 +2388,13 @@ function createCapabilities(atomicSave = false, caseSensitivePaths = false, maxS
1988
2388
  sourceBytes: false,
1989
2389
  limits: BACKEND_ENTITY_QUERY_LIMITS
1990
2390
  },
2391
+ displayNodeQuery: {
2392
+ scope: "component",
2393
+ filterFields: BACKEND_DISPLAY_NODE_FILTER_FIELDS,
2394
+ projection: "summary",
2395
+ sourceBytes: false,
2396
+ limits: BACKEND_DISPLAY_NODE_QUERY_LIMITS
2397
+ },
1991
2398
  sessionState: {
1992
2399
  sourceBytes: false,
1993
2400
  limits: BACKEND_SESSION_READ_LIMITS.model
@@ -2150,6 +2557,9 @@ var BackendRuntime = class {
2150
2557
  queryEntity(input) {
2151
2558
  return this.readService.queryEntity(input);
2152
2559
  }
2560
+ queryDisplayNodes(input) {
2561
+ return this.readService.queryDisplayNodes(input);
2562
+ }
2153
2563
  readSessionState(input) {
2154
2564
  return this.readService.readSessionState(input);
2155
2565
  }
@@ -2186,4 +2596,4 @@ var BackendRuntime = class {
2186
2596
  }
2187
2597
  };
2188
2598
  //#endregion
2189
- export { ProjectWriteTransactionError as a, BACKEND_CAPABILITY_SCHEMA_VERSION as c, BACKEND_TRANSACTION_PREVIEW_LIMITS as i, BACKEND_COMPATIBILITY_POLICY as l, BACKEND_ENTITY_QUERY_LIMITS as n, normalizeComparablePath as o, BACKEND_SESSION_READ_LIMITS as r, resolveFairyPath as s, BackendRuntime as t, BACKEND_CONTRACT_VERSION as u };
2599
+ export { BACKEND_SESSION_READ_LIMITS as a, normalizeComparablePath as c, BACKEND_COMPATIBILITY_POLICY as d, BACKEND_CONTRACT_VERSION as f, BACKEND_ENTITY_QUERY_LIMITS as i, resolveFairyPath as l, BACKEND_DISPLAY_NODE_FILTER_FIELDS as n, BACKEND_TRANSACTION_PREVIEW_LIMITS as o, BACKEND_DISPLAY_NODE_QUERY_LIMITS as r, ProjectWriteTransactionError as s, BackendRuntime as t, BACKEND_CAPABILITY_SCHEMA_VERSION as u };
package/docs/workflow.md CHANGED
@@ -21,7 +21,7 @@ All CLI JSON uses `{schemaVersion:1,command,success:true,result}` or `{schemaVer
21
21
  ## Edit safely
22
22
 
23
23
  1. Read capabilities. Existing projects use openSession (with host authorization and a lifetime lock); openProjectSession accepts a host-supplied authoritative UAM, not a shortcut around lossy file-session guards.
24
- 2. Read getProjectOutline to discover exact identities, then queryEntity for the relevant current properties and actual revision. Capabilities list the supported read.entityQuery.kinds: project, package, resource, component, displayNode, controller and transition. Project queries use target {kind:"project"} without a selector; package queries use {kind:"package",selector:{packageId}}. Both return identity and complete entity.properties.settings. Controllers use packageId + componentResourceId + controllerName; transitions use packageId + componentResourceId + transitionName. Names are exact and component-scoped; duplicates fail as ambiguous. Controller snapshots include pages/actions; transition snapshots include items. Gears are already included in displayNode snapshots. Fixed projections exclude source bytes; budget failures require host inspection.
24
+ 2. Read getProjectOutline to discover exact identities, use queryDisplayNodes when filtering candidate display nodes inside a component by modeled properties (kind, name, text, title, group, resourceId, url, visibility/lock/touchable or gear/relation presence; default limit 50, max 200), then call queryEntity when full entity properties are needed at the actual revision. Capabilities list read.displayNodeQuery and read.entityQuery.kinds: project, package, resource, component, displayNode, controller and transition. Project queries use target {kind:"project"} without a selector; package queries use {kind:"package",selector:{packageId}}. Both return identity and complete entity.properties.settings. Controllers use packageId + componentResourceId + controllerName; transitions use packageId + componentResourceId + transitionName. Names are exact and component-scoped; duplicates fail as ambiguous. Controller snapshots include pages/actions; transition snapshots include items. Gears are already included in displayNode snapshots. Fixed projections exclude source bytes; budget failures require host inspection. Commits still require exact IDs.
25
25
  3. Read the operation and method schemas. Plan the smallest authorized batch using current identifiers and expectedRevision.
26
26
  4. preflightTransaction executes on an isolated snapshot and discards it. Inspect projectedRevision, impact.entities (exact identities and changed fields, including reference normalization), impact.files (ProjectWriter model diff, not a disk write plan) and persistence.nextAction. The diff starts at the current revision, not the last save. It contains no source bytes. Summary overflow or serialization failure returns transaction_preview_failed without a partial result. No revision is reserved; writeVerified is always false. It does not save files or guarantee later apply/save/publish.
27
27
  5. Only when authorized, applyTransaction with the planned batch and expectedRevision. On stale_write, refresh and replan; never blindly substitute a newer revision.
@@ -36,7 +36,7 @@ updateController and updateTransition replace complete snapshots, not partial pa
36
36
 
37
37
  ## Consume the committed session state
38
38
 
39
- For complete public UAM consumption, use readSessionState({sessionId, expectedRevision?}); use queryEntity for targeted properties. The detached model excludes only asset resources' primary sourceBytes, retaining sourcePath and JSON extensions. It includes revision, dirty, lastSavedRevision, readComplete, readDiagnostics and uamFidelity. Only this read-model output schema accepts unnamed object fields; transaction input contracts remain unchanged.
39
+ For complete public UAM consumption, use readSessionState({sessionId, expectedRevision?}); use queryEntity for targeted properties. The detached model excludes only asset resources' primary sourceBytes, retaining sourcePath and JSON extensions. It includes revision, dirty, lastSavedRevision, readComplete, readDiagnostics, uamFidelity and (when uamFidelity is unsupported) a bounded uamFidelityReport. Only this read-model output schema accepts unnamed object fields; transaction input contracts remain unchanged.
40
40
 
41
41
  Read each asset with readResourceBytes({sessionId, expectedRevision: state.revision, selector:{packageId,resourceId}}). Bytes are detached Uint8Array values in the SDK and integer arrays in MCP, limited to the primary file already held in memory. There is no disk hydration or auxiliary-file discovery. Components are unsupported; unavailable bytes produce session_read_failed with reason bytes_unavailable.
42
42
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfairygui/backend",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "description": "FairyGUI Headless Authoring SDK — stateful backend runtime and session services.",
5
5
  "author": "OpenFairyGUI Contributors",
6
6
  "license": "MIT",
@@ -65,12 +65,11 @@
65
65
  "runtime"
66
66
  ],
67
67
  "dependencies": {
68
- "@openfairygui/functions": "0.7.1",
69
- "@openfairygui/core": "0.7.1"
68
+ "@openfairygui/core": "0.8.0",
69
+ "@openfairygui/functions": "0.8.0"
70
70
  },
71
71
  "devDependencies": {
72
72
  "ava": "^7.0.0",
73
- "tsx": "^4.0.0",
74
73
  "@openfairygui/test-utils": "0.3.0"
75
74
  },
76
75
  "scripts": {