@flexkit/studio 0.2.34 → 0.2.35
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.
- package/dist/chat-page-IR4RF46H.js +4 -0
- package/dist/chat-page-IR4RF46H.js.map +1 -0
- package/dist/{chunk-CHNQZU2P.js → chunk-7N3LTSVX.js} +2 -2
- package/dist/{chunk-CHNQZU2P.js.map → chunk-7N3LTSVX.js.map} +1 -1
- package/dist/chunk-BTH7HU5Y.js +2 -0
- package/dist/chunk-BTH7HU5Y.js.map +1 -0
- package/dist/chunk-DEG7QP5C.js +30 -0
- package/dist/chunk-DEG7QP5C.js.map +1 -0
- package/dist/{chunk-DFBG7PUJ.js → chunk-FJRDLP7V.js} +4 -4
- package/dist/{chunk-DFBG7PUJ.js.map → chunk-FJRDLP7V.js.map} +1 -1
- package/dist/{chunk-RBGXXVF4.js → chunk-J6EGNRRT.js} +3 -3
- package/dist/{chunk-RBGXXVF4.js.map → chunk-J6EGNRRT.js.map} +1 -1
- package/dist/chunk-KEGJNZLW.js +378 -0
- package/dist/chunk-KEGJNZLW.js.map +1 -0
- package/dist/chunk-PMLDA2FF.js +2 -0
- package/dist/chunk-PMLDA2FF.js.map +1 -0
- package/dist/{chunk-HR4QZ5TD.js → chunk-PWGLA33F.js} +3 -3
- package/dist/chunk-PWGLA33F.js.map +1 -0
- package/dist/chunk-PZWEC6KD.js +2 -0
- package/dist/chunk-PZWEC6KD.js.map +1 -0
- package/dist/{chunk-YC7PBLTK.js → chunk-Q4CWQHBJ.js} +2 -2
- package/dist/{chunk-YC7PBLTK.js.map → chunk-Q4CWQHBJ.js.map} +1 -1
- package/dist/{chunk-PSECMZJC.js → chunk-R6DPAMLC.js} +3 -3
- package/dist/{chunk-PSECMZJC.js.map → chunk-R6DPAMLC.js.map} +1 -1
- package/dist/{chunk-7JA6SI5H.js → chunk-RAUQCO6W.js} +2 -2
- package/dist/{chunk-7JA6SI5H.js.map → chunk-RAUQCO6W.js.map} +1 -1
- package/dist/{chunk-XYFS6X74.js → chunk-RFKMFD2O.js} +2 -2
- package/dist/{chunk-XYFS6X74.js.map → chunk-RFKMFD2O.js.map} +1 -1
- package/dist/{chunk-VRDTHLA3.js → chunk-TI3EHLRE.js} +3 -3
- package/dist/{chunk-VRDTHLA3.js.map → chunk-TI3EHLRE.js.map} +1 -1
- package/dist/chunk-W7JDZHCV.js +2 -0
- package/dist/chunk-W7JDZHCV.js.map +1 -0
- package/dist/chunk-XYE6ZAUB.js +2 -0
- package/dist/{chunk-3OBELKJU.js.map → chunk-XYE6ZAUB.js.map} +1 -1
- package/dist/chunk-ZMONKGWJ.js +4 -0
- package/dist/{chunk-2FCVATRT.js.map → chunk-ZMONKGWJ.js.map} +1 -1
- package/dist/{chunk-6AJRQSFO.js → chunk-ZRTWLY77.js} +3 -3
- package/dist/{chunk-6AJRQSFO.js.map → chunk-ZRTWLY77.js.map} +1 -1
- package/dist/entry-NQRN7SWV.js +2 -0
- package/dist/{entry-APJ4V7PW.js.map → entry-NQRN7SWV.js.map} +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/{list-7IHDJM54.js → list-7SCWJXUE.js} +3 -3
- package/dist/{list-7IHDJM54.js.map → list-7SCWJXUE.js.map} +1 -1
- package/dist/list-RPIG75US.js +2 -0
- package/dist/{list-7WFALOUT.js.map → list-RPIG75US.js.map} +1 -1
- package/dist/{pages-BV3ABSFQ.js → pages-KXERA5Z6.js} +3 -3
- package/dist/{pages-BV3ABSFQ.js.map → pages-KXERA5Z6.js.map} +1 -1
- package/dist/{plugin-pages-OWGJPPWV.js → plugin-pages-NXA4BT7Y.js} +2 -2
- package/dist/{plugin-pages-OWGJPPWV.js.map → plugin-pages-NXA4BT7Y.js.map} +1 -1
- package/dist/{project-selector-V5N2724B.js → project-selector-SA6UUVBK.js} +2 -2
- package/dist/{project-selector-V5N2724B.js.map → project-selector-SA6UUVBK.js.map} +1 -1
- package/dist/record-links-RTMCYEPM.js +2 -0
- package/dist/{record-links-3P3XSW66.js.map → record-links-RTMCYEPM.js.map} +1 -1
- package/dist/{root-GBBZ3DX5.js → root-6H6K3YQF.js} +3 -3
- package/dist/{root-GBBZ3DX5.js.map → root-6H6K3YQF.js.map} +1 -1
- package/dist/root-IBZPU2D4.js +23 -0
- package/dist/{root-RGZZYETM.js.map → root-IBZPU2D4.js.map} +1 -1
- package/dist/{root-F2GTYDJM.js → root-MBFQXX4E.js} +2 -2
- package/dist/{root-F2GTYDJM.js.map → root-MBFQXX4E.js.map} +1 -1
- package/dist/root-TSZ3CSJU.js +14 -0
- package/dist/root-TSZ3CSJU.js.map +1 -0
- package/dist/{root-NIL2UHKS.js → root-TZIXWEZO.js} +2 -2
- package/dist/{root-NIL2UHKS.js.map → root-TZIXWEZO.js.map} +1 -1
- package/dist/{root-J62PBDZ2.js → root-W5ZPSNQ2.js} +2 -2
- package/dist/{root-J62PBDZ2.js.map → root-W5ZPSNQ2.js.map} +1 -1
- package/dist/{search-IIGNCQEZ.js → search-ZLEYFT3T.js} +2 -2
- package/dist/{search-IIGNCQEZ.js.map → search-ZLEYFT3T.js.map} +1 -1
- package/dist/{skills-pages-T52MF4DO.js → skills-pages-RPMWIBLS.js} +2 -2
- package/dist/{skills-pages-T52MF4DO.js.map → skills-pages-RPMWIBLS.js.map} +1 -1
- package/dist/source-VYWE5EB5.js +2 -0
- package/dist/{source-IJAAJDGW.js.map → source-VYWE5EB5.js.map} +1 -1
- package/package.json +3 -3
- package/dist/chat-page-7XT4K75G.js +0 -4
- package/dist/chat-page-7XT4K75G.js.map +0 -1
- package/dist/chunk-2FCVATRT.js +0 -4
- package/dist/chunk-3OBELKJU.js +0 -2
- package/dist/chunk-4PUMSUJL.js +0 -30
- package/dist/chunk-4PUMSUJL.js.map +0 -1
- package/dist/chunk-ERDARDGB.js +0 -2
- package/dist/chunk-ERDARDGB.js.map +0 -1
- package/dist/chunk-HR4QZ5TD.js.map +0 -1
- package/dist/chunk-KO2JLLUJ.js +0 -2
- package/dist/chunk-KO2JLLUJ.js.map +0 -1
- package/dist/chunk-PC5Z37LT.js +0 -378
- package/dist/chunk-PC5Z37LT.js.map +0 -1
- package/dist/chunk-U6NFYYTF.js +0 -2
- package/dist/chunk-U6NFYYTF.js.map +0 -1
- package/dist/chunk-XMOSCJOI.js +0 -2
- package/dist/chunk-XMOSCJOI.js.map +0 -1
- package/dist/chunk-YDVO6XWD.js +0 -2
- package/dist/chunk-YDVO6XWD.js.map +0 -1
- package/dist/entry-APJ4V7PW.js +0 -2
- package/dist/list-7WFALOUT.js +0 -2
- package/dist/record-links-3P3XSW66.js +0 -2
- package/dist/root-LYRL7VPN.js +0 -14
- package/dist/root-LYRL7VPN.js.map +0 -1
- package/dist/root-RGZZYETM.js +0 -23
- package/dist/source-IJAAJDGW.js +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/get-display-attribute.ts","../src/core/attribute-scope.ts","../src/graphql-client/queries.ts"],"names":["getDisplayAttribute","entity","attr","getAttributeScope","attribute","FULL_ASSET_CONNECTION_LIMIT","LIST_ASSET_CONNECTION_LIMIT","NESTED_RELATIONSHIP_LIMIT","stringTypes","temporalTypes","assetFields","assetFieldsWithoutLqip","listAssetPreviewFields","isAssetRelationshipAttribute","hasOrderedAssetConnectionProperties","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","DEFAULT_SCOPE_KEY","defaultValueSelection","defaultScope","getDisplayAttributeSelection","primaryAttribute","scope","schema","forList","additionalScope","defaultValue","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","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","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","localAttributesCreate","relationshipAttributesCreate","isMultipleRelationship","hasRelationships","connectNodes","getRelatedItemsQuery","queryEntityName","getEntityAssetConnectionQuery","normalizedEntityName","assetSchema","getLocalAttributeIdsFromUpdateResponse","response","updateKey","payload","entities","nodeId"],"mappings":"iHAOO,SAASA,CAAAA,CAAoBC,CAAAA,CAAmD,CACrF,GAAKA,GAAQ,UAAA,CAAW,MAAA,CAIxB,OAAIA,CAAAA,CAAO,QACFA,CAAAA,CAAO,UAAA,CAAW,IAAA,CAAMC,CAAAA,EAASA,EAAK,IAAA,GAASD,CAAAA,CAAO,OAAO,CAAA,EAAKA,CAAAA,CAAO,UAAA,CAAW,CAAC,CAAA,CAGvFA,EAAO,UAAA,CAAW,CAAC,CAC5B,CCfO,SAASE,CAAAA,CAAkBC,CAAAA,CAAiC,CACjE,OAAIA,EAAU,QAAA,GAAa,OAAA,CAClB,QAAA,CAGFA,CAAAA,CAAU,KACnB,CC6BO,IAAMC,EAAAA,CAA8B,EAAA,CAErCC,GAA8B,CAAA,CAE9BC,EAAAA,CAA4B,CAAA,CAE5BC,EAAAA,CAA0B,CAAC,IAAA,CAAM,QAAQ,CAAA,CACzCC,EAAAA,CAA4B,CAAC,MAAA,CAAQ,UAAA,CAAY,UAAA,CAAY,MAAM,EACnEC,CAAAA,CAAc,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAAA,CAAA,CAUdC,CAAAA,CAAyB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAA,CAAA,CASzBC,EAAAA,CAAyB,CAAA;AAAA;AAAA,aAAA,EAkB/B,SAASC,CAAAA,CAA6BT,CAAAA,CAA2C,CAC/E,OAAKA,CAAAA,CAKHD,EAAkBC,CAAS,CAAA,GAAM,gBACjCA,CAAAA,CAAU,YAAA,EAAc,OAAS,UAAA,EACjCA,CAAAA,CAAU,aAAa,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AOA,CAAAA,EAAW,SACxB,EAAC,CAGHwF,CAAAA,CAAa,UAAA,CAAW,OAA4C,CAAC0G,CAAAA,CAAK/L,IAAc,CAC7F,GAAID,EAAkBC,CAAS,CAAA,GAAM,OAAA,CACnC,OAAO+L,EAIT,IAAMwC,CAAAA,CADO7M,EAAY7B,CAAAA,CAAsCG,CAAAA,CAAU,IAAI,CAAC,CAAA,EACzD,GAAA,CAErB,OAAI,OAAOuO,CAAAA,EAAW,QAAA,EAAYA,EAAO,MAAA,GAAW,CAAA,CAC3CxC,EAGF,CACL,GAAGA,EACH,CAAC/L,CAAAA,CAAU,IAAI,EAAGuO,CACpB,CACF,CAAA,CAAG,EAAE,CACP","file":"chunk-KEGJNZLW.js","sourcesContent":["import type { Attribute, Entity } from './types';\n\n/**\n * Resolve the attribute used as the entity's human-readable label.\n * Uses `entity.display` when it matches an attribute name; otherwise the first attribute.\n * The effective display attribute must not be space-bound (enforced at define/deploy time).\n */\nexport function getDisplayAttribute(entity: Entity | undefined): Attribute | undefined {\n if (!entity?.attributes.length) {\n return undefined;\n }\n\n if (entity.display) {\n return entity.attributes.find((attr) => attr.name === entity.display) ?? entity.attributes[0];\n }\n\n return entity.attributes[0];\n}\n","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","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/** The default scope when a project names none; also the key results carry the default value under. */\nexport const DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Selects the default scope's value under the key `default`, whatever the\n * project named its default scope (`default: eu`), so results always read\n * the fallback value as `.default`.\n */\nexport function defaultValueSelection(defaultScope: string): string {\n return defaultScope === DEFAULT_SCOPE_KEY ? DEFAULT_SCOPE_KEY : `${DEFAULT_SCOPE_KEY}: ${defaultScope}`;\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 defaultScope = DEFAULT_SCOPE_KEY\n): string {\n if (!primaryAttribute) {\n return '';\n }\n\n const additionalScope = scope === defaultScope ? '' : `${scope}\\n `;\n const defaultValue = defaultValueSelection(defaultScope);\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 ${defaultValue}\\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 ${defaultValue}\\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 defaultScope = DEFAULT_SCOPE_KEY\n): string {\n const defaultValue = defaultValueSelection(defaultScope);\n\n return (\n relatedEntity?.attributes.reduce((relatedAcc, relatedAttribute) => {\n const additionalScope = scope === defaultScope ? '' : `${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 ${defaultValue}\\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 ${defaultValue}\\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 /** The project's default scope (the one with `isDefault`). */\n defaultScope?: string;\n }\n): EntityQuery {\n const defaultScope = options?.defaultScope ?? DEFAULT_SCOPE_KEY;\n const defaultValue = defaultValueSelection(defaultScope);\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 ${defaultValue}\\n }\\n `,\n ''\n );\n const scopedAttribute = localAttributes.reduce(\n (acc, attribute) => `${acc}\\n ${attribute} {\\n _id\\n ${defaultValue}\\n ${scope}\\n }\\n `,\n ''\n );\n const localAttributesList: string = scope === defaultScope ? 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, defaultScope);\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, defaultScope);\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 defaultScope = DEFAULT_SCOPE_KEY\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, defaultScope) : null,\n disabled: Boolean(\n localAttribute &&\n localAttribute[scope] === null &&\n getAttributeScope(attributeSchema) === 'local' &&\n scope !== defaultScope\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 defaultScope: 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 !== defaultScope),\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; defaultScope?: 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 ??\n formatResponseFieldsForMutation(schema, entityNamePlural, scope, options?.defaultScope ?? DEFAULT_SCOPE_KEY);\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(\n schema: Schema,\n entityNamePlural: string,\n scope: string,\n defaultScope: string\n): string {\n const defaultValue = defaultValueSelection(defaultScope);\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 ${defaultValue}\\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 ${defaultValue}\\n ${scope}\\n }\\n`;\n }\n\n if (getAttributeScope(attribute) === 'relationship') {\n const additionalScope = scope === defaultScope ? '' : `${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 ${defaultValue}\\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; defaultScope?: string }\n): string {\n // A new record's values go to the default scope.\n const defaultScope = options?.defaultScope ?? DEFAULT_SCOPE_KEY;\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, defaultScope, _id);\n const imageAttributes = imageAttributesCreate(attributes, data);\n const relationshipAttributes = relationshipAttributesCreate(attributes, data);\n const responseType = entityNamePlural;\n const attributeNamesList = formatResponseFieldsForMutation(schema, responseType, defaultScope, defaultScope);\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 defaultScope,\n relatedEntityName,\n scope,\n schema,\n}: {\n attributeName: string;\n defaultScope?: 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 defaultScope,\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"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import'./index.css';import {c as c$3,i,j,d as d$2,l,f,b as b$1}from'./chunk-PWGLA33F.js';import {c as c$4}from'./chunk-MBBE4RND.js';import {e,g,a,b,c as c$1,d as d$1}from'./chunk-G5N6HEPW.js';import {a as a$1,d,c,e as e$1,g as g$1}from'./chunk-S7Z6KKIN.js';import {c as c$2,a as a$2}from'./chunk-X3SHNHHM.js';import {useId,useState}from'react';import {useNavigate}from'react-router-dom';import {ShoppingBag,MessageSquareText,Sparkles,Loader2}from'lucide-react';import ve,{mutate}from'swr';import {jsx,jsxs}from'react/jsx-runtime';function Le(e,t,o=[]){return o.find(n=>n.id===e)?.name??t.find(n=>n.projectId===e)?.title??e}function He(e,t){let o=new Map;for(let n of e){let m=t.find(c=>c.id===n),f=m?.team.id??"",s=o.get(f)??{label:m?.team.name??"",projectIds:[]};s.projectIds.push(n),o.set(f,s);}return o.size<=1?[{label:null,projectIds:e}]:[...o.values()].map(n=>({label:n.label||null,projectIds:n.projectIds}))}var se="Could not create the project. Please try again.";async function ie(e){let t=await b$1(c$4.myProjects,"POST",e,se);return t.ok?!t.project?.id||!t.team?.id?{ok:false,code:"unknown_error",message:se}:{ok:true,project:t.project,team:t.team}:t}function me(e){return e.filter(t=>t.role==="owner")}function de(e){return `/${e}/ai/agent`}var F="hosted-session";async function he(){try{let e=await fetch(c$4.me,{credentials:"same-origin"});return e.status===401?{kind:"anonymous"}:e.ok?{kind:"ready",data:await e.json()}:{kind:"error",message:`Flexkit answered ${String(e.status)} while loading your projects.`}}catch(e){return {kind:"error",message:e instanceof Error?e.message:"Flexkit is not reachable."}}}function xe(e){return e?e.kind==="anonymous"?{status:"anonymous"}:e.kind==="error"?{status:"error",message:e.message}:{status:"ready",projects:e.data.projects,teams:e.data.teams??[],user:e.data.user}:{status:"loading"}}function Ue(){let{data:e}=ve(F,he,{revalidateOnFocus:false,revalidateOnReconnect:false,shouldRetryOnError:false});return xe(e)}function Pe(e,t){if(e?.kind!=="ready"||e.data.projects.some(m=>m.id===t.project.id))return e;let o=e.data.teams??[],n={avatarUrl:null,id:t.project.id,name:t.project.name,readOnly:false,role:"owner",suspended:false,team:t.team};return {kind:"ready",data:{...e.data,projects:[...e.data.projects,n],teams:o.some(m=>m.id===t.team.id)?o:[...o,{...t.team,role:"owner"}]}}}async function x(e){await mutate(F,t=>Pe(t,e),{revalidate:false});}function we(e,t){return e?.kind!=="ready"?e:{kind:"ready",data:{...e.data,user:{...e.data.user,displayName:t}}}}async function ce(e){await mutate(F,t=>we(t,e),{revalidate:false});}function rt({askForName:e$2=false,isFirstProject:t=false,onCancel:o,onCreated:n,teams:m}){let f$1=useNavigate(),s={you:useId(),name:useId(),team:useId(),description:useId(),sample:useId()},c$2=me(m),[E,j$1]=useState(e$2?"you":"project"),[R,ue]=useState(""),[P,fe]=useState(""),[U,pe]=useState(null),w=c$2.some(a=>a.id===U)?U??"":c$2[0]?.id??"",[k,N]=useState("starter"),[B,ke]=useState(true),[C,ge]=useState(""),[O,l$1]=useState(null),[u,g$2]=useState(false),[v,ye]=useState(null);async function be(){let a=R.trim();if(!a){l$1("Tell us your name.");return}l$1(null),g$2(true);let p=await c$3(a);if(g$2(false),!p.ok){l$1(p.message);return}await ce(a),j$1("project");}function Se(){let a=i(P);l$1(a),a||j$1("start");}async function je(){if(k==="describe"&&!C.trim()){l$1("Describe your business in a sentence or two, or pick another way to start.");return}l$1(null),g$2(true);let a=v??await ie({name:P.trim(),...w?{teamId:w}:{}});if(!a.ok){l$1(a.message),g$2(false),a.code==="invalid_name"&&j$1("project");return}ye(a);let p=a.project.id,y=j(k,B,C),I={};if(y.kind==="starter"){let $=await d$2(p,{template:y.template,sampleData:y.sampleData});if(!$.ok){l$1(`${a.project.name} was created, but the starter could not be applied: ${$.message}`),g$2(false),!t&&!v&&await x(a);return}l({projectId:p});}else y.kind==="describe"&&(I={onboardingPrompt:f(y.description)});let K=de(p);t?(f$1(K,{state:I}),await x(a)):(await x(a),f$1(K,{state:I})),n?.(p);}let T=O?jsx(e,{variant:"destructive",children:jsx(g,{children:O})}):null;return E==="you"?jsxs(M,{onSubmit:()=>{be();},children:[jsxs("div",{className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(a,{htmlFor:s.you,children:"Your name"}),jsx(b,{autoComplete:"name",autoFocus:true,disabled:u,id:s.you,maxLength:80,onChange:a=>{ue(a.target.value);},placeholder:"e.g. Ann Meyer",value:R}),jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"Your teammates see it on changes and comments."})]}),T,jsx(A,{isSubmitting:u,submitLabel:"Continue"})]}):E==="project"?jsxs(M,{onSubmit:Se,children:[jsxs("div",{className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(a,{htmlFor:s.name,children:"Project name"}),jsx(b,{"aria-invalid":O?true:void 0,autoComplete:"off",autoFocus:true,id:s.name,maxLength:48,onChange:a=>{fe(a.target.value);},placeholder:"e.g. Aven Living",value:P}),jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"Usually your store or company name. You can change it later."})]}),c$2.length>1?jsxs("div",{className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(a,{htmlFor:s.team,children:"Team"}),jsxs(a$1,{onValueChange:pe,value:w,children:[jsx(d,{id:s.team,children:jsx(c,{})}),jsx(e$1,{children:c$2.map(a=>jsx(g$1,{value:a.id,children:a.name},a.id))})]})]}):null,T,jsx(A,{onCancel:o,submitLabel:"Continue"})]}):jsxs(M,{onSubmit:()=>{je();},children:[jsxs("div",{className:"fk:flex fk:flex-col fk:gap-2",children:[jsx("p",{className:"fk:text-sm fk:font-medium",id:`${s.name}-start`,children:"How do you want to start?"}),jsxs("div",{"aria-labelledby":`${s.name}-start`,className:"fk:flex fk:flex-col fk:gap-2",role:"radiogroup",children:[jsx(D,{checked:k==="starter",description:"22 ready-made entities for catalog, inventory, orders, customers and marketing, with EU, UK and US markets.",disabled:u,icon:ShoppingBag,onSelect:()=>{N("starter");},recommended:true,title:"Commerce starter",children:jsxs("div",{className:"fk:flex fk:items-center fk:justify-between fk:gap-3 fk:pt-1",children:[jsx(a,{className:"fk:text-xs fk:font-normal fk:text-muted-foreground",htmlFor:s.sample,children:"Add a sample store (Aven Living) to try things out"}),jsx(c$1,{checked:B,disabled:u,id:s.sample,onCheckedChange:ke})]})}),jsx(D,{checked:k==="describe",description:"Tell the agent what you sell and how you work; it proposes a schema for you to review.",disabled:u,icon:MessageSquareText,onSelect:()=>{N("describe");},title:"Describe your business",children:jsx(d$1,{"aria-label":"Your business",autoFocus:true,disabled:u,id:s.description,maxLength:2e3,onChange:a=>{ge(a.target.value);},placeholder:"e.g. We sell handmade ceramics online and to 40 shops in Europe, with seasonal collections.",rows:3,value:C})}),jsx(D,{checked:k==="empty",description:"Start with an empty project and build the schema in the chat.",disabled:u,icon:Sparkles,onSelect:()=>{N("empty");},title:"Start from scratch"})]})]}),T,jsx(A,{isSubmitting:u,onBack:v?void 0:()=>{l$1(null),j$1("project");},submitLabel:v?"Continue":"Create project"})]})}function M({children:e,onSubmit:t}){return jsx("form",{className:"fk:flex fk:w-full fk:flex-col fk:gap-4",onSubmit:o=>{o.preventDefault(),t();},children:e})}function A({isSubmitting:e=false,onBack:t,onCancel:o,submitLabel:n}){let m=t??o;return jsxs("div",{className:"fk:flex fk:justify-end fk:gap-2",children:[m?jsx(c$2,{disabled:e,onClick:m,type:"button",variant:"outline",children:t?"Back":"Cancel"}):null,jsxs(c$2,{className:m?void 0:"fk:w-full",disabled:e,type:"submit",children:[e?jsx(Loader2,{className:"fk:h-4 fk:w-4 fk:animate-spin"}):null,n]})]})}function D({checked:e,children:t,description:o,disabled:n,icon:m,onSelect:f,recommended:s=false,title:c}){return jsxs("div",{className:a$2("fk:rounded-lg fk:border fk:p-3 fk:transition-colors",e?"fk:border-foreground/70 fk:bg-muted/50 fk:ring-1 fk:ring-foreground/20":"fk:border-border fk:hover:bg-muted/30"),children:[jsxs("button",{"aria-checked":e,className:"fk:flex fk:w-full fk:items-start fk:gap-3 fk:text-left fk:disabled:opacity-60",disabled:n,onClick:f,role:"radio",type:"button",children:[jsx(m,{className:"fk:mt-0.5 fk:h-4 fk:w-4 fk:shrink-0 fk:text-muted-foreground"}),jsxs("span",{className:"fk:flex fk:flex-col fk:gap-0.5",children:[jsxs("span",{className:"fk:flex fk:items-center fk:gap-2 fk:text-sm fk:font-medium",children:[c,s?jsx("span",{className:"fk:rounded-full fk:bg-primary/10 fk:px-2 fk:py-0.5 fk:text-[11px] fk:font-medium fk:text-primary",children:"Recommended"}):null]}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:o})]})]}),e&&t?jsx("div",{className:"fk:mt-2 fk:pl-7",children:t}):null]})}export{Le as a,He as b,Ue as c,rt as d};//# sourceMappingURL=chunk-PMLDA2FF.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-PMLDA2FF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ui/components/project-label.ts","../src/core/config/create-project.ts","../src/core/config/use-hosted-session.ts","../src/ui/components/new-project-flow.tsx"],"names":["getProjectLabel","projectId","projects","projectSummaries","project","groupProjectIdsByTeam","projectIds","teams","id","summary","key","group","FALLBACK_MESSAGE","createHostedProject","input","outcome","send","userApiPaths","ownedTeams","team","newProjectPath","SESSION_KEY","fetchMe","response","error","toHostedSession","useHostedSession","data","useSWR","withCreatedProject","created","rememberCreatedProject","mutate","current","withDisplayName","displayName","rememberDisplayName","NewProjectFlow","askForName","isFirstProject","onCancel","onCreated","navigate","useNavigate","ids","useId","owned","step","setStep","useState","setDisplayName","name","setName","pickedTeamId","setPickedTeamId","selectedTeamId","startKind","setStartKind","sampleData","setSampleData","description","setDescription","setError","isSubmitting","setIsSubmitting","setCreated","submitName","trimmed","saveDisplayName","submitProjectName","invalid","validateProjectName","createProject","start","toProjectStart","state","applied","applyStarter","watchStarter","describeBusinessPrompt","path","errorAlert","jsx","Alert","AlertDescription","jsxs","StepForm","Label","Input","event","StepActions","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","StartOption","ShoppingBag","Switch","MessageSquareText","Textarea","Sparkles","children","onSubmit","onBack","submitLabel","secondary","Button","Loader2","checked","disabled","Icon","onSelect","recommended","title","cn"],"mappings":"khBAGO,SAASA,GACdC,CAAAA,CACAC,CAAAA,CACAC,EAAqC,EAAC,CAC9B,CACR,OACEA,CAAAA,CAAiB,KAAMC,CAAAA,EAAYA,CAAAA,CAAQ,KAAOH,CAAS,CAAA,EAAG,MAC9DC,CAAAA,CAAS,IAAA,CAAME,GAAYA,CAAAA,CAAQ,SAAA,GAAcH,CAAS,CAAA,EAAG,OAC7DA,CAEJ,CAGO,SAASI,EAAAA,CACdC,CAAAA,CACAH,EACkD,CAClD,IAAMI,EAAQ,IAAI,GAAA,CAElB,QAAWC,CAAAA,IAAMF,CAAAA,CAAY,CAC3B,IAAMG,CAAAA,CAAUN,EAAiB,IAAA,CAAMC,CAAAA,EAAYA,CAAAA,CAAQ,EAAA,GAAOI,CAAE,CAAA,CAC9DE,CAAAA,CAAMD,GAAS,IAAA,CAAK,EAAA,EAAM,GAC1BE,CAAAA,CAAQJ,CAAAA,CAAM,IAAIG,CAAG,CAAA,EAAK,CAAE,KAAA,CAAOD,CAAAA,EAAS,KAAK,IAAA,EAAQ,EAAA,CAAI,WAAY,EAAG,CAAA,CAClFE,CAAAA,CAAM,WAAW,IAAA,CAAKH,CAAE,EACxBD,CAAAA,CAAM,GAAA,CAAIG,EAAKC,CAAK,EACtB,CAEA,OAAIJ,CAAAA,CAAM,MAAQ,CAAA,CACT,CAAC,CAAE,KAAA,CAAO,IAAA,CAAM,WAAAD,CAAW,CAAC,CAAA,CAG9B,CAAC,GAAGC,CAAAA,CAAM,MAAA,EAAQ,CAAA,CAAE,GAAA,CAAKI,IAAW,CAAE,KAAA,CAAOA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,CACA,YAAA1C,CAAAA,CACA,QAAA,CAAAkD,EACA,IAAA,CAAMC,CAAAA,CACN,SAAAC,CAAAA,CACA,WAAA,CAAAC,EAAc,KAAA,CACd,KAAA,CAAAC,CACF,CAAA,CASgB,CACd,OACE7B,IAAAA,CAAC,KAAA,CAAA,CACC,SAAA,CAAW8B,GAAAA,CACT,sDACAN,CAAAA,CACI,wEAAA,CACA,uCACN,CAAA,CAEA,QAAA,CAAA,CAAAxB,KAAC,QAAA,CAAA,CACC,cAAA,CAAcwB,EACd,SAAA,CAAU,+EAAA,CACV,SAAUC,CAAAA,CACV,OAAA,CAASE,EACT,IAAA,CAAK,OAAA,CACL,KAAK,QAAA,CAEL,QAAA,CAAA,CAAA9B,GAAAA,CAAC6B,CAAAA,CAAA,CAAK,SAAA,CAAU,8DAAA,CAA+D,EAC/E1B,IAAAA,CAAC,MAAA,CAAA,CAAK,UAAU,gCAAA,CACd,QAAA,CAAA,CAAAA,KAAC,MAAA,CAAA,CAAK,SAAA,CAAU,6DACb,QAAA,CAAA,CAAA6B,CAAAA,CACAD,EACC/B,GAAAA,CAAC,MAAA,CAAA,CAAK,UAAU,kGAAA,CAAmG,QAAA,CAAA,aAAA,CAEnH,EACE,IAAA,CAAA,CACN,CAAA,CACAA,IAAC,MAAA,CAAA,CAAK,SAAA,CAAU,sCAAuC,QAAA,CAAAtB,CAAAA,CAAY,GACrE,CAAA,CAAA,CACF,CAAA,CACCiD,GAAWP,CAAAA,CAAWpB,GAAAA,CAAC,OAAI,SAAA,CAAU,iBAAA,CAAmB,SAAAoB,CAAAA,CAAS,CAAA,CAAS,MAC7E,CAEJ","file":"chunk-PMLDA2FF.js","sourcesContent":["import type { ProjectSummary, ProjectUiConfig } from '../../core/config/types';\n\n/** Name of a project: the listed name, else the deployed schema title, else the id. */\nexport function getProjectLabel(\n projectId: string,\n projects: ProjectUiConfig[],\n projectSummaries: ProjectSummary[] = []\n): string {\n return (\n projectSummaries.find((project) => project.id === projectId)?.name ??\n projects.find((project) => project.projectId === projectId)?.title ??\n projectId\n );\n}\n\n/** Groups ids by team when the summaries span more than one team; otherwise a single unnamed group. */\nexport function groupProjectIdsByTeam(\n projectIds: string[],\n projectSummaries: ProjectSummary[]\n): { label: string | null; projectIds: string[] }[] {\n const teams = new Map<string, { label: string; projectIds: string[] }>();\n\n for (const id of projectIds) {\n const summary = projectSummaries.find((project) => project.id === id);\n const key = summary?.team.id ?? '';\n const group = teams.get(key) ?? { label: summary?.team.name ?? '', projectIds: [] };\n group.projectIds.push(id);\n teams.set(key, group);\n }\n\n if (teams.size <= 1) {\n return [{ label: null, projectIds }];\n }\n\n return [...teams.values()].map((group) => ({ label: group.label || null, projectIds: group.projectIds }));\n}\n","import { userApiPaths } from '../api-paths';\nimport { send } from './onboarding';\nimport type { HostedTeam } from './types';\n\n/** What `POST /api/me/projects` answers: the new project and the team it went to (possibly a new personal team). */\nexport type CreatedProject = { project: { id: string; name: string }; team: { id: string; name: string } };\n\nexport type CreateProjectOutcome = ({ ok: true } & CreatedProject) | { ok: false; code: string; message: string };\n\nconst FALLBACK_MESSAGE = 'Could not create the project. Please try again.';\n\n/** Hosted mode: creates a project for the signed-in user (Free plan, user as owner). */\nexport async function createHostedProject(input: { name: string; teamId?: string }): Promise<CreateProjectOutcome> {\n const outcome = await send<Partial<CreatedProject>>(userApiPaths.myProjects, 'POST', input, FALLBACK_MESSAGE);\n\n if (!outcome.ok) {\n return outcome;\n }\n\n if (!outcome.project?.id || !outcome.team?.id) {\n return { ok: false, code: 'unknown_error', message: FALLBACK_MESSAGE };\n }\n\n return { ok: true, project: outcome.project, team: outcome.team };\n}\n\n/** Teams the user may create projects in, in the order `/api/me` lists them (oldest first). */\nexport function ownedTeams(teams: HostedTeam[]): HostedTeam[] {\n return teams.filter((team) => team.role === 'owner');\n}\n\n/**\n * Where a new project opens: the AI chat, which can design its schema. The\n * chat route itself, not `/ai`: that redirect would drop the navigation state\n * carrying the onboarding prompt.\n */\nexport function newProjectPath(projectId: string): string {\n return `/${projectId}/ai/agent`;\n}\n","'use client';\n\nimport useSWR, { mutate } from 'swr';\nimport { userApiPaths } from '../api-paths';\nimport type { CreatedProject } from './create-project';\nimport type { HostedTeam, HostedUser, ProjectSummary } from './types';\n\nexport type HostedSession =\n | { status: 'loading' }\n | { status: 'anonymous' }\n | { status: 'error'; message: string }\n | { status: 'ready'; user: HostedUser; projects: ProjectSummary[]; teams: HostedTeam[] };\n\n/** `teams` is missing from backends older than Studio onboarding. */\ntype MeResponse = { projects: ProjectSummary[]; teams?: HostedTeam[]; user: HostedUser };\n\nconst SESSION_KEY = 'hosted-session';\nexport type MeOutcome =\n | { kind: 'anonymous' }\n | { kind: 'error'; message: string }\n | { kind: 'ready'; data: MeResponse };\n\nasync function fetchMe(): Promise<MeOutcome> {\n try {\n const response = await fetch(userApiPaths.me, { credentials: 'same-origin' });\n\n if (response.status === 401) {\n return { kind: 'anonymous' };\n }\n\n if (!response.ok) {\n return { kind: 'error', message: `Flexkit answered ${String(response.status)} while loading your projects.` };\n }\n\n return { kind: 'ready', data: (await response.json()) as MeResponse };\n } catch (error) {\n return { kind: 'error', message: error instanceof Error ? error.message : 'Flexkit is not reachable.' };\n }\n}\n\nexport function toHostedSession(outcome: MeOutcome | undefined): HostedSession {\n if (!outcome) {\n return { status: 'loading' };\n }\n\n if (outcome.kind === 'anonymous') {\n return { status: 'anonymous' };\n }\n\n if (outcome.kind === 'error') {\n return { status: 'error', message: outcome.message };\n }\n\n return {\n status: 'ready',\n projects: outcome.data.projects,\n teams: outcome.data.teams ?? [],\n user: outcome.data.user,\n };\n}\n\n/**\n * Hosted mode: who is signed in and which projects they can open. Fetched once\n * per page load; `rememberCreatedProject` adds a project the user just created.\n */\nexport function useHostedSession(): HostedSession {\n const { data } = useSWR(SESSION_KEY, fetchMe, {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n });\n\n return toHostedSession(data);\n}\n\n/** The session with a just-created project (and its team, if new) added; the user owns both. */\nexport function withCreatedProject(outcome: MeOutcome | undefined, created: CreatedProject): MeOutcome | undefined {\n if (outcome?.kind !== 'ready' || outcome.data.projects.some((project) => project.id === created.project.id)) {\n return outcome;\n }\n\n const teams = outcome.data.teams ?? [];\n const project: ProjectSummary = {\n avatarUrl: null,\n id: created.project.id,\n name: created.project.name,\n readOnly: false,\n role: 'owner',\n suspended: false,\n team: created.team,\n };\n\n return {\n kind: 'ready',\n data: {\n ...outcome.data,\n projects: [...outcome.data.projects, project],\n teams: teams.some((team) => team.id === created.team.id) ? teams : [...teams, { ...created.team, role: 'owner' }],\n },\n };\n}\n\n/**\n * Adds a project the user just created to the session, so the Studio can open\n * it at once. No `/api/me` round trip: the create response says everything the\n * session needs, and a failed re-read must not hide a project that exists.\n */\nexport async function rememberCreatedProject(created: CreatedProject): Promise<void> {\n await mutate<MeOutcome>(SESSION_KEY, (current) => withCreatedProject(current, created), { revalidate: false });\n}\n\n/** The session with the signed-in user's new display name. */\nexport function withDisplayName(outcome: MeOutcome | undefined, displayName: string): MeOutcome | undefined {\n if (outcome?.kind !== 'ready') {\n return outcome;\n }\n\n return { kind: 'ready', data: { ...outcome.data, user: { ...outcome.data.user, displayName } } };\n}\n\n/** Shows a display name the user just saved, without re-reading `/api/me`. */\nexport async function rememberDisplayName(displayName: string): Promise<void> {\n await mutate<MeOutcome>(SESSION_KEY, (current) => withDisplayName(current, displayName), { revalidate: false });\n}\n","import { useId, useState, type JSX, type ReactNode } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport { Loader2, MessageSquareText, ShoppingBag, Sparkles, type LucideIcon } from 'lucide-react';\nimport { watchStarter } from '../../apps/ai/starter-watch';\nimport {\n createHostedProject,\n newProjectPath,\n ownedTeams,\n type CreateProjectOutcome,\n} from '../../core/config/create-project';\nimport {\n applyStarter,\n describeBusinessPrompt,\n saveDisplayName,\n toProjectStart,\n validateProjectName,\n type OnboardingNavigationState,\n type ProjectStart,\n} from '../../core/config/onboarding';\nimport type { HostedTeam } from '../../core/config/types';\nimport { rememberCreatedProject, rememberDisplayName } from '../../core/config/use-hosted-session';\nimport { cn } from '../lib/utils';\nimport { Alert, AlertDescription } from '../primitives/alert';\nimport { Button } from '../primitives/button';\nimport { Input } from '../primitives/input';\nimport { Label } from '../primitives/label';\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../primitives/select';\nimport { Switch } from '../primitives/switch';\nimport { Textarea } from '../primitives/textarea';\n\ntype Step = 'you' | 'project' | 'start';\ntype StartKind = ProjectStart['kind'];\n\n/**\n * Hosted mode: create a project in at most three short steps. Your name (only\n * when the account has none, e.g. an email sign-up), the project name, and how\n * to start: the commerce starter (schema plus an optional sample store), a\n * description the agent turns into a schema, or an empty project. The project\n * then opens in its AI chat.\n */\nexport function NewProjectFlow({\n askForName = false,\n isFirstProject = false,\n onCancel,\n onCreated,\n teams,\n}: {\n /** Ask for the user's own name first. */\n askForName?: boolean;\n /**\n * The user has no project yet, so the Studio shows this at `/`. Leave `/`\n * before the session lists the project: there, `/` redirects to the project\n * root instead of its AI chat.\n */\n isFirstProject?: boolean;\n onCancel?: () => void;\n /** Called with the new project's id once the Studio opened it. */\n onCreated?: (projectId: string) => void;\n teams: HostedTeam[];\n}): JSX.Element {\n const navigate = useNavigate();\n const ids = { you: useId(), name: useId(), team: useId(), description: useId(), sample: useId() };\n const owned = ownedTeams(teams);\n const [step, setStep] = useState<Step>(askForName ? 'you' : 'project');\n const [displayName, setDisplayName] = useState('');\n const [name, setName] = useState('');\n const [pickedTeamId, setPickedTeamId] = useState<string | null>(null);\n // Follow the teams prop: a pick that is no longer owned falls back to the first owned team.\n const selectedTeamId = owned.some((team) => team.id === pickedTeamId) ? (pickedTeamId ?? '') : (owned[0]?.id ?? '');\n const [startKind, setStartKind] = useState<StartKind>('starter');\n const [sampleData, setSampleData] = useState(true);\n const [description, setDescription] = useState('');\n const [error, setError] = useState<string | null>(null);\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set once the project exists, so a failed starter is retried on it instead of creating another project.\n const [created, setCreated] = useState<Extract<CreateProjectOutcome, { ok: true }> | null>(null);\n\n async function submitName(): Promise<void> {\n const trimmed = displayName.trim();\n\n if (!trimmed) {\n setError('Tell us your name.');\n\n return;\n }\n\n setError(null);\n setIsSubmitting(true);\n\n const outcome = await saveDisplayName(trimmed);\n\n setIsSubmitting(false);\n\n if (!outcome.ok) {\n setError(outcome.message);\n\n return;\n }\n\n await rememberDisplayName(trimmed);\n setStep('project');\n }\n\n function submitProjectName(): void {\n const invalid = validateProjectName(name);\n\n setError(invalid);\n\n if (!invalid) {\n setStep('start');\n }\n }\n\n async function createProject(): Promise<void> {\n if (startKind === 'describe' && !description.trim()) {\n setError('Describe your business in a sentence or two, or pick another way to start.');\n\n return;\n }\n\n setError(null);\n setIsSubmitting(true);\n\n // No owned team yet: let the backend create the personal team.\n const outcome =\n created ??\n (await createHostedProject({\n name: name.trim(),\n ...(selectedTeamId ? { teamId: selectedTeamId } : {}),\n }));\n\n if (!outcome.ok) {\n setError(outcome.message);\n setIsSubmitting(false);\n\n if (outcome.code === 'invalid_name') {\n setStep('project');\n }\n\n return;\n }\n\n setCreated(outcome);\n\n const projectId = outcome.project.id;\n const start = toProjectStart(startKind, sampleData, description);\n let state: OnboardingNavigationState = {};\n\n if (start.kind === 'starter') {\n const applied = await applyStarter(projectId, { template: start.template, sampleData: start.sampleData });\n\n if (!applied.ok) {\n setError(`${outcome.project.name} was created, but the starter could not be applied: ${applied.message}`);\n setIsSubmitting(false);\n\n // List it now, so closing the dialog does not hide the project until a reload. The welcome screen\n // (first project) would leave this flow once the session lists a project, so it waits for Continue.\n if (!isFirstProject && !created) {\n await rememberCreatedProject(outcome);\n }\n\n return;\n }\n\n watchStarter({ projectId });\n } else if (start.kind === 'describe') {\n state = { onboardingPrompt: describeBusinessPrompt(start.description) };\n }\n\n const path = newProjectPath(projectId);\n\n // Inside a project the Studio only opens ids the session lists, so add it first there.\n if (isFirstProject) {\n navigate(path, { state });\n await rememberCreatedProject(outcome);\n } else {\n await rememberCreatedProject(outcome);\n navigate(path, { state });\n }\n\n onCreated?.(projectId);\n }\n\n const errorAlert = error ? (\n <Alert variant=\"destructive\">\n <AlertDescription>{error}</AlertDescription>\n </Alert>\n ) : null;\n\n if (step === 'you') {\n return (\n <StepForm onSubmit={() => void submitName()}>\n <div className=\"fk:flex fk:flex-col fk:gap-2\">\n <Label htmlFor={ids.you}>Your name</Label>\n <Input\n autoComplete=\"name\"\n autoFocus\n disabled={isSubmitting}\n id={ids.you}\n maxLength={80}\n onChange={(event) => {\n setDisplayName(event.target.value);\n }}\n placeholder=\"e.g. Ann Meyer\"\n value={displayName}\n />\n <p className=\"fk:text-xs fk:text-muted-foreground\">Your teammates see it on changes and comments.</p>\n </div>\n {errorAlert}\n <StepActions isSubmitting={isSubmitting} submitLabel=\"Continue\" />\n </StepForm>\n );\n }\n\n if (step === 'project') {\n return (\n <StepForm onSubmit={submitProjectName}>\n <div className=\"fk:flex fk:flex-col fk:gap-2\">\n <Label htmlFor={ids.name}>Project name</Label>\n <Input\n aria-invalid={error ? true : undefined}\n autoComplete=\"off\"\n autoFocus\n id={ids.name}\n maxLength={48}\n onChange={(event) => {\n setName(event.target.value);\n }}\n placeholder=\"e.g. Aven Living\"\n value={name}\n />\n <p className=\"fk:text-xs fk:text-muted-foreground\">\n Usually your store or company name. You can change it later.\n </p>\n </div>\n {owned.length > 1 ? (\n <div className=\"fk:flex fk:flex-col fk:gap-2\">\n <Label htmlFor={ids.team}>Team</Label>\n <Select onValueChange={setPickedTeamId} value={selectedTeamId}>\n <SelectTrigger id={ids.team}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {owned.map((team) => (\n <SelectItem key={team.id} value={team.id}>\n {team.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n ) : null}\n {errorAlert}\n <StepActions onCancel={onCancel} submitLabel=\"Continue\" />\n </StepForm>\n );\n }\n\n return (\n <StepForm onSubmit={() => void createProject()}>\n <div className=\"fk:flex fk:flex-col fk:gap-2\">\n <p className=\"fk:text-sm fk:font-medium\" id={`${ids.name}-start`}>\n How do you want to start?\n </p>\n <div aria-labelledby={`${ids.name}-start`} className=\"fk:flex fk:flex-col fk:gap-2\" role=\"radiogroup\">\n <StartOption\n checked={startKind === 'starter'}\n description=\"22 ready-made entities for catalog, inventory, orders, customers and marketing, with EU, UK and US markets.\"\n disabled={isSubmitting}\n icon={ShoppingBag}\n onSelect={() => {\n setStartKind('starter');\n }}\n recommended\n title=\"Commerce starter\"\n >\n <div className=\"fk:flex fk:items-center fk:justify-between fk:gap-3 fk:pt-1\">\n <Label className=\"fk:text-xs fk:font-normal fk:text-muted-foreground\" htmlFor={ids.sample}>\n Add a sample store (Aven Living) to try things out\n </Label>\n <Switch checked={sampleData} disabled={isSubmitting} id={ids.sample} onCheckedChange={setSampleData} />\n </div>\n </StartOption>\n <StartOption\n checked={startKind === 'describe'}\n description=\"Tell the agent what you sell and how you work; it proposes a schema for you to review.\"\n disabled={isSubmitting}\n icon={MessageSquareText}\n onSelect={() => {\n setStartKind('describe');\n }}\n title=\"Describe your business\"\n >\n <Textarea\n aria-label=\"Your business\"\n autoFocus\n disabled={isSubmitting}\n id={ids.description}\n maxLength={2000}\n onChange={(event) => {\n setDescription(event.target.value);\n }}\n placeholder=\"e.g. We sell handmade ceramics online and to 40 shops in Europe, with seasonal collections.\"\n rows={3}\n value={description}\n />\n </StartOption>\n <StartOption\n checked={startKind === 'empty'}\n description=\"Start with an empty project and build the schema in the chat.\"\n disabled={isSubmitting}\n icon={Sparkles}\n onSelect={() => {\n setStartKind('empty');\n }}\n title=\"Start from scratch\"\n />\n </div>\n </div>\n {errorAlert}\n <StepActions\n isSubmitting={isSubmitting}\n onBack={\n created\n ? undefined\n : () => {\n setError(null);\n setStep('project');\n }\n }\n submitLabel={created ? 'Continue' : 'Create project'}\n />\n </StepForm>\n );\n}\n\nfunction StepForm({ children, onSubmit }: { children: ReactNode; onSubmit: () => void }): JSX.Element {\n return (\n <form\n className=\"fk:flex fk:w-full fk:flex-col fk:gap-4\"\n onSubmit={(event) => {\n event.preventDefault();\n onSubmit();\n }}\n >\n {children}\n </form>\n );\n}\n\nfunction StepActions({\n isSubmitting = false,\n onBack,\n onCancel,\n submitLabel,\n}: {\n isSubmitting?: boolean;\n onBack?: () => void;\n onCancel?: () => void;\n submitLabel: string;\n}): JSX.Element {\n const secondary = onBack ?? onCancel;\n\n return (\n <div className=\"fk:flex fk:justify-end fk:gap-2\">\n {secondary ? (\n <Button disabled={isSubmitting} onClick={secondary} type=\"button\" variant=\"outline\">\n {onBack ? 'Back' : 'Cancel'}\n </Button>\n ) : null}\n <Button className={secondary ? undefined : 'fk:w-full'} disabled={isSubmitting} type=\"submit\">\n {isSubmitting ? <Loader2 className=\"fk:h-4 fk:w-4 fk:animate-spin\" /> : null}\n {submitLabel}\n </Button>\n </div>\n );\n}\n\nfunction StartOption({\n checked,\n children,\n description,\n disabled,\n icon: Icon,\n onSelect,\n recommended = false,\n title,\n}: {\n checked: boolean;\n children?: ReactNode;\n description: string;\n disabled: boolean;\n icon: LucideIcon;\n onSelect: () => void;\n recommended?: boolean;\n title: string;\n}): JSX.Element {\n return (\n <div\n className={cn(\n 'fk:rounded-lg fk:border fk:p-3 fk:transition-colors',\n checked\n ? 'fk:border-foreground/70 fk:bg-muted/50 fk:ring-1 fk:ring-foreground/20'\n : 'fk:border-border fk:hover:bg-muted/30'\n )}\n >\n <button\n aria-checked={checked}\n className=\"fk:flex fk:w-full fk:items-start fk:gap-3 fk:text-left fk:disabled:opacity-60\"\n disabled={disabled}\n onClick={onSelect}\n role=\"radio\"\n type=\"button\"\n >\n <Icon className=\"fk:mt-0.5 fk:h-4 fk:w-4 fk:shrink-0 fk:text-muted-foreground\" />\n <span className=\"fk:flex fk:flex-col fk:gap-0.5\">\n <span className=\"fk:flex fk:items-center fk:gap-2 fk:text-sm fk:font-medium\">\n {title}\n {recommended ? (\n <span className=\"fk:rounded-full fk:bg-primary/10 fk:px-2 fk:py-0.5 fk:text-[11px] fk:font-medium fk:text-primary\">\n Recommended\n </span>\n ) : null}\n </span>\n <span className=\"fk:text-xs fk:text-muted-foreground\">{description}</span>\n </span>\n </button>\n {checked && children ? <div className=\"fk:mt-2 fk:pl-7\">{children}</div> : null}\n </div>\n );\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import'./index.css';import {d as d$1}from'./chunk-
|
|
2
|
-
`)}var x=["Which variants are running low on stock, and what is already on order?","Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.","Which products are missing prices, titles or SEO copy in the UK or US?","Show last month\u2019s revenue by market and sales channel.","Which open support tickets need attention today?"],v=["Design a schema for my business. Ask me what you need to know first.","Set up a product catalog with variants, prices per market and stock per warehouse.","Help me import my products from a spreadsheet."];function _(t){let e=t.trim();return e?e.length>48?"Project names can be up to 48 characters.":null:"Give your project a name."}function O(t,e,a){switch(t){case "starter":return {kind:"starter",template:"commerce",sampleData:e};case "describe":return {kind:"describe",description:a};case "empty":return {kind:"empty"}}}var h=2e3,f=300,u=new Set;async function y(t){let e=await fetch(i(t),{credentials:"include"});return e.ok?(await e.json()).starter??"missing":null}function k(t){return t.state==="seeding"||t.state==="completed"}function F({fetchStatus:t,projectId:e,publish:a=r=>mutate(i(e),{starter:r},{revalidate:false}),revalidate:c=d$1,sleep:s=r=>new Promise(o=>setTimeout(o,r))}){if(u.has(e))return;u.add(e);let r=t??(()=>y(e));(async()=>{let o=false;try{for(let l=0;l<f;l+=1){await s(h);let n=null;try{n=await r();}catch{n=null;}if(n==="missing")return;if(n!==null&&(await a(n),!o&&k(n)&&(o=!0,await c(e)),!g(n)))return}}finally{u.delete(e);}})();}export{i as a,d as b,w as c,b as d,g as e,T as f,x as g,v as h,_ as i,O as j,F as
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import'./index.css';import {d as d$1}from'./chunk-TI3EHLRE.js';import {c}from'./chunk-MBBE4RND.js';import {mutate}from'swr';function i(t){return `/api/flexkit/${t}/starter`}async function d(t,e,a,c="Something went wrong. Please try again."){try{let s=await fetch(t,{method:e,credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),r=await s.json().catch(()=>({}));return s.ok?{...r,ok:!0}:{ok:!1,code:r.code??"unknown_error",message:r.error??c}}catch{return {ok:false,code:"network_error",message:"Flexkit is not reachable. Check your connection and try again."}}}function w(t){return d(c.me,"PATCH",{displayName:t})}function b(t,e){return d(i(t),"POST",e)}function g(t){return t?.state==="queued"||t?.state==="deploying"||t?.state==="seeding"}function T(t){return [`I'm setting up Flexkit for my business: ${t.trim()}`,"","Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records."].join(`
|
|
2
|
+
`)}var x=["Which variants are running low on stock, and what is already on order?","Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.","Which products are missing prices, titles or SEO copy in the UK or US?","Show last month\u2019s revenue by market and sales channel.","Which open support tickets need attention today?"],v=["Design a schema for my business. Ask me what you need to know first.","Set up a product catalog with variants, prices per market and stock per warehouse.","Help me import my products from a spreadsheet."];function _(t){let e=t.trim();return e?e.length>48?"Project names can be up to 48 characters.":null:"Give your project a name."}function O(t,e,a){switch(t){case "starter":return {kind:"starter",template:"commerce",sampleData:e};case "describe":return {kind:"describe",description:a};case "empty":return {kind:"empty"}}}var h=2e3,f=300,u=new Set;async function y(t){let e=await fetch(i(t),{credentials:"include"});return e.ok?(await e.json()).starter??"missing":null}function k(t){return t.state==="seeding"||t.state==="completed"}function F({fetchStatus:t,projectId:e,publish:a=r=>mutate(i(e),{starter:r},{revalidate:false}),revalidate:c=d$1,sleep:s=r=>new Promise(o=>setTimeout(o,r))}){if(u.has(e))return;u.add(e);let r=t??(()=>y(e));(async()=>{let o=false;try{for(let l=0;l<f;l+=1){await s(h);let n=null;try{n=await r();}catch{n=null;}if(n==="missing")return;if(n!==null&&(await a(n),!o&&k(n)&&(o=!0,await c(e)),!g(n)))return}}finally{u.delete(e);}})();}export{i as a,d as b,w as c,b as d,g as e,T as f,x as g,v as h,_ as i,O as j,k,F as l};//# sourceMappingURL=chunk-PWGLA33F.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-PWGLA33F.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/config/onboarding.ts","../src/apps/ai/starter-watch.ts"],"names":["starterPath","projectId","send","url","method","body","fallbackMessage","response","json","saveDisplayName","displayName","userApiPaths","applyStarter","starter","isStarterRunning","status","describeBusinessPrompt","description","COMMERCE_STARTER_PROMPTS","EMPTY_STARTER_PROMPTS","validateProjectName","name","trimmed","toProjectStart","kind","sampleData","POLL_INTERVAL_MS","POLL_LIMIT","watching","fetchStarter","starterSchemaDeployed","watchStarter","fetchStatus","publish","mutate","revalidate","revalidateProjectSchema","sleep","ms","resolve","load","schemaLoaded","attempt"],"mappings":"4HAuBO,SAASA,CAAAA,CAAYC,CAAAA,CAA2B,CACrD,OAAO,gBAAgBA,CAAS,CAAA,QAAA,CAClC,CAKA,eAAsBC,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,EAAkB,yCAAA,CACqB,CACvC,GAAI,CACF,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAMJ,EAAK,CAChC,MAAA,CAAAC,CAAAA,CACA,WAAA,CAAa,aAAA,CACb,OAAA,CAAS,CAAE,cAAA,CAAgB,kBAAmB,CAAA,CAC9C,IAAA,CAAM,IAAA,CAAK,SAAA,CAAUC,CAAI,CAC3B,CAAC,CAAA,CACKG,EAAQ,MAAMD,CAAAA,CAAS,IAAA,EAAK,CAAE,KAAA,CAAM,KAAO,EAAC,CAAE,EAEpD,OAAIA,CAAAA,CAAS,EAAA,CACJ,CAAE,GAAGC,CAAAA,CAAM,EAAA,CAAI,CAAA,CAAK,EAGtB,CACL,EAAA,CAAI,CAAA,CAAA,CACJ,IAAA,CAAM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AAAA,CAAS,GAAA,CAAI3B,CAAS,CAAA,CAEtB,IAAMuC,CAAAA,CAAOR,CAAAA,GAAgB,IAAMH,CAAAA,CAAa5B,CAAS,CAAA,CAAA,CAAA,CAEnD,SAAY,CAChB,IAAIwC,CAAAA,CAAe,KAAA,CAEnB,GAAI,CACF,IAAA,IAASC,CAAAA,CAAU,CAAA,CAAGA,CAAAA,CAAUf,CAAAA,CAAYe,CAAAA,EAAW,CAAA,CAAG,CACxD,MAAML,CAAAA,CAAMX,CAAgB,CAAA,CAE5B,IAAIX,CAAAA,CAA2C,IAAA,CAE/C,GAAI,CACFA,CAAAA,CAAS,MAAMyB,CAAAA,GACjB,CAAA,KAAQ,CACNzB,CAAAA,CAAS,KACX,CAEA,GAAIA,CAAAA,GAAW,SAAA,CACb,OAGF,GAAIA,CAAAA,GAAW,IAAA,GAIf,MAAMkB,CAAAA,CAAQlB,CAAM,CAAA,CAEhB,CAAC0B,CAAAA,EAAgBX,CAAAA,CAAsBf,CAAM,CAAA,GAC/C0B,CAAAA,CAAe,CAAA,CAAA,CACf,MAAMN,CAAAA,CAAWlC,CAAS,CAAA,CAAA,CAGxB,CAACa,CAAAA,CAAiBC,CAAM,CAAA,CAAA,CAC1B,MAEJ,CACF,CAAA,OAAE,CACAa,CAAAA,CAAS,MAAA,CAAO3B,CAAS,EAC3B,CACF,CAAA,IACF","file":"chunk-PWGLA33F.js","sourcesContent":["import { userApiPaths } from '../api-paths';\n\n/** Starter templates a new project can begin from; the backend owns their schema and sample data. */\nexport type StarterTemplate = 'commerce';\n\nexport type StarterStatus = {\n template: StarterTemplate;\n sampleData: boolean;\n state: 'queued' | 'deploying' | 'seeding' | 'completed' | 'failed';\n progress?: { done: number; total: number };\n error?: string;\n completedAt?: string;\n};\n\n/** How the user chose to start a new project, carried to its AI chat in the navigation state. */\nexport type ProjectStart =\n | { kind: 'starter'; template: StarterTemplate; sampleData: boolean }\n | { kind: 'describe'; description: string }\n | { kind: 'empty' };\n\n/** Navigation state the onboarding hands the AI chat of a new project. */\nexport type OnboardingNavigationState = { onboardingPrompt?: string };\n\nexport function starterPath(projectId: string): string {\n return `/api/flexkit/${projectId}/starter`;\n}\n\nexport type Failure = { ok: false; code: string; message: string };\n\n/** A JSON request to the hosted BFF, with its failures mapped to a message the UI can show. */\nexport async function send<T>(\n url: string,\n method: 'PATCH' | 'POST',\n body: unknown,\n fallbackMessage = 'Something went wrong. Please try again.'\n): Promise<({ ok: true } & T) | Failure> {\n try {\n const response = await fetch(url, {\n method,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n const json = (await response.json().catch(() => ({}))) as { code?: string; error?: string } & T;\n\n if (response.ok) {\n return { ...json, ok: true };\n }\n\n return {\n ok: false,\n code: json.code ?? 'unknown_error',\n message: json.error ?? fallbackMessage,\n };\n } catch {\n return {\n ok: false,\n code: 'network_error',\n message: 'Flexkit is not reachable. Check your connection and try again.',\n };\n }\n}\n\n/** Hosted mode: saves the signed-in user's display name. */\nexport function saveDisplayName(displayName: string): Promise<{ ok: true } | Failure> {\n return send(userApiPaths.me, 'PATCH', { displayName });\n}\n\n/** Applies a starter template to a new, empty project; the schema and sample data arrive in the background. */\nexport function applyStarter(\n projectId: string,\n starter: { template: StarterTemplate; sampleData: boolean }\n): Promise<({ ok: true } & { starter: StarterStatus }) | Failure> {\n return send<{ starter: StarterStatus }>(starterPath(projectId), 'POST', starter);\n}\n\nexport function isStarterRunning(status: StarterStatus | null | undefined): boolean {\n return status?.state === 'queued' || status?.state === 'deploying' || status?.state === 'seeding';\n}\n\n/** The first message of a project whose owner described the business instead of picking a template. */\nexport function describeBusinessPrompt(description: string): string {\n return [\n `I'm setting up Flexkit for my business: ${description.trim()}`,\n '',\n 'Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records.',\n ].join('\\n');\n}\n\n/** Questions the commerce sample store can answer; each one finds a problem planted in the data. */\nexport const COMMERCE_STARTER_PROMPTS = [\n 'Which variants are running low on stock, and what is already on order?',\n 'Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.',\n 'Which products are missing prices, titles or SEO copy in the UK or US?',\n 'Show last month’s revenue by market and sales channel.',\n 'Which open support tickets need attention today?',\n] as const;\n\nexport const EMPTY_STARTER_PROMPTS = [\n 'Design a schema for my business. Ask me what you need to know first.',\n 'Set up a product catalog with variants, prices per market and stock per warehouse.',\n 'Help me import my products from a spreadsheet.',\n] as const;\n\n/** Only what the field can tell; the backend owns the character rules and says what it refuses. */\nexport function validateProjectName(name: string): string | null {\n const trimmed = name.trim();\n\n if (!trimmed) {\n return 'Give your project a name.';\n }\n\n if (trimmed.length > 48) {\n return 'Project names can be up to 48 characters.';\n }\n\n return null;\n}\n\n/** The choice on the last step, as sent to the backend and the AI chat. */\nexport function toProjectStart(kind: ProjectStart['kind'], sampleData: boolean, description: string): ProjectStart {\n switch (kind) {\n case 'starter':\n return { kind: 'starter', template: 'commerce', sampleData };\n case 'describe':\n return { kind: 'describe', description };\n case 'empty':\n return { kind: 'empty' };\n }\n}\n","import { mutate } from 'swr';\nimport { isStarterRunning, starterPath, type StarterStatus } from '../../core/config/onboarding';\nimport { revalidateProjectSchema } from '../../core/config/use-project-schemas';\n\nconst POLL_INTERVAL_MS = 2_000;\n/** About ten minutes; a starter usually finishes in two. */\nconst POLL_LIMIT = 300;\nconst watching = new Set<string>();\n\n/** `null` = transient failure (keep polling). */\nexport type StarterFetcher = () => Promise<StarterStatus | null | 'missing'>;\n\nasync function fetchStarter(projectId: string): Promise<StarterStatus | null | 'missing'> {\n const response = await fetch(starterPath(projectId), { credentials: 'include' });\n\n if (!response.ok) {\n return null;\n }\n\n const body = (await response.json()) as { starter?: StarterStatus | null };\n\n return body.starter ?? 'missing';\n}\n\n/** The schema is live once the starter got past its deploy. */\nexport function starterSchemaDeployed(status: StarterStatus): boolean {\n return status.state === 'seeding' || status.state === 'completed';\n}\n\n/**\n * Follows a running starter until it settles, independently of which\n * component started it and of navigation inside the Studio. Shares its\n * results through the SWR cache of `starterPath`, and reloads the project\n * schema once, as soon as the starter's schema is deployed.\n */\nexport function watchStarter({\n fetchStatus,\n projectId,\n publish = (status) => mutate(starterPath(projectId), { starter: status }, { revalidate: false }),\n revalidate = revalidateProjectSchema,\n sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n}: {\n fetchStatus?: StarterFetcher;\n projectId: string;\n publish?: (_status: StarterStatus) => Promise<unknown>;\n revalidate?: (_projectId: string) => Promise<unknown>;\n sleep?: (_ms: number) => Promise<void>;\n}): void {\n if (watching.has(projectId)) {\n return;\n }\n\n watching.add(projectId);\n\n const load = fetchStatus ?? (() => fetchStarter(projectId));\n\n void (async () => {\n let schemaLoaded = false;\n\n try {\n for (let attempt = 0; attempt < POLL_LIMIT; attempt += 1) {\n await sleep(POLL_INTERVAL_MS);\n\n let status: StarterStatus | null | 'missing' = null;\n\n try {\n status = await load();\n } catch {\n status = null;\n }\n\n if (status === 'missing') {\n return;\n }\n\n if (status === null) {\n continue;\n }\n\n await publish(status);\n\n if (!schemaLoaded && starterSchemaDeployed(status)) {\n schemaLoaded = true;\n await revalidate(projectId);\n }\n\n if (!isStarterRunning(status)) {\n return;\n }\n }\n } finally {\n watching.delete(projectId);\n }\n })();\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import'./index.css';import {f as f$1}from'./chunk-KEGJNZLW.js';import {f as f$2}from'./chunk-TI3EHLRE.js';import {createContext,useReducer,useContext}from'react';import {jsx}from'react/jsx-runtime';var d="core.context.scope:",a={breadcrumbs:[],isRouteLoading:false,pageTitle:"",scope:"",relationships:{}},u=createContext(a),l=createContext(()=>{});function f(e,t){let{type:n,payload:o}=t;switch(n){case "setScope":return typeof localStorage<"u"&&o.projectId&&localStorage.setItem(`${d}${o.projectId}`,o.scope),{...e,scope:o.scope};case "setRelationship":return {...e,relationships:{...e.relationships,...o}};default:throw Error(`Unknown action: ${n}`)}}function x({children:e}){let[t,n]=useReducer(f,a);return jsx(u.Provider,{value:t,children:jsx(l.Provider,{value:n,children:e})})}function m(){return useContext(u)}function C(){return useContext(l)}function A(e){return e?.find(t=>t.isDefault)?.name??e?.[0]?.name??f$1}function E(){let{currentProject:e}=f$2();return A(e?.scopes)}export{d as a,x as b,m as c,C as d,A as e,E as f};//# sourceMappingURL=chunk-PZWEC6KD.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-PZWEC6KD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/app-context.tsx","../src/core/default-scope.ts"],"names":["SCOPE_STORAGE_KEY","initialState","AppContext","createContext","AppDispatchContext","reducer","state","action","type","payload","AppProvider","children","dispatch","useReducer","jsx","useAppContext","useContext","useAppDispatch","defaultScopeName","scopes","scope","DEFAULT_SCOPE_KEY","useDefaultScope","currentProject","useConfig"],"mappings":"sMAMO,IAAMA,CAAAA,CAAoB,sBAE3BC,CAAAA,CAAe,CACnB,YAAa,EAAC,CACd,eAAgB,KAAA,CAChB,SAAA,CAAW,GACX,KAAA,CAAO,EAAA,CACP,cAAe,EACjB,EAEMC,CAAAA,CAAaC,aAAAA,CAA8BF,CAAY,CAAA,CAEvDG,CAAAA,CAAqBD,cAAgE,IAAM,CAEjG,CAAC,EAED,SAASE,EAAQC,CAAAA,CAAuBC,CAAAA,CAAgE,CACtG,GAAM,CAAE,KAAAC,CAAAA,CAAM,OAAA,CAAAC,CAAQ,CAAA,CAAIF,CAAAA,CAE1B,OAAQC,CAAAA,EACN,KAAK,UAAA,CACH,OAAI,OAAO,YAAA,CAAiB,GAAA,EAAeC,EAAQ,SAAA,EACjD,YAAA,CAAa,QAAQ,CAAA,EAAGT,CAAiB,GAAGS,CAAAA,CAAQ,SAAS,GAAIA,CAAAA,CAAQ,KAAK,EAGzE,CACL,GAAGH,EACH,KAAA,CAAOG,CAAAA,CAAQ,KACjB,CAAA,CACF,KAAK,kBACH,OAAO,CACL,GAAGH,CAAAA,CACH,aAAA,CAAe,CAAE,GAAGA,CAAAA,CAAM,cAAe,GAAGG,CAAQ,CACtD,CAAA,CACF,QACE,MAAM,KAAA,CAAM,CAAA,gBAAA,EAAmBD,CAAc,CAAA,CAAE,CACnD,CACF,CAEO,SAASE,EAAY,CAAE,QAAA,CAAAC,CAAS,CAAA,CAAyC,CAC9E,GAAM,CAACL,CAAAA,CAAOM,CAAQ,CAAA,CAAIC,UAAAA,CAAWR,EAASJ,CAAY,CAAA,CAE1D,OACEa,GAAAA,CAACZ,CAAAA,CAAW,SAAX,CAAoB,KAAA,CAAOI,EAC1B,QAAA,CAAAQ,GAAAA,CAACV,EAAmB,QAAA,CAAnB,CAA4B,MAAOQ,CAAAA,CAAW,QAAA,CAAAD,EAAS,CAAA,CAC1D,CAEJ,CAEO,SAASI,CAAAA,EAAgC,CAC9C,OAAOC,UAAAA,CAAWd,CAAU,CAC9B,CAEO,SAASe,CAAAA,EAAmE,CACjF,OAAOD,UAAAA,CAAWZ,CAAkB,CACtC,CCpDO,SAASc,EAAiBC,CAAAA,CAAyD,CACxF,OAAOA,CAAAA,EAAQ,IAAA,CAAMC,GAAUA,CAAAA,CAAM,SAAS,GAAG,IAAA,EAAQD,CAAAA,GAAS,CAAC,CAAA,EAAG,IAAA,EAAQE,GAChF,CAGO,SAASC,GAA0B,CACxC,GAAM,CAAE,cAAA,CAAAC,CAAe,EAAIC,GAAAA,EAAU,CAErC,OAAON,CAAAA,CAAiBK,CAAAA,EAAgB,MAAM,CAChD","file":"chunk-PZWEC6KD.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","import { DEFAULT_SCOPE_KEY } from '../graphql-client/queries';\nimport { useConfig } from './config/config-context';\n\ntype ScopeLike = { name: string; isDefault?: boolean };\n\n/**\n * The scope local values fall back to: the one marked `isDefault`, whatever\n * its name. A project without scopes has a single scope named `default`.\n */\nexport function defaultScopeName(scopes: readonly ScopeLike[] | null | undefined): string {\n return scopes?.find((scope) => scope.isDefault)?.name ?? scopes?.[0]?.name ?? DEFAULT_SCOPE_KEY;\n}\n\n/** The current project's default scope. */\nexport function useDefaultScope(): string {\n const { currentProject } = useConfig();\n\n return defaultScopeName(currentProject?.scopes);\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import'./index.css';import {e,c,b,a,g,h as h$1,m,k as k$2,n}from'./chunk-CHNQZU2P.js';import {m as m$1,s as s$3}from'./chunk-PC5Z37LT.js';import {b as b$2}from'./chunk-DSLPTDZX.js';import {j as j$1}from'./chunk-6AJRQSFO.js';import {c as c$4}from'./chunk-XMOSCJOI.js';import {t,s,u,q as q$2,v,k as k$1,i,o as o$1,r as r$1,p as p$2}from'./chunk-7KLXWCDS.js';import {a as a$2}from'./chunk-ERDARDGB.js';import {f}from'./chunk-VRDTHLA3.js';import {ja,o,p as p$1,q as q$1,r,s as s$2,t as t$3,ma}from'./chunk-RULCANNM.js';import {t as t$1}from'./chunk-A4DPLZZF.js';import {b as b$4}from'./chunk-G5N6HEPW.js';import {b as b$1,c as c$3,e as e$2,f as f$1,g as g$1,h,j}from'./chunk-5JUG4BEF.js';import {k,p,q,s as s$1,t as t$2}from'./chunk-S7Z6KKIN.js';import {a as a$1,b as b$3,c as c$2,e as e$1}from'./chunk-N33S7BSG.js';import {c as c$1}from'./chunk-X3SHNHHM.js';import {useState,useMemo,useDeferredValue}from'react';import {BookOpenTextIcon,PaperclipIcon,ChevronRightIcon,LayersIcon,XIcon,PlusIcon,Unlink2Icon,LoaderCircle,SearchIcon}from'lucide-react';import {Link}from'react-router-dom';import H from'swr';import Qe from'swr/infinite';import {jsxs,Fragment,jsx}from'react/jsx-runtime';var Be=50;function fe({disabled:n,label:l,onClick:o}){return jsxs(b$3,{children:[jsx(c$2,{asChild:true,children:jsx(c$1,{"aria-label":l,className:"fk:size-7 fk:shrink-0",disabled:n,size:"icon",variant:"ghost",onClick:o,children:jsx(Unlink2Icon,{className:"fk:size-4"})})}),jsx(e$1,{children:l})]})}function Xe({api:n$1,attachedIds:l,onAttached:o,onOpenChange:a,open:s,projectId:u,target:r,targetLabel:c$1}){let[p$1,h]=useState(""),m$1=useDeferredValue(p$1.trim()),[y,f]=useState(null),b$1=(k,K)=>!s||K&&!K.hasMore?null:c(u).sources({limit:Be,offset:k*Be,search:m$1||void 0}),{data:v,error:w,isLoading:x,setSize:i$1,size:d}=Qe(b$1,b,{keepPreviousData:true}),g=useMemo(()=>r$1(v?.flatMap(k=>k.sources)??[],l),[l,v]),L=v?.[v.length-1]?.hasMore??false,C=v!==void 0&&d>v.length;async function A(k){f(k.id);try{let K=await n$1.linkSource(k.id,r);ma.success(K.linked?`Attached "${k.title}".`:`"${k.title}" was already attached.`),o(k),a(!1);}catch(K){ma.error(h$1(K,"The document could not be attached."));}finally{f(null);}}let R;return w?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):x&&!v?R=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-3 fk:py-2",children:[jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"})]}):g.length===0&&!L?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-muted-foreground",children:m$1?"No documents match your search.":"Every document is attached already, or there are none yet. Add documents in Knowledge first."}):R=jsxs("ul",{className:"fk:flex fk:max-h-80 fk:flex-col fk:overflow-y-auto fk:-mx-2",children:[g.map(k=>{let K=k$1(k),B=y===k.id;return jsx("li",{children:jsxs("button",{className:"fk:flex fk:w-full fk:min-w-0 fk:items-center fk:gap-3 fk:rounded-lg fk:px-2 fk:py-2 fk:text-left fk:transition-colors fk:hover:bg-accent fk:focus-visible:bg-accent fk:focus-visible:outline-none fk:disabled:opacity-60 fk:corner-squircle",disabled:y!==null,type:"button",onClick:()=>{A(k);},children:[jsx(m,{source:k}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:k.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i(k)," \xB7 ",K.detail]})]}),B?jsx(LoaderCircle,{className:"fk:size-4 fk:shrink-0 fk:animate-spin fk:text-muted-foreground"}):jsx(k$2,{label:K.label,tone:K.tone})]})},k.id)}),L&&!C?jsx("li",{"aria-hidden":true,children:jsx(n,{onVisible:()=>{i$1(k=>k+1);}})}):null,C?jsx("li",{className:"fk:flex fk:justify-center fk:py-2",children:jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin fk:text-muted-foreground"})}):null]}),jsx(k,{open:s,onOpenChange:a,children:jsxs(p,{className:"fk:sm:max-w-lg",children:[jsxs(q,{children:[jsx(s$1,{children:"Attach a document"}),jsx(t$2,{children:r.recordId===void 0?`Documents attached to every ${c$1} are searched before the rest of Knowledge when a question is about one of them, or about ${c$1} in general.`:`Documents attached to ${c$1} are searched before the rest of Knowledge when a question is about it.`})]}),jsxs("div",{className:"fk:relative",children:[jsx(SearchIcon,{className:"fk:pointer-events-none fk:absolute fk:left-2.5 fk:top-1/2 fk:size-4 fk:-translate-y-1/2 fk:text-muted-foreground"}),jsx(b$4,{"aria-label":"Search documents",autoFocus:true,className:"fk:pl-8",placeholder:"Search documents by title",value:p$1,onChange:k=>h(k.target.value)})]}),R]})})}function re({projectId:n,renderAction:l,sources:o}){return jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1 fk:-mx-2",children:o.map(a=>{let s=k$1(a);return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1.5 fk:corner-squircle",children:[jsxs(Link,{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-3 fk:rounded-md fk:hover:underline fk:underline-offset-2",to:o$1(n,a.id),children:[jsx(m,{source:a}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:a.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i(a)," \xB7 ",s.detail]})]})]}),jsx(k$2,{label:s.label,tone:s.tone}),l?.(a)]},a.id)})})}function yt({entityName:n}){let{api:l,projectId:o}=e(),{currentProject:a$1}=f(),[s$1,u$1]=useState(false),r=t(a$1?.schema??[],n),c$2=!!r&&s(n),{data:p,error:h}=H(o&&c$2?c(o).entitySources(n):null,b);if(!l||!o||!r||!c$2||h instanceof a&&h.status===404)return null;let m=p?.sources.length??0;return jsxs(Fragment,{children:[jsxs(c$1,{"aria-label":`Knowledge for every ${u(r)}`,className:"fk:mr-2 fk:h-8","data-knowledge-entity-button":true,size:"sm",variant:"outline",onClick:()=>u$1(true),children:[jsx(BookOpenTextIcon,{}),"Knowledge",m>0?jsx(b$1,{className:"fk:corner-squircle",variant:"secondary",children:m}):null]}),jsx(Ue,{api:l,entityLabel:u(r),entityName:n,open:s$1,projectId:o,onOpenChange:u$1})]})}function Ue({api:n,entityLabel:l,entityName:o,onOpenChange:a,open:s,projectId:u}){let r=b$2(),[c$2,p$1]=useState(false),[h,m]=useState(null),{data:y,error:f,isLoading:b$3,mutate:v}=H(c(u).entitySources(o),b),w=y?.sources??[],x=useMemo(()=>({entity:o}),[o]);async function i(g$1){m(g$1.id);try{await n.unlinkSource(g$1.id,x),ma.success(`"${g$1.title}" no longer applies to every ${l}.`),await v({sources:w.filter(L=>L.id!==g$1.id)},{revalidate:!1}),g();}catch(L){ma.error(h$1(L,"The document could not be detached."));}finally{m(null);}}let d;return f?d=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):b$3&&!y?d=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):w.length===0?d=jsxs("p",{className:"fk:text-sm fk:text-muted-foreground",children:["No documents apply to every ",l," yet. Attach a guide, a policy or a spec that holds for all of them and the agent searches it first when asked about any ",l,", or about ",l," in general."]}):d=jsx(re,{projectId:u,sources:w,renderAction:g=>r?jsx(fe,{disabled:h!==null,label:`Detach ${g.title}`,onClick:()=>{i(g);}}):null}),jsx(k,{open:s,onOpenChange:a,children:jsxs(p,{className:"fk:sm:max-w-lg","data-knowledge-entity-dialog":true,children:[jsxs(q,{children:[jsxs(s$1,{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(BookOpenTextIcon,{className:"fk:size-4 fk:text-muted-foreground"}),"Knowledge for every ",l,y?jsx(b$1,{className:"fk:corner-squircle",variant:"outline",children:w.length}):null]}),jsxs(t$2,{children:["Documents attached here apply to every ",l,"; each record can hold its own on top."]})]}),jsx("div",{className:"fk:max-h-80 fk:overflow-y-auto",children:d}),jsx("div",{className:"fk:flex fk:justify-end",children:jsx(ja,{disabled:!r,children:jsxs(c$1,{disabled:!r,size:"sm",variant:"outline",onClick:()=>p$1(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})})}),jsx(Xe,{api:n,attachedIds:w.map(g=>g.id),open:c$2,projectId:u,target:x,targetLabel:l,onAttached:g$1=>{v({sources:w.some(L=>L.id===g$1.id)?w:[...w,g$1]},{revalidate:false}),g();},onOpenChange:p$1})]})})}function bt({entityName:n,recordId:l,recordLabel:o$1}){let{api:a$2,projectId:s$1}=e(),{currentProject:u$1}=f(),r=b$2(),[c$2,p]=useState(false),[h,m]=useState(false),[y,f$1]=useState(null),b$3=useMemo(()=>({entity:n,recordId:l}),[n,l]),v=t(u$1?.schema??[],n),w=v?u(v):n,x=s(n),{data:i,error:d,isLoading:g$1,mutate:L}=H(s$1&&x?c(s$1).recordSources(b$3):null,b);if(!a$2||!s$1||!x||d instanceof a&&d.status===404)return null;let C=i?.sources??[],A=i?.inherited??[],R=C.map(N=>N.id),k=a$2;async function K(N){f$1(N.id);try{await k.unlinkSource(N.id,b$3),ma.success(`Detached "${N.title}".`),await L({sources:C.filter($=>$.id!==N.id),inherited:A},{revalidate:!1}),g();}catch($){ma.error(h$1($,"The document could not be detached."));}finally{f$1(null);}}let B;return d?B=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The attached documents could not be loaded."}):g$1&&!i?B=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):B=jsxs("div",{className:"fk:flex fk:flex-col fk:gap-4",children:[C.length===0?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:A.length>0?"No documents attached to this record itself; the ones below apply to every record of its type.":"No documents attached. Attach a manual, spec or contract and the agent will use it alongside the record's data when asked about this record."}):jsx(re,{projectId:s$1,sources:C,renderAction:N=>r?jsx(fe,{disabled:y!==null,label:`Detach ${N.title}`,onClick:()=>{K(N);}}):null}),A.length>0?jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1","data-knowledge-inherited":true,children:[jsxs("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:["Applies to every ",w]}),jsx(re,{projectId:s$1,sources:A})]}):null]}),jsx(a$1,{children:jsxs(o,{className:`fk:z-10 fk:flex fk:shrink-0 fk:flex-col fk:border-t fk:bg-background ${c$2?"fk:h-1/2":""}`,"data-knowledge-record-panel":true,open:c$2,onOpenChange:p,children:[jsxs("div",{className:"fk:flex fk:shrink-0 fk:items-center fk:gap-2 fk:pl-4 fk:pr-10 fk:py-2",children:[jsx(p$1,{asChild:true,children:jsxs("button",{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-2 fk:rounded-md fk:py-1 fk:text-left fk:text-sm fk:font-semibold fk:tracking-tight fk:hover:text-foreground/80 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",type:"button",children:[jsx(ChevronRightIcon,{className:`fk:size-4 fk:shrink-0 fk:text-muted-foreground fk:transition-transform ${c$2?"fk:rotate-90":""}`}),jsx(BookOpenTextIcon,{className:"fk:size-4 fk:shrink-0 fk:text-muted-foreground"}),"Knowledge",i?jsx(b$1,{className:"fk:corner-squircle",variant:"outline",children:C.length+A.length}):null]})}),c$2?jsx(ja,{disabled:!r,children:jsxs(c$1,{disabled:!r,size:"sm",variant:"outline",onClick:()=>m(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})}):null]}),jsx(q$1,{className:"fk:min-h-0 fk:flex-1 fk:overflow-y-auto fk:px-10 fk:pb-6",children:B}),jsx(Xe,{api:a$2,attachedIds:R,open:h,projectId:s$1,target:b$3,targetLabel:o$1||`this ${n}`,onAttached:N=>{L({sources:C.some($=>$.id===N.id)?C:[...C,N],inherited:A.filter($=>$.id!==N.id)},{revalidate:false}),g();},onOpenChange:m})]})})}function Ze(n,l,o){let{scope:a}=c$4(),s=n.links.map(r=>r.recordId),{data:u}=s$3({entityNamePlural:n.entityPlural,schema:l,scope:a,selection:"display",includeCount:false,variables:{where:{_id:{in:s}},limit:s.length}});return useMemo(()=>{let r={};for(let c of u??[]){let p=c[o.name];typeof p=="string"&&p.trim()&&(r[c._id]=p);}return r},[u,o])}function Ye(n){let{currentProject:l}=f(),o=useMemo(()=>l?.schema??[],[l]),a=m$1(o,n.group.entityPlural),s=a$2(a);return !a||!s?jsx(Je,{...n,entityLabel:a?u(a):n.group.entityPlural,labels:{}}):jsx(et,{...n,displayAttribute:s,schema:o,entityLabel:u(a)})}function et({displayAttribute:n,entityLabel:l,schema:o,...a}){let s=Ze(a.group,o,n);return jsx(Je,{...a,entityLabel:l,labels:s})}function Je({canMutate:n,detachingKey:l,entityLabel:o,group:a,labels:s,onDetach:u}){let r=j$1();return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1",children:[jsx("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:o}),jsx("ul",{className:"fk:flex fk:flex-col fk:-mx-2",children:a.links.map(c=>{let p=p$2(c,s[c.recordId]),h=`${c.entity}:${c.recordId}`;return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1 fk:corner-squircle",children:[jsx("button",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:text-left fk:text-sm fk:hover:underline fk:underline-offset-2",title:c.recordId,type:"button",onClick:()=>r({type:"EditEntity",payload:{entityId:c.recordId,entityNamePlural:a.entityPlural}}),children:p}),n?jsx(fe,{disabled:l!==null,label:`Detach from ${p}`,onClick:()=>u(c)}):null]},h)})})]})}function vt({api:n,projectId:l,source:o}){let a=b$2(),[s,u$1]=useState(null),{data:r,error:c$1,isLoading:p,mutate:h}=H(c(l).links(o.id),b),m=useMemo(()=>r?.links??[],[r]),y=useMemo(()=>r?.entities??[],[r]),f=useMemo(()=>q$2(m),[m]);async function b$3(i){u$1(`${i.entity}:${i.recordId}`);try{await n.unlinkSource(o.id,{entity:i.entity,recordId:i.recordId}),ma.success("Detached."),await h({links:m.filter(d=>d.entity!==i.entity||d.recordId!==i.recordId),entities:y},{revalidate:!1}),g();}catch(d){ma.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function v(i){u$1(`${i.entity}:*`);try{await n.unlinkSource(o.id,{entity:i.entity}),ma.success("Detached."),await h({links:m,entities:y.filter(d=>d.entity!==i.entity)},{revalidate:!1}),g();}catch(d){ma.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function w(i){u$1(`${i.name}:+`);try{let d=await n.linkSource(o.id,{entity:i.name});ma.success(d.linked?`Applies to every ${u(i)} now.`:`Already applied to every ${u(i)}.`),await h({links:m,entities:y.some(g=>g.entity===i.name)?y:[...y,{entity:i.name,entityPlural:i.plural}]},{revalidate:!1}),g();}catch(d){ma.error(h$1(d,"The document could not be attached."));}finally{u$1(null);}}let x;return c$1?x=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The linked records could not be loaded."}):p&&!r?x=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-6 fk:w-1/2"}),jsx(t$1,{className:"fk:h-6 fk:w-1/3"})]}):f.length===0?x=jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:'Not attached to any record. Open a record in the Desk and use "Attach document" so the agent searches this document before the rest of Knowledge when asked about that record.'}):x=jsx("div",{className:"fk:flex fk:flex-col fk:gap-4",children:f.map(i=>jsx(Ye,{canMutate:a,detachingKey:s,group:i,onDetach:d=>{b$3(d);}},i.entityPlural))}),jsxs(Fragment,{children:[jsx(tt,{busy:s!==null,canMutate:a,entities:y,isLoading:p&&!r,onAttach:i=>{w(i);},onDetach:i=>{v(i);}}),jsxs("div",{className:"fk:mt-2 fk:flex fk:items-center fk:gap-2",children:[jsx(PaperclipIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Linked records"}),m.length>0?jsx(b$1,{className:"fk:corner-squircle",variant:"outline",children:m.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"When a question is about one of these records, the agent searches this document before the rest."}),x]})}function tt({busy:n,canMutate:l,entities:o,isLoading:a,onAttach:s,onDetach:u$1}){let{currentProject:r$1}=f(),c=useMemo(()=>r$1?.schema??[],[r$1]),[p,h$1]=useState(false),m=useMemo(()=>v(c,o),[o,c]),y=f=>{let b=t(c,f.entity);return b?u(b):f.entityPlural};return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-3","data-knowledge-applies-to":true,children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(LayersIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Applies to"}),o.length>0?jsx(b$1,{className:"fk:corner-squircle",variant:"outline",children:o.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"Attach this document to a whole entity type and the agent searches it before the rest of Knowledge for every record of that type, and for questions about the type in general."}),a?jsx(t$1,{className:"fk:h-7 fk:w-1/3"}):jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[o.map(f=>{let b=y(f);return jsxs(b$1,{className:"fk:gap-1 fk:py-1 fk:pl-2.5 fk:pr-1 fk:corner-squircle",variant:"secondary",children:[jsx("span",{className:"fk:capitalize",children:b}),l?jsxs(b$3,{children:[jsx(c$2,{asChild:true,children:jsx("button",{"aria-label":`No longer apply to every ${b}`,className:"fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:hover:text-foreground fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:disabled:opacity-50",disabled:n,type:"button",onClick:()=>u$1(f),children:jsx(XIcon,{className:"fk:size-3"})})}),jsxs(e$1,{children:["No longer apply to every ",b]})]}):null]},f.entity)}),jsxs(r,{open:p,onOpenChange:h$1,children:[jsx(ja,{disabled:!l,children:jsx(s$2,{asChild:true,children:jsxs(c$1,{className:"fk:h-7",disabled:!l||m.length===0,size:"sm",variant:"outline",children:[jsx(PlusIcon,{}),"Add entity type"]})})}),jsx(t$3,{align:"start",className:"fk:w-64 fk:p-0",children:jsxs(c$3,{children:[jsx(e$2,{placeholder:"Search entity types"}),jsxs(f$1,{children:[jsx(g$1,{children:"No entity type matches."}),jsx(h,{children:m.map(f=>jsx(j,{keywords:[u(f),f.name,f.plural],value:f.name,onSelect:()=>{h$1(false),s(f);},children:jsx("span",{className:"fk:capitalize",children:u(f)})},f.name))})]})]})})]})]})]})}export{yt as a,bt as b,vt as c};//# sourceMappingURL=chunk-YC7PBLTK.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import'./index.css';import {e,c,b,a,g,h as h$1,m,k as k$2,n}from'./chunk-7N3LTSVX.js';import {e as e$3}from'./chunk-W7JDZHCV.js';import {b as b$2}from'./chunk-DSLPTDZX.js';import {j as j$1}from'./chunk-ZRTWLY77.js';import {c as c$4}from'./chunk-PZWEC6KD.js';import {t,s,u,q as q$2,v,k as k$1,i,o as o$1,r as r$1,p as p$2}from'./chunk-7KLXWCDS.js';import {s as s$3,b as b$5}from'./chunk-KEGJNZLW.js';import {f}from'./chunk-TI3EHLRE.js';import {ja,o,p as p$1,q as q$1,r,s as s$2,t as t$3,ma}from'./chunk-RULCANNM.js';import {t as t$1}from'./chunk-A4DPLZZF.js';import {b as b$4}from'./chunk-G5N6HEPW.js';import {b as b$1,c as c$3,e as e$2,f as f$1,g as g$1,h,j}from'./chunk-5JUG4BEF.js';import {k,p,q,s as s$1,t as t$2}from'./chunk-S7Z6KKIN.js';import {a as a$1,b as b$3,c as c$2,e as e$1}from'./chunk-N33S7BSG.js';import {c as c$1}from'./chunk-X3SHNHHM.js';import {useState,useMemo,useDeferredValue}from'react';import {BookOpenTextIcon,PaperclipIcon,ChevronRightIcon,LayersIcon,XIcon,PlusIcon,Unlink2Icon,LoaderCircle,SearchIcon}from'lucide-react';import {Link}from'react-router-dom';import H from'swr';import Qe from'swr/infinite';import {jsxs,Fragment,jsx}from'react/jsx-runtime';var Be=50;function fe({disabled:n,label:l,onClick:o}){return jsxs(b$3,{children:[jsx(c$2,{asChild:true,children:jsx(c$1,{"aria-label":l,className:"fk:size-7 fk:shrink-0",disabled:n,size:"icon",variant:"ghost",onClick:o,children:jsx(Unlink2Icon,{className:"fk:size-4"})})}),jsx(e$1,{children:l})]})}function Xe({api:n$1,attachedIds:l,onAttached:o,onOpenChange:a,open:s,projectId:u,target:r,targetLabel:c$1}){let[p$1,h]=useState(""),m$1=useDeferredValue(p$1.trim()),[y,f]=useState(null),b$1=(k,K)=>!s||K&&!K.hasMore?null:c(u).sources({limit:Be,offset:k*Be,search:m$1||void 0}),{data:v,error:w,isLoading:x,setSize:i$1,size:d}=Qe(b$1,b,{keepPreviousData:true}),g=useMemo(()=>r$1(v?.flatMap(k=>k.sources)??[],l),[l,v]),L=v?.[v.length-1]?.hasMore??false,C=v!==void 0&&d>v.length;async function A(k){f(k.id);try{let K=await n$1.linkSource(k.id,r);ma.success(K.linked?`Attached "${k.title}".`:`"${k.title}" was already attached.`),o(k),a(!1);}catch(K){ma.error(h$1(K,"The document could not be attached."));}finally{f(null);}}let R;return w?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):x&&!v?R=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-3 fk:py-2",children:[jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"})]}):g.length===0&&!L?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-muted-foreground",children:m$1?"No documents match your search.":"Every document is attached already, or there are none yet. Add documents in Knowledge first."}):R=jsxs("ul",{className:"fk:flex fk:max-h-80 fk:flex-col fk:overflow-y-auto fk:-mx-2",children:[g.map(k=>{let K=k$1(k),B=y===k.id;return jsx("li",{children:jsxs("button",{className:"fk:flex fk:w-full fk:min-w-0 fk:items-center fk:gap-3 fk:rounded-lg fk:px-2 fk:py-2 fk:text-left fk:transition-colors fk:hover:bg-accent fk:focus-visible:bg-accent fk:focus-visible:outline-none fk:disabled:opacity-60 fk:corner-squircle",disabled:y!==null,type:"button",onClick:()=>{A(k);},children:[jsx(m,{source:k}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:k.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i(k)," \xB7 ",K.detail]})]}),B?jsx(LoaderCircle,{className:"fk:size-4 fk:shrink-0 fk:animate-spin fk:text-muted-foreground"}):jsx(k$2,{label:K.label,tone:K.tone})]})},k.id)}),L&&!C?jsx("li",{"aria-hidden":true,children:jsx(n,{onVisible:()=>{i$1(k=>k+1);}})}):null,C?jsx("li",{className:"fk:flex fk:justify-center fk:py-2",children:jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin fk:text-muted-foreground"})}):null]}),jsx(k,{open:s,onOpenChange:a,children:jsxs(p,{className:"fk:sm:max-w-lg",children:[jsxs(q,{children:[jsx(s$1,{children:"Attach a document"}),jsx(t$2,{children:r.recordId===void 0?`Documents attached to every ${c$1} are searched before the rest of Knowledge when a question is about one of them, or about ${c$1} in general.`:`Documents attached to ${c$1} are searched before the rest of Knowledge when a question is about it.`})]}),jsxs("div",{className:"fk:relative",children:[jsx(SearchIcon,{className:"fk:pointer-events-none fk:absolute fk:left-2.5 fk:top-1/2 fk:size-4 fk:-translate-y-1/2 fk:text-muted-foreground"}),jsx(b$4,{"aria-label":"Search documents",autoFocus:true,className:"fk:pl-8",placeholder:"Search documents by title",value:p$1,onChange:k=>h(k.target.value)})]}),R]})})}function re({projectId:n,renderAction:l,sources:o}){return jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1 fk:-mx-2",children:o.map(a=>{let s=k$1(a);return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1.5 fk:corner-squircle",children:[jsxs(Link,{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-3 fk:rounded-md fk:hover:underline fk:underline-offset-2",to:o$1(n,a.id),children:[jsx(m,{source:a}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:a.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i(a)," \xB7 ",s.detail]})]})]}),jsx(k$2,{label:s.label,tone:s.tone}),l?.(a)]},a.id)})})}function yt({entityName:n}){let{api:l,projectId:o}=e(),{currentProject:a$1}=f(),[s$1,u$1]=useState(false),r=t(a$1?.schema??[],n),c$2=!!r&&s(n),{data:p,error:h}=H(o&&c$2?c(o).entitySources(n):null,b);if(!l||!o||!r||!c$2||h instanceof a&&h.status===404)return null;let m=p?.sources.length??0;return jsxs(Fragment,{children:[jsxs(c$1,{"aria-label":`Knowledge for every ${u(r)}`,className:"fk:mr-2 fk:h-8","data-knowledge-entity-button":true,size:"sm",variant:"outline",onClick:()=>u$1(true),children:[jsx(BookOpenTextIcon,{}),"Knowledge",m>0?jsx(b$1,{className:"fk:corner-squircle",variant:"secondary",children:m}):null]}),jsx(Ue,{api:l,entityLabel:u(r),entityName:n,open:s$1,projectId:o,onOpenChange:u$1})]})}function Ue({api:n,entityLabel:l,entityName:o,onOpenChange:a,open:s,projectId:u}){let r=b$2(),[c$2,p$1]=useState(false),[h,m]=useState(null),{data:y,error:f,isLoading:b$3,mutate:v}=H(c(u).entitySources(o),b),w=y?.sources??[],x=useMemo(()=>({entity:o}),[o]);async function i(g$1){m(g$1.id);try{await n.unlinkSource(g$1.id,x),ma.success(`"${g$1.title}" no longer applies to every ${l}.`),await v({sources:w.filter(L=>L.id!==g$1.id)},{revalidate:!1}),g();}catch(L){ma.error(h$1(L,"The document could not be detached."));}finally{m(null);}}let d;return f?d=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):b$3&&!y?d=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):w.length===0?d=jsxs("p",{className:"fk:text-sm fk:text-muted-foreground",children:["No documents apply to every ",l," yet. Attach a guide, a policy or a spec that holds for all of them and the agent searches it first when asked about any ",l,", or about ",l," in general."]}):d=jsx(re,{projectId:u,sources:w,renderAction:g=>r?jsx(fe,{disabled:h!==null,label:`Detach ${g.title}`,onClick:()=>{i(g);}}):null}),jsx(k,{open:s,onOpenChange:a,children:jsxs(p,{className:"fk:sm:max-w-lg","data-knowledge-entity-dialog":true,children:[jsxs(q,{children:[jsxs(s$1,{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(BookOpenTextIcon,{className:"fk:size-4 fk:text-muted-foreground"}),"Knowledge for every ",l,y?jsx(b$1,{className:"fk:corner-squircle",variant:"outline",children:w.length}):null]}),jsxs(t$2,{children:["Documents attached here apply to every ",l,"; each record can hold its own on top."]})]}),jsx("div",{className:"fk:max-h-80 fk:overflow-y-auto",children:d}),jsx("div",{className:"fk:flex fk:justify-end",children:jsx(ja,{disabled:!r,children:jsxs(c$1,{disabled:!r,size:"sm",variant:"outline",onClick:()=>p$1(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})})}),jsx(Xe,{api:n,attachedIds:w.map(g=>g.id),open:c$2,projectId:u,target:x,targetLabel:l,onAttached:g$1=>{v({sources:w.some(L=>L.id===g$1.id)?w:[...w,g$1]},{revalidate:false}),g();},onOpenChange:p$1})]})})}function bt({entityName:n,recordId:l,recordLabel:o$1}){let{api:a$2,projectId:s$1}=e(),{currentProject:u$1}=f(),r=b$2(),[c$2,p]=useState(false),[h,m]=useState(false),[y,f$1]=useState(null),b$3=useMemo(()=>({entity:n,recordId:l}),[n,l]),v=t(u$1?.schema??[],n),w=v?u(v):n,x=s(n),{data:i,error:d,isLoading:g$1,mutate:L}=H(s$1&&x?c(s$1).recordSources(b$3):null,b);if(!a$2||!s$1||!x||d instanceof a&&d.status===404)return null;let C=i?.sources??[],A=i?.inherited??[],R=C.map(N=>N.id),k=a$2;async function K(N){f$1(N.id);try{await k.unlinkSource(N.id,b$3),ma.success(`Detached "${N.title}".`),await L({sources:C.filter($=>$.id!==N.id),inherited:A},{revalidate:!1}),g();}catch($){ma.error(h$1($,"The document could not be detached."));}finally{f$1(null);}}let B;return d?B=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The attached documents could not be loaded."}):g$1&&!i?B=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):B=jsxs("div",{className:"fk:flex fk:flex-col fk:gap-4",children:[C.length===0?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:A.length>0?"No documents attached to this record itself; the ones below apply to every record of its type.":"No documents attached. Attach a manual, spec or contract and the agent will use it alongside the record's data when asked about this record."}):jsx(re,{projectId:s$1,sources:C,renderAction:N=>r?jsx(fe,{disabled:y!==null,label:`Detach ${N.title}`,onClick:()=>{K(N);}}):null}),A.length>0?jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1","data-knowledge-inherited":true,children:[jsxs("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:["Applies to every ",w]}),jsx(re,{projectId:s$1,sources:A})]}):null]}),jsx(a$1,{children:jsxs(o,{className:`fk:z-10 fk:flex fk:shrink-0 fk:flex-col fk:border-t fk:bg-background ${c$2?"fk:h-1/2":""}`,"data-knowledge-record-panel":true,open:c$2,onOpenChange:p,children:[jsxs("div",{className:"fk:flex fk:shrink-0 fk:items-center fk:gap-2 fk:pl-4 fk:pr-10 fk:py-2",children:[jsx(p$1,{asChild:true,children:jsxs("button",{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-2 fk:rounded-md fk:py-1 fk:text-left fk:text-sm fk:font-semibold fk:tracking-tight fk:hover:text-foreground/80 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",type:"button",children:[jsx(ChevronRightIcon,{className:`fk:size-4 fk:shrink-0 fk:text-muted-foreground fk:transition-transform ${c$2?"fk:rotate-90":""}`}),jsx(BookOpenTextIcon,{className:"fk:size-4 fk:shrink-0 fk:text-muted-foreground"}),"Knowledge",i?jsx(b$1,{className:"fk:corner-squircle",variant:"outline",children:C.length+A.length}):null]})}),c$2?jsx(ja,{disabled:!r,children:jsxs(c$1,{disabled:!r,size:"sm",variant:"outline",onClick:()=>m(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})}):null]}),jsx(q$1,{className:"fk:min-h-0 fk:flex-1 fk:overflow-y-auto fk:px-10 fk:pb-6",children:B}),jsx(Xe,{api:a$2,attachedIds:R,open:h,projectId:s$1,target:b$3,targetLabel:o$1||`this ${n}`,onAttached:N=>{L({sources:C.some($=>$.id===N.id)?C:[...C,N],inherited:A.filter($=>$.id!==N.id)},{revalidate:false}),g();},onOpenChange:m})]})})}function Ze(n,l,o){let{scope:a}=c$4(),s=n.links.map(r=>r.recordId),{data:u}=e$3({entityNamePlural:n.entityPlural,schema:l,scope:a,selection:"display",includeCount:false,variables:{where:{_id:{in:s}},limit:s.length}});return useMemo(()=>{let r={};for(let c of u??[]){let p=c[o.name];typeof p=="string"&&p.trim()&&(r[c._id]=p);}return r},[u,o])}function Ye(n){let{currentProject:l}=f(),o=useMemo(()=>l?.schema??[],[l]),a=s$3(o,n.group.entityPlural),s=b$5(a);return !a||!s?jsx(Je,{...n,entityLabel:a?u(a):n.group.entityPlural,labels:{}}):jsx(et,{...n,displayAttribute:s,schema:o,entityLabel:u(a)})}function et({displayAttribute:n,entityLabel:l,schema:o,...a}){let s=Ze(a.group,o,n);return jsx(Je,{...a,entityLabel:l,labels:s})}function Je({canMutate:n,detachingKey:l,entityLabel:o,group:a,labels:s,onDetach:u}){let r=j$1();return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1",children:[jsx("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:o}),jsx("ul",{className:"fk:flex fk:flex-col fk:-mx-2",children:a.links.map(c=>{let p=p$2(c,s[c.recordId]),h=`${c.entity}:${c.recordId}`;return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1 fk:corner-squircle",children:[jsx("button",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:text-left fk:text-sm fk:hover:underline fk:underline-offset-2",title:c.recordId,type:"button",onClick:()=>r({type:"EditEntity",payload:{entityId:c.recordId,entityNamePlural:a.entityPlural}}),children:p}),n?jsx(fe,{disabled:l!==null,label:`Detach from ${p}`,onClick:()=>u(c)}):null]},h)})})]})}function vt({api:n,projectId:l,source:o}){let a=b$2(),[s,u$1]=useState(null),{data:r,error:c$1,isLoading:p,mutate:h}=H(c(l).links(o.id),b),m=useMemo(()=>r?.links??[],[r]),y=useMemo(()=>r?.entities??[],[r]),f=useMemo(()=>q$2(m),[m]);async function b$3(i){u$1(`${i.entity}:${i.recordId}`);try{await n.unlinkSource(o.id,{entity:i.entity,recordId:i.recordId}),ma.success("Detached."),await h({links:m.filter(d=>d.entity!==i.entity||d.recordId!==i.recordId),entities:y},{revalidate:!1}),g();}catch(d){ma.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function v(i){u$1(`${i.entity}:*`);try{await n.unlinkSource(o.id,{entity:i.entity}),ma.success("Detached."),await h({links:m,entities:y.filter(d=>d.entity!==i.entity)},{revalidate:!1}),g();}catch(d){ma.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function w(i){u$1(`${i.name}:+`);try{let d=await n.linkSource(o.id,{entity:i.name});ma.success(d.linked?`Applies to every ${u(i)} now.`:`Already applied to every ${u(i)}.`),await h({links:m,entities:y.some(g=>g.entity===i.name)?y:[...y,{entity:i.name,entityPlural:i.plural}]},{revalidate:!1}),g();}catch(d){ma.error(h$1(d,"The document could not be attached."));}finally{u$1(null);}}let x;return c$1?x=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The linked records could not be loaded."}):p&&!r?x=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-6 fk:w-1/2"}),jsx(t$1,{className:"fk:h-6 fk:w-1/3"})]}):f.length===0?x=jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:'Not attached to any record. Open a record in the Desk and use "Attach document" so the agent searches this document before the rest of Knowledge when asked about that record.'}):x=jsx("div",{className:"fk:flex fk:flex-col fk:gap-4",children:f.map(i=>jsx(Ye,{canMutate:a,detachingKey:s,group:i,onDetach:d=>{b$3(d);}},i.entityPlural))}),jsxs(Fragment,{children:[jsx(tt,{busy:s!==null,canMutate:a,entities:y,isLoading:p&&!r,onAttach:i=>{w(i);},onDetach:i=>{v(i);}}),jsxs("div",{className:"fk:mt-2 fk:flex fk:items-center fk:gap-2",children:[jsx(PaperclipIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Linked records"}),m.length>0?jsx(b$1,{className:"fk:corner-squircle",variant:"outline",children:m.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"When a question is about one of these records, the agent searches this document before the rest."}),x]})}function tt({busy:n,canMutate:l,entities:o,isLoading:a,onAttach:s,onDetach:u$1}){let{currentProject:r$1}=f(),c=useMemo(()=>r$1?.schema??[],[r$1]),[p,h$1]=useState(false),m=useMemo(()=>v(c,o),[o,c]),y=f=>{let b=t(c,f.entity);return b?u(b):f.entityPlural};return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-3","data-knowledge-applies-to":true,children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(LayersIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Applies to"}),o.length>0?jsx(b$1,{className:"fk:corner-squircle",variant:"outline",children:o.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"Attach this document to a whole entity type and the agent searches it before the rest of Knowledge for every record of that type, and for questions about the type in general."}),a?jsx(t$1,{className:"fk:h-7 fk:w-1/3"}):jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[o.map(f=>{let b=y(f);return jsxs(b$1,{className:"fk:gap-1 fk:py-1 fk:pl-2.5 fk:pr-1 fk:corner-squircle",variant:"secondary",children:[jsx("span",{className:"fk:capitalize",children:b}),l?jsxs(b$3,{children:[jsx(c$2,{asChild:true,children:jsx("button",{"aria-label":`No longer apply to every ${b}`,className:"fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:hover:text-foreground fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:disabled:opacity-50",disabled:n,type:"button",onClick:()=>u$1(f),children:jsx(XIcon,{className:"fk:size-3"})})}),jsxs(e$1,{children:["No longer apply to every ",b]})]}):null]},f.entity)}),jsxs(r,{open:p,onOpenChange:h$1,children:[jsx(ja,{disabled:!l,children:jsx(s$2,{asChild:true,children:jsxs(c$1,{className:"fk:h-7",disabled:!l||m.length===0,size:"sm",variant:"outline",children:[jsx(PlusIcon,{}),"Add entity type"]})})}),jsx(t$3,{align:"start",className:"fk:w-64 fk:p-0",children:jsxs(c$3,{children:[jsx(e$2,{placeholder:"Search entity types"}),jsxs(f$1,{children:[jsx(g$1,{children:"No entity type matches."}),jsx(h,{children:m.map(f=>jsx(j,{keywords:[u(f),f.name,f.plural],value:f.name,onSelect:()=>{h$1(false),s(f);},children:jsx("span",{className:"fk:capitalize",children:u(f)})},f.name))})]})]})})]})]})]})}export{yt as a,bt as b,vt as c};//# sourceMappingURL=chunk-Q4CWQHBJ.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-Q4CWQHBJ.js.map
|