@flexkit/studio 0.2.34 → 0.2.36

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 (110) hide show
  1. package/dist/{activity-nav-button-ZHQOZBCC.js → activity-nav-button-KOOMUTOW.js} +2 -2
  2. package/dist/{activity-nav-button-ZHQOZBCC.js.map → activity-nav-button-KOOMUTOW.js.map} +1 -1
  3. package/dist/chat-page-NDVHLH5Q.js +4 -0
  4. package/dist/chat-page-NDVHLH5Q.js.map +1 -0
  5. package/dist/chunk-27JTWTU6.js +2 -0
  6. package/dist/{chunk-3OBELKJU.js.map → chunk-27JTWTU6.js.map} +1 -1
  7. package/dist/chunk-2PBDHGRR.js +2 -0
  8. package/dist/chunk-2PBDHGRR.js.map +1 -0
  9. package/dist/{chunk-6AJRQSFO.js → chunk-474MQNDK.js} +3 -3
  10. package/dist/{chunk-6AJRQSFO.js.map → chunk-474MQNDK.js.map} +1 -1
  11. package/dist/{chunk-XYFS6X74.js → chunk-CGMKGENV.js} +2 -2
  12. package/dist/{chunk-XYFS6X74.js.map → chunk-CGMKGENV.js.map} +1 -1
  13. package/dist/chunk-FF5EBXYN.js +30 -0
  14. package/dist/chunk-FF5EBXYN.js.map +1 -0
  15. package/dist/chunk-FJS4SN3K.js +378 -0
  16. package/dist/chunk-FJS4SN3K.js.map +1 -0
  17. package/dist/chunk-FXUD4JRG.js +2 -0
  18. package/dist/chunk-FXUD4JRG.js.map +1 -0
  19. package/dist/{chunk-HR4QZ5TD.js → chunk-GTR4M2BQ.js} +3 -3
  20. package/dist/chunk-GTR4M2BQ.js.map +1 -0
  21. package/dist/{chunk-RBGXXVF4.js → chunk-HXPETSXC.js} +3 -3
  22. package/dist/{chunk-RBGXXVF4.js.map → chunk-HXPETSXC.js.map} +1 -1
  23. package/dist/{chunk-WU2KCXBC.js → chunk-L5Z56DDM.js} +2 -2
  24. package/dist/{chunk-WU2KCXBC.js.map → chunk-L5Z56DDM.js.map} +1 -1
  25. package/dist/{chunk-7JA6SI5H.js → chunk-LTM3MW2D.js} +2 -2
  26. package/dist/{chunk-7JA6SI5H.js.map → chunk-LTM3MW2D.js.map} +1 -1
  27. package/dist/{chunk-36DLIVZF.js → chunk-LVKBKU6Q.js} +2 -2
  28. package/dist/{chunk-36DLIVZF.js.map → chunk-LVKBKU6Q.js.map} +1 -1
  29. package/dist/chunk-LXLEUEWT.js +2 -0
  30. package/dist/chunk-LXLEUEWT.js.map +1 -0
  31. package/dist/chunk-MHEFVYKP.js +2 -0
  32. package/dist/chunk-MHEFVYKP.js.map +1 -0
  33. package/dist/{chunk-YC7PBLTK.js → chunk-NKDQQHCL.js} +2 -2
  34. package/dist/{chunk-YC7PBLTK.js.map → chunk-NKDQQHCL.js.map} +1 -1
  35. package/dist/chunk-OJ4RI6IQ.js +4 -0
  36. package/dist/{chunk-2FCVATRT.js.map → chunk-OJ4RI6IQ.js.map} +1 -1
  37. package/dist/chunk-PLCI2RJA.js +3 -0
  38. package/dist/chunk-PLCI2RJA.js.map +1 -0
  39. package/dist/{chunk-PSECMZJC.js → chunk-SOA2F7Z6.js} +3 -3
  40. package/dist/{chunk-PSECMZJC.js.map → chunk-SOA2F7Z6.js.map} +1 -1
  41. package/dist/{chunk-VRDTHLA3.js → chunk-TWA6OG5U.js} +3 -3
  42. package/dist/{chunk-VRDTHLA3.js.map → chunk-TWA6OG5U.js.map} +1 -1
  43. package/dist/{chunk-CHNQZU2P.js → chunk-VIBGMCLS.js} +2 -2
  44. package/dist/{chunk-CHNQZU2P.js.map → chunk-VIBGMCLS.js.map} +1 -1
  45. package/dist/{chunk-DFBG7PUJ.js → chunk-YJ4NWJCC.js} +4 -4
  46. package/dist/{chunk-DFBG7PUJ.js.map → chunk-YJ4NWJCC.js.map} +1 -1
  47. package/dist/entry-XHH3NKN2.js +2 -0
  48. package/dist/{entry-APJ4V7PW.js.map → entry-XHH3NKN2.js.map} +1 -1
  49. package/dist/index.d.ts +5 -1
  50. package/dist/index.js +7 -7
  51. package/dist/index.js.map +1 -1
  52. package/dist/list-R64THLZD.js +2 -0
  53. package/dist/{list-7WFALOUT.js.map → list-R64THLZD.js.map} +1 -1
  54. package/dist/{list-7IHDJM54.js → list-XIE55HYD.js} +3 -3
  55. package/dist/{list-7IHDJM54.js.map → list-XIE55HYD.js.map} +1 -1
  56. package/dist/{pages-BV3ABSFQ.js → pages-OWXBU64L.js} +3 -3
  57. package/dist/{pages-BV3ABSFQ.js.map → pages-OWXBU64L.js.map} +1 -1
  58. package/dist/{plugin-pages-OWGJPPWV.js → plugin-pages-JBJQHBIN.js} +2 -2
  59. package/dist/{plugin-pages-OWGJPPWV.js.map → plugin-pages-JBJQHBIN.js.map} +1 -1
  60. package/dist/{project-selector-V5N2724B.js → project-selector-L2WZ3MB5.js} +2 -2
  61. package/dist/{project-selector-V5N2724B.js.map → project-selector-L2WZ3MB5.js.map} +1 -1
  62. package/dist/record-links-BEKOPDDR.js +2 -0
  63. package/dist/{record-links-3P3XSW66.js.map → record-links-BEKOPDDR.js.map} +1 -1
  64. package/dist/{root-F2GTYDJM.js → root-B5XP6VYU.js} +2 -2
  65. package/dist/{root-F2GTYDJM.js.map → root-B5XP6VYU.js.map} +1 -1
  66. package/dist/{root-NIL2UHKS.js → root-DUQULYRX.js} +2 -2
  67. package/dist/{root-NIL2UHKS.js.map → root-DUQULYRX.js.map} +1 -1
  68. package/dist/{root-GBBZ3DX5.js → root-I22KNOFC.js} +3 -3
  69. package/dist/{root-GBBZ3DX5.js.map → root-I22KNOFC.js.map} +1 -1
  70. package/dist/{root-J62PBDZ2.js → root-O4DMQLEH.js} +2 -2
  71. package/dist/{root-J62PBDZ2.js.map → root-O4DMQLEH.js.map} +1 -1
  72. package/dist/root-RUOT5OSO.js +23 -0
  73. package/dist/{root-RGZZYETM.js.map → root-RUOT5OSO.js.map} +1 -1
  74. package/dist/root-VLD6GNZL.js +14 -0
  75. package/dist/root-VLD6GNZL.js.map +1 -0
  76. package/dist/{search-IIGNCQEZ.js → search-4UQR6ENH.js} +2 -2
  77. package/dist/{search-IIGNCQEZ.js.map → search-4UQR6ENH.js.map} +1 -1
  78. package/dist/{skills-pages-T52MF4DO.js → skills-pages-VUIOUEYQ.js} +2 -2
  79. package/dist/{skills-pages-T52MF4DO.js.map → skills-pages-VUIOUEYQ.js.map} +1 -1
  80. package/dist/source-L54C4T3X.js +2 -0
  81. package/dist/{source-IJAAJDGW.js.map → source-L54C4T3X.js.map} +1 -1
  82. package/package.json +2 -2
  83. package/dist/chat-page-7XT4K75G.js +0 -4
  84. package/dist/chat-page-7XT4K75G.js.map +0 -1
  85. package/dist/chunk-2FCVATRT.js +0 -4
  86. package/dist/chunk-3OBELKJU.js +0 -2
  87. package/dist/chunk-4PUMSUJL.js +0 -30
  88. package/dist/chunk-4PUMSUJL.js.map +0 -1
  89. package/dist/chunk-ERDARDGB.js +0 -2
  90. package/dist/chunk-ERDARDGB.js.map +0 -1
  91. package/dist/chunk-HR4QZ5TD.js.map +0 -1
  92. package/dist/chunk-KO2JLLUJ.js +0 -2
  93. package/dist/chunk-KO2JLLUJ.js.map +0 -1
  94. package/dist/chunk-PC5Z37LT.js +0 -378
  95. package/dist/chunk-PC5Z37LT.js.map +0 -1
  96. package/dist/chunk-U6NFYYTF.js +0 -2
  97. package/dist/chunk-U6NFYYTF.js.map +0 -1
  98. package/dist/chunk-U6VZY3V2.js +0 -3
  99. package/dist/chunk-U6VZY3V2.js.map +0 -1
  100. package/dist/chunk-XMOSCJOI.js +0 -2
  101. package/dist/chunk-XMOSCJOI.js.map +0 -1
  102. package/dist/chunk-YDVO6XWD.js +0 -2
  103. package/dist/chunk-YDVO6XWD.js.map +0 -1
  104. package/dist/entry-APJ4V7PW.js +0 -2
  105. package/dist/list-7WFALOUT.js +0 -2
  106. package/dist/record-links-3P3XSW66.js +0 -2
  107. package/dist/root-LYRL7VPN.js +0 -14
  108. package/dist/root-LYRL7VPN.js.map +0 -1
  109. package/dist/root-RGZZYETM.js +0 -23
  110. package/dist/source-IJAAJDGW.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/graphql-client/queries.ts","../src/graphql-client/refetch-entity-lists.ts","../src/graphql-client/use-entity-query.ts"],"names":["FULL_ASSET_CONNECTION_LIMIT","LIST_ASSET_CONNECTION_LIMIT","NESTED_RELATIONSHIP_LIMIT","stringTypes","temporalTypes","assetFields","assetFieldsWithoutLqip","listAssetPreviewFields","isAssetRelationshipAttribute","attribute","getAttributeScope","hasOrderedAssetConnectionProperties","entity","tagSchema","isAssetAttribute","getOrderedAssetsFromConnection","connection","typedConnection","edges","totalCount","result","edge","index","a","b","getKnownAssetSortOrders","assets","asset","unwrapNode","value","getAssetConnectionNodeFields","includeLqip","previewOnly","getAssetConnectionSelection","attributeName","includeProperties","first","propertiesSelection","nodeFields","connectionArguments","getConnectionCount","getEntityCount","results","entityNamePlural","total","getConnectionCountSelection","fieldName","whereArgument","getTopLevelCountSelection","includeCount","countMode","getDisplayAttributeSelection","primaryAttribute","scope","schema","forList","additionalScope","field","nestedEntity","find","propEq","fieldAttribute","localAttributeQuery","getFullRelatedEntityAttributesSelection","relatedEntity","relatedAcc","relatedAttribute","relationshipEntity","relationshipAttribute","getAttributesByName","attributes","attributesByName","shouldSelectAttributeInList","getSortNotNullWhere","sort","primarySort","sortAttributeName","sortAttribute","getEntityQuery","options","requestedSelection","selection","filters","entitySchema","getEntitySchema","entityName","displayAttribute","getDisplayAttribute","heading","operationName","getOperationEntityName","globalAttributesList","getAttributeListByScope","imageAttributes","getImageAttributes","localAttributes","defaultScopedAttr","acc","scopedAttribute","localAttributesList","imageFieldsSelection","imageAttributesList","relationshipAttributesList","primarySelection","relatedLimit","attributesNameList","mapQueryResult","count","items","sliceFirstThreeItems","values","primaryAttributeName","item","scopedNode","mappedQueryResult","_id","updatedAt","globalAttributes","relationshipAttributes","relatedEntityName","localValue","primaryAttributeScope","relatedItems","relatedNode","primaryScopedNode","mapQueryResultForFormFields","attributeSchema","localAttribute","getValueByScope","rawValue","aggregateCount","attr","option","getEntityUpdateMutation","entityId","originalData","dataToMutate","pluralizedEntityName","capitalize","data","filterOutInvalidAttributes","globalAttributesUpdate","localAttributesUpdate","imageAttributesUpdate","relationshipAttributesUpdate","responseType","attributeNamesList","formatResponseFieldsForMutation","nonUpdatableAttributes","omit","pick","type","attributeType","schemaAttributes","operation","toPairs","valueToStringify","typedValue","stringifyValue","getLinkedAssetId","attributeValue","nextId","originalId","disconnect","stringifyStringLiteral","connect","imageAttributesCreate","assetId","dataType","inputType","relationship","orderedAssetRelationshipUpdate","disconnectIds","uniq","idsToConnect","node","originalValue","orderedConnections","orderedConnectionIds","originalSortOrderById","getRelationshipSortOrderById","disconnectedIds","newConnections","reorderedConnections","originalSortOrder","getOrderedAssetDisconnectString","getOrderedAssetConnectString","reorder","getOrderedAssetReorderString","fieldValue","sortOrder","ids","disconnectString","connections","getOrderedAssetConnectNodes","connectString","updateString","globalAttributesArray","localAttributesArray","relationshipAttributesArray","fields","relationshipMode","relationshipEntityName","relationshipEntityAttributes","list","multipleRelationshipAttributes","str","getEntityDeleteMutation","idList","localAttributesDelete","getEntityDeleteWhere","localIds","id","idFilter","getEntityCreateMutation","entityData","_options","localAttributesCreate","relationshipAttributesCreate","defaultScope","isMultipleRelationship","hasRelationships","connectNodes","getRelatedItemsQuery","queryEntityName","getEntityAssetConnectionQuery","normalizedEntityName","assetSchema","getLocalAttributeIdsFromUpdateResponse","response","updateKey","payload","entities","nodeId","refetchTimer","pendingQueryNames","pendingResolvers","listeners","removalListeners","patchListeners","getEntityListQueryName","entityNameOrPlural","byPlural","byName","plural","subscribeEntityListRefetch","listener","subscribeEntityListRemoval","subscribeEntityListPatch","scheduleEntityListRemoval","apolloClient","queryName","entityIds","scheduleEntityListRefetch","scheduleEntityListPatch","patches","nextPatches","patch","_apolloClient","resolve","reject","names","resolvers","finish","error","fail","useEntityQuery","variables","isForm","fetchPolicy","setResult","useState","isLoadingMore","setIsLoadingMore","isReloading","setIsReloading","unsupportedTotalCount","setUnsupportedTotalCount","isLoadingMoreRef","useRef","isReloadingRef","nextOffsetRef","syncedQueryKeyRef","pendingQueryKeyRef","totalCountField","queryDocument","useMemo","gql","fetchMoreDocument","schemaErrorMessage","setSchemaErrorMessage","useGraphQLError","isLoading","fetchNextPage","refetch","networkStatus","useQuery","fetchNextPageRef","refetchRef","fetchMoreDocumentRef","previousNetworkStatusRef","variablesRef","isMissingTotalCountField","isMissingGraphQLFieldError","shouldFallbackToAggregate","effectiveError","isTotalCountFallbackLoading","serverError","getServerError","schemaMismatchMessage","getGraphQLSchemaMismatchMessage","isProjectDisabled","isProjectReadOnly","responseBody","parseErrorBody","useEffect","fetchMore","useCallback","args","limit","offset","res","mappedFetchMoreResults","mapResults","pageLength","prevRows","merged","uniqBy","prop","fetchError","reload","preserve","queryKey","mapped","getVariablesOffset","previousStatus","NetworkStatus","listQueryName","unsubscribeRefetch","queryNames","unsubscribeRemoval","prev","nextResults","row","rowId","removedCount","unsubscribePatch","applyEntityListPatches","patchById","didPatch","sortEntityListResults","primarySortEntry","sortField","sortDirection","direction","left","right","leftValue","rightValue","leftText","rightText"],"mappings":"8aAqCaA,EAAAA,CAA8B,EAAA,CAErCC,EAAAA,CAA8B,CAAA,CAE9BC,EAAAA,CAA4B,CAAA,CAE5BC,EAAAA,CAA0B,CAAC,KAAM,QAAQ,CAAA,CACzCC,EAAAA,CAA4B,CAAC,MAAA,CAAQ,UAAA,CAAY,UAAA,CAAY,MAAM,EACnEC,EAAAA,CAAc,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAAA,CAAA,CAUdC,EAAAA,CAAyB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAA,CAAA,CASzBC,EAAAA,CAAyB,CAAA;AAAA;AAAA,aAAA,EAkB/B,SAASC,EAAAA,CAA6BC,CAAAA,CAA2C,CAC/E,OAAKA,CAAAA,CAKHC,EAAkBD,CAAS,CAAA,GAAM,gBAC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CAA4DpT,CAAAA,CAAcgC,CAAAA,CAAoB,CACrG,GAAI,CAAC,KAAA,CAAM,OAAA,CAAQA,CAAI,CAAA,EAAKA,CAAAA,CAAK,MAAA,GAAW,EAC1C,OAAOhC,CAAAA,CAGT,GAAM,CAACiC,CAAW,CAAA,CAAID,EAEtB,GAAI,CAACC,CAAAA,EAAe,OAAOA,CAAAA,EAAgB,QAAA,CACzC,OAAOjC,CAAAA,CAGT,GAAM,CAACqT,CAAgB,CAAA,CAAI,MAAA,CAAO,OAAA,CAAQpR,CAAyC,CAAA,CAC7E,CAACqR,CAAAA,CAAWC,CAAa,CAAA,CAAIF,CAAAA,EAAoB,EAAC,CAExD,GAAI,CAACC,CAAAA,EAAcC,CAAAA,GAAkB,KAAA,EAASA,IAAkB,MAAA,CAC9D,OAAOvT,CAAAA,CAGT,IAAMwT,CAAAA,CAAYD,CAAAA,GAAkB,OAAS,EAAA,CAAK,CAAA,CAElD,OAAO,CAAC,GAAGvT,CAAO,EAAE,IAAA,CAAK,CAACyT,CAAAA,CAAMC,CAAAA,GAAU,CACxC,IAAMC,EAAYF,CAAAA,CAAKH,CAAS,CAAA,CAC1BM,CAAAA,CAAaF,CAAAA,CAAMJ,CAAS,EAC5BO,CAAAA,CAAW,OAAOF,CAAAA,EAAc,QAAA,CAAWA,CAAAA,CAAY,EAAA,CACvDG,EAAY,OAAOF,CAAAA,EAAe,QAAA,CAAWA,CAAAA,CAAa,EAAA,CAEhE,OAAOC,CAAAA,CAAS,aAAA,CAAcC,CAAS,CAAA,CAAIN,CAC7C,CAAC,CACH","file":"chunk-PC5Z37LT.js","sourcesContent":["import { find, omit, pick, propEq, toPairs, uniq } from 'ramda';\nimport { getAttributeScope } from '../core/attribute-scope';\nimport { getDisplayAttribute } from '../core/get-display-attribute';\nimport { assetSchema } from '../entities/assets-schema';\nimport { tagSchema } from '../entities/tags-schema';\nimport type { User } from '../auth/types';\nimport type { Attribute, Entity, DataType, Schema, ScopeType, MultipleRelationshipConnection } from '../core/types';\nimport type {\n AttributeValue,\n EntityItem,\n EntityQueryResults,\n FormEntityItem,\n FormFieldValue,\n MappedEntityItem,\n MappedEntityQueryResults,\n MappedFormEntityQueryResults,\n EntityQueryResult,\n ImageValue,\n OrderedAssetValue,\n EntityQuerySelection,\n} from './types';\n\ntype EntityQuery = {\n queryEntityName: string;\n query: string;\n};\n\nexport type EntityQueryCountMode = 'aggregate' | 'total';\nexport type SortNotNullWhere = {\n NOT: {\n [attributeName: string]: {\n eq: null;\n };\n };\n};\n\n/** Page size for asset connections in forms (galleries, ordered assets). */\nexport const FULL_ASSET_CONNECTION_LIMIT = 25;\n/** List grids render at most 3 stacked asset thumbnails (plus a \"+N\" badge). */\nconst LIST_ASSET_CONNECTION_LIMIT = 3;\n/** Grids preview at most 3 nested relationship values (sliceFirstThreeItems). */\nconst NESTED_RELATIONSHIP_LIMIT = 3;\n\nconst stringTypes: DataType[] = ['id', 'string'];\nconst temporalTypes: DataType[] = ['date', 'datetime', 'duration', 'time'];\nconst assetFields = `_id\n originalFilename\n mimeType\n path\n url\n size\n height\n width\n lqip`;\n\nconst assetFieldsWithoutLqip = `_id\n originalFilename\n mimeType\n path\n url\n size\n height\n width`;\n/** List grids resolve thumbnails from the asset URL; extra metadata is unused. */\nconst listAssetPreviewFields = `_id\n path\n url`;\n\ntype AssetRelationshipConnection = {\n aggregate?: {\n count?: {\n nodes?: number;\n };\n };\n edges?: {\n properties?: {\n sortOrder?: number | null;\n } | null;\n node?: OrderedAssetValue | null;\n }[];\n};\n\nfunction isAssetRelationshipAttribute(attribute: Attribute | undefined): boolean {\n if (!attribute) {\n return false;\n }\n\n return (\n getAttributeScope(attribute) === 'relationship' &&\n attribute.relationship?.mode === 'multiple' &&\n attribute.relationship.entity === '_asset'\n );\n}\n\nfunction hasOrderedAssetConnectionProperties(attribute: Attribute | undefined, entity: Entity | undefined): boolean {\n if (!attribute || !isAssetRelationshipAttribute(attribute)) {\n return false;\n }\n\n return entity?.name !== tagSchema.name || attribute.name !== 'assets';\n}\n\nfunction isAssetAttribute(attribute: Attribute | undefined): boolean {\n return attribute?.dataType === 'asset' || attribute?.inputType === 'asset';\n}\n\nexport function getOrderedAssetsFromConnection(connection: unknown): OrderedAssetValue[] {\n const typedConnection = connection as AssetRelationshipConnection | undefined;\n const edges = typedConnection?.edges ?? [];\n // Edges are bounded by `first`; the aggregate count carries the real total so\n // consumers (e.g. the \"+N\" badge in list grids) do not undercount.\n const totalCount = typedConnection?.aggregate?.count?.nodes ?? edges.length;\n\n return edges\n .reduce<OrderedAssetValue[]>((result, edge, index) => {\n if (!edge.node) {\n return result;\n }\n\n result.push({\n ...edge.node,\n sortOrder: edge.properties?.sortOrder ?? index,\n totalCount,\n });\n\n return result;\n }, [])\n .sort((a, b) => (a.sortOrder ?? Number.MAX_SAFE_INTEGER) - (b.sortOrder ?? Number.MAX_SAFE_INTEGER));\n}\n\n/** Build the sort-order map update mutations use to detect new vs existing assets. */\nexport function getKnownAssetSortOrders(assets: OrderedAssetValue[]): { [id: string]: number } {\n return assets.reduce<{ [id: string]: number }>((result, asset, index) => {\n if (!asset._id) {\n return result;\n }\n\n return {\n ...result,\n [asset._id]: asset.sortOrder ?? index,\n };\n }, {});\n}\n\n/**\n * Relationship fields are list-typed in the generated schema ([Type!]!), so\n * single-valued fields (local attributes, global assets, single-mode\n * relationships) come back as arrays of 0..1 nodes. Unwraps to the first node,\n * tolerating the legacy single-object shape.\n */\nfunction unwrapNode(value: unknown): AttributeValue | null {\n if (Array.isArray(value)) {\n return (value[0] as AttributeValue | undefined) ?? null;\n }\n\n return (value as AttributeValue | null) ?? null;\n}\n\n/**\n * Asset connections must always be bounded: without `first` the generated\n * Cypher expands every connected asset per row (tags with thousands of assets\n * made list queries take seconds). The aggregate count is still selected, so\n * consumers can show \"+N more\" from `totalCount`.\n */\nfunction getAssetConnectionNodeFields(includeLqip: boolean, previewOnly: boolean): string {\n if (previewOnly) {\n return listAssetPreviewFields;\n }\n\n if (includeLqip) {\n return assetFields;\n }\n\n return assetFieldsWithoutLqip;\n}\n\nfunction getAssetConnectionSelection(\n attributeName: string,\n includeProperties = true,\n includeLqip = true,\n first = FULL_ASSET_CONNECTION_LIMIT,\n previewOnly = false\n): string {\n const propertiesSelection = includeProperties\n ? ` properties {\\n` + ` sortOrder\\n` + ` }\\n`\n : '';\n const nodeFields = getAssetConnectionNodeFields(includeLqip, previewOnly);\n // Edge sort input only exists when the relationship carries properties.\n const connectionArguments = includeProperties\n ? `(first: ${first}, sort: [{ edge: { sortOrder: ASC } }])`\n : `(first: ${first})`;\n\n return (\n ` ${attributeName}Connection${connectionArguments} {\\n` +\n ` aggregate {\\n` +\n ` count {\\n` +\n ` nodes\\n` +\n ` }\\n` +\n ` }\\n` +\n ` edges {\\n` +\n propertiesSelection +\n ` node {\\n` +\n ` ${nodeFields}\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }\\n`\n );\n}\n\n/**\n * Counts moved inside connection fields in Neo4j GraphQL v7:\n * xConnection \\{ aggregate \\{ count \\{ nodes \\} \\} \\}. Reads that shape back.\n */\nfunction getConnectionCount(value: unknown): number {\n const aggregate = (value as { aggregate?: { count?: { nodes?: number } } } | null | undefined)?.aggregate;\n\n return aggregate?.count?.nodes ?? 0;\n}\n\nfunction getEntityCount(results: EntityQueryResults, entityNamePlural: string): number {\n const total = results[`${entityNamePlural}Total`];\n\n if (typeof total === 'number') {\n return total;\n }\n\n return getConnectionCount(results[`${entityNamePlural}Connection`]);\n}\n\nfunction getConnectionCountSelection(fieldName: string, whereArgument = ''): string {\n return (\n ` ${fieldName}Connection${whereArgument} {\\n` +\n ` aggregate {\\n` +\n ` count {\\n` +\n ` nodes\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }\\n`\n );\n}\n\nfunction getTopLevelCountSelection(\n entityNamePlural: string,\n includeCount: boolean,\n countMode: EntityQueryCountMode\n): string {\n if (!includeCount) {\n return '';\n }\n\n if (countMode === 'total') {\n return ` ${entityNamePlural}Total\\n`;\n }\n\n return getConnectionCountSelection(entityNamePlural, '(where: $where)');\n}\n\n/**\n * Selection set for a related entity's display attribute only — enough for list-grid\n * relationship columns (mapQueryResult / sliceFirstThreeItems).\n */\nfunction getDisplayAttributeSelection(\n primaryAttribute: Attribute | undefined,\n scope: string,\n schema: Schema,\n forList = false\n): string {\n if (!primaryAttribute) {\n return '';\n }\n\n const additionalScope = scope === 'default' ? '' : `${scope}\\n `;\n\n if (isAssetAttribute(primaryAttribute)) {\n if (forList) {\n return ` ${primaryAttribute.name} {\\n _id\\n path\\n url\\n }\\n`;\n }\n\n return ` ${primaryAttribute.name} {\\n ${assetFields}\\n }\\n`;\n }\n\n if (getAttributeScope(primaryAttribute) === 'local') {\n return ` ${primaryAttribute.name} {\\n _id\\n default\\n ${additionalScope}}\\n`;\n }\n\n if (getAttributeScope(primaryAttribute) === 'relationship') {\n const field = primaryAttribute.relationship?.field;\n\n if (!field) {\n return ` ${primaryAttribute.name}\\n`;\n }\n\n const nestedEntity = find(propEq(primaryAttribute.relationship?.entity, 'name'))(schema) as Entity | undefined;\n const fieldAttribute = find(propEq(field, 'name'))(nestedEntity?.attributes ?? []) as Attribute | undefined;\n const localAttributeQuery =\n fieldAttribute && getAttributeScope(fieldAttribute) === 'local'\n ? `{\\n _id\\n default\\n ${additionalScope}}\\n`\n : '';\n\n if (primaryAttribute.relationship?.mode === 'single') {\n return ` ${primaryAttribute.name} {\\n ${field} ${localAttributeQuery}}\\n`;\n }\n\n return ` ${primaryAttribute.name} (limit: 3, offset: 0) {\\n ${field} ${localAttributeQuery}}\\n`;\n }\n\n return ` ${primaryAttribute.name}\\n`;\n}\n\nfunction getFullRelatedEntityAttributesSelection(\n relatedEntity: Entity | undefined,\n scope: string,\n schema: Schema\n): string {\n return (\n relatedEntity?.attributes.reduce((relatedAcc, relatedAttribute) => {\n const additionalScope = scope === 'default' ? '' : `${scope}\\n `;\n\n // Related-entity assets only render as CDN-path thumbnails in grids; the\n // base64 lqip payload is form-field-only and skipped at this depth.\n if (isAssetAttribute(relatedAttribute)) {\n return `${relatedAcc}\\n ${relatedAttribute.name} {\\n ${assetFieldsWithoutLqip}\\n }\\n `;\n }\n\n if (getAttributeScope(relatedAttribute) === 'local') {\n return `${relatedAcc}\\n ${relatedAttribute.name} {\\n _id\\n default\\n ${additionalScope}\\n}\\n `;\n }\n\n if (getAttributeScope(relatedAttribute) === 'relationship') {\n const relationshipEntity = find(propEq(relatedAttribute.relationship?.entity, 'name'))(schema) as\n | Entity\n | undefined;\n const relationshipAttribute = find(propEq(relatedAttribute.relationship?.field, 'name'))(\n relationshipEntity?.attributes ?? []\n ) as Attribute;\n const localAttributeQuery =\n getAttributeScope(relationshipAttribute) === 'local'\n ? `{\\n _id\\n default\\n ${additionalScope}}\\n `\n : '';\n\n if (relatedAttribute.relationship?.mode === 'single') {\n return `${relatedAcc}\\n ${relatedAttribute.name} {\\n ${relatedAttribute.relationship.field} ${localAttributeQuery}}\\n `;\n }\n\n if (relatedAttribute.relationship?.field) {\n return `${relatedAcc}\\n ${relatedAttribute.name} (limit: ${NESTED_RELATIONSHIP_LIMIT}, offset: 0) {\\n ${relatedAttribute.relationship.field} ${localAttributeQuery}}\\n `;\n }\n }\n\n return `${relatedAcc}\\n ${relatedAttribute.name}\\n `;\n }, '') ?? ''\n );\n}\n\nfunction getAttributesByName(attributes: Attribute[]): { [name: string]: Attribute | undefined } {\n const attributesByName: { [name: string]: Attribute | undefined } = {};\n\n for (const attribute of attributes) {\n attributesByName[attribute.name] = attribute;\n }\n\n return attributesByName;\n}\n\nfunction shouldSelectAttributeInList(attribute: Attribute | undefined): boolean {\n if (!attribute) {\n return false;\n }\n\n // Computed asset URL is hidden from the grid but required to preview and copy links.\n if (attribute.name === 'url') {\n return true;\n }\n\n if (attribute.hidden === true || attribute.name === 'lqip') {\n return false;\n }\n\n return true;\n}\n\nexport function getSortNotNullWhere(sort: unknown, entity: Entity | undefined): SortNotNullWhere | undefined {\n if (!Array.isArray(sort) || sort.length === 0) {\n return undefined;\n }\n\n const [primarySort] = sort;\n\n if (!primarySort || typeof primarySort !== 'object') {\n return undefined;\n }\n\n const [sortAttributeName] = Object.keys(primarySort);\n\n if (!sortAttributeName || ['_id', '_createdAt', '_updatedAt'].includes(sortAttributeName)) {\n return undefined;\n }\n\n const sortAttribute = entity?.attributes.find((attribute) => attribute.name === sortAttributeName);\n\n if (\n !sortAttribute ||\n getAttributeScope(sortAttribute) !== 'global' ||\n sortAttribute.dataType === 'asset'\n ) {\n return undefined;\n }\n\n return {\n NOT: {\n [sortAttributeName]: {\n eq: null,\n },\n },\n };\n}\n\nexport function getEntityQuery(\n entityNamePlural: string,\n scope: string,\n schema: Schema,\n options?: {\n selection?: EntityQuerySelection;\n /**\n * The top-level aggregate count is a filtered label scan on the server.\n * Pagination pages (fetchMore) skip it — the total from the first page\n * still stands.\n */\n includeCount?: boolean;\n countMode?: EntityQueryCountMode;\n operationName?: string;\n }\n): EntityQuery {\n const requestedSelection = options?.selection ?? 'full';\n const selection = requestedSelection === 'display' ? 'list' : requestedSelection;\n const includeCount = options?.includeCount ?? true;\n const countMode = options?.countMode ?? 'aggregate';\n const filters = `(where: $where, limit: $limit, offset: $offset, sort: $sort)`;\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const entityName = entitySchema?.name ?? entityNamePlural;\n const displayAttribute = getDisplayAttribute(entitySchema);\n const attributes = requestedSelection === 'display'\n ? (displayAttribute ? [displayAttribute] : [])\n : entitySchema?.attributes ?? [];\n const attributesByName = getAttributesByName(attributes);\n const heading = `$where: ${entityName}Where, $limit: Int, $offset: Int, $sort: [${entityName}Sort!]`;\n const operationName = options?.operationName ?? `Get${getOperationEntityName(entityNamePlural)}`;\n\n if (!entitySchema) {\n throw new Error(`Entity '${entityName}' not found in the schema`);\n }\n\n if (attributes.length === 0) {\n throw new Error(`Entity '${entityName}' has no attributes defined in the schema`);\n }\n\n const globalAttributesList: string = getAttributeListByScope('global', attributes)\n .filter((attributeName) => {\n if (attributeName === '_updatedAt') {\n return false;\n }\n\n if (selection === 'list') {\n return requestedSelection === 'display' || shouldSelectAttributeInList(attributesByName[attributeName]);\n }\n\n return true;\n })\n .join('\\n ');\n const imageAttributes = getImageAttributes(attributes).filter((attributeName) =>\n selection !== 'list' || requestedSelection === 'display' || shouldSelectAttributeInList(attributesByName[attributeName])\n );\n const localAttributes: readonly string[] = getAttributeListByScope(['local'], attributes).filter((attributeName) => {\n if (selection !== 'list') {\n return true;\n }\n\n return requestedSelection === 'display' || shouldSelectAttributeInList(attributesByName[attributeName]);\n });\n const defaultScopedAttr = localAttributes.reduce(\n (acc, attribute) => `${acc}\\n ${attribute} {\\n _id\\n default\\n }\\n `,\n ''\n );\n const scopedAttribute = localAttributes.reduce(\n (acc, attribute) => `${acc}\\n ${attribute} {\\n _id\\n default\\n ${scope}\\n }\\n `,\n ''\n );\n const localAttributesList: string = scope === 'default' ? defaultScopedAttr : scopedAttribute;\n let imageFieldsSelection = `_id\\n path\\n url`;\n\n if (selection !== 'list') {\n imageFieldsSelection =\n `_id\\n originalFilename\\n mimeType\\n path\\n url\\n size\\n height\\n width\\n lqip`;\n }\n\n const imageAttributesList: string = imageAttributes.reduce((acc, attribute) => {\n return `${acc}\\n ${attribute} {\\n ${imageFieldsSelection}\\n }\\n `;\n }, '');\n\n const relationshipAttributes = attributes.filter((attribute) => getAttributeScope(attribute) === 'relationship');\n const relationshipAttributesList: string = relationshipAttributes.reduce((acc, attribute) => {\n if (selection === 'list' && requestedSelection !== 'display' && attribute.hidden === true) {\n return acc;\n }\n\n if (isAssetRelationshipAttribute(attribute)) {\n return `${acc}\\n${getAssetConnectionSelection(\n attribute.name,\n hasOrderedAssetConnectionProperties(attribute, entitySchema),\n selection !== 'list',\n selection === 'list' ? LIST_ASSET_CONNECTION_LIMIT : FULL_ASSET_CONNECTION_LIMIT,\n selection === 'list'\n )}`;\n }\n\n const relatedEntity = find(propEq(attribute.relationship?.entity, 'name'))(schema) as Entity | undefined;\n\n if (selection === 'list') {\n const displayAttribute = getDisplayAttribute(relatedEntity);\n const primarySelection = getDisplayAttributeSelection(displayAttribute, scope, schema, true);\n const relatedLimit = attribute.relationship?.mode === 'single' ? 1 : 3;\n\n return (\n `${acc}\\n ${attribute.name} (limit: ${relatedLimit}, offset: 0) {\\n` +\n ` _id\\n` +\n `${primarySelection}` +\n ` }\\n `\n );\n }\n\n const attributesNameList = getFullRelatedEntityAttributesSelection(relatedEntity, scope, schema);\n\n return (\n `${getConnectionCountSelection(attribute.name).trim()}` +\n `${acc}\\n ${attribute.name} (limit: 25, offset: 0) { _id ${attributesNameList}` +\n `}\\n `\n );\n }, '');\n\n return {\n queryEntityName: entityNamePlural,\n query:\n `query ${operationName}(${heading}) {\\n` +\n getTopLevelCountSelection(entityNamePlural, includeCount, countMode) +\n ` ${entityNamePlural}${filters} {\\n` +\n ` _id\\n` +\n ` _updatedAt\\n` +\n ` ${globalAttributesList}` +\n ` ${localAttributesList}` +\n ` ${imageAttributesList}` +\n ` ${relationshipAttributesList}` +\n `}\\n` +\n `}\\n`,\n };\n}\n\n/**\n * Map the GraphQl results JSON to a key-value pair array. The values inside the scopedAttributes key are flattened to the first level.\n */\nexport function mapQueryResult(\n entityNamePlural: string,\n scope: string,\n results: EntityQueryResults,\n schema: Schema\n): MappedEntityQueryResults {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const attributes = entitySchema?.attributes ?? [];\n\n if (attributes.length === 0) {\n return {\n count: 0,\n results: [],\n };\n }\n\n const count = getEntityCount(results, entityNamePlural);\n const items = results[entityNamePlural] as EntityQueryResult[];\n const sliceFirstThreeItems = (values: EntityItem[], primaryAttribute: Attribute): string => {\n const primaryAttributeName = primaryAttribute.name;\n\n return values\n .slice(0, 3)\n .map((item) => {\n if (getAttributeScope(primaryAttribute) !== 'local') {\n return item[primaryAttributeName];\n }\n\n const scopedNode = unwrapNode(item[primaryAttributeName]);\n\n return scopedNode?.[scope] ?? scopedNode?.default;\n })\n .join(', ');\n };\n const mappedQueryResult = items.map((entity) => {\n const { _id } = entity;\n const updatedAt = typeof entity._updatedAt === 'string' ? entity._updatedAt : '';\n const globalAttributes = getAttributeListByScope('global', attributes)\n .filter((attributeName) => attributeName !== '_updatedAt')\n .reduce((acc, attributeName) => ({ ...acc, [attributeName]: entity[attributeName] }), {});\n const localAttributes = getAttributeListByScope('local', attributes).reduce((acc, attributeName) => {\n const scopedAttribute = unwrapNode(entity[attributeName]);\n\n return {\n ...acc,\n [attributeName]: scopedAttribute?.[scope] ? scopedAttribute[scope] : scopedAttribute?.default,\n };\n }, {});\n const imageAttributes = getImageAttributes(attributes).reduce(\n (acc, attributeName) => ({ ...acc, [attributeName]: unwrapNode(entity[attributeName]) }),\n {}\n );\n const relationshipAttributes = getAttributeListByScope(['relationship'], attributes).reduce(\n (acc, attributeName) => {\n const relationshipAttribute = find(propEq(attributeName, 'name'))(attributes) as Attribute;\n const relatedEntityName = relationshipAttribute.relationship?.entity ?? '';\n const relatedEntity = find(propEq(relatedEntityName, 'name'))(schema) as Entity | undefined;\n const primaryAttribute = getDisplayAttribute(relatedEntity);\n const localValue = entity[attributeName];\n\n if (isAssetRelationshipAttribute(relationshipAttribute)) {\n const assets = getOrderedAssetsFromConnection(entity[`${attributeName}Connection`]);\n\n return {\n ...acc,\n [attributeName]: assets,\n };\n }\n\n if (!primaryAttribute) {\n throw new Error(`There is an error in the schema for the relationship attribute \"${attributeName}\"`);\n }\n\n const primaryAttributeName = primaryAttribute.name;\n const primaryAttributeScope = getAttributeScope(primaryAttribute);\n\n // All relationship fields are lists in the schema, so the mode from the\n // JSON schema (not the value shape) decides single vs multiple mapping.\n if (relationshipAttribute.relationship?.mode === 'multiple') {\n const relatedItems = (Array.isArray(localValue) ? localValue : []) as EntityItem[];\n\n return {\n ...acc,\n [attributeName]: sliceFirstThreeItems(relatedItems, primaryAttribute),\n };\n }\n\n const relatedNode = unwrapNode(localValue);\n\n if (primaryAttributeScope === 'global') {\n return {\n ...acc,\n [attributeName]: relatedNode?.[primaryAttributeName],\n };\n }\n\n const primaryScopedNode = unwrapNode(relatedNode?.[primaryAttributeName]);\n\n return {\n ...acc,\n [attributeName]: primaryScopedNode?.[scope] ?? primaryScopedNode?.default,\n };\n },\n {}\n );\n\n return {\n _id,\n ...globalAttributes,\n ...localAttributes,\n ...imageAttributes,\n ...relationshipAttributes,\n _updatedAt: updatedAt,\n };\n });\n\n return {\n count,\n results: mappedQueryResult,\n };\n}\n\n/**\n * Like mapQueryResult but the local attribute values are returned as an object:\n * \\{_id: string, value: string, disabled: boolean, scope: string\\}.\n */\nexport function mapQueryResultForFormFields(\n entityNamePlural: string,\n scope: string,\n results: EntityQueryResults,\n schema: Schema\n): MappedFormEntityQueryResults {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const attributes = entitySchema?.attributes ?? [];\n\n if (attributes.length === 0) {\n return {\n count: 0,\n results: [],\n };\n }\n\n const count = getEntityCount(results, entityNamePlural);\n const items = results[entityNamePlural] as EntityQueryResult[];\n const mappedQueryResult = items.map((entity) => {\n const globalAttributes = getAttributeListByScope('global', attributes).reduce(\n (acc, attribute) => ({\n ...acc,\n [attribute]: {\n value: entity[attribute],\n disabled: false,\n scope: 'default',\n _id: '',\n },\n }),\n {}\n );\n const localAttributes = getAttributeListByScope('local', attributes).reduce((acc, attributeName) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(attributes) as Attribute;\n const localAttribute = unwrapNode(entity[attributeName]);\n\n return {\n ...acc,\n [attributeName]: {\n value: localAttribute ? getValueByScope(localAttribute, scope) : null,\n disabled: Boolean(\n localAttribute &&\n localAttribute[scope] === null &&\n getAttributeScope(attributeSchema) === 'local' &&\n scope !== 'default'\n ),\n scope,\n _id: localAttribute ? localAttribute._id : null,\n },\n };\n }, {});\n const imageAttributes = getImageAttributes(attributes).reduce(\n (acc, attribute) => ({\n ...acc,\n [attribute]: {\n value: unwrapNode(entity[attribute]),\n disabled: false,\n scope: 'default',\n _id: '',\n },\n }),\n {}\n );\n const relationshipAttributes = getAttributeListByScope(['relationship'], attributes).reduce(\n (acc, attributeName) => {\n const relationshipAttribute = find(propEq(attributeName, 'name'))(attributes) as Attribute;\n const rawValue = entity[attributeName];\n // Single-mode relationships come back as lists of 0..1 nodes; multiple\n // mode keeps the array so downstream grids receive it unchanged.\n const value = (\n relationshipAttribute.relationship?.mode === 'single' ? unwrapNode(rawValue) : rawValue\n ) as AttributeValue | null;\n const _id = value?._id;\n const aggregateCount = getConnectionCount(entity[`${attributeName}Connection`]);\n\n if (isAssetRelationshipAttribute(relationshipAttribute)) {\n const assets = getOrderedAssetsFromConnection(entity[`${attributeName}Connection`]);\n\n return {\n ...acc,\n [attributeName]: {\n count: aggregateCount,\n _id,\n knownAssetSortOrders: getKnownAssetSortOrders(assets),\n value: assets,\n disabled: false,\n scope,\n },\n };\n }\n\n return {\n ...acc,\n [attributeName]: {\n count: aggregateCount,\n _id,\n value,\n disabled: false,\n scope,\n },\n };\n },\n {}\n );\n\n return { ...globalAttributes, ...localAttributes, ...imageAttributes, ...relationshipAttributes };\n });\n\n return {\n count,\n results: mappedQueryResult,\n };\n}\n\n/**\n * Attribute values can be an object or an array of objects if the attribute is a multi-select.\n */\nfunction getValueByScope(\n attribute: AttributeValue | AttributeValue[],\n scope: string\n): FormFieldValue[] | AttributeValue | AttributeValue[] | string | null {\n if (Array.isArray(attribute)) {\n return attribute.reduce((result: FormFieldValue[], attr: AttributeValue) => {\n if (attr[scope] ?? attr.default) {\n const option = {\n _id: attr._id,\n disabled: Boolean(attr.scope === null && scope !== 'default'),\n scope,\n value: attr[scope] ?? attr.default,\n };\n\n result.push(option);\n }\n\n return result;\n }, []);\n }\n\n return attribute[scope] ?? attribute.default ?? null;\n}\n\n/**\n * Returns a string with the GraphQl query needed to mutate the dataToMutate object for the given entity and scope.\n */\nexport function getEntityUpdateMutation(\n entityNamePlural: string,\n entityId: string,\n scope: string,\n schema: Schema,\n originalData: FormEntityItem,\n dataToMutate: FormEntityItem,\n options?: { currentUser?: User; responseFields?: string }\n): string {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const entityName = entitySchema?.name ?? entityNamePlural;\n const attributes = entitySchema?.attributes ?? [];\n const pluralizedEntityName = capitalize(entityNamePlural);\n\n if (attributes.length === 0) {\n return '';\n }\n\n const data = filterOutInvalidAttributes(attributes, dataToMutate);\n const globalAttributes = globalAttributesUpdate(attributes, data);\n const localAttributes = localAttributesUpdate(entityId, attributes, data, scope);\n const imageAttributes = imageAttributesUpdate(attributes, originalData, data);\n const relationshipAttributes = relationshipAttributesUpdate(attributes, originalData, data);\n const responseType = entityNamePlural;\n const attributeNamesList =\n options?.responseFields ?? formatResponseFieldsForMutation(schema, entityNamePlural, scope);\n const operationName = `Update${getOperationEntityName(entityNamePlural)}`;\n\n return (\n `mutation ${operationName}($where: ${entityName}Where) {\\n` +\n ` update${pluralizedEntityName}(\\n` +\n ` where: $where\\n` +\n ` update: {${globalAttributes}${localAttributes}${imageAttributes}${relationshipAttributes}\\n }\\n` +\n ` ) {\\n` +\n ` ${responseType} {\\n` +\n ` _id\\n` +\n ` ${attributeNamesList}` +\n ` }\\n` +\n ` }\\n` +\n `}\\n`\n );\n}\n\n/**\n * Filter out any attribute received from the form that does not exist in the schema.\n */\nfunction filterOutInvalidAttributes(attributes: Attribute[], dataToMutate: FormEntityItem): FormEntityItem {\n // Read-only attributes are never written by the Studio.\n const nonUpdatableAttributes: readonly string[] = attributes\n .filter((attribute) => attribute.readOnly === true)\n .map((attribute) => attribute.name);\n const data = omit(nonUpdatableAttributes, dataToMutate);\n\n return pick(\n attributes.map((attribute) => attribute.name) as unknown as readonly [number, ...number[]],\n data\n ) as FormEntityItem;\n}\n\n/**\n * Filter attributes by scope: local, global or relationship.\n */\nfunction getAttributeListByScope(type: ScopeType | ScopeType[], attributes: Attribute[]): Attribute['name'][] {\n if (Array.isArray(type)) {\n return type.reduce((acc: Attribute['name'][], attributeType: ScopeType) => {\n return acc.concat(getAttributeListByScope(attributeType, attributes));\n }, []);\n }\n\n const filteredAttributes = attributes.filter(\n (attribute) => getAttributeScope(attribute) === type && attribute.inputType !== 'asset'\n );\n\n return filteredAttributes.map((attribute) => attribute.name);\n}\n\n/**\n * Get all attributes that are of type image.\n */\nfunction getImageAttributes(attributes: Attribute[]): Attribute['name'][] {\n const filteredAttributes = attributes.filter(isAssetAttribute);\n\n return filteredAttributes.map((attribute) => attribute.name);\n}\n\n/**\n * Update inputs require the dedicated set operator in Neo4j GraphQL v7\n * (name: \\{ set: value \\}); create inputs still take plain values.\n */\nfunction globalAttributesUpdate(\n schemaAttributes: Attribute[],\n data: FormEntityItem,\n operation: 'create' | 'update' = 'update'\n): string {\n const globalAttributes = pick(getAttributeListByScope('global', schemaAttributes) as [string], data);\n const attributesString = toPairs(globalAttributes).reduce((acc, [attributeName, value]) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const valueToStringify = Array.isArray(value?.value) ? null : (value?.value ?? null);\n const typedValue = stringifyValue(attributeSchema.dataType, valueToStringify);\n\n // Omit empty optional globals on create — `field: ` with no value is invalid GraphQL.\n if (operation === 'create' && (typedValue === null || typedValue === '')) {\n return acc;\n }\n\n if (operation === 'update') {\n return `${acc}\\n ${attributeName}: { set: ${typedValue} }`;\n }\n\n return `${acc}\\n ${attributeName}: ${typedValue}`;\n }, '');\n\n return attributesString;\n}\n\n/**\n * Returns the asset _id of a field value when it points at a real asset.\n * Cleared fields keep a stub value without a path, so path is required too.\n */\nfunction getLinkedAssetId(value: ImageValue | null | undefined): string {\n if (!value?._id || !value.path) {\n return '';\n }\n\n return value._id;\n}\n\n/**\n * Asset nodes are created up front by the /assets endpoint, so entity saves\n * only connect/disconnect them by _id. Disconnect runs before connect so the\n * field keeps at most one linked asset.\n */\nfunction imageAttributesUpdate(\n schemaAttributes: Attribute[],\n originalData: FormEntityItem,\n data: FormEntityItem\n): string {\n const imageAttributes = pick(getImageAttributes(schemaAttributes) as [string], data);\n const attributesArray: [string, FormFieldValue][] = toPairs(imageAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const nextId = getLinkedAssetId(attributeValue.value as ImageValue | null);\n const originalId = getLinkedAssetId(originalData[attributeName]?.value as ImageValue | null | undefined);\n\n if (nextId === originalId) {\n return acc;\n }\n\n const disconnect = originalId\n ? ` {\\n disconnect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(originalId)} }\\n }\\n }\\n }]\\n }\\n`\n : '';\n const connect = nextId\n ? ` {\\n connect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(nextId)} }\\n }\\n }\\n }]\\n }\\n`\n : '';\n\n return `${acc}\\n ${attributeName}: [\\n${disconnect}${connect} ]`;\n }, '');\n\n return attributesString;\n}\n\nfunction imageAttributesCreate(schemaAttributes: Attribute[], data: FormEntityItem): string {\n const imageAttributes = pick(getImageAttributes(schemaAttributes) as [string], data);\n const attributesArray: [string, FormFieldValue][] = toPairs(imageAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const assetId = getLinkedAssetId(attributeValue.value as ImageValue | null);\n\n if (!assetId) {\n return acc;\n }\n\n return (\n `${acc}\\n ${attributeName}: {\\n` +\n ` connect: [{\\n` +\n ` where: {\\n` +\n ` node: {\\n` +\n ` _id: { eq: ${stringifyStringLiteral(assetId)} }\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }]\\n` +\n ` }`\n );\n }, '');\n\n return attributesString;\n}\n\nfunction localAttributesUpdate(\n entityId: string,\n schemaAttributes: Attribute[],\n data: FormEntityItem,\n scope: string\n): string {\n const localAttributes = pick(getAttributeListByScope('local', schemaAttributes) as [string], data);\n const attributesArray: [string, FormFieldValue][] = toPairs(localAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const { dataType } = attributeSchema;\n const typedValue =\n attributeValue.disabled || Array.isArray(attributeValue.value)\n ? 'null'\n : stringifyValue(dataType, attributeValue.value);\n\n if (attributeValue._id) {\n return `${acc}\\n ${attributeName}: [{\\n update: {\\n node: {\\n ${scope}: { set: ${typedValue} }\\n }\\n }\\n }]`;\n }\n\n // Match localAttributesCreate: never create nodes for empty values. Empty\n // locals used to stringify to the string \"null\" and create with a\n // deterministic id; the next save then hit a unique-constraint failure\n // because the form still had no _id for those fields.\n if (\n attributeValue.disabled ||\n Array.isArray(attributeValue.value) ||\n attributeValue.value === undefined ||\n attributeValue.value === null ||\n attributeValue.value === '' ||\n typedValue === null ||\n typedValue === ''\n ) {\n return acc;\n }\n\n return (\n `${acc}\\n ${attributeName}: [{\\n` +\n ` create: {\\n` +\n ` node: {\\n` +\n ` _id: ${stringifyStringLiteral(`${entityId}:${attributeName}`)}\\n` +\n ` _type: \"${dataType}\"\\n` +\n ` ${scope}: ${typedValue}\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }]`\n );\n }, '');\n\n return attributesString;\n}\n\nfunction relationshipAttributesUpdate(\n schemaAttributes: Attribute[],\n originalData: FormEntityItem,\n data: FormEntityItem\n): string {\n const relationshipAttributes = pick(getAttributeListByScope('relationship', schemaAttributes) as [string], data);\n const attributesArray = toPairs(relationshipAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const { inputType, relationship } = attributeSchema;\n\n if (inputType === 'relationship' && relationship?.mode === 'single') {\n const originalId = originalData[attributeName]._id ?? '';\n const nextId = attributeValue._id ?? '';\n\n if (originalId === nextId) {\n return acc;\n }\n\n // Relationship fields are lists in the schema; disconnect runs before\n // connect so the field keeps at most one related node.\n const disconnect = originalId\n ? ` {\\n disconnect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(originalId)} }\\n }\\n }\\n }]\\n }\\n`\n : '';\n const connect = nextId\n ? ` {\\n connect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(nextId)} }\\n }\\n }\\n }]\\n }\\n`\n : '';\n\n return `${acc}\\n ${attributeName}: [\\n${disconnect}${connect} ]`;\n }\n\n if (inputType === 'relationship' && relationship?.mode === 'multiple') {\n if (relationship.entity === '_asset') {\n return `${acc}${orderedAssetRelationshipUpdate(attributeName, originalData[attributeName], attributeValue)}`;\n }\n\n // Neo4j GraphQL v7 expects list-shaped connect/disconnect entries with\n // `where.node`. The old `disconnect.where.OR` form drops the filter and\n // disconnects every related node.\n const disconnectIds = uniq(attributeValue.relationships?.disconnect ?? []).filter(Boolean);\n const connections = (attributeValue.relationships?.connect as MultipleRelationshipConnection | null) ?? [];\n const idsToConnect = connections.map((node) => stringifyStringLiteral(node._id)).join(', ');\n const disconnect = disconnectIds.length\n ? ` {\\n disconnect: [\\n${disconnectIds\n .map(\n (_id) =>\n ` {\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(_id)} }\\n }\\n }\\n }\\n`\n )\n .join('')} ]\\n }\\n`\n : '';\n const connect = idsToConnect\n ? ` {\\n connect: [{\\n where: {\\n node: {\\n _id: { in: [${idsToConnect}] }\\n }\\n }\\n }]\\n }\\n`\n : '';\n\n if (!disconnect && !connect) {\n return acc;\n }\n\n return `${acc}\\n ${attributeName}: [\\n${disconnect}${connect} ]`;\n }\n\n return `${acc}\\n`;\n }, '');\n\n return attributesString;\n}\n\nfunction orderedAssetRelationshipUpdate(\n attributeName: string,\n originalValue: FormFieldValue | undefined,\n attributeValue: FormFieldValue\n): string {\n const connections = (attributeValue.relationships?.connect as MultipleRelationshipConnection | null) ?? [];\n const orderedConnections = connections.map((connection, index) => ({\n ...connection,\n sortOrder: connection.sortOrder ?? index,\n }));\n const orderedConnectionIds = orderedConnections.map((connection) => connection._id);\n // Merge paged-in server assets from the live field so load-more edges are not\n // mistaken for brand-new connects (which would duplicate relationship edges).\n const originalSortOrderById = {\n ...getRelationshipSortOrderById(originalValue),\n ...(originalValue?.knownAssetSortOrders ?? {}),\n ...(attributeValue.knownAssetSortOrders ?? {}),\n };\n const disconnectedIds = uniq(attributeValue.relationships?.disconnect ?? []).filter(\n (_id) => _id && !orderedConnectionIds.includes(_id)\n );\n // In Neo4j GraphQL v7 connect always creates a new relationship, so\n // reconnecting an already-connected asset would duplicate the edge. New\n // assets are connected; existing ones with a changed sortOrder get a nested\n // update on the edge instead.\n const newConnections = orderedConnections.filter((connection) => originalSortOrderById[connection._id] === undefined);\n const reorderedConnections = orderedConnections.filter((connection) => {\n const originalSortOrder = originalSortOrderById[connection._id];\n\n return originalSortOrder !== undefined && originalSortOrder !== connection.sortOrder;\n });\n const disconnect = getOrderedAssetDisconnectString(disconnectedIds);\n const connect = getOrderedAssetConnectString(newConnections);\n const reorder = getOrderedAssetReorderString(reorderedConnections);\n\n if (!disconnect && !connect && !reorder) {\n return '';\n }\n\n return `\\n ${attributeName}: [\\n${disconnect}${connect}${reorder} ]`;\n}\n\nfunction getRelationshipSortOrderById(fieldValue: FormFieldValue | undefined): { [id: string]: number } {\n const value = fieldValue?.value;\n\n if (!Array.isArray(value)) {\n return {};\n }\n\n return value.reduce<{ [id: string]: number }>((result, item, index) => {\n if (typeof item !== 'object' || !item || !('_id' in item)) {\n return result;\n }\n\n const { _id } = item;\n\n if (typeof _id !== 'string' || _id.length === 0) {\n return result;\n }\n\n const sortOrder = 'sortOrder' in item && typeof item.sortOrder === 'number' ? item.sortOrder : index;\n\n return {\n ...result,\n [_id]: sortOrder,\n };\n }, {});\n}\n\nfunction getOrderedAssetDisconnectString(ids: string[]): string {\n if (ids.length === 0) {\n return '';\n }\n\n const nodes = ids.reduce((disconnectString, _id) => {\n return `${disconnectString} {\\n where: { node: { _id: { eq: ${stringifyStringLiteral(_id)} } } }\\n }\\n`;\n }, '');\n\n return ` {\\n disconnect: [\\n${nodes} ]\\n }\\n`;\n}\n\nfunction getOrderedAssetConnectString(connections: MultipleRelationshipConnection): string {\n if (connections.length === 0) {\n return '';\n }\n\n const nodes = getOrderedAssetConnectNodes(connections);\n\n return ` {\\n connect: [\\n${nodes} ]\\n }\\n`;\n}\n\nfunction getOrderedAssetConnectNodes(connections: MultipleRelationshipConnection): string {\n return connections.reduce((connectString, connection, index) => {\n const sortOrder = connection.sortOrder ?? index;\n\n return (\n `${connectString} {\\n` +\n ` where: { node: { _id: { eq: ${stringifyStringLiteral(connection._id)} } } }\\n` +\n ` edge: { sortOrder: ${sortOrder} }\\n` +\n ` }\\n`\n );\n }, '');\n}\n\nfunction getOrderedAssetReorderString(connections: MultipleRelationshipConnection): string {\n if (connections.length === 0) {\n return '';\n }\n\n const nodes = connections.reduce((updateString, connection, index) => {\n const sortOrder = connection.sortOrder ?? index;\n\n return (\n `${updateString} {\\n` +\n ` update: {\\n` +\n ` where: { node: { _id: { eq: ${stringifyStringLiteral(connection._id)} } } }\\n` +\n ` edge: { sortOrder: { set: ${sortOrder} } }\\n` +\n ` }\\n` +\n ` }\\n`\n );\n }, '');\n\n return nodes;\n}\n\nfunction stringifyValue(\n type: DataType,\n value: boolean | number | string | MappedEntityItem | EntityItem | AttributeValue | ImageValue | null | undefined\n): string | null {\n if (temporalTypes.includes(type)) {\n return value?.toString() ? stringifyStringLiteral(value.toString()) : null;\n }\n\n if (stringTypes.includes(type)) {\n // null/undefined must be GraphQL null, not the string literal \"null\".\n if (value === undefined || value === null) {\n return null;\n }\n\n return stringifyStringLiteral(value.toString());\n }\n\n // Empty optional numbers/booleans must not stringify to \"\" (breaks GraphQL as `field: `).\n if (value === undefined || value === null || value === '') {\n return null;\n }\n\n return value.toString();\n}\n\nfunction stringifyNullableString(value: string | null | undefined): string {\n return value ? stringifyStringLiteral(value) : 'null';\n}\n\nfunction stringifyStringLiteral(value: string): string {\n return JSON.stringify(value);\n}\n\nfunction formatResponseFieldsForMutation(schema: Schema, entityNamePlural: string, scope: string): string {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const schemaAttributes = entitySchema?.attributes ?? [];\n const globalAttributesArray = getAttributeListByScope('global', schemaAttributes);\n const localAttributesArray = getAttributeListByScope('local', schemaAttributes);\n const relationshipAttributesArray = getAttributeListByScope('relationship', schemaAttributes);\n\n let fields = globalAttributesArray.reduce((acc, attributeName: string) => {\n return `${acc}${attributeName}\\n `;\n }, '');\n\n fields += localAttributesArray.reduce((acc, attributeName: string) => {\n return `${acc} ${attributeName} {\\n _id\\n ${scope}\\n }\\n `;\n }, '');\n\n fields += relationshipAttributesArray.reduce((acc, attributeName: string) => {\n const relationshipAttribute = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute | undefined;\n const relationshipMode = relationshipAttribute?.relationship?.mode ?? 'single';\n\n if (isAssetRelationshipAttribute(relationshipAttribute)) {\n return `${acc}${getAssetConnectionSelection(\n attributeName,\n hasOrderedAssetConnectionProperties(relationshipAttribute, entitySchema)\n )}`;\n }\n\n const relationshipEntityName = relationshipAttribute?.relationship?.entity ?? '';\n const relationshipEntitySchema = find(propEq(relationshipEntityName, 'name'))(schema) as Entity | undefined;\n const relationshipEntityAttributes = relationshipEntitySchema?.attributes ?? [];\n const primaryAttributeName =\n relationshipAttribute?.relationship?.field ?? '[invalid_relationship_field_name_in_schema]';\n const primaryAttribute = find(propEq(primaryAttributeName, 'name'))(relationshipEntityAttributes) as Attribute;\n const primaryAttributeScope = getAttributeScope(primaryAttribute);\n let list = '';\n\n if (relationshipMode === 'single') {\n if (primaryAttributeScope === 'global') {\n list = ` ${attributeName} {\\n _id\\n ${primaryAttributeName}\\n }\\n `;\n }\n\n if (primaryAttributeScope === 'local') {\n list = ` ${attributeName} {\\n _id\\n ${primaryAttributeName} {\\n _id\\n default\\n ${scope}\\n }\\n }\\n `;\n }\n }\n\n if (relationshipMode === 'multiple' && relationshipEntityAttributes.length) {\n const multipleRelationshipAttributes = relationshipEntityAttributes.reduce((str, attribute) => {\n if (getAttributeScope(attribute) === 'local') {\n return `${str} ${attribute.name} {\\n _id\\n default\\n ${scope}\\n }\\n`;\n }\n\n if (getAttributeScope(attribute) === 'relationship') {\n const additionalScope = scope === 'default' ? '' : `${scope}\\n `;\n const relationshipEntity = find(propEq(attribute.relationship?.entity, 'name'))(schema) as Entity | undefined;\n const relationshipAttribute = find(propEq(attribute.relationship?.field, 'name'))(\n relationshipEntity?.attributes ?? []\n ) as Attribute;\n const localAttributeQuery =\n getAttributeScope(relationshipAttribute) === 'local'\n ? `{\\n _id\\n default\\n ${additionalScope}}\\n `\n : '';\n\n if (attribute.relationship?.mode === 'single') {\n return `${str} ${attribute.name} {\\n ${attribute.relationship.field} ${localAttributeQuery}}\\n `;\n }\n\n if (attribute.relationship?.field) {\n return `${str} ${attribute.name} (limit: ${NESTED_RELATIONSHIP_LIMIT}, offset: 0) {\\n ${attribute.relationship.field} ${localAttributeQuery}}\\n `;\n }\n }\n\n // Display-only at this depth; lqip is a form-field concern.\n if (isAssetAttribute(attribute)) {\n return `${str} ${attribute.name} {\\n ${assetFieldsWithoutLqip}\\n }\\n`;\n }\n\n return `${str} ${attribute.name}\\n `;\n }, '');\n\n list =\n getConnectionCountSelection(attributeName) +\n ` ${attributeName} (limit: 25, offset: 0) {\\n${multipleRelationshipAttributes}` +\n ` }\\n`;\n }\n\n return `${acc}${list}`;\n }, '');\n\n return fields;\n}\n\n/**\n * Returns a string with the GraphQl mutation needed to delete one or more entities.\n */\nexport function getEntityDeleteMutation(\n entityName: string,\n schema: Schema,\n ids: string | readonly string[]\n): string {\n const idList = typeof ids === 'string' ? [ids] : [...ids];\n const entitySchema = find(propEq(entityName, 'name'))(schema) as Entity | undefined;\n const attributes = entitySchema?.attributes ?? [];\n const pluralizedEntityName = capitalize(entitySchema?.plural ?? '');\n const localAttributes = localAttributesDelete(attributes, idList);\n const operationName = `Delete${getOperationEntityName(entitySchema?.plural ?? entityName)}`;\n\n if (entityName === '_asset') {\n return (\n `mutation ${operationName}($where: ${entityName}Where) {\\n` +\n ` delete_assets(\\n` +\n ` where: $where\\n` +\n ` ) {\\n` +\n ` nodesDeleted\\n` +\n ` relationshipsDeleted\\n` +\n ` }\\n` +\n `}\\n`\n );\n }\n\n return (\n `mutation ${operationName}($where: ${entityName}Where) {\\n` +\n ` delete${pluralizedEntityName}(\\n` +\n ` where: $where\\n` +\n `${localAttributes ? ` delete: {\\n ${localAttributes}\\n }\\n` : ''}` +\n ` ) {\\n` +\n ` nodesDeleted\\n` +\n ` relationshipsDeleted\\n` +\n ` }\\n` +\n `}\\n`\n );\n}\n\nexport function getEntityDeleteWhere(ids: string | readonly string[]): { _id: { eq: string } } | { _id: { in: string[] } } {\n const idList = typeof ids === 'string' ? [ids] : [...ids];\n\n if (idList.length === 1) {\n return { _id: { eq: idList[0] as string } };\n }\n\n return { _id: { in: idList } };\n}\n\nfunction localAttributesDelete(schemaAttributes: Attribute[], ids: readonly string[]): string {\n const localAttributes = getAttributeListByScope('local', schemaAttributes);\n const attributesString: string = localAttributes.reduce((acc, attributeName) => {\n const localIds = ids.map((id) => stringifyStringLiteral(`${id}:${attributeName}`)).join(', ');\n const idFilter = ids.length === 1 ? `_id: { eq: ${localIds} }` : `_id: { in: [${localIds}] }`;\n\n return (\n `${acc}\\n` +\n ` ${attributeName}: [{\\n` +\n ` where: {\\n` +\n ` node: {\\n` +\n ` ${idFilter}\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }]`\n );\n }, '');\n\n return attributesString;\n}\n\nexport function getEntityCreateMutation(\n entityNamePlural: string,\n schema: Schema,\n entityData: FormEntityItem,\n _id: string,\n _options?: { currentUser?: User }\n): string {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const attributes = entitySchema?.attributes ?? [];\n const pluralizedEntityName = capitalize(entitySchema?.plural ?? '');\n\n if (attributes.length === 0) {\n return '';\n }\n\n const data = filterOutInvalidAttributes(attributes, entityData);\n const globalAttributes = globalAttributesUpdate(attributes, data, 'create');\n const localAttributes = localAttributesCreate(attributes, data, 'default', _id);\n const imageAttributes = imageAttributesCreate(attributes, data);\n const relationshipAttributes = relationshipAttributesCreate(attributes, data);\n const responseType = entityNamePlural;\n const attributeNamesList = formatResponseFieldsForMutation(schema, responseType, 'default');\n const operationName = `Create${getOperationEntityName(entityNamePlural)}`;\n\n return (\n `mutation ${operationName} {\\n` +\n ` create${pluralizedEntityName}(\\n` +\n ` input: [{\\n` +\n ` _id: ${stringifyStringLiteral(_id)}` +\n ` ${globalAttributes}` +\n ` ${localAttributes}\\n` +\n ` ${imageAttributes}\\n` +\n ` ${relationshipAttributes}\\n` +\n ` }]\\n` +\n ` ) {\\n` +\n ` ${responseType} {\\n` +\n ` _id\\n` +\n ` ${attributeNamesList}` +\n ` }\\n` +\n ` }\\n` +\n `}\\n`\n );\n}\n\nfunction localAttributesCreate(\n schemaAttributes: Attribute[],\n data: FormEntityItem,\n defaultScope: string,\n _id: string\n): string {\n const localAttributes = pick(getAttributeListByScope('local', schemaAttributes) as [string], data);\n const attributesArray = toPairs(localAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n if (attributeValue?.value === undefined || attributeValue.value === null || attributeValue.value === '') {\n return acc;\n }\n\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const typedValue = Array.isArray(attributeValue.value)\n ? 'null'\n : stringifyValue(attributeSchema.dataType, attributeValue.value);\n\n return (\n `${acc}\\n` +\n ` ${attributeName}: {\\n` +\n ` create: [{\\n` +\n ` node: {\\n` +\n ` _id: ${stringifyStringLiteral(`${_id}:${attributeName}`)}\\n` +\n ` _type: \"${attributeSchema.dataType}\"\\n` +\n ` ${defaultScope}: ${typedValue}\\n` +\n ` }\\n` +\n ` }]\\n` +\n ` }`\n );\n }, '');\n\n return attributesString;\n}\n\nfunction relationshipAttributesCreate(schemaAttributes: Attribute[], data: FormEntityItem): string {\n const relationshipAttributes = pick(getAttributeListByScope('relationship', schemaAttributes) as [string], data);\n const attributesArray = toPairs(relationshipAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const { inputType, relationship } = attributeSchema;\n\n if (inputType === 'relationship' && relationship?.mode === 'single') {\n if (!attributeValue._id) {\n return acc;\n }\n\n const connect = `connect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(attributeValue._id)} }\\n }\\n }\\n }]\\n`;\n\n return `${acc}\\n ${attributeName}: {\\n ${connect} }`;\n }\n\n const isMultipleRelationship = inputType === 'relationship' && relationship?.mode === 'multiple';\n const hasRelationships =\n Array.isArray(attributeValue.relationships?.connect) && attributeValue.relationships.connect.length > 0;\n if (isMultipleRelationship && hasRelationships) {\n const connections = (attributeValue.relationships?.connect as MultipleRelationshipConnection | null) ?? [];\n\n if (relationship?.entity === '_asset') {\n const connectNodes = getOrderedAssetConnectNodes(\n connections.map((connection, index) => ({\n ...connection,\n sortOrder: connection.sortOrder ?? index,\n }))\n );\n\n return `${acc}\\n ${attributeName}: {\\n connect: [\\n${connectNodes} ]\\n }`;\n }\n\n const idsToConnect = connections.map((node) => stringifyStringLiteral(node._id)).join(', ');\n const connect = idsToConnect\n ? `connect: {\\n where: {\\n node: {\\n _id: { in: [${idsToConnect}] }\\n }\\n }\\n }\\n`\n : '';\n\n return `${acc}\\n ${attributeName}: {\\n ${connect} }`;\n }\n\n return `${acc}\\n`;\n }, '');\n\n return attributesString;\n}\n\nexport function getRelatedItemsQuery({\n relatedEntityName,\n scope,\n schema,\n}: {\n attributeName: string;\n relatedEntityName: string;\n scope: string;\n schema: Schema;\n}): EntityQuery {\n const entitySchema = find(propEq(relatedEntityName, 'name'))(schema) as Entity | undefined;\n const queryEntityName = entitySchema?.plural ?? '';\n\n if (!queryEntityName) {\n return {\n queryEntityName: '',\n query: '',\n };\n }\n\n return getEntityQuery(queryEntityName, scope, schema, {\n selection: 'list',\n operationName: `GetRelated${getOperationEntityName(queryEntityName)}`,\n });\n}\n\n/**\n * Pages an entity's ordered asset connection beyond the initial form `first`.\n * Callers grow `first` (e.g. loaded + page size) so already-fetched edges are\n * re-returned in sortOrder and can be merged without a cursor.\n */\nexport function getEntityAssetConnectionQuery({\n attributeName,\n entityName,\n entityNamePlural,\n schema,\n}: {\n attributeName: string;\n entityName: string;\n entityNamePlural: string;\n schema: Schema;\n}): EntityQuery {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const attribute = find(propEq(attributeName, 'name'))(entitySchema?.attributes ?? []) as Attribute | undefined;\n const includeProperties = hasOrderedAssetConnectionProperties(attribute, entitySchema);\n const propertiesSelection = includeProperties\n ? ` properties {\\n` + ` sortOrder\\n` + ` }\\n`\n : '';\n const connectionArguments = includeProperties\n ? '(first: $first, sort: [{ edge: { sortOrder: ASC } }])'\n : '(first: $first)';\n const operationName = `Get${getOperationEntityName(entityName)}AssetConnection`;\n\n return {\n queryEntityName: entityNamePlural,\n query:\n `query ${operationName}($where: ${entityName}Where, $first: Int) {\\n` +\n ` ${entityNamePlural}(where: $where) {\\n` +\n ` ${attributeName}Connection${connectionArguments} {\\n` +\n ` aggregate {\\n` +\n ` count {\\n` +\n ` nodes\\n` +\n ` }\\n` +\n ` }\\n` +\n ` edges {\\n` +\n propertiesSelection +\n ` node {\\n` +\n ` ${assetFields}\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }\\n` +\n `}\\n`,\n };\n}\n\nconst capitalize = (str: string): string => {\n return str.charAt(0).toUpperCase() + str.slice(1);\n};\n\nexport function getOperationEntityName(entityName: string): string {\n const normalizedEntityName = entityName\n .split(/[^0-9A-Za-z]+/)\n .filter(Boolean)\n .map(capitalize)\n .join('');\n\n if (!normalizedEntityName) {\n return 'Entity';\n }\n\n if (/^[A-Za-z_]/.test(normalizedEntityName)) {\n return normalizedEntityName;\n }\n\n return `Entity${normalizedEntityName}`;\n}\n\nexport function getEntitySchema(schema: Schema, entityNamePlural: string): Entity | undefined {\n if (entityNamePlural === '_assets') {\n return assetSchema;\n }\n\n return find(propEq(entityNamePlural, 'plural'))(schema) as Entity | undefined;\n}\n\n/**\n * Pulls local-attribute node _ids out of an update mutation response so the\n * form can adopt them without a full refetch (which re-dirties the drawer).\n */\nexport function getLocalAttributeIdsFromUpdateResponse(\n response: unknown,\n entityNamePlural: string,\n schema: Schema\n): { [attributeName: string]: string } {\n if (!response || typeof response !== 'object') {\n return {};\n }\n\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n\n if (!entitySchema) {\n return {};\n }\n\n const updateKey = `update${capitalize(entityNamePlural)}`;\n const payload = (response as { [key: string]: unknown })[updateKey];\n\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const entities = (payload as { [key: string]: unknown })[entityNamePlural];\n const entity = Array.isArray(entities) ? entities[0] : undefined;\n\n if (!entity || typeof entity !== 'object') {\n return {};\n }\n\n return entitySchema.attributes.reduce<{ [attributeName: string]: string }>((ids, attribute) => {\n if (getAttributeScope(attribute) !== 'local') {\n return ids;\n }\n\n const node = unwrapNode((entity as { [key: string]: unknown })[attribute.name]);\n const nodeId = node?._id;\n\n if (typeof nodeId !== 'string' || nodeId.length === 0) {\n return ids;\n }\n\n return {\n ...ids,\n [attribute.name]: nodeId,\n };\n }, {});\n}\n","import type { ApolloClient } from '@apollo/client';\nimport type { Schema } from '../core/types';\nimport { assetSchema } from '../entities/assets-schema';\nimport { getOperationEntityName } from './queries';\n\ntype EntityListRefreshListener = (queryNames: ReadonlySet<string>) => void | Promise<void>;\ntype EntityListRemovalListener = (queryName: string, entityIds: ReadonlySet<string>) => void;\ntype EntityListPatchListener = (queryName: string, patches: EntityListRowPatch[]) => void;\n\nexport type EntityListRowPatch = {\n _id: string;\n attributes: { [key: string]: string };\n};\n\nlet refetchTimer: ReturnType<typeof setTimeout> | null = null;\nconst pendingQueryNames = new Set<string>();\nconst pendingResolvers: Array<{ resolve: () => void; reject: (error: unknown) => void }> = [];\nconst listeners = new Set<EntityListRefreshListener>();\nconst removalListeners = new Set<EntityListRemovalListener>();\nconst patchListeners = new Set<EntityListPatchListener>();\n\nexport function getEntityListQueryName(entityNameOrPlural: string, schema: Schema): string {\n if (entityNameOrPlural === '_asset' || entityNameOrPlural === '_assets') {\n return `Get${getOperationEntityName(assetSchema.plural)}`;\n }\n\n const byPlural = schema.find((entity) => entity.plural === entityNameOrPlural);\n const byName = schema.find((entity) => entity.name === entityNameOrPlural);\n const plural = byPlural?.plural ?? byName?.plural ?? entityNameOrPlural;\n\n return `Get${getOperationEntityName(plural)}`;\n}\n\n/**\n * Subscribe to soft list refreshes. Listeners should refetch their own query and\n * remap local paginated state (useEntityQuery ignores Apollo cache writes after sync).\n */\nexport function subscribeEntityListRefetch(listener: EntityListRefreshListener): () => void {\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * Subscribe to optimistic row removals (e.g. after delete) before the soft-refetch lands.\n */\nexport function subscribeEntityListRemoval(listener: EntityListRemovalListener): () => void {\n removalListeners.add(listener);\n\n return () => {\n removalListeners.delete(listener);\n };\n}\n\n/**\n * Subscribe to in-place row patches (e.g. tag connect/disconnect) without a full list refetch.\n */\nexport function subscribeEntityListPatch(listener: EntityListPatchListener): () => void {\n patchListeners.add(listener);\n\n return () => {\n patchListeners.delete(listener);\n };\n}\n\n/**\n * Immediately drop rows from mounted lists, then soft-refetch to sync counts/pages.\n */\nexport function scheduleEntityListRemoval(\n apolloClient: ApolloClient,\n queryName: string,\n entityIds: string[]\n): Promise<void> {\n const ids = new Set(entityIds.filter(Boolean));\n\n if (ids.size > 0) {\n for (const listener of removalListeners) {\n listener(queryName, ids);\n }\n }\n\n return scheduleEntityListRefetch(apolloClient, queryName);\n}\n\n/**\n * Patch mounted list rows in place. Use when a mutation cannot change list cardinality\n * (e.g. tag connect/disconnect) so we avoid a full GetAssets soft-refetch.\n */\nexport function scheduleEntityListPatch(queryName: string, patches: EntityListRowPatch[]): void {\n const nextPatches = patches.filter((patch) => Boolean(patch._id));\n\n if (nextPatches.length === 0) {\n return;\n }\n\n for (const listener of patchListeners) {\n listener(queryName, nextPatches);\n }\n}\n\n/**\n * Ask mounted entity lists to soft-refresh. Debounced so batch deletes coalesce.\n */\nexport function scheduleEntityListRefetch(_apolloClient: ApolloClient, queryName: string): Promise<void> {\n pendingQueryNames.add(queryName);\n\n return new Promise<void>((resolve, reject) => {\n pendingResolvers.push({ resolve, reject });\n\n if (refetchTimer) {\n clearTimeout(refetchTimer);\n }\n\n refetchTimer = setTimeout(() => {\n const names = new Set(pendingQueryNames);\n const resolvers = pendingResolvers.splice(0);\n pendingQueryNames.clear();\n refetchTimer = null;\n\n void Promise.all([...listeners].map((listener) => Promise.resolve(listener(names))))\n .then(() => {\n for (const { resolve: finish } of resolvers) {\n finish();\n }\n })\n .catch((error: unknown) => {\n console.error('Error refreshing entity lists:', error);\n\n for (const { reject: fail } of resolvers) {\n fail(error);\n }\n });\n }, 50);\n });\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { prop, uniqBy } from 'ramda';\nimport { gql, NetworkStatus } from '@apollo/client';\nimport type { OperationVariables } from '@apollo/client';\nimport { useQuery } from '@apollo/client/react';\nimport {\n getGraphQLSchemaMismatchMessage,\n getServerError,\n isMissingGraphQLFieldError,\n parseErrorBody,\n} from './error-utils';\nimport {\n getEntityQuery,\n getEntitySchema,\n getOperationEntityName,\n mapQueryResult,\n mapQueryResultForFormFields,\n} from './queries';\nimport {\n subscribeEntityListPatch,\n subscribeEntityListRefetch,\n subscribeEntityListRemoval,\n type EntityListRowPatch,\n} from './refetch-entity-lists';\nimport { useGraphQLError } from './graphql-context';\nimport type {\n EntityQueryAggregate,\n EntityQueryResults,\n FormEntityItem,\n MappedEntityQueryResults,\n MappedEntityItem,\n MappedFormEntityQueryResults,\n UseEntityQueryParams,\n ImageValue,\n} from './types';\n\ntype FetchMoreOptions = {\n // `offset` is accepted for call-site compatibility but overridden by nextOffsetRef.\n // `where`/`sort` are inherited from the active query unless overridden here.\n variables: OperationVariables & { offset: number; limit: number };\n};\ntype Results = (MappedEntityQueryResults | MappedFormEntityQueryResults) | { count: 0; results: [] };\n\nexport function useEntityQuery({\n entityNamePlural,\n schema,\n scope,\n variables,\n isForm,\n selection = 'full',\n includeCount = true,\n fetchPolicy,\n}: UseEntityQueryParams): {\n count: number;\n data: MappedEntityItem[] | FormEntityItem[] | ImageValue[] | undefined;\n fetchMore: (args: FetchMoreOptions) => void;\n isLoading: boolean;\n isLoadingMore: boolean;\n isProjectDisabled: boolean;\n isProjectReadOnly: boolean;\n reload: (options?: { preserve?: boolean }) => Promise<void>;\n schemaErrorMessage: string | null;\n} {\n const [result, setResult] = useState<Results>({\n count: 0,\n results: [],\n });\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n const [isReloading, setIsReloading] = useState(false);\n const [unsupportedTotalCount, setUnsupportedTotalCount] = useState<{\n field: string;\n schema: UseEntityQueryParams['schema'];\n } | null>(null);\n const isLoadingMoreRef = useRef(false);\n const isReloadingRef = useRef(false);\n // Next offset for fetchMore — advanced by each requested page window, not by the\n // deduplicated row count. Using unique rows.length as offset collapses when pages\n // overlap (unstable sorts / tied timestamps) into irregular steps like 25→35→42.\n const nextOffsetRef = useRef(0);\n // Tracks the query identity we last synced into local result state.\n // fetchMore updates Apollo `data` without changing this identity; syncing those\n // updates would wipe accumulated pages and retrigger infinite load-more.\n // Must include entity/scope — variables alone collide across entity navigations.\n const syncedQueryKeyRef = useRef<string | null>(null);\n const pendingQueryKeyRef = useRef<string | null>(null);\n const totalCountField = `${entityNamePlural}Total`;\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const canUseTotalCount =\n variables?.where === undefined &&\n (entitySchema?.spaces?.length ?? 0) === 0 &&\n (unsupportedTotalCount?.field !== totalCountField || unsupportedTotalCount.schema !== schema);\n const countMode = canUseTotalCount ? 'total' : 'aggregate';\n const queryDocument = useMemo(\n () => gql(getEntityQuery(entityNamePlural, scope, schema, { selection, countMode, includeCount }).query),\n [entityNamePlural, scope, schema, selection, countMode, includeCount]\n );\n // fetchMore pages skip the top-level aggregate count (a filtered label scan\n // on the server); the total from the first page still stands.\n const fetchMoreDocument = useMemo(\n () => gql(getEntityQuery(entityNamePlural, scope, schema, { selection, includeCount: false }).query),\n [entityNamePlural, scope, schema, selection]\n );\n const { schemaErrorMessage, setSchemaErrorMessage } = useGraphQLError();\n const {\n loading: isLoading,\n data,\n fetchMore: fetchNextPage,\n refetch,\n error,\n networkStatus,\n } = useQuery<EntityQueryResults & EntityQueryAggregate>(queryDocument, {\n variables,\n notifyOnNetworkStatusChange: true,\n fetchPolicy,\n });\n const fetchNextPageRef = useRef(fetchNextPage);\n const refetchRef = useRef(refetch);\n const fetchMoreDocumentRef = useRef(fetchMoreDocument);\n const previousNetworkStatusRef = useRef(networkStatus);\n const variablesRef = useRef(variables);\n fetchNextPageRef.current = fetchNextPage;\n refetchRef.current = refetch;\n fetchMoreDocumentRef.current = fetchMoreDocument;\n variablesRef.current = variables;\n\n // Parse 403 error response to determine the specific error code\n const isMissingTotalCountField = includeCount && isMissingGraphQLFieldError(error, totalCountField);\n const shouldFallbackToAggregate = countMode === 'total' && isMissingTotalCountField;\n const effectiveError = isMissingTotalCountField ? undefined : error;\n const isTotalCountFallbackLoading = isMissingTotalCountField && !data?.[entityNamePlural];\n const serverError = getServerError(effectiveError);\n const schemaMismatchMessage = getGraphQLSchemaMismatchMessage(effectiveError);\n\n const { isProjectDisabled, isProjectReadOnly } = (() => {\n if (serverError?.statusCode === 403) {\n const responseBody = parseErrorBody<{ code?: string }>(serverError.bodyText);\n\n if (responseBody && typeof responseBody.code === 'string') {\n if (responseBody.code === 'PROJECT_PAUSED') {\n return {\n isProjectDisabled: true,\n isProjectReadOnly: false,\n };\n }\n\n if (responseBody.code === 'READ_ONLY_MODE') {\n return {\n isProjectDisabled: false,\n isProjectReadOnly: true,\n };\n }\n }\n\n return {\n isProjectDisabled: true,\n isProjectReadOnly: false,\n };\n }\n\n return {\n isProjectDisabled: false,\n isProjectReadOnly: false,\n };\n })();\n\n useEffect(() => {\n if (!shouldFallbackToAggregate) {\n return;\n }\n\n setUnsupportedTotalCount({ field: totalCountField, schema });\n }, [schema, shouldFallbackToAggregate, totalCountField]);\n\n const fetchMore = useCallback(\n (args: FetchMoreOptions): void => {\n if (isLoadingMoreRef.current || isReloadingRef.current) {\n return;\n }\n\n isLoadingMoreRef.current = true;\n setIsLoadingMore(true);\n\n const { limit } = args.variables;\n const offset = nextOffsetRef.current;\n\n fetchNextPageRef\n .current({\n ...args,\n query: fetchMoreDocumentRef.current,\n variables: {\n // fetchMore uses a count-free document, so Apollo will not inherit\n // the original operation's where/sort unless we pass them again.\n ...variablesRef.current,\n ...args.variables,\n offset,\n limit,\n },\n })\n .then(({ data: res }) => {\n const mappedFetchMoreResults = mapResults({ data: res, entityNamePlural, isForm, schema, scope });\n // Advance by the fetched page window (capped at limit), not by how many unique\n // rows survived client-side merge. Cap protects against Apollo returning a\n // merged cache blob larger than the requested page.\n const pageLength = mappedFetchMoreResults.results.length;\n nextOffsetRef.current = offset + (pageLength === 0 ? 0 : Math.min(pageLength, limit));\n\n setResult((prevRows) => {\n const merged = uniqBy(prop('_id'), [\n ...prevRows.results,\n ...mappedFetchMoreResults.results,\n ]) as Results['results'];\n\n // Empty/duplicate pages must end pagination, otherwise load-more loops forever\n // when aggregate count is ahead of rows that the where-clause can actually return.\n if (merged.length === prevRows.results.length) {\n return {\n count: prevRows.results.length,\n results: prevRows.results,\n } as Results;\n }\n\n // Count-free pagination pages report 0; the first page's total stands.\n return {\n count: mappedFetchMoreResults.count || prevRows.count,\n results: merged,\n } as Results;\n });\n })\n .catch((fetchError: unknown) => {\n console.error('Error fetching more data:', fetchError);\n })\n .finally(() => {\n isLoadingMoreRef.current = false;\n setIsLoadingMore(false);\n });\n },\n [entityNamePlural, isForm, schema, scope]\n );\n\n const reload = useCallback(\n (options?: { preserve?: boolean }): Promise<void> => {\n if (isReloadingRef.current) {\n return Promise.resolve();\n }\n\n const preserve = options?.preserve === true;\n\n isReloadingRef.current = true;\n isLoadingMoreRef.current = false;\n setIsLoadingMore(false);\n\n if (!preserve) {\n syncedQueryKeyRef.current = null;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = 0;\n setIsReloading(true);\n setResult({ count: 0, results: [] });\n }\n\n return refetchRef\n .current()\n .then(({ data: res }) => {\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data: res, entityNamePlural, isForm, schema, scope });\n\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n })\n .catch((fetchError: unknown) => {\n console.error('Error reloading data:', fetchError);\n })\n .finally(() => {\n isReloadingRef.current = false;\n setIsReloading(false);\n });\n },\n [entityNamePlural, isForm, schema, scope, selection, includeCount, variables]\n );\n\n useEffect(() => {\n if (schemaMismatchMessage) {\n setSchemaErrorMessage(schemaMismatchMessage);\n\n return;\n }\n\n if (data && schemaErrorMessage && !effectiveError) {\n setSchemaErrorMessage(null);\n }\n }, [data, effectiveError, schemaErrorMessage, schemaMismatchMessage, setSchemaErrorMessage]);\n\n useEffect(() => {\n if (effectiveError || schemaMismatchMessage || isTotalCountFallbackLoading) {\n return;\n }\n\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n\n // Already synced for this query identity — ignore Apollo `data` updates from fetchMore.\n if (syncedQueryKeyRef.current === queryKey) {\n return;\n }\n\n if (isLoading && pendingQueryKeyRef.current !== queryKey) {\n pendingQueryKeyRef.current = queryKey;\n nextOffsetRef.current = 0;\n setResult({ count: 0, results: [] });\n\n return;\n }\n\n if (isLoading) {\n return;\n }\n\n const mapped = mapResults({ data, entityNamePlural, isForm, schema, scope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n }, [\n data,\n effectiveError,\n entityNamePlural,\n isForm,\n isLoading,\n isTotalCountFallbackLoading,\n schema,\n schemaMismatchMessage,\n scope,\n selection,\n includeCount,\n variables,\n ]);\n\n // After an Apollo refetch (delete/upload), replace accumulated pages with the\n // fresh first page. fetchMore uses NetworkStatus.fetchMore and is ignored.\n useEffect(() => {\n const previousStatus = previousNetworkStatusRef.current;\n previousNetworkStatusRef.current = networkStatus;\n\n if (effectiveError || schemaMismatchMessage || isReloadingRef.current || isTotalCountFallbackLoading) {\n return;\n }\n\n if (previousStatus !== NetworkStatus.refetch || networkStatus !== NetworkStatus.ready || !data) {\n return;\n }\n\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data, entityNamePlural, isForm, schema, scope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n }, [\n data,\n effectiveError,\n entityNamePlural,\n isForm,\n isTotalCountFallbackLoading,\n networkStatus,\n schema,\n schemaMismatchMessage,\n scope,\n selection,\n includeCount,\n variables,\n ]);\n\n // Soft-refresh after mutations (tags, deletes, uploads). Local paginated state\n // ignores Apollo cache writes, so we must refetch and remap explicitly.\n useEffect(() => {\n if (isForm) {\n return;\n }\n\n const listQueryName = `Get${getOperationEntityName(entityNamePlural)}`;\n\n const unsubscribeRefetch = subscribeEntityListRefetch((queryNames) => {\n if (!queryNames.has(listQueryName) || isLoadingMoreRef.current || isReloadingRef.current) {\n return;\n }\n\n return refetchRef\n .current()\n .then(({ data: res }) => {\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data: res, entityNamePlural, isForm, schema, scope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n })\n .catch((fetchError: unknown) => {\n console.error('Error soft-refreshing entity list:', fetchError);\n });\n });\n\n const unsubscribeRemoval = subscribeEntityListRemoval((queryName, entityIds) => {\n if (queryName !== listQueryName) {\n return;\n }\n\n setResult((prev) => {\n const nextResults = prev.results.filter((row) => {\n const rowId = typeof row._id === 'string' ? row._id : undefined;\n\n return !rowId || !entityIds.has(rowId);\n });\n const removedCount = prev.results.length - nextResults.length;\n\n if (removedCount === 0) {\n return prev;\n }\n\n return {\n count: Math.max(0, prev.count - removedCount),\n results: nextResults,\n } as Results;\n });\n });\n\n const unsubscribePatch = subscribeEntityListPatch((queryName, patches) => {\n if (queryName !== listQueryName) {\n return;\n }\n\n setResult((prev) => applyEntityListPatches(prev, patches, variables?.sort));\n });\n\n return () => {\n unsubscribeRefetch();\n unsubscribeRemoval();\n unsubscribePatch();\n };\n }, [entityNamePlural, isForm, schema, scope, selection, includeCount, variables]);\n\n return {\n // Refetch keeps existing rows visible; only initial load / explicit reload show as loading.\n isLoading:\n (isLoading && networkStatus !== NetworkStatus.refetch) || isReloading || isTotalCountFallbackLoading,\n isLoadingMore,\n fetchMore,\n reload,\n count: result.count,\n data: result.results,\n isProjectDisabled,\n isProjectReadOnly,\n schemaErrorMessage,\n };\n}\n\nfunction getVariablesOffset(variables: OperationVariables | undefined): number {\n const offset = variables?.offset;\n\n return typeof offset === 'number' && Number.isFinite(offset) ? offset : 0;\n}\n\nfunction mapResults(\n args: {\n data: (EntityQueryResults & EntityQueryAggregate) | undefined;\n } & UseEntityQueryParams\n): MappedEntityQueryResults | MappedFormEntityQueryResults {\n const entityNamePlural = args.entityNamePlural as keyof FormEntityItem;\n\n if (!args.data?.[entityNamePlural]) {\n return { count: 0, results: [] };\n }\n\n return args.isForm\n ? mapQueryResultForFormFields(args.entityNamePlural, args.scope, args.data, args.schema)\n : mapQueryResult(args.entityNamePlural, args.scope, args.data, args.schema);\n}\n\nfunction applyEntityListPatches(\n prev: Results,\n patches: EntityListRowPatch[],\n sort: unknown\n): Results {\n const patchById = new Map(patches.map((patch) => [patch._id, patch]));\n let didPatch = false;\n const nextResults = prev.results.map((row) => {\n const rowId = typeof row._id === 'string' ? row._id : undefined;\n\n if (!rowId) {\n return row;\n }\n\n const patch = patchById.get(rowId);\n\n if (!patch) {\n return row;\n }\n\n didPatch = true;\n\n return {\n ...row,\n ...patch.attributes,\n };\n });\n\n if (!didPatch) {\n return prev;\n }\n\n return {\n count: prev.count,\n results: sortEntityListResults(nextResults, sort),\n } as Results;\n}\n\nfunction sortEntityListResults<T extends { [key: string]: unknown }>(results: T[], sort: unknown): T[] {\n if (!Array.isArray(sort) || sort.length === 0) {\n return results;\n }\n\n const [primarySort] = sort;\n\n if (!primarySort || typeof primarySort !== 'object') {\n return results;\n }\n\n const [primarySortEntry] = Object.entries(primarySort as { [key: string]: unknown });\n const [sortField, sortDirection] = primarySortEntry ?? [];\n\n if (!sortField || (sortDirection !== 'ASC' && sortDirection !== 'DESC')) {\n return results;\n }\n\n const direction = sortDirection === 'DESC' ? -1 : 1;\n\n return [...results].sort((left, right) => {\n const leftValue = left[sortField];\n const rightValue = right[sortField];\n const leftText = typeof leftValue === 'string' ? leftValue : '';\n const rightText = typeof rightValue === 'string' ? rightValue : '';\n\n return leftText.localeCompare(rightText) * direction;\n });\n}\n"]}
@@ -1,2 +0,0 @@
1
- import'./index.css';import {c}from'./chunk-XMOSCJOI.js';import {a}from'./chunk-ERDARDGB.js';import {f}from'./chunk-VRDTHLA3.js';import {d}from'./chunk-MBBE4RND.js';import {useMemo}from'react';import A from'swr';import {find,propEq}from'ramda';function T(n,o){let{scope:c$1}=c(),{currentProject:r}=f(),a=useMemo(()=>r?.schema??[],[r]),m=r?.scopes?.find(t=>t.isDefault)?.name??"default",e=o?.commonParams.q?JSON.stringify(o):null,{data:s,error:i,isLoading:y}=A(e,()=>fetch(d(n).search,{headers:{"Content-Type":"application/json"},body:JSON.stringify(o),method:"POST",mode:"cors"}).then(t=>t.json()),{keepPreviousData:true});return {results:useMemo(()=>e?E(s?.results??[],n,a,c$1,m)??[]:[],[s,m,n,a,c$1,e]),error:i,isLoading:y}}function E(n,o,c,r,a$1){return n?.filter(l=>l?.hits?.length>0).map(l=>{let m=l,e=m.collection.replace(`${o}_`,"").replace(/_\d+$/,""),s=find(propEq(e,"plural"))(c);if(!s)return [];let i=a(s)?.name??"",y=s?.name??e;return m.hits.map(({document:u})=>{let t=u[i],b=(t&&typeof t!="string"?t[r]??t[a$1]:null)??u[i],N=Object.entries(u).reduce((d,[p,f])=>{if(p!==i&&p!=="id"&&p!=="_updatedAt"){let _=typeof f!="string"?f[r]??f[a$1]:f;d[p]=_;}return d},{});return {_id:u.id,_entityName:y,_entityNamePlural:e,[i]:b,...N}})}).flat()}export{T as a};//# sourceMappingURL=chunk-U6NFYYTF.js.map
2
- //# sourceMappingURL=chunk-U6NFYYTF.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/use-search.tsx"],"names":["useSearch","projectId","searchRequest","scope","useAppContext","currentProject","useConfig","schema","useMemo","defaultScope","s","swrKey","data","error","isLoading","useSWR","apiPaths","res","mapResults","results","result","item","entityNamePlural","entitySchema","find","propEq","primaryAttributeName","getDisplayAttribute","entityName","document","primaryAttribute","primaryAttributeValue","attributes","acc","key","value","scopedValue"],"mappings":"mPAWO,SAASA,EACdC,CAAAA,CACAC,CAAAA,CACwE,CACxE,GAAM,CAAE,KAAA,CAAAC,GAAM,CAAA,CAAIC,GAAc,CAC1B,CAAE,cAAA,CAAAC,CAAe,EAAIC,CAAAA,EAAU,CAC/BC,CAAAA,CAASC,OAAAA,CAAQ,IAAMH,CAAAA,EAAgB,MAAA,EAAU,EAAC,CAAG,CAACA,CAAc,CAAC,CAAA,CAErEI,EADSJ,CAAAA,EAAgB,MAAA,EACF,IAAA,CAAMK,CAAAA,EAAMA,EAAE,SAAS,CAAA,EAAG,IAAA,EAAQ,SAAA,CACzDC,EAAST,CAAAA,EAAe,YAAA,CAAa,CAAA,CAAI,IAAA,CAAK,SAAA,CAAUA,CAAa,CAAA,CAAI,IAAA,CACzE,CAAE,IAAA,CAAAU,CAAAA,CAAM,KAAA,CAAAC,CAAAA,CAAO,UAAAC,CAAU,CAAA,CAAIC,CAAAA,CACjCJ,CAAAA,CACA,IACE,KAAA,CAAMK,CAAAA,CAASf,CAAS,CAAA,CAAE,MAAA,CAAQ,CAChC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AAc,IAAA,EAAQD,CAAAA,CAGzC,OAAOD,CAAAA,CAAK,IAAA,CAAK,GAAA,CAAI,CAAC,CAAE,QAAA,CAAAQ,CAAS,CAAA,GAAM,CACrC,IAAMC,CAAAA,CAAmBD,CAAAA,CAASH,CAAoB,EAKhDK,CAAAA,CAAAA,CAHJD,CAAAA,EAAoB,OAAOA,CAAAA,EAAqB,SAC3CA,CAAAA,CAAiB3B,CAAK,CAAA,EAAK2B,CAAAA,CAAiBrB,GAAY,CAAA,CACzD,IAAA,GACkDoB,CAAAA,CAASH,CAAoB,CAAA,CAC/EM,CAAAA,CAAa,MAAA,CAAO,OAAA,CAAQH,CAAQ,CAAA,CAAE,MAAA,CAC1C,CAACI,EAA0E,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAM,CAC1F,GAAID,CAAAA,GAAQR,CAAAA,EAAwBQ,IAAQ,IAAA,EAAQA,CAAAA,GAAQ,YAAA,CAAc,CACxE,IAAME,CAAAA,CAAc,OAAOD,CAAAA,EAAU,QAAA,CAAYA,EAAMhC,CAAK,CAAA,EAAKgC,CAAAA,CAAM1B,GAAY,CAAA,CAAK0B,CAAAA,CAExFF,CAAAA,CAAIC,CAAG,EAAIE,EACb,CAEA,OAAOH,CACT,EACA,EACF,CAAA,CAEA,OAAO,CACL,GAAA,CAAKJ,CAAAA,CAAS,EAAA,CACd,WAAA,CAAaD,CAAAA,CACb,iBAAA,CAAmBN,CAAAA,CACnB,CAACI,CAAoB,EAAGK,CAAAA,CACxB,GAAGC,CACL,CACF,CAAC,CACH,CAAC,CAAA,CACA,MACL","file":"chunk-U6NFYYTF.js","sourcesContent":["'use client';\n\nimport { useMemo } from 'react';\nimport useSWR from 'swr';\nimport { find, propEq } from 'ramda';\nimport { apiPaths } from './api-paths';\nimport { useAppContext } from './app-context';\nimport { useConfig } from './config/config-context';\nimport { getDisplayAttribute } from './get-display-attribute';\nimport type { Entity, RawResultItem, RawSearchResultItems, SearchRequestProps, SearchResultItem } from './types';\n\nexport function useSearch(\n projectId: string,\n searchRequest: SearchRequestProps | null\n): { results: SearchResultItem[] | []; error: Error; isLoading: boolean } {\n const { scope } = useAppContext();\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const scopes = currentProject?.scopes;\n const defaultScope = scopes?.find((s) => s.isDefault)?.name ?? 'default';\n const swrKey = searchRequest?.commonParams.q ? JSON.stringify(searchRequest) : null;\n const { data, error, isLoading } = useSWR(\n swrKey,\n () =>\n fetch(apiPaths(projectId).search, {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(searchRequest),\n method: 'POST',\n mode: 'cors',\n }).then((res) => res.json() as Promise<{ results: RawSearchResultItems }>),\n // Show the previous hits until the next request lands instead of flashing an empty list per keystroke.\n { keepPreviousData: true }\n );\n const results = useMemo(\n // SWR keeps the previous key's data while a new key loads, and also after the key becomes null.\n // Callers treat an empty query as \"no search\", so return no hits once there is nothing to search for.\n () => (swrKey ? (mapResults(data?.results ?? [], projectId, schema, scope, defaultScope) ?? []) : []),\n [data, defaultScope, projectId, schema, scope, swrKey]\n );\n\n return { results, error, isLoading };\n}\n\nfunction mapResults(\n results: RawSearchResultItems | undefined,\n projectId: string,\n schema: Entity[],\n scope: string,\n defaultScope: string\n): SearchResultItem[] | undefined {\n return results\n ?.filter((result) => (result as RawResultItem)?.hits?.length > 0)\n .map((result) => {\n const item = result as RawResultItem;\n const entityNamePlural = item.collection.replace(`${projectId}_`, '').replace(/_\\d+$/, '');\n const entitySchema = find<Entity>(propEq(entityNamePlural, 'plural'))(schema);\n\n if (!entitySchema) {\n return [];\n }\n\n const primaryAttributeName = getDisplayAttribute(entitySchema)?.name ?? '';\n const entityName = entitySchema?.name ?? entityNamePlural;\n\n // iterate over the hits and return an object with the primary attribute value first and then the rest of the attributes.\n return item.hits.map(({ document }) => {\n const primaryAttribute = document[primaryAttributeName];\n const scopedPrimaryAttribute =\n primaryAttribute && typeof primaryAttribute !== 'string'\n ? (primaryAttribute[scope] ?? primaryAttribute[defaultScope])\n : null;\n const primaryAttributeValue = scopedPrimaryAttribute ?? document[primaryAttributeName];\n const attributes = Object.entries(document).reduce(\n (acc: Omit<SearchResultItem, '_id' | '_entityName' | '_entityNamePlural'>, [key, value]) => {\n if (key !== primaryAttributeName && key !== 'id' && key !== '_updatedAt') {\n const scopedValue = typeof value !== 'string' ? (value[scope] ?? value[defaultScope]) : value;\n\n acc[key] = scopedValue;\n }\n\n return acc;\n },\n {}\n );\n\n return {\n _id: document.id,\n _entityName: entityName,\n _entityNamePlural: entityNamePlural,\n [primaryAttributeName]: primaryAttributeValue as string,\n ...attributes,\n };\n });\n })\n .flat();\n}\n"]}
@@ -1,3 +0,0 @@
1
- import'./index.css';import {e}from'./chunk-7KLXWCDS.js';import {b as b$1,c}from'./chunk-5CVDMZUI.js';import {put}from'@vercel/blob/client';function w(s,e){let l=e.trim();return l?s.trim()?/\s$/.test(s)||/^[.,!?;:]/.test(l)?`${s}${l}`:`${s} ${l}`:s.length===0?l:`${s}${l}`:s}async function C(s){if(typeof window>"u")throw new Error("Dictation is only available in the browser.");let e=window.AudioContext??window.webkitAudioContext;if(!e)throw new Error("This browser cannot decode recorded audio.");let l=await s.arrayBuffer(),u=new e;try{let n=await u.decodeAudioData(l.slice(0)),i=$(n),t=I(i,n.sampleRate,24e3),o=P(t),a=t.length/24e3;if(a<.25)throw new Error("No speech was captured. Try again.");if(a>60)throw new Error(`Dictation is limited to ${String(60)} seconds.`);return {durationSeconds:a,pcm:new Blob([o],{type:"audio/pcm"})}}finally{await u.close();}}function $(s){let{length:e,numberOfChannels:l}=s;if(l===1)return s.getChannelData(0).slice();let u=new Float32Array(e);for(let n=0;n<e;n+=1){let i=0;for(let t=0;t<l;t+=1)i+=s.getChannelData(t)[n]??0;u[n]=i/l;}return u}function I(s,e,l){if(e===l)return s;let u=e/l,n=Math.max(1,Math.round(s.length/u)),i=new Float32Array(n);for(let t=0;t<n;t+=1){let o=t*u,a=Math.floor(o),c=Math.min(a+1,s.length-1),r=o-a,g=s[a]??0,d=s[c]??0;i[t]=g+(d-g)*r;}return i}function P(s){let e=new ArrayBuffer(s.length*2),l=new DataView(e);for(let u=0;u<s.length;u+=1){let n=Math.max(-1,Math.min(1,s[u]??0));l.setInt16(u*2,n<0?n*32768:n*32767,true);}return e}async function b(s){if(!(typeof crypto>"u"||!crypto.subtle))try{let e=await crypto.subtle.digest("SHA-256",await s.arrayBuffer());return Array.from(new Uint8Array(e),l=>l.toString(16).padStart(2,"0")).join("")}catch{return}}var m=class extends Error{code;status;constructor(e,l,u=null){super(l),this.name="AgentUploadError",this.code=u,this.status=e;}};function y(){if(typeof window>"u")return "flexkit.io";if(b$1())return c;let{hostname:s}=window.location;return s==="localhost"||s==="127.0.0.1"||s==="flexkit.test"||s.endsWith(".flexkit.test")?"flexkit.test":"flexkit.io"}function v(){return `https://${y()}`}function x(s,e){return `https://${s}.api.${y()}/automations/webhook/${encodeURIComponent(e)}`}function N(s){let e$1=`/api/flexkit/${s}`,l=`${e$1}/automations`,u=`${e$1}/skills`,n=`${e$1}/agent/chats`;async function i(t,o){let a=await fetch(t,{credentials:"include",headers:{"Content-Type":"application/json",...o?.headers??{}},...o}),c=await a.json();if(!a.ok){let r=c&&typeof c=="object"&&"error"in c?String(c.error):"Request failed";throw new Error(r)}return c}return {connectPlugins:t=>i(`${e$1}/plugins/connect`,{method:"POST",body:JSON.stringify(t)}),connectPluginToken:t=>i(`${e$1}/plugins/connect-token`,{method:"POST",body:JSON.stringify(t)}),connectPluginCredentials:t=>i(`${e$1}/plugins/connect-credentials`,{method:"POST",body:JSON.stringify(t)}),pluginOAuthStatus:t=>i(`${e$1}/plugins/oauth-transactions/${encodeURIComponent(t)}`),updatePluginConnection:(t,o)=>i(`${e$1}/plugin-connections/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(o)}),disconnectPlugin:t=>i(`${e$1}/plugin-connections/${encodeURIComponent(t)}`,{method:"DELETE"}),installPlugin:t=>i(`${e$1}/plugins/${encodeURIComponent(t)}/installation`,{method:"PUT",body:JSON.stringify({})}),setPluginPolicy:(t,o)=>i(`${e$1}/plugins/${encodeURIComponent(t)}/policy`,{method:"PATCH",body:JSON.stringify(o)}),refreshPluginTools:t=>i(`${e$1}/plugin-connections/${encodeURIComponent(t)}/tools/refresh`,{method:"POST"}),cancelRun:async t=>i(`${l}/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"}),createAgentChat:async t=>i(n,{body:JSON.stringify({modelId:t?.modelId??null}),method:"POST"}),deleteAgentChat:async t=>i(`${n}/${encodeURIComponent(t)}`,{method:"DELETE"}),getAgentChatStreamUrl:(t,o)=>`${n}/${encodeURIComponent(t)}/stream?workflowRunId=${encodeURIComponent(o)}`,renameAgentChat:async(t,o)=>i(`${n}/${encodeURIComponent(t)}`,{body:JSON.stringify({title:o}),method:"PATCH"}),sendAgentChatMessage:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/messages`,{body:JSON.stringify(o),method:"POST"}),announcePluginConnected:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/plugin-connected`,{body:JSON.stringify({pluginId:o}),method:"POST"}),sendAgentChatFollowUp:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/follow-ups`,{body:JSON.stringify(o),method:"POST"}),answerAgentChatQuestion:async(t,o,a)=>{let c=await fetch(`${n}/${encodeURIComponent(t)}/questions/${encodeURIComponent(o)}/answer`,{body:JSON.stringify(a),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST"}),r=await c.json();if(!c.ok&&!r.question)throw new Error(r.errorMessage??r.error??"Request failed");return {errorMessage:c.ok?void 0:r.errorMessage,question:r.question}},startAgentChat:async({attachments:t,content:o,modelId:a})=>i(n,{body:JSON.stringify({message:{attachments:t,content:o},modelId:a??null}),method:"POST"}),startQueuedAgentChatMessage:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/follow-ups/${encodeURIComponent(o)}/start`,{method:"POST"}),stopAgentChat:async t=>i(`${n}/${encodeURIComponent(t)}/stop`,{method:"POST"}),stopAgentChatMonitor:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/monitors/${encodeURIComponent(o)}/stop`,{method:"POST"}),transcribeAgentAudio:async(t,o)=>{let{durationSeconds:a,pcm:c}=await C(t),r=new FormData;r.append("file",c,"audio.pcm"),r.append("durationSeconds",String(a));let g=await fetch(`${e$1}/agent/transcribe`,{body:r,credentials:"include",method:"POST",signal:o}),d=await g.json();if(!g.ok){let S=d&&typeof d=="object"&&d.error?String(d.error):"Request failed";throw new Error(S)}if(!d.text?.trim())throw new Error("No speech was recognized. Try again.");return {text:d.text}},uploadAgentChatAttachment:async(t,o)=>{let[a,c]=await Promise.all([fetch(`${e$1}/agent/uploads`,{body:JSON.stringify({filename:t.name,mediaType:t.type||null,sizeBytes:t.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:o}),e({name:t.name,size:t.size})===null?b(t):void 0]),r=await a.json();if(!a.ok||!r.pathname||!r.token||!r.mediaType)throw new m(a.status,r.error?String(r.error):"The file could not be uploaded.",r.code??null);let g=await put(r.pathname,t,{abortSignal:o,access:"public",contentType:r.mediaType,token:r.token});return {filename:t.name,mediaType:r.mediaType,sizeBytes:t.size,url:g.url,...c?{sha256:c}:{}}},decideApproval:async(t,o)=>{let a=await fetch(`${l}/approvals/${encodeURIComponent(t)}/decide`,{body:JSON.stringify(o),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST"}),c=await a.json();if(!a.ok&&typeof c.success!="boolean")throw new Error(c.error?String(c.error):"Request failed");return c},markActivityRead:async t=>i(`${e$1}/activity/read`,{body:JSON.stringify(t==="all"?{all:true}:{ids:t}),method:"POST"}),setActivityItemState:async(t,o)=>i(`${e$1}/activity/${encodeURIComponent(t)}`,{body:JSON.stringify({state:o}),method:"PATCH"}),createAutomation:async t=>i(l,{body:JSON.stringify(t),method:"POST"}),createSkill:async t=>i(u,{body:JSON.stringify(t),method:"POST"}),deleteAutomation:async t=>i(`${l}/${encodeURIComponent(t)}`,{method:"DELETE"}),deleteSkill:async t=>i(`${u}/${encodeURIComponent(t)}`,{method:"DELETE"}),getArtifactUrl:(t,o)=>{let a=o?.download?"?download=1":"";return `${l}/artifacts/${encodeURIComponent(t)}/content${a}`},getRunArtifacts:async t=>i(`${l}/runs/${encodeURIComponent(t)}/artifacts`).then(o=>o.artifacts),getStreamUrl:t=>`${l}/runs/${encodeURIComponent(t)}/stream`,getTranscriptUrl:t=>`${l}/runs/${encodeURIComponent(t)}/transcript`,listChannels:async(t,o)=>{let a=o?`${e$1}/plugin-connections/${encodeURIComponent(o)}/channels`:`${e$1}/plugins/${t}/channels`,c=await fetch(a,{credentials:"include",headers:{"Content-Type":"application/json"}}),r=await c.json();if(c.ok)return {channels:r.channels??[],errorMessage:r.errorMessage,success:r.success??true};if(r.success===false)return {channels:r.channels??[],errorMessage:r.errorMessage??`Failed to load ${t==="slack"?"Slack":"Teams"} channels.`,success:false};let g=r.error?String(r.error):"Request failed";throw new Error(g)},runAutomation:async t=>i(`${l}/${encodeURIComponent(t)}/runs`,{method:"POST"}),updateAutomation:async(t,o)=>i(`${l}/${encodeURIComponent(t)}`,{body:JSON.stringify(o),method:"PATCH"}),updateSkill:async(t,o)=>i(`${u}/${encodeURIComponent(t)}`,{body:JSON.stringify(o),method:"PATCH"})}}var p=class extends Error{status;constructor(e,l="Request failed"){super(l),this.name="FetcherError",this.status=e;}},D=async s=>{let e=await fetch(s,{credentials:"include"});if(!e.ok)throw new p(e.status);return await e.json()};function E(s){let e=`/api/flexkit/${s}/automations`,l=`/api/flexkit/${s}/skills`,u=`/api/flexkit/${s}/agent/chats`;return {activity:(n={})=>{let{filter:i="all",limit:t=25,offset:o=0}=n,a=new URLSearchParams({filter:i,limit:t.toString(),offset:o.toString()});return `/api/flexkit/${s}/activity?${a.toString()}`},activityItem:n=>`/api/flexkit/${s}/activity/${encodeURIComponent(n)}`,activitySummary:n=>n?`/api/flexkit/${s}/activity/summary?since=${encodeURIComponent(n)}`:`/api/flexkit/${s}/activity/summary`,agentChat:n=>`${u}/${encodeURIComponent(n)}`,agentChatSearch:n=>`${u}/search?q=${encodeURIComponent(n)}`,agentChats:(n=0)=>`${u}?offset=${n.toString()}`,agentProfile:()=>`/api/flexkit/${s}/agent/profile`,approval:n=>`${e}/approvals/${encodeURIComponent(n)}`,approvals:(n={})=>{let{limit:i=25,offset:t=0,runId:o,status:a}=n,c=new URLSearchParams({limit:i.toString(),offset:t.toString()});return a&&c.set("status",a),o&&c.set("runId",o),`${e}/approvals?${c.toString()}`},approvalsCount:`${e}/approvals?limit=1`,automation:n=>`${e}/${encodeURIComponent(n)}`,automationRuns:(n,i=0,t=25)=>`${e}/${encodeURIComponent(n)}/runs?offset=${i.toString()}&limit=${t.toString()}`,automations:(n={})=>{let{enabled:i,limit:t=25,offset:o=0,search:a,visibility:c}=n,r=new URLSearchParams({limit:t.toString(),offset:o.toString()});i&&i.length>0&&r.set("enabled",i.map(d=>d?"true":"false").join(",")),c&&c.length>0&&r.set("visibility",c.join(","));let g=a?.trim();return g&&r.set("q",g),`${e}?${r.toString()}`},creditBalance:`${e}/credits`,entities:`${e}/entities`,run:n=>`${e}/runs/${encodeURIComponent(n)}`,runHistory:(n,i=0,t=25)=>`${e}/runs?scope=${n}&offset=${i.toString()}&limit=${t.toString()}`,skill:n=>`${l}/${encodeURIComponent(n)}`,skills:(n={})=>{let{limit:i=25,offset:t=0,search:o,visibility:a}=n,c=new URLSearchParams({limit:i.toString(),offset:t.toString()});a&&a.length>0&&c.set("visibility",a.join(","));let r=o?.trim();return r&&c.set("q",r),`${l}?${c.toString()}`},spaces:`/api/flexkit/${s}/spaces`,members:n=>n?`/api/flexkit/${s}/members?spaceId=${encodeURIComponent(n)}`:`/api/flexkit/${s}/members`,tools:n=>n?`${e}/${encodeURIComponent(n)}/tools`:`${e}/tools`}}
2
- export{w as a,v as b,x as c,N as d,p as e,D as f,E as g};//# sourceMappingURL=chunk-U6VZY3V2.js.map
3
- //# sourceMappingURL=chunk-U6VZY3V2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/apps/ai/agent/dictation.ts","../src/apps/ai/api.ts"],"names":["appendDictatedText","existing","transcript","dictated","convertRecordedAudioToPcm","blob","AudioContextCtor","arrayBuffer","audioContext","audioBuffer","mono","mixToMono","resampled","resample","pcm","floatToPcm16","durationSeconds","buffer","length","channelCount","index","sum","channel","samples","sourceRate","targetRate","ratio","outputLength","output","sourceIndex","left","right","fraction","leftSample","rightSample","view","sample","sha256Hex","file","digest","byte","AgentUploadError","status","message","code","getApiRootDomain","getDesktop","flexkitDomain","hostname","getPlatformOrigin","getWebhookTriggerUrl","projectId","token","createApiClient","projectBasePath","automationsBasePath","skillsBasePath","agentChatsBasePath","request","url","init","response","data","error","input","id","runId","chatId","workflowRunId","title","pluginId","questionId","result","attachments","content","modelId","messageId","monitorId","audio","signal","formData","tokenResponse","sha256","getKnowledgeFileProblem","tokenData","put","approvalId","ids","itemId","state","automationId","skillId","artifactId","options","suffix","provider","connectionId","FetcherError","fetcher","paths","basePath","filter","limit","offset","params","since","query","enabled","search","visibility","value","trimmedSearch","scope","spaceId"],"mappings":"2IAIO,SAASA,CAAAA,CAAmBC,CAAAA,CAAkBC,CAAAA,CAA4B,CAC/E,IAAMC,CAAAA,CAAWD,CAAAA,CAAW,IAAA,EAAK,CAEjC,OAAKC,CAAAA,CAIAF,CAAAA,CAAS,MAAK,CAIf,KAAA,CAAM,IAAA,CAAKA,CAAQ,CAAA,EAAK,WAAA,CAAY,IAAA,CAAKE,CAAQ,CAAA,CAC5C,CAAA,EAAGF,CAAQ,CAAA,EAAGE,CAAQ,CAAA,CAAA,CAGxB,CAAA,EAAGF,CAAQ,IAAIE,CAAQ,CAAA,CAAA,CAPrBF,CAAAA,CAAS,MAAA,GAAW,CAAA,CAAIE,CAAAA,CAAW,CAAA,EAAGF,CAAQ,CAAA,EAAGE,CAAQ,CAAA,CAAA,CAJzDF,CAYX,CAEA,eAAsBG,CAAAA,CAA0BC,CAAAA,CAA6D,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,CAAAA,CAAS,CAAA,CAAG,MAAA,CAAAK,CAAAA,CAAQ,UAAA,CAAAC,CAAW,CAAA,CAAIhB,CAAAA,CACjDW,CAAAA,CAAS,IAAI,eAAA,CAAgB,CACjC,KAAA,CAAOF,CAAAA,CAAM,UAAS,CACtB,MAAA,CAAQC,CAAAA,CAAO,QAAA,EACjB,CAAC,CAAA,CAEGM,CAAAA,EAAcA,CAAAA,CAAW,MAAA,CAAS,CAAA,EACpCL,CAAAA,CAAO,GAAA,CAAI,YAAA,CAAcK,CAAAA,CAAW,IAAA,CAAK,GAAG,CAAC,CAAA,CAG/C,IAAME,CAAAA,CAAgBH,CAAAA,EAAQ,IAAA,EAAK,CAEnC,OAAIG,CAAAA,EACFP,CAAAA,CAAO,GAAA,CAAI,GAAA,CAAKO,CAAa,CAAA,CAGxB,CAAA,EAAGvD,CAAc,IAAIgD,CAAAA,CAAO,QAAA,EAAU,CAAA,CAC/C,CAAA,CACA,MAAA,CAAQ,CAAA,aAAA,EAAgBrD,CAAS,CAAA,OAAA,CAAA,CACjC,OAAA,CAAU8D,CAAAA,EACRA,CAAAA,CACI,CAAA,aAAA,EAAgB9D,CAAS,CAAA,iBAAA,EAAoB,kBAAA,CAAmB8D,CAAO,CAAC,CAAA,CAAA,CACxE,CAAA,aAAA,EAAgB9D,CAAS,CAAA,QAAA,CAAA,CAC/B,KAAA,CAAQuC,CAAAA,EACNA,CAAAA,CAAe,GAAGU,CAAQ,CAAA,CAAA,EAAI,kBAAA,CAAmBV,CAAY,CAAC,CAAA,MAAA,CAAA,CAAW,CAAA,EAAGU,CAAQ,QACxF,CACF","file":"chunk-U6VZY3V2.js","sourcesContent":["export const DICTATION_SAMPLE_RATE = 24_000;\nexport const DICTATION_MAX_DURATION_SECONDS = 60;\nexport const DICTATION_MIN_DURATION_SECONDS = 0.25;\n\nexport function appendDictatedText(existing: string, transcript: string): string {\n const dictated = transcript.trim();\n\n if (!dictated) {\n return existing;\n }\n\n if (!existing.trim()) {\n return existing.length === 0 ? dictated : `${existing}${dictated}`;\n }\n\n if (/\\s$/.test(existing) || /^[.,!?;:]/.test(dictated)) {\n return `${existing}${dictated}`;\n }\n\n return `${existing} ${dictated}`;\n}\n\nexport async function convertRecordedAudioToPcm(blob: Blob): Promise<{ durationSeconds: number; pcm: Blob }> {\n if (typeof window === 'undefined') {\n throw new Error('Dictation is only available in the browser.');\n }\n\n const AudioContextCtor = window.AudioContext ?? window.webkitAudioContext;\n\n if (!AudioContextCtor) {\n throw new Error('This browser cannot decode recorded audio.');\n }\n\n const arrayBuffer = await blob.arrayBuffer();\n const audioContext = new AudioContextCtor();\n\n try {\n const audioBuffer = await audioContext.decodeAudioData(arrayBuffer.slice(0));\n const mono = mixToMono(audioBuffer);\n const resampled = resample(mono, audioBuffer.sampleRate, DICTATION_SAMPLE_RATE);\n const pcm = floatToPcm16(resampled);\n const durationSeconds = resampled.length / DICTATION_SAMPLE_RATE;\n\n if (durationSeconds < DICTATION_MIN_DURATION_SECONDS) {\n throw new Error('No speech was captured. Try again.');\n }\n\n if (durationSeconds > DICTATION_MAX_DURATION_SECONDS) {\n throw new Error(`Dictation is limited to ${String(DICTATION_MAX_DURATION_SECONDS)} seconds.`);\n }\n\n return {\n durationSeconds,\n pcm: new Blob([pcm], { type: 'audio/pcm' }),\n };\n } finally {\n await audioContext.close();\n }\n}\n\nfunction mixToMono(buffer: AudioBuffer): Float32Array {\n const { length, numberOfChannels: channelCount } = buffer;\n\n if (channelCount === 1) {\n return buffer.getChannelData(0).slice();\n }\n\n const mono = new Float32Array(length);\n\n for (let index = 0; index < length; index += 1) {\n let sum = 0;\n\n for (let channel = 0; channel < channelCount; channel += 1) {\n sum += buffer.getChannelData(channel)[index] ?? 0;\n }\n\n mono[index] = sum / channelCount;\n }\n\n return mono;\n}\n\nfunction resample(samples: Float32Array, sourceRate: number, targetRate: number): Float32Array {\n if (sourceRate === targetRate) {\n return samples;\n }\n\n const ratio = sourceRate / targetRate;\n const outputLength = Math.max(1, Math.round(samples.length / ratio));\n const output = new Float32Array(outputLength);\n\n for (let index = 0; index < outputLength; index += 1) {\n const sourceIndex = index * ratio;\n const left = Math.floor(sourceIndex);\n const right = Math.min(left + 1, samples.length - 1);\n const fraction = sourceIndex - left;\n const leftSample = samples[left] ?? 0;\n const rightSample = samples[right] ?? 0;\n output[index] = leftSample + (rightSample - leftSample) * fraction;\n }\n\n return output;\n}\n\nfunction floatToPcm16(samples: Float32Array): ArrayBuffer {\n const buffer = new ArrayBuffer(samples.length * 2);\n const view = new DataView(buffer);\n\n for (let index = 0; index < samples.length; index += 1) {\n const sample = Math.max(-1, Math.min(1, samples[index] ?? 0));\n view.setInt16(index * 2, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);\n }\n\n return buffer;\n}\n\ndeclare global {\n interface Window {\n webkitAudioContext?: typeof AudioContext;\n }\n}\n","import { getKnowledgeFileProblem } from '../knowledge/knowledge';\nimport type { PluginConnection, PluginScope, PluginTools } from './plugin-types';\nimport { put } from '@vercel/blob/client';\nimport { convertRecordedAudioToPcm } from './agent/dictation';\nimport { getDesktop } from '../../core/desktop';\nimport { flexkitDomain } from '../../core/domains';\nimport type {\n ActivityItem,\n ActivityItemState,\n AgentChat,\n AgentChatAttachment,\n AgentChatFollowUpResult,\n AgentChatMessage,\n AgentChatMonitor,\n AgentChatQuestion,\n AgentChatQuestionResponse,\n AgentChatTurn,\n Automation,\n AutomationApproval,\n AutomationApprovalStatus,\n AutomationArtifact,\n AutomationInput,\n AutomationToolChannel,\n AutomationToolProvider,\n AutomationVisibility,\n MutationResult,\n Skill,\n SkillInput,\n} from './types';\n\nexport interface DecideApprovalInput {\n /** Approve and always allow this plugin tool for the automation. */\n remember?: boolean;\n approved: boolean;\n /** For a proposed automation: the approver's edited instructions and whether to run it once now. */\n automationEdits?: { instructions?: string; runOnce?: boolean };\n force?: boolean;\n reason?: string;\n /** For a proposed skill: the fields the approver edited. */\n skillEdits?: { content?: string; description?: string; name?: string };\n}\n\nexport interface SendAgentChatMessageInput {\n attachments?: AgentChatAttachment[];\n content: string;\n modelId?: string | null;\n}\n\n/** A new chat and its first turn, started by one request. */\nexport interface StartAgentChatResult {\n chat: AgentChat;\n turn: AgentChatTurn;\n}\n\n/** Lowercase hex SHA-256 of a file, or undefined where the browser cannot hash (insecure contexts). */\nasync function sha256Hex(file: File): Promise<string | undefined> {\n if (typeof crypto === 'undefined' || !crypto.subtle) {\n return undefined;\n }\n\n try {\n const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer());\n\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n } catch {\n return undefined;\n }\n}\n\n/** Thrown when the API refuses an upload; `code` lets the UI tailor the message. */\nexport class AgentUploadError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'AgentUploadError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ApiClient {\n /** Starts OAuth for a new account, or for `connectionId` to reconnect that specific account. */\n connectPlugins: (_input: {\n pluginId: string;\n scope: PluginScope;\n studioOrigin: string;\n connectionId?: string;\n }) => Promise<{ transactionId: string; authorizeUrl: string; completionOrigin: string; launchTicket: string }>;\n /** Connects a credentials plugin from its form, or replaces the credentials of `connectionId`. */\n connectPluginCredentials: (_input: {\n pluginId: string;\n scope: PluginScope;\n method?: string;\n values: { [key: string]: string };\n connectionId?: string;\n }) => Promise<{ connection: PluginConnection }>;\n /** Connects a token plugin with a pasted token, or replaces the token of `connectionId`. */\n connectPluginToken: (_input: {\n pluginId: string;\n scope: PluginScope;\n token: string;\n connectionId?: string;\n }) => Promise<{ connection: PluginConnection }>;\n /** Renames (label null resets to the provider name) or makes a connection primary. */\n updatePluginConnection: (\n _id: string,\n _input: { label?: string | null; primary?: true }\n ) => Promise<{ connection: PluginConnection }>;\n pluginOAuthStatus: (\n _id: string\n ) => Promise<{ id: string; status: 'pending' | 'exchanging' | 'complete' | 'failed'; expires_at: string }>;\n disconnectPlugin: (_id: string) => Promise<{ success: boolean }>;\n installPlugin: (_id: string) => Promise<unknown>;\n setPluginPolicy: (_id: string, _input: { enabled: boolean; allowPersonal: boolean }) => Promise<{ success: boolean }>;\n refreshPluginTools: (_id: string) => Promise<PluginTools>;\n\n cancelRun: (_runId: string) => Promise<MutationResult>;\n createAgentChat: (_input?: { modelId?: string | null }) => Promise<{ chat: AgentChat }>;\n deleteAgentChat: (_chatId: string) => Promise<{ success: boolean }>;\n getAgentChatStreamUrl: (_chatId: string, _workflowRunId: string) => string;\n renameAgentChat: (_chatId: string, _title: string) => Promise<{ chat: AgentChat }>;\n sendAgentChatMessage: (_chatId: string, _input: SendAgentChatMessageInput) => Promise<AgentChatTurn>;\n /**\n * Sends a message while the chat's turn is running. The platform decides\n * whether it steers that turn or waits as the next one; if the turn has\n * meanwhile ended, the message starts the next turn.\n */\n sendAgentChatFollowUp: (_chatId: string, _input: SendAgentChatMessageInput) => Promise<AgentChatFollowUpResult>;\n /** The user connected a plugin from the chat's connect card: starts the turn that uses it, or queues it. */\n announcePluginConnected: (\n _chatId: string,\n _pluginId: string\n ) => Promise<Extract<AgentChatFollowUpResult, { followUp: unknown } | { turn: unknown }>>;\n /** Answers (or dismisses) the questions a chat turn waits on; a settled question comes back with an error. */\n answerAgentChatQuestion: (\n _chatId: string,\n _questionId: string,\n _response: AgentChatQuestionResponse\n ) => Promise<{ errorMessage?: string; question?: AgentChatQuestion }>;\n /** Creates a chat and sends its first message in one request. */\n startAgentChat: (_input: SendAgentChatMessageInput) => Promise<StartAgentChatResult>;\n /** Starts the next turn from a queued follow-up once the previous turn has ended. */\n startQueuedAgentChatMessage: (_chatId: string, _messageId: string) => Promise<AgentChatTurn>;\n stopAgentChat: (_chatId: string) => Promise<{ message: AgentChatMessage }>;\n stopAgentChatMonitor: (_chatId: string, _monitorId: string) => Promise<{ monitor: AgentChatMonitor }>;\n transcribeAgentAudio: (_audio: Blob, _signal?: AbortSignal) => Promise<{ text: string }>;\n /** Uploads a chat attachment straight to the platform file store. */\n uploadAgentChatAttachment: (_file: File, _signal?: AbortSignal) => Promise<AgentChatAttachment>;\n decideApproval: (\n _approvalId: string,\n _input: DecideApprovalInput\n ) => Promise<MutationResult & { approval?: AutomationApproval }>;\n createAutomation: (_input: AutomationInput) => Promise<MutationResult & { automation?: Automation }>;\n createSkill: (_input: SkillInput) => Promise<MutationResult & { skill?: Skill }>;\n deleteAutomation: (_automationId: string) => Promise<MutationResult>;\n deleteSkill: (_skillId: string) => Promise<MutationResult>;\n getArtifactUrl: (_artifactId: string, _options?: { download?: boolean }) => string;\n getRunArtifacts: (_workflowRunId: string) => Promise<AutomationArtifact[]>;\n getStreamUrl: (_workflowRunId: string) => string;\n /** JSON transcript of a finished run (owners and developers). */\n getTranscriptUrl: (_runId: string) => string;\n /** Lists delivery channels of `connectionId`, or of the provider's primary project account when omitted. */\n listChannels: (\n _provider: AutomationToolProvider,\n _connectionId?: string | null\n ) => Promise<{\n channels: AutomationToolChannel[];\n errorMessage?: string;\n success: boolean;\n }>;\n runAutomation: (_automationId: string) => Promise<MutationResult & { runId?: string }>;\n updateAutomation: (\n _automationId: string,\n _input: AutomationInput\n ) => Promise<MutationResult & { automation?: Automation }>;\n updateSkill: (_skillId: string, _input: SkillInput) => Promise<MutationResult & { skill?: Skill }>;\n /** Marks the caller's Activity items read; `'all'` marks every unread item. */\n markActivityRead: (_ids: string[] | 'all') => Promise<{ success: boolean }>;\n setActivityItemState: (\n _itemId: string,\n _state: Extract<ActivityItemState, 'unread' | 'read' | 'dismissed'>\n ) => Promise<{ item: ActivityItem }>;\n}\n\nfunction getApiRootDomain(): string {\n if (typeof window === 'undefined') {\n return 'flexkit.io';\n }\n\n // The desktop app serves the Studio on its own scheme (`flexkit://app`), so\n // its page hostname says nothing; the backend it was built for does.\n if (getDesktop()) {\n return flexkitDomain;\n }\n\n const { hostname } = window.location;\n const isDevHost =\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === 'flexkit.test' ||\n hostname.endsWith('.flexkit.test');\n\n return isDevHost ? 'flexkit.test' : 'flexkit.io';\n}\n\n/** Origin that hosts plugin OAuth start and completion. */\nexport function getPlatformOrigin(): string {\n return `https://${getApiRootDomain()}`;\n}\n\n/** Public URL an external system calls to fire a webhook trigger. */\nexport function getWebhookTriggerUrl(projectId: string, token: string): string {\n return `https://${projectId}.api.${getApiRootDomain()}/automations/webhook/${encodeURIComponent(token)}`;\n}\n\nexport function createApiClient(projectId: string): ApiClient {\n const projectBasePath = `/api/flexkit/${projectId}`;\n const automationsBasePath = `${projectBasePath}/automations`;\n const skillsBasePath = `${projectBasePath}/skills`;\n const agentChatsBasePath = `${projectBasePath}/agent/chats`;\n\n async function request<T>(url: string, init?: RequestInit): Promise<T> {\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n ...(init?.headers ?? {}),\n },\n ...init,\n });\n const data = (await response.json()) as T;\n\n if (!response.ok) {\n const error = data && typeof data === 'object' && 'error' in data ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n }\n\n return data;\n }\n\n return {\n connectPlugins: (input) =>\n request(`${projectBasePath}/plugins/connect`, { method: 'POST', body: JSON.stringify(input) }),\n connectPluginToken: (input) =>\n request(`${projectBasePath}/plugins/connect-token`, { method: 'POST', body: JSON.stringify(input) }),\n connectPluginCredentials: (input) =>\n request(`${projectBasePath}/plugins/connect-credentials`, { method: 'POST', body: JSON.stringify(input) }),\n pluginOAuthStatus: (id) => request(`${projectBasePath}/plugins/oauth-transactions/${encodeURIComponent(id)}`),\n updatePluginConnection: (id, input) =>\n request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body: JSON.stringify(input),\n }),\n disconnectPlugin: (id) =>\n request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}`, { method: 'DELETE' }),\n installPlugin: (id) =>\n request(`${projectBasePath}/plugins/${encodeURIComponent(id)}/installation`, {\n method: 'PUT',\n body: JSON.stringify({}),\n }),\n setPluginPolicy: (id, input) =>\n request(`${projectBasePath}/plugins/${encodeURIComponent(id)}/policy`, {\n method: 'PATCH',\n body: JSON.stringify(input),\n }),\n refreshPluginTools: (id) =>\n request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}/tools/refresh`, { method: 'POST' }),\n cancelRun: async (runId) =>\n request<MutationResult>(`${automationsBasePath}/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }),\n createAgentChat: async (input) =>\n request<{ chat: AgentChat }>(agentChatsBasePath, {\n body: JSON.stringify({ modelId: input?.modelId ?? null }),\n method: 'POST',\n }),\n deleteAgentChat: async (chatId) =>\n request<{ success: boolean }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}`, { method: 'DELETE' }),\n getAgentChatStreamUrl: (chatId, workflowRunId) =>\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/stream?workflowRunId=${encodeURIComponent(workflowRunId)}`,\n renameAgentChat: async (chatId, title) =>\n request<{ chat: AgentChat }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}`, {\n body: JSON.stringify({ title }),\n method: 'PATCH',\n }),\n sendAgentChatMessage: async (chatId, input) =>\n request<AgentChatTurn>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/messages`, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n announcePluginConnected: async (chatId, pluginId) =>\n request(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/plugin-connected`, {\n body: JSON.stringify({ pluginId }),\n method: 'POST',\n }),\n sendAgentChatFollowUp: async (chatId, input) =>\n request<AgentChatFollowUpResult>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/follow-ups`, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n answerAgentChatQuestion: async (chatId, questionId, response) => {\n const result = await fetch(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/questions/${encodeURIComponent(questionId)}/answer`,\n {\n body: JSON.stringify(response),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n }\n );\n const data = (await result.json()) as { errorMessage?: string; error?: string; question?: AgentChatQuestion };\n\n // A question settled elsewhere (409) comes back with its final state for the card to show.\n if (!result.ok && !data.question) {\n throw new Error(data.errorMessage ?? data.error ?? 'Request failed');\n }\n\n return { errorMessage: result.ok ? undefined : data.errorMessage, question: data.question };\n },\n startAgentChat: async ({ attachments, content, modelId }) =>\n request<StartAgentChatResult>(agentChatsBasePath, {\n body: JSON.stringify({ message: { attachments, content }, modelId: modelId ?? null }),\n method: 'POST',\n }),\n startQueuedAgentChatMessage: async (chatId, messageId) =>\n request<AgentChatTurn>(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/follow-ups/${encodeURIComponent(messageId)}/start`,\n { method: 'POST' }\n ),\n stopAgentChat: async (chatId) =>\n request<{ message: AgentChatMessage }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/stop`, {\n method: 'POST',\n }),\n stopAgentChatMonitor: async (chatId, monitorId) =>\n request<{ monitor: AgentChatMonitor }>(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/monitors/${encodeURIComponent(monitorId)}/stop`,\n { method: 'POST' }\n ),\n transcribeAgentAudio: async (audio, signal) => {\n const { durationSeconds, pcm } = await convertRecordedAudioToPcm(audio);\n const formData = new FormData();\n formData.append('file', pcm, 'audio.pcm');\n formData.append('durationSeconds', String(durationSeconds));\n\n const response = await fetch(`${projectBasePath}/agent/transcribe`, {\n body: formData,\n credentials: 'include',\n method: 'POST',\n signal,\n });\n const data = (await response.json()) as { error?: string; text?: string };\n\n if (!response.ok) {\n const error = data && typeof data === 'object' && data.error ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n }\n\n if (!data.text?.trim()) {\n throw new Error('No speech was recognized. Try again.');\n }\n\n return { text: data.text };\n },\n uploadAgentChatAttachment: async (file, signal) => {\n // The platform issues a token scoped to one pathname, type and size; the\n // browser then writes the bytes to the store directly, so large files\n // never pass through the API function body limit. The hash is computed\n // alongside: Knowledge documents are keyed by it, so the platform can tell\n // later whether this file is already one.\n const [tokenResponse, sha256] = await Promise.all([\n fetch(`${projectBasePath}/agent/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal,\n }),\n // Only files Knowledge can index are worth hashing; a screenshot never matches a document.\n getKnowledgeFileProblem({ name: file.name, size: file.size }) === null ? sha256Hex(file) : undefined,\n ]);\n const tokenData = (await tokenResponse.json()) as {\n code?: string;\n error?: string;\n mediaType?: string;\n pathname?: string;\n token?: string;\n };\n\n if (!tokenResponse.ok || !tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new AgentUploadError(\n tokenResponse.status,\n tokenData.error ? String(tokenData.error) : 'The file could not be uploaded.',\n tokenData.code ?? null\n );\n }\n\n const blob = await put(tokenData.pathname, file, {\n abortSignal: signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return {\n filename: file.name,\n mediaType: tokenData.mediaType,\n sizeBytes: file.size,\n url: blob.url,\n ...(sha256 ? { sha256 } : {}),\n };\n },\n decideApproval: async (approvalId, input) => {\n const response = await fetch(`${automationsBasePath}/approvals/${encodeURIComponent(approvalId)}/decide`, {\n body: JSON.stringify(input),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n const data = (await response.json()) as MutationResult & { approval?: AutomationApproval; error?: string };\n\n // Business errors (stale_preview, already_decided) come back as 400\n // with a structured body the caller must be able to inspect.\n if (!response.ok && typeof data.success !== 'boolean') {\n throw new Error(data.error ? String(data.error) : 'Request failed');\n }\n\n return data;\n },\n markActivityRead: async (ids) =>\n request<{ success: boolean }>(`${projectBasePath}/activity/read`, {\n body: JSON.stringify(ids === 'all' ? { all: true } : { ids }),\n method: 'POST',\n }),\n setActivityItemState: async (itemId, state) =>\n request<{ item: ActivityItem }>(`${projectBasePath}/activity/${encodeURIComponent(itemId)}`, {\n body: JSON.stringify({ state }),\n method: 'PATCH',\n }),\n createAutomation: async (input) =>\n request<MutationResult & { automation?: Automation }>(automationsBasePath, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n createSkill: async (input) =>\n request<MutationResult & { skill?: Skill }>(skillsBasePath, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n deleteAutomation: async (automationId) =>\n request<MutationResult>(`${automationsBasePath}/${encodeURIComponent(automationId)}`, { method: 'DELETE' }),\n deleteSkill: async (skillId) =>\n request<MutationResult>(`${skillsBasePath}/${encodeURIComponent(skillId)}`, { method: 'DELETE' }),\n getArtifactUrl: (artifactId, options) => {\n const suffix = options?.download ? '?download=1' : '';\n\n return `${automationsBasePath}/artifacts/${encodeURIComponent(artifactId)}/content${suffix}`;\n },\n getRunArtifacts: async (workflowRunId) =>\n request<{ artifacts: AutomationArtifact[] }>(\n `${automationsBasePath}/runs/${encodeURIComponent(workflowRunId)}/artifacts`\n ).then((response) => response.artifacts),\n getStreamUrl: (workflowRunId) => `${automationsBasePath}/runs/${encodeURIComponent(workflowRunId)}/stream`,\n getTranscriptUrl: (runId) => `${automationsBasePath}/runs/${encodeURIComponent(runId)}/transcript`,\n listChannels: async (provider, connectionId) => {\n const url = connectionId\n ? `${projectBasePath}/plugin-connections/${encodeURIComponent(connectionId)}/channels`\n : `${projectBasePath}/plugins/${provider}/channels`;\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n const data = (await response.json()) as {\n channels?: AutomationToolChannel[];\n error?: string;\n errorMessage?: string;\n success?: boolean;\n };\n\n if (response.ok) {\n return {\n channels: data.channels ?? [],\n errorMessage: data.errorMessage,\n success: data.success ?? true,\n };\n }\n\n if (data.success === false) {\n return {\n channels: data.channels ?? [],\n errorMessage: data.errorMessage ?? `Failed to load ${provider === 'slack' ? 'Slack' : 'Teams'} channels.`,\n success: false,\n };\n }\n\n const error = data.error ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n },\n runAutomation: async (automationId) =>\n request<MutationResult & { runId?: string }>(`${automationsBasePath}/${encodeURIComponent(automationId)}/runs`, {\n method: 'POST',\n }),\n updateAutomation: async (automationId, input) =>\n request<MutationResult & { automation?: Automation }>(\n `${automationsBasePath}/${encodeURIComponent(automationId)}`,\n {\n body: JSON.stringify(input),\n method: 'PATCH',\n }\n ),\n updateSkill: async (skillId, input) =>\n request<MutationResult & { skill?: Skill }>(`${skillsBasePath}/${encodeURIComponent(skillId)}`, {\n body: JSON.stringify(input),\n method: 'PATCH',\n }),\n };\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function paths(projectId: string): {\n activity: (_options?: { filter?: 'all' | 'needs_action'; limit?: number; offset?: number }) => string;\n activityItem: (_itemId: string) => string;\n /** Badge counts; with `since`, also the unread items created after it. */\n activitySummary: (_since?: string | null) => string;\n agentChat: (_chatId: string) => string;\n agentChatSearch: (_query: string) => string;\n agentChats: (_offset?: number) => string;\n agentProfile: () => string;\n approval: (_approvalId: string) => string;\n approvals: (_options?: {\n limit?: number;\n offset?: number;\n runId?: string;\n status?: AutomationApprovalStatus;\n }) => string;\n approvalsCount: string;\n automation: (_automationId: string) => string;\n automationRuns: (_automationId: string, _offset?: number, _limit?: number) => string;\n automations: (_options?: {\n enabled?: boolean[];\n limit?: number;\n offset?: number;\n search?: string;\n visibility?: AutomationVisibility[];\n }) => string;\n creditBalance: string;\n entities: string;\n run: (_runId: string) => string;\n runHistory: (_scope: 'mine' | 'team', _offset?: number, _limit?: number) => string;\n skill: (_skillId: string) => string;\n skills: (_options?: {\n limit?: number;\n offset?: number;\n search?: string;\n visibility?: AutomationVisibility[];\n }) => string;\n spaces: string;\n /** Members for pickers; with a space id, only members who can see that space. */\n members: (_spaceId?: string | null) => string;\n tools: (_automationId?: string) => string;\n} {\n const basePath = `/api/flexkit/${projectId}/automations`;\n const skillsBasePath = `/api/flexkit/${projectId}/skills`;\n const agentChatsBasePath = `/api/flexkit/${projectId}/agent/chats`;\n\n return {\n activity: (options = {}) => {\n const { filter = 'all', limit = 25, offset = 0 } = options;\n const params = new URLSearchParams({ filter, limit: limit.toString(), offset: offset.toString() });\n\n return `/api/flexkit/${projectId}/activity?${params.toString()}`;\n },\n activityItem: (itemId) => `/api/flexkit/${projectId}/activity/${encodeURIComponent(itemId)}`,\n activitySummary: (since) =>\n since\n ? `/api/flexkit/${projectId}/activity/summary?since=${encodeURIComponent(since)}`\n : `/api/flexkit/${projectId}/activity/summary`,\n agentChat: (chatId) => `${agentChatsBasePath}/${encodeURIComponent(chatId)}`,\n agentChatSearch: (query) => `${agentChatsBasePath}/search?q=${encodeURIComponent(query)}`,\n agentChats: (offset = 0) => `${agentChatsBasePath}?offset=${offset.toString()}`,\n agentProfile: () => `/api/flexkit/${projectId}/agent/profile`,\n approval: (approvalId) => `${basePath}/approvals/${encodeURIComponent(approvalId)}`,\n approvals: (options = {}) => {\n const { limit = 25, offset = 0, runId, status } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (status) {\n params.set('status', status);\n }\n\n if (runId) {\n params.set('runId', runId);\n }\n\n return `${basePath}/approvals?${params.toString()}`;\n },\n approvalsCount: `${basePath}/approvals?limit=1`,\n automation: (automationId) => `${basePath}/${encodeURIComponent(automationId)}`,\n automationRuns: (automationId, offset = 0, limit = 25) =>\n `${basePath}/${encodeURIComponent(automationId)}/runs?offset=${offset.toString()}&limit=${limit.toString()}`,\n automations: (options = {}) => {\n const { enabled, limit = 25, offset = 0, search, visibility } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (enabled && enabled.length > 0) {\n params.set('enabled', enabled.map((value) => (value ? 'true' : 'false')).join(','));\n }\n\n if (visibility && visibility.length > 0) {\n params.set('visibility', visibility.join(','));\n }\n\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n return `${basePath}?${params.toString()}`;\n },\n creditBalance: `${basePath}/credits`,\n entities: `${basePath}/entities`,\n run: (runId) => `${basePath}/runs/${encodeURIComponent(runId)}`,\n runHistory: (scope, offset = 0, limit = 25) =>\n `${basePath}/runs?scope=${scope}&offset=${offset.toString()}&limit=${limit.toString()}`,\n skill: (skillId) => `${skillsBasePath}/${encodeURIComponent(skillId)}`,\n skills: (options = {}) => {\n const { limit = 25, offset = 0, search, visibility } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (visibility && visibility.length > 0) {\n params.set('visibility', visibility.join(','));\n }\n\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n return `${skillsBasePath}?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n members: (spaceId) =>\n spaceId\n ? `/api/flexkit/${projectId}/members?spaceId=${encodeURIComponent(spaceId)}`\n : `/api/flexkit/${projectId}/members`,\n tools: (automationId) =>\n automationId ? `${basePath}/${encodeURIComponent(automationId)}/tools` : `${basePath}/tools`,\n };\n}\n"]}
@@ -1,2 +0,0 @@
1
- import'./index.css';import {createContext,useReducer,useContext}from'react';import {jsx}from'react/jsx-runtime';var u="core.context.scope:",r={breadcrumbs:[],isRouteLoading:false,pageTitle:"",scope:"",relationships:{}},s=createContext(r),a=createContext(()=>{});function A(t,p){let{type:o,payload:e}=p;switch(o){case "setScope":return typeof localStorage<"u"&&e.projectId&&localStorage.setItem(`${u}${e.projectId}`,e.scope),{...t,scope:e.scope};case "setRelationship":return {...t,relationships:{...t.relationships,...e}};default:throw Error(`Unknown action: ${o}`)}}function d({children:t}){let[p,o]=useReducer(A,r);return jsx(s.Provider,{value:p,children:jsx(a.Provider,{value:o,children:t})})}function h(){return useContext(s)}function x(){return useContext(a)}export{u as a,d as b,h as c,x as d};//# sourceMappingURL=chunk-XMOSCJOI.js.map
2
- //# sourceMappingURL=chunk-XMOSCJOI.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/app-context.tsx"],"names":["SCOPE_STORAGE_KEY","initialState","AppContext","createContext","AppDispatchContext","reducer","state","action","type","payload","AppProvider","children","dispatch","useReducer","jsx","useAppContext","useContext","useAppDispatch"],"mappings":"gHAMO,IAAMA,CAAAA,CAAoB,qBAAA,CAE3BC,CAAAA,CAAe,CACnB,WAAA,CAAa,EAAC,CACd,cAAA,CAAgB,MAChB,SAAA,CAAW,EAAA,CACX,KAAA,CAAO,EAAA,CACP,cAAe,EACjB,CAAA,CAEMC,CAAAA,CAAaC,cAA8BF,CAAY,CAAA,CAEvDG,CAAAA,CAAqBD,aAAAA,CAAgE,IAAM,CAEjG,CAAC,EAED,SAASE,CAAAA,CAAQC,CAAAA,CAAuBC,CAAAA,CAAgE,CACtG,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,OAAA,CAAAC,CAAQ,CAAA,CAAIF,CAAAA,CAE1B,OAAQC,CAAAA,EACN,KAAK,UAAA,CACH,OAAI,OAAO,aAAiB,GAAA,EAAeC,CAAAA,CAAQ,SAAA,EACjD,YAAA,CAAa,QAAQ,CAAA,EAAGT,CAAiB,CAAA,EAAGS,CAAAA,CAAQ,SAAS,CAAA,CAAA,CAAIA,CAAAA,CAAQ,KAAK,CAAA,CAGzE,CACL,GAAGH,CAAAA,CACH,KAAA,CAAOG,CAAAA,CAAQ,KACjB,CAAA,CACF,KAAK,iBAAA,CACH,OAAO,CACL,GAAGH,CAAAA,CACH,aAAA,CAAe,CAAE,GAAGA,CAAAA,CAAM,aAAA,CAAe,GAAGG,CAAQ,CACtD,CAAA,CACF,QACE,MAAM,MAAM,CAAA,gBAAA,EAAmBD,CAAc,CAAA,CAAE,CACnD,CACF,CAEO,SAASE,CAAAA,CAAY,CAAE,SAAAC,CAAS,CAAA,CAAyC,CAC9E,GAAM,CAACL,CAAAA,CAAOM,CAAQ,CAAA,CAAIC,UAAAA,CAAWR,EAASJ,CAAY,CAAA,CAE1D,OACEa,GAAAA,CAACZ,EAAW,QAAA,CAAX,CAAoB,KAAA,CAAOI,CAAAA,CAC1B,SAAAQ,GAAAA,CAACV,CAAAA,CAAmB,QAAA,CAAnB,CAA4B,MAAOQ,CAAAA,CAAW,QAAA,CAAAD,CAAAA,CAAS,CAAA,CAC1D,CAEJ,CAEO,SAASI,CAAAA,EAAgC,CAC9C,OAAOC,UAAAA,CAAWd,CAAU,CAC9B,CAEO,SAASe,CAAAA,EAAmE,CACjF,OAAOD,UAAAA,CAAWZ,CAAkB,CACtC","file":"chunk-XMOSCJOI.js","sourcesContent":["'use client';\n\nimport { createContext, useContext, useReducer } from 'react';\nimport type { Dispatch, JSX, ReactNode } from 'react';\nimport type { ActionSetRelationship, ActionSetScope, AppContextType } from './types';\n\nexport const SCOPE_STORAGE_KEY = 'core.context.scope:';\n\nconst initialState = {\n breadcrumbs: [],\n isRouteLoading: false,\n pageTitle: '',\n scope: '',\n relationships: {},\n};\n\nconst AppContext = createContext<AppContextType>(initialState);\n\nconst AppDispatchContext = createContext<Dispatch<ActionSetRelationship | ActionSetScope>>(() => {\n /* void */\n});\n\nfunction reducer(state: AppContextType, action: ActionSetRelationship | ActionSetScope): AppContextType {\n const { type, payload } = action;\n\n switch (type) {\n case 'setScope':\n if (typeof localStorage !== 'undefined' && payload.projectId) {\n localStorage.setItem(`${SCOPE_STORAGE_KEY}${payload.projectId}`, payload.scope);\n }\n\n return {\n ...state,\n scope: payload.scope,\n };\n case 'setRelationship':\n return {\n ...state,\n relationships: { ...state.relationships, ...payload },\n };\n default:\n throw Error(`Unknown action: ${type as string}`);\n }\n}\n\nexport function AppProvider({ children }: { children: ReactNode }): JSX.Element {\n const [state, dispatch] = useReducer(reducer, initialState);\n\n return (\n <AppContext.Provider value={state}>\n <AppDispatchContext.Provider value={dispatch}>{children}</AppDispatchContext.Provider>\n </AppContext.Provider>\n );\n}\n\nexport function useAppContext(): AppContextType {\n return useContext(AppContext);\n}\n\nexport function useAppDispatch(): Dispatch<ActionSetRelationship | ActionSetScope> {\n return useContext(AppDispatchContext);\n}\n"]}
@@ -1,2 +0,0 @@
1
- import'./index.css';function t(e){return e.dataType==="asset"?"global":e.scope}export{t as a};//# sourceMappingURL=chunk-YDVO6XWD.js.map
2
- //# sourceMappingURL=chunk-YDVO6XWD.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/attribute-scope.ts"],"names":["getAttributeScope","attribute"],"mappings":"oBAEO,SAASA,CAAAA,CAAkBC,EAAiC,CACjE,OAAIA,EAAU,QAAA,GAAa,OAAA,CAClB,QAAA,CAGFA,CAAAA,CAAU,KACnB","file":"chunk-YDVO6XWD.js","sourcesContent":["import type { Attribute, ScopeType } from './types';\n\nexport function getAttributeScope(attribute: Attribute): ScopeType {\n if (attribute.dataType === 'asset') {\n return 'global';\n }\n\n return attribute.scope;\n}\n"]}
@@ -1,2 +0,0 @@
1
- import'./index.css';import {g,e,x}from'./chunk-4PUMSUJL.js';import'./chunk-YDVO6XWD.js';import'./chunk-ERDARDGB.js';import {f}from'./chunk-VRDTHLA3.js';import'./chunk-MBBE4RND.js';import'./chunk-5CVDMZUI.js';import'./chunk-RULCANNM.js';import'./chunk-A4DPLZZF.js';import'./chunk-G5N6HEPW.js';import'./chunk-5JUG4BEF.js';import'./chunk-S7Z6KKIN.js';import'./chunk-U45E5X3H.js';import {b,c,e as e$1,a}from'./chunk-N33S7BSG.js';import {c as c$1}from'./chunk-X3SHNHHM.js';import {Waypoints}from'lucide-react';import {useNavigate}from'react-router-dom';import {jsxs,jsx}from'react/jsx-runtime';function S({entityName:n,selectedIds:t}){let{currentProjectId:i,currentProjectSchema:r}=f(),l=useNavigate(),e$2=g(r,n);if(!i||!e$2||e(e$2).length===0)return null;let a=t.length>0?`Open ${t.length} in Graph`:"Open in Graph";return jsxs(b,{children:[jsx(c,{asChild:true,children:jsxs(c$1,{"aria-label":a,className:"fk:mr-2 fk:h-8",onClick:()=>l(x(i,{entity:n,ids:t})),size:"sm",variant:"outline",children:[jsx(Waypoints,{className:"fk:size-4",strokeWidth:1.5}),t.length>0?`Graph (${t.length})`:"Graph"]})}),jsx(e$1,{children:t.length>0?"Show the selected records and their relationships":"Explore these records as a graph"})]})}function B({entityName:n,recordId:t,onNavigate:i}){let{currentProjectId:r,currentProjectSchema:l}=f(),e$2=useNavigate(),a$1=g(l,n);return !r||!a$1||!t||e(a$1).length===0?null:jsx(a,{children:jsxs(b,{children:[jsx(c,{asChild:true,children:jsx(c$1,{"aria-label":"View in Graph",className:"fk:h-9 fk:w-9",onClick:()=>{e$2(x(r,{entity:n,ids:[t]})),i?.();},size:"icon",variant:"outline",children:jsx(Waypoints,{className:"fk:size-4",strokeWidth:1.5})})}),jsx(e$1,{children:"View in Graph"})]})})}export{S as EntityGraphButton,B as RecordGraphButton};//# sourceMappingURL=entry-APJ4V7PW.js.map
2
- //# sourceMappingURL=entry-APJ4V7PW.js.map