@flexkit/studio 0.2.29 → 0.2.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/{chat-page-UT5M3PM3.js → chat-page-JS5SJ4OG.js} +3 -3
  2. package/dist/{chat-page-UT5M3PM3.js.map → chat-page-JS5SJ4OG.js.map} +1 -1
  3. package/dist/{chunk-FRTHKTAS.js → chunk-57X5WRMY.js} +2 -2
  4. package/dist/{chunk-FRTHKTAS.js.map → chunk-57X5WRMY.js.map} +1 -1
  5. package/dist/{chunk-BSUCDQYM.js → chunk-5NQ47SWN.js} +3 -3
  6. package/dist/{chunk-BSUCDQYM.js.map → chunk-5NQ47SWN.js.map} +1 -1
  7. package/dist/{chunk-D3TJCUTA.js → chunk-6GXNHR6H.js} +2 -2
  8. package/dist/{chunk-D3TJCUTA.js.map → chunk-6GXNHR6H.js.map} +1 -1
  9. package/dist/chunk-D76P4TER.js +378 -0
  10. package/dist/chunk-D76P4TER.js.map +1 -0
  11. package/dist/{chunk-7AN2E6TU.js → chunk-GQTWNWT7.js} +2 -2
  12. package/dist/{chunk-7AN2E6TU.js.map → chunk-GQTWNWT7.js.map} +1 -1
  13. package/dist/{chunk-6A6NT3H3.js → chunk-GXQSNOGM.js} +3 -3
  14. package/dist/{chunk-6A6NT3H3.js.map → chunk-GXQSNOGM.js.map} +1 -1
  15. package/dist/{chunk-UET5IDEW.js → chunk-KVYQ3O4F.js} +3 -3
  16. package/dist/{chunk-UET5IDEW.js.map → chunk-KVYQ3O4F.js.map} +1 -1
  17. package/dist/{chunk-T44KNWQD.js → chunk-LF4B2TQI.js} +4 -4
  18. package/dist/{chunk-T44KNWQD.js.map → chunk-LF4B2TQI.js.map} +1 -1
  19. package/dist/{chunk-AZG72R2F.js → chunk-OMYDXVWS.js} +3 -3
  20. package/dist/{chunk-AZG72R2F.js.map → chunk-OMYDXVWS.js.map} +1 -1
  21. package/dist/{chunk-BRGTUEFL.js → chunk-SZ3DX7XD.js} +2 -2
  22. package/dist/{chunk-BRGTUEFL.js.map → chunk-SZ3DX7XD.js.map} +1 -1
  23. package/dist/{chunk-BIFQCOZD.js → chunk-T4SEZXGL.js} +2 -2
  24. package/dist/{chunk-BIFQCOZD.js.map → chunk-T4SEZXGL.js.map} +1 -1
  25. package/dist/{chunk-ZUGTNE5M.js → chunk-W74OKBZG.js} +2 -2
  26. package/dist/{chunk-ZUGTNE5M.js.map → chunk-W74OKBZG.js.map} +1 -1
  27. package/dist/chunk-XLFAJBPN.js +3 -0
  28. package/dist/chunk-XLFAJBPN.js.map +1 -0
  29. package/dist/{entry-QGRB2B7V.js → entry-PFXS633U.js} +2 -2
  30. package/dist/{entry-QGRB2B7V.js.map → entry-PFXS633U.js.map} +1 -1
  31. package/dist/index.d.ts +4 -2
  32. package/dist/index.js +2 -2
  33. package/dist/index.js.map +1 -1
  34. package/dist/{list-L6YZSBWF.js → list-EWWRLK4I.js} +3 -3
  35. package/dist/{list-L6YZSBWF.js.map → list-EWWRLK4I.js.map} +1 -1
  36. package/dist/list-R7SJFXCX.js +2 -0
  37. package/dist/list-R7SJFXCX.js.map +1 -0
  38. package/dist/{pages-K4XZAMXY.js → pages-UKJWXOMO.js} +3 -3
  39. package/dist/{pages-K4XZAMXY.js.map → pages-UKJWXOMO.js.map} +1 -1
  40. package/dist/{plugin-pages-RCWAF6VC.js → plugin-pages-X3V2VPAU.js} +2 -2
  41. package/dist/{plugin-pages-RCWAF6VC.js.map → plugin-pages-X3V2VPAU.js.map} +1 -1
  42. package/dist/record-links-VH2TPCK4.js +2 -0
  43. package/dist/{record-links-R7OV4VVH.js.map → record-links-VH2TPCK4.js.map} +1 -1
  44. package/dist/{root-R4Y6L62R.js → root-4QRY7KAC.js} +3 -3
  45. package/dist/{root-R4Y6L62R.js.map → root-4QRY7KAC.js.map} +1 -1
  46. package/dist/{root-L6Y4PSSA.js → root-7YXE6DEA.js} +3 -3
  47. package/dist/{root-L6Y4PSSA.js.map → root-7YXE6DEA.js.map} +1 -1
  48. package/dist/{root-3M4DIRWC.js → root-FNXHGVQT.js} +2 -2
  49. package/dist/{root-3M4DIRWC.js.map → root-FNXHGVQT.js.map} +1 -1
  50. package/dist/{root-36COMEVE.js → root-HQQ4TNTR.js} +2 -2
  51. package/dist/{root-36COMEVE.js.map → root-HQQ4TNTR.js.map} +1 -1
  52. package/dist/{root-XMZYVO37.js → root-NYAXP66A.js} +3 -3
  53. package/dist/{root-XMZYVO37.js.map → root-NYAXP66A.js.map} +1 -1
  54. package/dist/{root-HETKL6EN.js → root-OJ4UFMRX.js} +2 -2
  55. package/dist/{root-HETKL6EN.js.map → root-OJ4UFMRX.js.map} +1 -1
  56. package/dist/{search-UXL3U2EH.js → search-LSIHN6OI.js} +2 -2
  57. package/dist/{search-UXL3U2EH.js.map → search-LSIHN6OI.js.map} +1 -1
  58. package/dist/{skills-pages-KEXNO6DN.js → skills-pages-W47HECK3.js} +2 -2
  59. package/dist/{skills-pages-KEXNO6DN.js.map → skills-pages-W47HECK3.js.map} +1 -1
  60. package/dist/{source-CWVJGMEZ.js → source-3N7BQVYO.js} +2 -2
  61. package/dist/{source-CWVJGMEZ.js.map → source-3N7BQVYO.js.map} +1 -1
  62. package/package.json +2 -2
  63. package/dist/chunk-H534S4KD.js +0 -3
  64. package/dist/chunk-H534S4KD.js.map +0 -1
  65. package/dist/chunk-RZZOOPEF.js +0 -378
  66. package/dist/chunk-RZZOOPEF.js.map +0 -1
  67. package/dist/list-OPL5OO32.js +0 -2
  68. package/dist/list-OPL5OO32.js.map +0 -1
  69. package/dist/record-links-R7OV4VVH.js +0 -2
@@ -1,2 +1,2 @@
1
- import'./index.css';import {a,c,d,f as f$1,g as g$1,e as e$1,i,h as h$2}from'./chunk-2NXQF2F7.js';import {b as b$1}from'./chunk-V7C4EHK3.js';import {h}from'./chunk-7KLXWCDS.js';import {f}from'./chunk-H534S4KD.js';import {qa}from'./chunk-DGIY4SKN.js';import {e,g,h as h$1,j as j$1,o,n}from'./chunk-SZEGGBOC.js';import {b}from'./chunk-32ZU4MLE.js';import {b as b$2}from'./chunk-6NRQMG26.js';import {put}from'@vercel/blob/client';import {useMemo,useRef,useEffect,useState}from'react';import {LoaderCircle,EllipsisVerticalIcon,DownloadIcon,ExternalLinkIcon,Trash2Icon}from'lucide-react';import {mutate}from'swr';import {Document}from'@untitledui/file-icons/dist/solid/document.mjs';import {Docx}from'@untitledui/file-icons/dist/solid/docx.mjs';import {Html}from'@untitledui/file-icons/dist/solid/html.mjs';import {Pdf}from'@untitledui/file-icons/dist/solid/pdf.mjs';import {Pptx}from'@untitledui/file-icons/dist/solid/pptx.mjs';import {Txt}from'@untitledui/file-icons/dist/solid/txt.mjs';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var u=class extends Error{code;status;constructor(n,t,r=null){super(t),this.name="KnowledgeApiError",this.code=r,this.status=n;}},k=class extends Error{status;constructor(n,t="Request failed"){super(t),this.name="FetcherError",this.status=n;}},fe=async e=>{let n=await fetch(e,{credentials:"include"});if(!n.ok)throw new k(n.status);return await n.json()};function j(e){let n=`/api/flexkit/${e}/knowledge`;return {entitySources:t=>`${n}/entities/${encodeURIComponent(t)}/sources`,file:t=>`${n}/sources/${encodeURIComponent(t)}/file`,job:t=>`${n}/jobs/${encodeURIComponent(t)}`,links:t=>`${n}/sources/${encodeURIComponent(t)}/links`,passages:(t,{from:r,to:o})=>`${n}/sources/${encodeURIComponent(t)}/passages?from=${String(r)}&to=${String(o)}`,recordSources:({entity:t,recordId:r})=>`${n}/records/${encodeURIComponent(t)}/${encodeURIComponent(r)}/sources`,source:t=>`${n}/sources/${encodeURIComponent(t)}`,sources:(t={})=>{let{limit:r=25,offset:o=0,search:i,status:a}=t,l=new URLSearchParams({limit:r.toString(),offset:o.toString()}),c=i?.trim();return c&&l.set("q",c),a&&l.set("status",a),`${n}/sources?${l.toString()}`},spaces:`/api/flexkit/${e}/spaces`}}function N(e){return typeof e=="string"&&e.includes("/knowledge/sources?")}function J(e){return typeof e=="string"&&(e.includes("/knowledge/records/")||e.includes("/knowledge/entities/")||e.includes("/knowledge/sources/")&&e.endsWith("/links"))}async function L(e,n){let t={};try{t=await e.json();}catch{}return new u(e.status,t.error?String(t.error):n,t.code??null)}function O(e){let n=`/api/flexkit/${e}/knowledge`;async function t(o,i){let{fallback:a,...l}=i,c=await fetch(o,{credentials:"include",headers:{"Content-Type":"application/json",...l.headers??{}},...l});if(!c.ok)throw await L(c,a);return await c.json()}function r(o){return t(`${n}/sources`,{body:JSON.stringify(o),fallback:"The document could not be added.",method:"POST"})}return {addFile:async(o,i)=>{let a=await fetch(`${n}/uploads`,{body:JSON.stringify({filename:o.name,mediaType:o.type||null,sizeBytes:o.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:i?.signal});if(!a.ok)throw await L(a,"The file could not be uploaded.");let l=await a.json();if(!l.pathname||!l.token||!l.mediaType)throw new u(a.status,"The file could not be uploaded.");return await put(l.pathname,o,{abortSignal:i?.signal,access:"public",contentType:l.mediaType,token:l.token}),r({kind:"upload",pathname:l.pathname})},addUrl:({title:o,url:i})=>r({kind:"url",url:i,...o?{title:o}:{}}),addChatAttachment:({filename:o,url:i})=>r({filename:o,kind:"chat-attachment",url:i}),deleteSource:o=>t(`${n}/sources/${encodeURIComponent(o)}`,{fallback:"The document could not be removed.",method:"DELETE"}),linkSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}/links`,{body:JSON.stringify(i),fallback:"The document could not be attached.",method:"POST"}),reingestSource:o=>t(`${n}/sources/${encodeURIComponent(o)}/reingest`,{fallback:"The document could not be re-indexed.",method:"POST"}),unlinkSource:(o,{entity:i,recordId:a})=>t(`${n}/sources/${encodeURIComponent(o)}/links/${encodeURIComponent(i)}${a===void 0?"":`/${encodeURIComponent(a)}`}`,{fallback:"The document could not be detached.",method:"DELETE"}),updateSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}`,{body:JSON.stringify(i),fallback:"The document could not be updated.",method:"PATCH"})}}var ae={busy:"fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400",error:"fk:bg-destructive/15 fk:text-destructive",muted:"fk:bg-muted fk:text-muted-foreground",ready:"fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400"};function le(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?O(e):null,[e]),projectId:e}}function de(){return mutate(N,void 0,{revalidate:true})}function Pe(){return mutate(J,void 0,{revalidate:true})}function ce(e,n){return e instanceof u||e instanceof Error?e.message:n}function Ee(e,n){if(e.duplicate){qa.info(`"${e.source.title}" is already in Knowledge.`);return}qa.success(`Added ${n}. Indexing starts now.`);}function _e({children:e}){return jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:e})}function Me({label:e,tone:n}){return jsxs(b,{className:`fk:border-none fk:corner-squircle ${ae[n]}`,variant:"outline",children:[n==="busy"?jsx(LoaderCircle,{className:"fk:size-3 fk:animate-spin"}):null,e]})}var ue={document:Document,docx:Docx,html:Html,pdf:Pdf,pptx:Pptx,txt:Txt};function ge({className:e="",size:n=24,source:t}){let r=h(t),o=ue[r.icon];return jsx("span",{"aria-label":r.label,className:`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${e}`,"data-knowledge-type":r.icon,role:"img",children:jsx(o,{size:n})})}function Ue({source:e}){return jsx(ge,{size:40,source:e})}function Le({onVisible:e}){let n=useRef(null),t=useRef(e);return t.current=e,useEffect(()=>{let r=n.current;if(!r)return;let o=new IntersectionObserver(i=>{i.some(a=>a.isIntersecting)&&t.current();});return o.observe(r),()=>{o.disconnect();}},[]),jsx("div",{"aria-hidden":true,className:"fk:h-px",ref:n})}function je({isBusy:e$2=false,onOpen:n$1,onRemoved:t,source:r,trigger:o$1="row"}){let{api:i$1,projectId:a$1}=le(),l=b$1(),[c$1,p]=useState(false),[f,b]=useState(false);if(!i$1||!a$1)return null;let X=i$1;async function H(){b(true);try{await X.deleteSource(r.id),qa.success(`Removed "${r.title}".`),p(!1),t(),de();}catch(w){qa.error(ce(w,"The document could not be removed."));}finally{b(false);}}return jsxs(Fragment,{children:[jsxs(e,{children:[jsx(g,{asChild:true,children:jsx(b$2,{"aria-label":`Actions for ${r.title}`,className:o$1==="row"?"fk:size-8 fk:shrink-0 fk:text-muted-foreground":void 0,"data-knowledge-menu":true,size:"icon-sm",variant:o$1==="row"?"ghost":"outline",children:jsx(EllipsisVerticalIcon,{className:"fk:size-4"})})}),jsxs(h$1,{align:"end",children:[n$1?jsx(j$1,{onSelect:n$1,children:"Open"}):null,r.path?jsx(j$1,{asChild:true,children:jsxs("a",{href:j(a$1).file(r.id),children:[jsx(DownloadIcon,{}),"Download"]})}):null,r.originUrl?jsx(j$1,{asChild:true,children:jsxs("a",{href:r.originUrl,rel:"noreferrer",target:"_blank",children:[jsx(ExternalLinkIcon,{}),"Open page"]})}):null,n$1||r.path||r.originUrl?jsx(o,{}):null,jsxs(j$1,{disabled:!l||e$2,variant:"destructive",onSelect:()=>p(true),children:[jsx(Trash2Icon,{}),"Remove"]}),l?null:jsx(n,{className:"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground",children:"Your member role cannot remove documents."})]})]}),jsx(a,{open:c$1,onOpenChange:p,children:jsxs(c,{children:[jsxs(d,{children:[jsx(f$1,{children:"Remove this document?"}),jsxs(g$1,{children:['"',r.title,'" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep their citations, but the document can no longer be opened.']})]}),jsxs(e$1,{children:[jsx(i,{disabled:f,children:"Cancel"}),jsxs(h$2,{disabled:f,onClick:w=>{w.preventDefault(),H();},children:[f?jsx(LoaderCircle,{className:"fk:animate-spin"}):null,"Remove document"]})]})]})})]})}export{k as a,fe as b,j as c,O as d,le as e,de as f,Pe as g,ce as h,Ee as i,_e as j,Me as k,ge as l,Ue as m,Le as n,je as o};//# sourceMappingURL=chunk-D3TJCUTA.js.map
2
- //# sourceMappingURL=chunk-D3TJCUTA.js.map
1
+ import'./index.css';import {a,c,d,f as f$1,g as g$1,e as e$1,i,h as h$2}from'./chunk-2NXQF2F7.js';import {b as b$1}from'./chunk-V7C4EHK3.js';import {h}from'./chunk-7KLXWCDS.js';import {f}from'./chunk-XLFAJBPN.js';import {qa}from'./chunk-DGIY4SKN.js';import {e,g,h as h$1,j as j$1,o,n}from'./chunk-SZEGGBOC.js';import {b}from'./chunk-32ZU4MLE.js';import {b as b$2}from'./chunk-6NRQMG26.js';import {put}from'@vercel/blob/client';import {useMemo,useRef,useEffect,useState}from'react';import {LoaderCircle,EllipsisVerticalIcon,DownloadIcon,ExternalLinkIcon,Trash2Icon}from'lucide-react';import {mutate}from'swr';import {Document}from'@untitledui/file-icons/dist/solid/document.mjs';import {Docx}from'@untitledui/file-icons/dist/solid/docx.mjs';import {Html}from'@untitledui/file-icons/dist/solid/html.mjs';import {Pdf}from'@untitledui/file-icons/dist/solid/pdf.mjs';import {Pptx}from'@untitledui/file-icons/dist/solid/pptx.mjs';import {Txt}from'@untitledui/file-icons/dist/solid/txt.mjs';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var u=class extends Error{code;status;constructor(n,t,r=null){super(t),this.name="KnowledgeApiError",this.code=r,this.status=n;}},k=class extends Error{status;constructor(n,t="Request failed"){super(t),this.name="FetcherError",this.status=n;}},fe=async e=>{let n=await fetch(e,{credentials:"include"});if(!n.ok)throw new k(n.status);return await n.json()};function j(e){let n=`/api/flexkit/${e}/knowledge`;return {entitySources:t=>`${n}/entities/${encodeURIComponent(t)}/sources`,file:t=>`${n}/sources/${encodeURIComponent(t)}/file`,job:t=>`${n}/jobs/${encodeURIComponent(t)}`,links:t=>`${n}/sources/${encodeURIComponent(t)}/links`,passages:(t,{from:r,to:o})=>`${n}/sources/${encodeURIComponent(t)}/passages?from=${String(r)}&to=${String(o)}`,recordSources:({entity:t,recordId:r})=>`${n}/records/${encodeURIComponent(t)}/${encodeURIComponent(r)}/sources`,source:t=>`${n}/sources/${encodeURIComponent(t)}`,sources:(t={})=>{let{limit:r=25,offset:o=0,search:i,status:a}=t,l=new URLSearchParams({limit:r.toString(),offset:o.toString()}),c=i?.trim();return c&&l.set("q",c),a&&l.set("status",a),`${n}/sources?${l.toString()}`},spaces:`/api/flexkit/${e}/spaces`}}function N(e){return typeof e=="string"&&e.includes("/knowledge/sources?")}function J(e){return typeof e=="string"&&(e.includes("/knowledge/records/")||e.includes("/knowledge/entities/")||e.includes("/knowledge/sources/")&&e.endsWith("/links"))}async function L(e,n){let t={};try{t=await e.json();}catch{}return new u(e.status,t.error?String(t.error):n,t.code??null)}function O(e){let n=`/api/flexkit/${e}/knowledge`;async function t(o,i){let{fallback:a,...l}=i,c=await fetch(o,{credentials:"include",headers:{"Content-Type":"application/json",...l.headers??{}},...l});if(!c.ok)throw await L(c,a);return await c.json()}function r(o){return t(`${n}/sources`,{body:JSON.stringify(o),fallback:"The document could not be added.",method:"POST"})}return {addFile:async(o,i)=>{let a=await fetch(`${n}/uploads`,{body:JSON.stringify({filename:o.name,mediaType:o.type||null,sizeBytes:o.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:i?.signal});if(!a.ok)throw await L(a,"The file could not be uploaded.");let l=await a.json();if(!l.pathname||!l.token||!l.mediaType)throw new u(a.status,"The file could not be uploaded.");return await put(l.pathname,o,{abortSignal:i?.signal,access:"public",contentType:l.mediaType,token:l.token}),r({kind:"upload",pathname:l.pathname})},addUrl:({title:o,url:i})=>r({kind:"url",url:i,...o?{title:o}:{}}),addChatAttachment:({filename:o,url:i})=>r({filename:o,kind:"chat-attachment",url:i}),deleteSource:o=>t(`${n}/sources/${encodeURIComponent(o)}`,{fallback:"The document could not be removed.",method:"DELETE"}),linkSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}/links`,{body:JSON.stringify(i),fallback:"The document could not be attached.",method:"POST"}),reingestSource:o=>t(`${n}/sources/${encodeURIComponent(o)}/reingest`,{fallback:"The document could not be re-indexed.",method:"POST"}),unlinkSource:(o,{entity:i,recordId:a})=>t(`${n}/sources/${encodeURIComponent(o)}/links/${encodeURIComponent(i)}${a===void 0?"":`/${encodeURIComponent(a)}`}`,{fallback:"The document could not be detached.",method:"DELETE"}),updateSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}`,{body:JSON.stringify(i),fallback:"The document could not be updated.",method:"PATCH"})}}var ae={busy:"fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400",error:"fk:bg-destructive/15 fk:text-destructive",muted:"fk:bg-muted fk:text-muted-foreground",ready:"fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400"};function le(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?O(e):null,[e]),projectId:e}}function de(){return mutate(N,void 0,{revalidate:true})}function Pe(){return mutate(J,void 0,{revalidate:true})}function ce(e,n){return e instanceof u||e instanceof Error?e.message:n}function Ee(e,n){if(e.duplicate){qa.info(`"${e.source.title}" is already in Knowledge.`);return}qa.success(`Added ${n}. Indexing starts now.`);}function _e({children:e}){return jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:e})}function Me({label:e,tone:n}){return jsxs(b,{className:`fk:border-none fk:corner-squircle ${ae[n]}`,variant:"outline",children:[n==="busy"?jsx(LoaderCircle,{className:"fk:size-3 fk:animate-spin"}):null,e]})}var ue={document:Document,docx:Docx,html:Html,pdf:Pdf,pptx:Pptx,txt:Txt};function ge({className:e="",size:n=24,source:t}){let r=h(t),o=ue[r.icon];return jsx("span",{"aria-label":r.label,className:`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${e}`,"data-knowledge-type":r.icon,role:"img",children:jsx(o,{size:n})})}function Ue({source:e}){return jsx(ge,{size:40,source:e})}function Le({onVisible:e}){let n=useRef(null),t=useRef(e);return t.current=e,useEffect(()=>{let r=n.current;if(!r)return;let o=new IntersectionObserver(i=>{i.some(a=>a.isIntersecting)&&t.current();});return o.observe(r),()=>{o.disconnect();}},[]),jsx("div",{"aria-hidden":true,className:"fk:h-px",ref:n})}function je({isBusy:e$2=false,onOpen:n$1,onRemoved:t,source:r,trigger:o$1="row"}){let{api:i$1,projectId:a$1}=le(),l=b$1(),[c$1,p]=useState(false),[f,b]=useState(false);if(!i$1||!a$1)return null;let X=i$1;async function H(){b(true);try{await X.deleteSource(r.id),qa.success(`Removed "${r.title}".`),p(!1),t(),de();}catch(w){qa.error(ce(w,"The document could not be removed."));}finally{b(false);}}return jsxs(Fragment,{children:[jsxs(e,{children:[jsx(g,{asChild:true,children:jsx(b$2,{"aria-label":`Actions for ${r.title}`,className:o$1==="row"?"fk:size-8 fk:shrink-0 fk:text-muted-foreground":void 0,"data-knowledge-menu":true,size:"icon-sm",variant:o$1==="row"?"ghost":"outline",children:jsx(EllipsisVerticalIcon,{className:"fk:size-4"})})}),jsxs(h$1,{align:"end",children:[n$1?jsx(j$1,{onSelect:n$1,children:"Open"}):null,r.path?jsx(j$1,{asChild:true,children:jsxs("a",{href:j(a$1).file(r.id),children:[jsx(DownloadIcon,{}),"Download"]})}):null,r.originUrl?jsx(j$1,{asChild:true,children:jsxs("a",{href:r.originUrl,rel:"noreferrer",target:"_blank",children:[jsx(ExternalLinkIcon,{}),"Open page"]})}):null,n$1||r.path||r.originUrl?jsx(o,{}):null,jsxs(j$1,{disabled:!l||e$2,variant:"destructive",onSelect:()=>p(true),children:[jsx(Trash2Icon,{}),"Remove"]}),l?null:jsx(n,{className:"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground",children:"Your member role cannot remove documents."})]})]}),jsx(a,{open:c$1,onOpenChange:p,children:jsxs(c,{children:[jsxs(d,{children:[jsx(f$1,{children:"Remove this document?"}),jsxs(g$1,{children:['"',r.title,'" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep their citations, but the document can no longer be opened.']})]}),jsxs(e$1,{children:[jsx(i,{disabled:f,children:"Cancel"}),jsxs(h$2,{disabled:f,onClick:w=>{w.preventDefault(),H();},children:[f?jsx(LoaderCircle,{className:"fk:animate-spin"}):null,"Remove document"]})]})]})})]})}export{k as a,fe as b,j as c,O as d,le as e,de as f,Pe as g,ce as h,Ee as i,_e as j,Me as k,ge as l,Ue as m,Le as n,je as o};//# sourceMappingURL=chunk-6GXNHR6H.js.map
2
+ //# sourceMappingURL=chunk-6GXNHR6H.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apps/knowledge/api.ts","../src/apps/knowledge/shared.tsx"],"names":["KnowledgeApiError","status","message","code","FetcherError","fetcher","url","response","knowledgePaths","projectId","basePath","entity","sourceId","jobId","from","to","recordId","options","limit","offset","search","params","trimmedSearch","isKnowledgeListKey","key","isKnowledgeLinkKey","readError","fallback","data","createKnowledgeApi","request","init","requestInit","register","body","file","tokenResponse","tokenData","put","title","filename","target","patch","STATUS_TONE_CLASSES","useProjectKnowledge","currentProjectId","useConfig","useMemo","invalidateKnowledgeLists","mutateGlobal","invalidateKnowledgeLinks","describeApiError","error","announceRegistered","result","name","toast","PageMessage","children","jsx","StatusBadge","label","tone","jsxs","Badge","LoaderCircle","FILE_ICONS","Document","Docx","Html","Pdf","Pptx","Txt","KnowledgeTypeIcon","className","size","source","format","getKnowledgeFormat","Icon","SourceIcon","InfiniteScrollSentinel","onVisible","sentinelRef","useRef","onVisibleRef","useEffect","node","observer","entries","entry","SourceActionsMenu","isBusy","onOpen","onRemoved","trigger","api","canMutate","useCanMutate","isConfirmingRemoval","setIsConfirmingRemoval","useState","isRemoving","setIsRemoving","knowledgeApi","remove","removeError","Fragment","DropdownMenu","DropdownMenuTrigger","Button","EllipsisVerticalIcon","DropdownMenuContent","DropdownMenuItem","DownloadIcon","ExternalLinkIcon","DropdownMenuSeparator","Trash2Icon","DropdownMenuLabel","AlertDialog","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction","event"],"mappings":"0gCAYO,IAAMA,CAAAA,CAA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AA,CAAArC,KAACyD,CAAAA,CAAA,CACC,UAAAzD,IAAAA,CAAC0D,CAAAA,CAAA,CACC,QAAA,CAAA,CAAA9D,GAAAA,CAAC+D,GAAAA,CAAA,CAAiB,iCAAqB,CAAA,CACvC3D,IAAAA,CAAC4D,IAAA,CAAuB,QAAA,CAAA,CAAA,GAAA,CACpB/C,EAAO,KAAA,CAAM,qJAAA,CAAA,CAEjB,CAAA,CAAA,CACF,CAAA,CACAb,KAAC6D,GAAAA,CAAA,CACC,QAAA,CAAA,CAAAjE,GAAAA,CAACkE,EAAA,CAAkB,QAAA,CAAUvB,CAAAA,CAAY,QAAA,CAAA,QAAA,CAAM,EAC/CvC,IAAAA,CAAC+D,GAAAA,CAAA,CACC,QAAA,CAAUxB,CAAAA,CACV,QAAUyB,CAAAA,EAAsB,CAC9BA,CAAAA,CAAM,cAAA,GACDtB,CAAAA,GACP,EAEC,QAAA,CAAA,CAAAH,CAAAA,CAAa3C,IAACM,YAAAA,CAAA,CAAa,SAAA,CAAU,iBAAA,CAAkB,EAAK,IAAA,CAAK,iBAAA,CAAA,CAEpE,GACF,CAAA,CAAA,CACF,CAAA,CACF,GACF,CAEJ","file":"chunk-D3TJCUTA.js","sourcesContent":["import { put } from '@vercel/blob/client';\nimport type {\n KnowledgeJob,\n KnowledgeLinkTarget,\n KnowledgeRecordRef,\n KnowledgeSource,\n KnowledgeSourcePatch,\n KnowledgeSourceStatus,\n RegisterKnowledgeSourceResult,\n} from './knowledge';\n\n/** The platform refused a knowledge request; `code` lets the UI tailor the message. */\nexport class KnowledgeApiError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'KnowledgeApiError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ProjectSpace {\n code: string;\n id: string;\n label: string;\n}\n\nexport interface KnowledgeApi {\n /** Uploads a document to the file store, then registers it; resolves once indexing is queued or the file was already there. */\n addFile: (_file: File, _options?: { signal?: AbortSignal }) => Promise<RegisterKnowledgeSourceResult>;\n addUrl: (_input: { title?: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n /** Promotes a file the caller attached to a chat: the platform copies it into the knowledge folder. */\n addChatAttachment: (_input: { filename: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n deleteSource: (_sourceId: string) => Promise<{ deleted: true }>;\n /** Attaches the document to a record, or to every record of an entity type; `linked` is false when it already was. */\n linkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ linked: boolean }>;\n reingestSource: (_sourceId: string) => Promise<{ job: KnowledgeJob }>;\n unlinkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ unlinked: boolean }>;\n updateSource: (_sourceId: string, _patch: KnowledgeSourcePatch) => Promise<{ source: KnowledgeSource }>;\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function knowledgePaths(projectId: string): {\n /** The documents attached to every record of an entity type. */\n entitySources: (_entity: string) => string;\n /** The original file of an uploaded document, served under its name. */\n file: (_sourceId: string) => string;\n job: (_jobId: string) => string;\n /** The records a document is attached to, and the entity types it applies to. */\n links: (_sourceId: string) => string;\n passages: (_sourceId: string, _options: { from: number; to: number }) => string;\n /** The documents attached to a record. */\n recordSources: (_record: KnowledgeRecordRef) => string;\n source: (_sourceId: string) => string;\n sources: (_options?: { limit?: number; offset?: number; search?: string; status?: KnowledgeSourceStatus }) => string;\n spaces: string;\n} {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n return {\n entitySources: (entity) => `${basePath}/entities/${encodeURIComponent(entity)}/sources`,\n file: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/file`,\n job: (jobId) => `${basePath}/jobs/${encodeURIComponent(jobId)}`,\n links: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/links`,\n passages: (sourceId, { from, to }) =>\n `${basePath}/sources/${encodeURIComponent(sourceId)}/passages?from=${String(from)}&to=${String(to)}`,\n recordSources: ({ entity, recordId }) =>\n `${basePath}/records/${encodeURIComponent(entity)}/${encodeURIComponent(recordId)}/sources`,\n source: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}`,\n sources: (options = {}) => {\n const { limit = 25, offset = 0, search, status } = options;\n const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() });\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n if (status) {\n params.set('status', status);\n }\n\n return `${basePath}/sources?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n };\n}\n\n/** Whether an SWR key is a page of the document list, whatever its filters. */\nexport function isKnowledgeListKey(key: unknown): boolean {\n return typeof key === 'string' && key.includes('/knowledge/sources?');\n}\n\n/** Whether an SWR key lists the documents of a record or an entity type, or the links of a document. */\nexport function isKnowledgeLinkKey(key: unknown): boolean {\n return (\n typeof key === 'string' &&\n (key.includes('/knowledge/records/') ||\n key.includes('/knowledge/entities/') ||\n (key.includes('/knowledge/sources/') && key.endsWith('/links')))\n );\n}\n\nasync function readError(response: Response, fallback: string): Promise<KnowledgeApiError> {\n let data: { code?: string; error?: string } = {};\n\n try {\n data = (await response.json()) as { code?: string; error?: string };\n } catch {\n // Non-JSON error bodies keep the fallback message.\n }\n\n return new KnowledgeApiError(response.status, data.error ? String(data.error) : fallback, data.code ?? null);\n}\n\nexport function createKnowledgeApi(projectId: string): KnowledgeApi {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n async function request<T>(url: string, init: RequestInit & { fallback: string }): Promise<T> {\n const { fallback, ...requestInit } = init;\n const response = await fetch(url, {\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...(requestInit.headers ?? {}) },\n ...requestInit,\n });\n\n if (!response.ok) {\n throw await readError(response, fallback);\n }\n\n return (await response.json()) as T;\n }\n\n function register(body: Record<string, unknown>): Promise<RegisterKnowledgeSourceResult> {\n return request<RegisterKnowledgeSourceResult>(`${basePath}/sources`, {\n body: JSON.stringify(body),\n fallback: 'The document could not be added.',\n method: 'POST',\n });\n }\n\n return {\n addFile: async (file, options) => {\n // The platform issues a token pinned to one pathname, type and size; the\n // browser writes the bytes to the store itself, so a 20 MB document never\n // crosses the API function body limit. Registration then hashes the blob.\n const tokenResponse = await fetch(`${basePath}/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal: options?.signal,\n });\n\n if (!tokenResponse.ok) {\n throw await readError(tokenResponse, 'The file could not be uploaded.');\n }\n\n const tokenData = (await tokenResponse.json()) as { mediaType?: string; pathname?: string; token?: string };\n\n if (!tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new KnowledgeApiError(tokenResponse.status, 'The file could not be uploaded.');\n }\n\n await put(tokenData.pathname, file, {\n abortSignal: options?.signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return register({ kind: 'upload', pathname: tokenData.pathname });\n },\n addUrl: ({ title, url }) => register({ kind: 'url', url, ...(title ? { title } : {}) }),\n addChatAttachment: ({ filename, url }) => register({ filename, kind: 'chat-attachment', url }),\n deleteSource: (sourceId) =>\n request<{ deleted: true }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n fallback: 'The document could not be removed.',\n method: 'DELETE',\n }),\n linkSource: (sourceId, target) =>\n request<{ linked: boolean }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/links`, {\n body: JSON.stringify(target),\n fallback: 'The document could not be attached.',\n method: 'POST',\n }),\n reingestSource: (sourceId) =>\n request<{ job: KnowledgeJob }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/reingest`, {\n fallback: 'The document could not be re-indexed.',\n method: 'POST',\n }),\n unlinkSource: (sourceId, { entity, recordId }) =>\n request<{ unlinked: boolean }>(\n `${basePath}/sources/${encodeURIComponent(sourceId)}/links/${encodeURIComponent(entity)}${\n recordId === undefined ? '' : `/${encodeURIComponent(recordId)}`\n }`,\n { fallback: 'The document could not be detached.', method: 'DELETE' }\n ),\n updateSource: (sourceId, patch) =>\n request<{ source: KnowledgeSource }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n body: JSON.stringify(patch),\n fallback: 'The document could not be updated.',\n method: 'PATCH',\n }),\n };\n}\n","import type { JSX, MouseEvent } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { DownloadIcon, EllipsisVerticalIcon, ExternalLinkIcon, LoaderCircle, Trash2Icon } from 'lucide-react';\nimport { mutate as mutateGlobal } from 'swr';\n// File type icons: Untitled UI's free file icons, Solid variant. The set is\n// published as the MIT package `@untitledui/file-icons`; the page below shows\n// every icon and offers each as SVG or JSX should another format need one.\n// https://www.untitledui.com/resources/file-icons\nimport { Document } from '@untitledui/file-icons/dist/solid/document.mjs';\nimport { Docx } from '@untitledui/file-icons/dist/solid/docx.mjs';\nimport { Html } from '@untitledui/file-icons/dist/solid/html.mjs';\nimport { Pdf } from '@untitledui/file-icons/dist/solid/pdf.mjs';\nimport { Pptx } from '@untitledui/file-icons/dist/solid/pptx.mjs';\nimport { Txt } from '@untitledui/file-icons/dist/solid/txt.mjs';\nimport { useConfig } from '../../core/config/config-context';\nimport { useCanMutate } from '../../core/permissions';\nimport {\n Badge,\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n toast,\n} from '../../ui';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '../../ui/primitives/alert-dialog';\nimport {\n createKnowledgeApi,\n isKnowledgeLinkKey,\n isKnowledgeListKey,\n KnowledgeApiError,\n knowledgePaths,\n type KnowledgeApi,\n} from './api';\nimport {\n getKnowledgeFormat,\n type KnowledgeFileIcon,\n type KnowledgeSource,\n type KnowledgeStatusTone,\n type RegisterKnowledgeSourceResult,\n} from './knowledge';\n\nconst STATUS_TONE_CLASSES: { [tone in KnowledgeStatusTone]: string } = {\n busy: 'fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400',\n error: 'fk:bg-destructive/15 fk:text-destructive',\n muted: 'fk:bg-muted fk:text-muted-foreground',\n ready: 'fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400',\n};\n\nexport function useProjectKnowledge(): { api: KnowledgeApi | null; projectId: string | undefined } {\n const { currentProjectId } = useConfig();\n const api = useMemo(() => (currentProjectId ? createKnowledgeApi(currentProjectId) : null), [currentProjectId]);\n\n return { api, projectId: currentProjectId };\n}\n\n/** Drops every cached page of the document list, so the next visit fetches it afresh. */\nexport function invalidateKnowledgeLists(): Promise<unknown> {\n return mutateGlobal(isKnowledgeListKey, undefined, { revalidate: true });\n}\n\n/** Drops every cached link listing (a record's documents, a document's records) after a link changed. */\nexport function invalidateKnowledgeLinks(): Promise<unknown> {\n return mutateGlobal(isKnowledgeLinkKey, undefined, { revalidate: true });\n}\n\nexport function describeApiError(error: unknown, fallback: string): string {\n if (error instanceof KnowledgeApiError) {\n return error.message;\n }\n\n return error instanceof Error ? error.message : fallback;\n}\n\n/** What the user hears once a document was registered. */\nexport function announceRegistered(result: RegisterKnowledgeSourceResult, name: string): void {\n if (result.duplicate) {\n toast.info(`\"${result.source.title}\" is already in Knowledge.`);\n\n return;\n }\n\n toast.success(`Added ${name}. Indexing starts now.`);\n}\n\nexport function PageMessage({ children }: { children: string }): JSX.Element {\n return (\n <div className=\"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle\">\n {children}\n </div>\n );\n}\n\nexport function StatusBadge({ label, tone }: { label: string; tone: KnowledgeStatusTone }): JSX.Element {\n return (\n <Badge className={`fk:border-none fk:corner-squircle ${STATUS_TONE_CLASSES[tone]}`} variant=\"outline\">\n {tone === 'busy' ? <LoaderCircle className=\"fk:size-3 fk:animate-spin\" /> : null}\n {label}\n </Badge>\n );\n}\n\nconst FILE_ICONS: { [icon in KnowledgeFileIcon]: typeof Pdf } = {\n document: Document,\n docx: Docx,\n html: Html,\n pdf: Pdf,\n pptx: Pptx,\n txt: Txt,\n};\n\n/** The document's format as its file icon; the format's name is what a screen reader hears. */\nexport function KnowledgeTypeIcon({\n className = '',\n size = 24,\n source,\n}: {\n className?: string;\n size?: number;\n source: Pick<KnowledgeSource, 'kind' | 'mimeType'>;\n}): JSX.Element {\n const format = getKnowledgeFormat(source);\n const Icon = FILE_ICONS[format.icon];\n\n return (\n <span\n aria-label={format.label}\n className={`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${className}`}\n data-knowledge-type={format.icon}\n role=\"img\"\n >\n <Icon size={size} />\n </span>\n );\n}\n\n/** The larger file icon of the document page and the record panel: the same icon as the list, at 40px. */\nexport function SourceIcon({ source }: { source: Pick<KnowledgeSource, 'kind' | 'mimeType'> }): JSX.Element {\n return <KnowledgeTypeIcon size={40} source={source} />;\n}\n\nexport function InfiniteScrollSentinel({ onVisible }: { onVisible: () => void }): JSX.Element {\n const sentinelRef = useRef<HTMLDivElement>(null);\n const onVisibleRef = useRef(onVisible);\n\n onVisibleRef.current = onVisible;\n\n useEffect(() => {\n const node = sentinelRef.current;\n\n if (!node) {\n return;\n }\n\n const observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n onVisibleRef.current();\n }\n });\n\n observer.observe(node);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n return <div aria-hidden className=\"fk:h-px\" ref={sentinelRef} />;\n}\n\n/**\n * The actions of one document, behind a three-dots button: open (lists\n * only), download the original file (web pages open their address instead)\n * and remove, behind one confirmation. The list and the document page share\n * it so the copy, the download link and the busy rules stay the same.\n */\nexport function SourceActionsMenu({\n isBusy = false,\n onOpen,\n onRemoved,\n source,\n trigger = 'row',\n}: {\n /** Another action on the document is in flight; removing waits for it. */\n isBusy?: boolean;\n /** Offered as the first item when given (the document page is already open). */\n onOpen?: () => void;\n /** The document is gone: drop it from the list, or leave its page. The list invalidation is done here. */\n onRemoved: () => void;\n source: KnowledgeSource;\n /** How the button looks: a quiet icon in a row or card, an outlined one next to page actions. */\n trigger?: 'row' | 'page';\n}): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const canMutate = useCanMutate();\n const [isConfirmingRemoval, setIsConfirmingRemoval] = useState(false);\n const [isRemoving, setIsRemoving] = useState(false);\n\n if (!api || !projectId) {\n return null;\n }\n\n const knowledgeApi = api;\n\n async function remove(): Promise<void> {\n setIsRemoving(true);\n\n try {\n await knowledgeApi.deleteSource(source.id);\n toast.success(`Removed \"${source.title}\".`);\n setIsConfirmingRemoval(false);\n onRemoved();\n void invalidateKnowledgeLists();\n } catch (removeError) {\n toast.error(describeApiError(removeError, 'The document could not be removed.'));\n } finally {\n setIsRemoving(false);\n }\n }\n\n return (\n <>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n aria-label={`Actions for ${source.title}`}\n className={trigger === 'row' ? 'fk:size-8 fk:shrink-0 fk:text-muted-foreground' : undefined}\n data-knowledge-menu\n size=\"icon-sm\"\n variant={trigger === 'row' ? 'ghost' : 'outline'}\n >\n <EllipsisVerticalIcon className=\"fk:size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {onOpen ? <DropdownMenuItem onSelect={onOpen}>Open</DropdownMenuItem> : null}\n {source.path ? (\n <DropdownMenuItem asChild>\n <a href={knowledgePaths(projectId).file(source.id)}>\n <DownloadIcon />\n Download\n </a>\n </DropdownMenuItem>\n ) : null}\n {source.originUrl ? (\n <DropdownMenuItem asChild>\n <a href={source.originUrl} rel=\"noreferrer\" target=\"_blank\">\n <ExternalLinkIcon />\n Open page\n </a>\n </DropdownMenuItem>\n ) : null}\n {onOpen || source.path || source.originUrl ? <DropdownMenuSeparator /> : null}\n <DropdownMenuItem\n disabled={!canMutate || isBusy}\n variant=\"destructive\"\n onSelect={() => setIsConfirmingRemoval(true)}\n >\n <Trash2Icon />\n Remove\n </DropdownMenuItem>\n {canMutate ? null : (\n <DropdownMenuLabel className=\"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground\">\n Your member role cannot remove documents.\n </DropdownMenuLabel>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n <AlertDialog open={isConfirmingRemoval} onOpenChange={setIsConfirmingRemoval}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>Remove this document?</AlertDialogTitle>\n <AlertDialogDescription>\n \"{source.title}\" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep\n their citations, but the document can no longer be opened.\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={isRemoving}>Cancel</AlertDialogCancel>\n <AlertDialogAction\n disabled={isRemoving}\n onClick={(event: MouseEvent) => {\n event.preventDefault();\n void remove();\n }}\n >\n {isRemoving ? <LoaderCircle className=\"fk:animate-spin\" /> : null}\n Remove document\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n </>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/apps/knowledge/api.ts","../src/apps/knowledge/shared.tsx"],"names":["KnowledgeApiError","status","message","code","FetcherError","fetcher","url","response","knowledgePaths","projectId","basePath","entity","sourceId","jobId","from","to","recordId","options","limit","offset","search","params","trimmedSearch","isKnowledgeListKey","key","isKnowledgeLinkKey","readError","fallback","data","createKnowledgeApi","request","init","requestInit","register","body","file","tokenResponse","tokenData","put","title","filename","target","patch","STATUS_TONE_CLASSES","useProjectKnowledge","currentProjectId","useConfig","useMemo","invalidateKnowledgeLists","mutateGlobal","invalidateKnowledgeLinks","describeApiError","error","announceRegistered","result","name","toast","PageMessage","children","jsx","StatusBadge","label","tone","jsxs","Badge","LoaderCircle","FILE_ICONS","Document","Docx","Html","Pdf","Pptx","Txt","KnowledgeTypeIcon","className","size","source","format","getKnowledgeFormat","Icon","SourceIcon","InfiniteScrollSentinel","onVisible","sentinelRef","useRef","onVisibleRef","useEffect","node","observer","entries","entry","SourceActionsMenu","isBusy","onOpen","onRemoved","trigger","api","canMutate","useCanMutate","isConfirmingRemoval","setIsConfirmingRemoval","useState","isRemoving","setIsRemoving","knowledgeApi","remove","removeError","Fragment","DropdownMenu","DropdownMenuTrigger","Button","EllipsisVerticalIcon","DropdownMenuContent","DropdownMenuItem","DownloadIcon","ExternalLinkIcon","DropdownMenuSeparator","Trash2Icon","DropdownMenuLabel","AlertDialog","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction","event"],"mappings":"0gCAYO,IAAMA,CAAAA,CAAN,cAAgC,KAAM,CAC3C,IAAA,CACA,MAAA,CAEA,YAAYC,CAAAA,CAAgBC,CAAAA,CAAiBC,EAAsB,IAAA,CAAM,CACvE,MAAMD,CAAO,CAAA,CACb,IAAA,CAAK,IAAA,CAAO,oBACZ,IAAA,CAAK,IAAA,CAAOC,CAAAA,CACZ,IAAA,CAAK,OAASF,EAChB,CACF,CAAA,CAsBaG,CAAAA,CAAN,cAA2B,KAAM,CACtC,OAEA,WAAA,CAAYH,CAAAA,CAAgBC,EAAU,gBAAA,CAAkB,CACtD,KAAA,CAAMA,CAAO,EACb,IAAA,CAAK,IAAA,CAAO,cAAA,CACZ,IAAA,CAAK,OAASD,EAChB,CACF,CAAA,CAEaI,EAAAA,CAAU,MAAUC,CAAAA,EAA4B,CAC3D,IAAMC,CAAAA,CAAW,MAAM,MAAMD,CAAAA,CAAK,CAAE,WAAA,CAAa,SAAU,CAAC,CAAA,CAE5D,GAAI,CAACC,CAAAA,CAAS,EAAA,CACZ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,CAAa,SAAA,CAAU,iBAAA,CAAkB,EAAK,IAAA,CAAK,iBAAA,CAAA,CAEpE,GACF,CAAA,CAAA,CACF,CAAA,CACF,GACF,CAEJ","file":"chunk-6GXNHR6H.js","sourcesContent":["import { put } from '@vercel/blob/client';\nimport type {\n KnowledgeJob,\n KnowledgeLinkTarget,\n KnowledgeRecordRef,\n KnowledgeSource,\n KnowledgeSourcePatch,\n KnowledgeSourceStatus,\n RegisterKnowledgeSourceResult,\n} from './knowledge';\n\n/** The platform refused a knowledge request; `code` lets the UI tailor the message. */\nexport class KnowledgeApiError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'KnowledgeApiError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ProjectSpace {\n code: string;\n id: string;\n label: string;\n}\n\nexport interface KnowledgeApi {\n /** Uploads a document to the file store, then registers it; resolves once indexing is queued or the file was already there. */\n addFile: (_file: File, _options?: { signal?: AbortSignal }) => Promise<RegisterKnowledgeSourceResult>;\n addUrl: (_input: { title?: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n /** Promotes a file the caller attached to a chat: the platform copies it into the knowledge folder. */\n addChatAttachment: (_input: { filename: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n deleteSource: (_sourceId: string) => Promise<{ deleted: true }>;\n /** Attaches the document to a record, or to every record of an entity type; `linked` is false when it already was. */\n linkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ linked: boolean }>;\n reingestSource: (_sourceId: string) => Promise<{ job: KnowledgeJob }>;\n unlinkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ unlinked: boolean }>;\n updateSource: (_sourceId: string, _patch: KnowledgeSourcePatch) => Promise<{ source: KnowledgeSource }>;\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function knowledgePaths(projectId: string): {\n /** The documents attached to every record of an entity type. */\n entitySources: (_entity: string) => string;\n /** The original file of an uploaded document, served under its name. */\n file: (_sourceId: string) => string;\n job: (_jobId: string) => string;\n /** The records a document is attached to, and the entity types it applies to. */\n links: (_sourceId: string) => string;\n passages: (_sourceId: string, _options: { from: number; to: number }) => string;\n /** The documents attached to a record. */\n recordSources: (_record: KnowledgeRecordRef) => string;\n source: (_sourceId: string) => string;\n sources: (_options?: { limit?: number; offset?: number; search?: string; status?: KnowledgeSourceStatus }) => string;\n spaces: string;\n} {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n return {\n entitySources: (entity) => `${basePath}/entities/${encodeURIComponent(entity)}/sources`,\n file: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/file`,\n job: (jobId) => `${basePath}/jobs/${encodeURIComponent(jobId)}`,\n links: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/links`,\n passages: (sourceId, { from, to }) =>\n `${basePath}/sources/${encodeURIComponent(sourceId)}/passages?from=${String(from)}&to=${String(to)}`,\n recordSources: ({ entity, recordId }) =>\n `${basePath}/records/${encodeURIComponent(entity)}/${encodeURIComponent(recordId)}/sources`,\n source: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}`,\n sources: (options = {}) => {\n const { limit = 25, offset = 0, search, status } = options;\n const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() });\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n if (status) {\n params.set('status', status);\n }\n\n return `${basePath}/sources?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n };\n}\n\n/** Whether an SWR key is a page of the document list, whatever its filters. */\nexport function isKnowledgeListKey(key: unknown): boolean {\n return typeof key === 'string' && key.includes('/knowledge/sources?');\n}\n\n/** Whether an SWR key lists the documents of a record or an entity type, or the links of a document. */\nexport function isKnowledgeLinkKey(key: unknown): boolean {\n return (\n typeof key === 'string' &&\n (key.includes('/knowledge/records/') ||\n key.includes('/knowledge/entities/') ||\n (key.includes('/knowledge/sources/') && key.endsWith('/links')))\n );\n}\n\nasync function readError(response: Response, fallback: string): Promise<KnowledgeApiError> {\n let data: { code?: string; error?: string } = {};\n\n try {\n data = (await response.json()) as { code?: string; error?: string };\n } catch {\n // Non-JSON error bodies keep the fallback message.\n }\n\n return new KnowledgeApiError(response.status, data.error ? String(data.error) : fallback, data.code ?? null);\n}\n\nexport function createKnowledgeApi(projectId: string): KnowledgeApi {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n async function request<T>(url: string, init: RequestInit & { fallback: string }): Promise<T> {\n const { fallback, ...requestInit } = init;\n const response = await fetch(url, {\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...(requestInit.headers ?? {}) },\n ...requestInit,\n });\n\n if (!response.ok) {\n throw await readError(response, fallback);\n }\n\n return (await response.json()) as T;\n }\n\n function register(body: Record<string, unknown>): Promise<RegisterKnowledgeSourceResult> {\n return request<RegisterKnowledgeSourceResult>(`${basePath}/sources`, {\n body: JSON.stringify(body),\n fallback: 'The document could not be added.',\n method: 'POST',\n });\n }\n\n return {\n addFile: async (file, options) => {\n // The platform issues a token pinned to one pathname, type and size; the\n // browser writes the bytes to the store itself, so a 20 MB document never\n // crosses the API function body limit. Registration then hashes the blob.\n const tokenResponse = await fetch(`${basePath}/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal: options?.signal,\n });\n\n if (!tokenResponse.ok) {\n throw await readError(tokenResponse, 'The file could not be uploaded.');\n }\n\n const tokenData = (await tokenResponse.json()) as { mediaType?: string; pathname?: string; token?: string };\n\n if (!tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new KnowledgeApiError(tokenResponse.status, 'The file could not be uploaded.');\n }\n\n await put(tokenData.pathname, file, {\n abortSignal: options?.signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return register({ kind: 'upload', pathname: tokenData.pathname });\n },\n addUrl: ({ title, url }) => register({ kind: 'url', url, ...(title ? { title } : {}) }),\n addChatAttachment: ({ filename, url }) => register({ filename, kind: 'chat-attachment', url }),\n deleteSource: (sourceId) =>\n request<{ deleted: true }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n fallback: 'The document could not be removed.',\n method: 'DELETE',\n }),\n linkSource: (sourceId, target) =>\n request<{ linked: boolean }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/links`, {\n body: JSON.stringify(target),\n fallback: 'The document could not be attached.',\n method: 'POST',\n }),\n reingestSource: (sourceId) =>\n request<{ job: KnowledgeJob }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/reingest`, {\n fallback: 'The document could not be re-indexed.',\n method: 'POST',\n }),\n unlinkSource: (sourceId, { entity, recordId }) =>\n request<{ unlinked: boolean }>(\n `${basePath}/sources/${encodeURIComponent(sourceId)}/links/${encodeURIComponent(entity)}${\n recordId === undefined ? '' : `/${encodeURIComponent(recordId)}`\n }`,\n { fallback: 'The document could not be detached.', method: 'DELETE' }\n ),\n updateSource: (sourceId, patch) =>\n request<{ source: KnowledgeSource }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n body: JSON.stringify(patch),\n fallback: 'The document could not be updated.',\n method: 'PATCH',\n }),\n };\n}\n","import type { JSX, MouseEvent } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { DownloadIcon, EllipsisVerticalIcon, ExternalLinkIcon, LoaderCircle, Trash2Icon } from 'lucide-react';\nimport { mutate as mutateGlobal } from 'swr';\n// File type icons: Untitled UI's free file icons, Solid variant. The set is\n// published as the MIT package `@untitledui/file-icons`; the page below shows\n// every icon and offers each as SVG or JSX should another format need one.\n// https://www.untitledui.com/resources/file-icons\nimport { Document } from '@untitledui/file-icons/dist/solid/document.mjs';\nimport { Docx } from '@untitledui/file-icons/dist/solid/docx.mjs';\nimport { Html } from '@untitledui/file-icons/dist/solid/html.mjs';\nimport { Pdf } from '@untitledui/file-icons/dist/solid/pdf.mjs';\nimport { Pptx } from '@untitledui/file-icons/dist/solid/pptx.mjs';\nimport { Txt } from '@untitledui/file-icons/dist/solid/txt.mjs';\nimport { useConfig } from '../../core/config/config-context';\nimport { useCanMutate } from '../../core/permissions';\nimport {\n Badge,\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n toast,\n} from '../../ui';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '../../ui/primitives/alert-dialog';\nimport {\n createKnowledgeApi,\n isKnowledgeLinkKey,\n isKnowledgeListKey,\n KnowledgeApiError,\n knowledgePaths,\n type KnowledgeApi,\n} from './api';\nimport {\n getKnowledgeFormat,\n type KnowledgeFileIcon,\n type KnowledgeSource,\n type KnowledgeStatusTone,\n type RegisterKnowledgeSourceResult,\n} from './knowledge';\n\nconst STATUS_TONE_CLASSES: { [tone in KnowledgeStatusTone]: string } = {\n busy: 'fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400',\n error: 'fk:bg-destructive/15 fk:text-destructive',\n muted: 'fk:bg-muted fk:text-muted-foreground',\n ready: 'fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400',\n};\n\nexport function useProjectKnowledge(): { api: KnowledgeApi | null; projectId: string | undefined } {\n const { currentProjectId } = useConfig();\n const api = useMemo(() => (currentProjectId ? createKnowledgeApi(currentProjectId) : null), [currentProjectId]);\n\n return { api, projectId: currentProjectId };\n}\n\n/** Drops every cached page of the document list, so the next visit fetches it afresh. */\nexport function invalidateKnowledgeLists(): Promise<unknown> {\n return mutateGlobal(isKnowledgeListKey, undefined, { revalidate: true });\n}\n\n/** Drops every cached link listing (a record's documents, a document's records) after a link changed. */\nexport function invalidateKnowledgeLinks(): Promise<unknown> {\n return mutateGlobal(isKnowledgeLinkKey, undefined, { revalidate: true });\n}\n\nexport function describeApiError(error: unknown, fallback: string): string {\n if (error instanceof KnowledgeApiError) {\n return error.message;\n }\n\n return error instanceof Error ? error.message : fallback;\n}\n\n/** What the user hears once a document was registered. */\nexport function announceRegistered(result: RegisterKnowledgeSourceResult, name: string): void {\n if (result.duplicate) {\n toast.info(`\"${result.source.title}\" is already in Knowledge.`);\n\n return;\n }\n\n toast.success(`Added ${name}. Indexing starts now.`);\n}\n\nexport function PageMessage({ children }: { children: string }): JSX.Element {\n return (\n <div className=\"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle\">\n {children}\n </div>\n );\n}\n\nexport function StatusBadge({ label, tone }: { label: string; tone: KnowledgeStatusTone }): JSX.Element {\n return (\n <Badge className={`fk:border-none fk:corner-squircle ${STATUS_TONE_CLASSES[tone]}`} variant=\"outline\">\n {tone === 'busy' ? <LoaderCircle className=\"fk:size-3 fk:animate-spin\" /> : null}\n {label}\n </Badge>\n );\n}\n\nconst FILE_ICONS: { [icon in KnowledgeFileIcon]: typeof Pdf } = {\n document: Document,\n docx: Docx,\n html: Html,\n pdf: Pdf,\n pptx: Pptx,\n txt: Txt,\n};\n\n/** The document's format as its file icon; the format's name is what a screen reader hears. */\nexport function KnowledgeTypeIcon({\n className = '',\n size = 24,\n source,\n}: {\n className?: string;\n size?: number;\n source: Pick<KnowledgeSource, 'kind' | 'mimeType'>;\n}): JSX.Element {\n const format = getKnowledgeFormat(source);\n const Icon = FILE_ICONS[format.icon];\n\n return (\n <span\n aria-label={format.label}\n className={`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${className}`}\n data-knowledge-type={format.icon}\n role=\"img\"\n >\n <Icon size={size} />\n </span>\n );\n}\n\n/** The larger file icon of the document page and the record panel: the same icon as the list, at 40px. */\nexport function SourceIcon({ source }: { source: Pick<KnowledgeSource, 'kind' | 'mimeType'> }): JSX.Element {\n return <KnowledgeTypeIcon size={40} source={source} />;\n}\n\nexport function InfiniteScrollSentinel({ onVisible }: { onVisible: () => void }): JSX.Element {\n const sentinelRef = useRef<HTMLDivElement>(null);\n const onVisibleRef = useRef(onVisible);\n\n onVisibleRef.current = onVisible;\n\n useEffect(() => {\n const node = sentinelRef.current;\n\n if (!node) {\n return;\n }\n\n const observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n onVisibleRef.current();\n }\n });\n\n observer.observe(node);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n return <div aria-hidden className=\"fk:h-px\" ref={sentinelRef} />;\n}\n\n/**\n * The actions of one document, behind a three-dots button: open (lists\n * only), download the original file (web pages open their address instead)\n * and remove, behind one confirmation. The list and the document page share\n * it so the copy, the download link and the busy rules stay the same.\n */\nexport function SourceActionsMenu({\n isBusy = false,\n onOpen,\n onRemoved,\n source,\n trigger = 'row',\n}: {\n /** Another action on the document is in flight; removing waits for it. */\n isBusy?: boolean;\n /** Offered as the first item when given (the document page is already open). */\n onOpen?: () => void;\n /** The document is gone: drop it from the list, or leave its page. The list invalidation is done here. */\n onRemoved: () => void;\n source: KnowledgeSource;\n /** How the button looks: a quiet icon in a row or card, an outlined one next to page actions. */\n trigger?: 'row' | 'page';\n}): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const canMutate = useCanMutate();\n const [isConfirmingRemoval, setIsConfirmingRemoval] = useState(false);\n const [isRemoving, setIsRemoving] = useState(false);\n\n if (!api || !projectId) {\n return null;\n }\n\n const knowledgeApi = api;\n\n async function remove(): Promise<void> {\n setIsRemoving(true);\n\n try {\n await knowledgeApi.deleteSource(source.id);\n toast.success(`Removed \"${source.title}\".`);\n setIsConfirmingRemoval(false);\n onRemoved();\n void invalidateKnowledgeLists();\n } catch (removeError) {\n toast.error(describeApiError(removeError, 'The document could not be removed.'));\n } finally {\n setIsRemoving(false);\n }\n }\n\n return (\n <>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n aria-label={`Actions for ${source.title}`}\n className={trigger === 'row' ? 'fk:size-8 fk:shrink-0 fk:text-muted-foreground' : undefined}\n data-knowledge-menu\n size=\"icon-sm\"\n variant={trigger === 'row' ? 'ghost' : 'outline'}\n >\n <EllipsisVerticalIcon className=\"fk:size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {onOpen ? <DropdownMenuItem onSelect={onOpen}>Open</DropdownMenuItem> : null}\n {source.path ? (\n <DropdownMenuItem asChild>\n <a href={knowledgePaths(projectId).file(source.id)}>\n <DownloadIcon />\n Download\n </a>\n </DropdownMenuItem>\n ) : null}\n {source.originUrl ? (\n <DropdownMenuItem asChild>\n <a href={source.originUrl} rel=\"noreferrer\" target=\"_blank\">\n <ExternalLinkIcon />\n Open page\n </a>\n </DropdownMenuItem>\n ) : null}\n {onOpen || source.path || source.originUrl ? <DropdownMenuSeparator /> : null}\n <DropdownMenuItem\n disabled={!canMutate || isBusy}\n variant=\"destructive\"\n onSelect={() => setIsConfirmingRemoval(true)}\n >\n <Trash2Icon />\n Remove\n </DropdownMenuItem>\n {canMutate ? null : (\n <DropdownMenuLabel className=\"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground\">\n Your member role cannot remove documents.\n </DropdownMenuLabel>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n <AlertDialog open={isConfirmingRemoval} onOpenChange={setIsConfirmingRemoval}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>Remove this document?</AlertDialogTitle>\n <AlertDialogDescription>\n \"{source.title}\" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep\n their citations, but the document can no longer be opened.\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={isRemoving}>Cancel</AlertDialogCancel>\n <AlertDialogAction\n disabled={isRemoving}\n onClick={(event: MouseEvent) => {\n event.preventDefault();\n void remove();\n }}\n >\n {isRemoving ? <LoaderCircle className=\"fk:animate-spin\" /> : null}\n Remove document\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n </>\n );\n}\n"]}
@@ -0,0 +1,378 @@
1
+ import'./index.css';import {e,d,a as a$2,c,b as b$1}from'./chunk-GXQSNOGM.js';import {a}from'./chunk-YDVO6XWD.js';import {a as a$1}from'./chunk-ERDARDGB.js';import {b,c as c$1}from'./chunk-XLFAJBPN.js';import {find,propEq,omit,pick,toPairs,uniq,uniqBy,prop}from'ramda';import {useState,useRef,useMemo,useEffect,useCallback}from'react';import {gql,NetworkStatus}from'@apollo/client';import {useQuery}from'@apollo/client/react';var Wt=25,mn=3,Kt=3,hn=["id","string"],$n=["date","datetime","duration","time"],$t=`_id
2
+ originalFilename
3
+ mimeType
4
+ path
5
+ url
6
+ size
7
+ height
8
+ width
9
+ lqip`,At=`_id
10
+ originalFilename
11
+ mimeType
12
+ path
13
+ url
14
+ size
15
+ height
16
+ width`,An=`_id
17
+ path
18
+ url`;function tt(t){return t?a(t)==="relationship"&&t.relationship?.mode==="multiple"&&t.relationship.entity==="_asset":false}function Et(t,n){return !t||!tt(t)?false:n?.name!==c$1.name||t.name!=="assets"}function ct(t){return t?.dataType==="asset"||t?.inputType==="asset"}function Jt(t){let n=t,e=n?.edges??[],r=n?.aggregate?.count?.nodes??e.length;return e.reduce((i,s,o)=>(s.node&&i.push({...s.node,sortOrder:s.properties?.sortOrder??o,totalCount:r}),i),[]).sort((i,s)=>(i.sortOrder??Number.MAX_SAFE_INTEGER)-(s.sortOrder??Number.MAX_SAFE_INTEGER))}function En(t){return t.reduce((n,e,r)=>e._id?{...n,[e._id]:e.sortOrder??r}:n,{})}function B(t){return Array.isArray(t)?t[0]??null:t??null}function bn(t,n){return n?An:t?$t:At}function Pt(t,n=true,e=true,r=Wt,i=false){let s=n?` properties {
19
+ sortOrder
20
+ }
21
+ `:"",o=bn(e,i),l=n?`(first: ${r}, sort: [{ edge: { sortOrder: ASC } }])`:`(first: ${r})`;return ` ${t}Connection${l} {
22
+ aggregate {
23
+ count {
24
+ nodes
25
+ }
26
+ }
27
+ edges {
28
+ `+s+` node {
29
+ ${o}
30
+ }
31
+ }
32
+ }
33
+ `}function Xt(t){return t?.aggregate?.count?.nodes??0}function Zt(t,n){let e=t[`${n}Total`];return typeof e=="number"?e:Xt(t[`${n}Connection`])}function bt(t,n=""){return ` ${t}Connection${n} {
34
+ aggregate {
35
+ count {
36
+ nodes
37
+ }
38
+ }
39
+ }
40
+ `}function Sn(t,n,e){return n?e==="total"?` ${t}Total
41
+ `:bt(t,"(where: $where)"):""}function _n(t,n,e,r=false){if(!t)return "";let i=n==="default"?"":`${n}
42
+ `;if(ct(t))return r?` ${t.name} {
43
+ _id
44
+ path
45
+ url
46
+ }
47
+ `:` ${t.name} {
48
+ ${$t}
49
+ }
50
+ `;if(a(t)==="local")return ` ${t.name} {
51
+ _id
52
+ default
53
+ ${i}}
54
+ `;if(a(t)==="relationship"){let s=t.relationship?.field;if(!s)return ` ${t.name}
55
+ `;let o=find(propEq(t.relationship?.entity,"name"))(e),l=find(propEq(s,"name"))(o?.attributes??[]),c=l&&a(l)==="local"?`{
56
+ _id
57
+ default
58
+ ${i}}
59
+ `:"";return t.relationship?.mode==="single"?` ${t.name} {
60
+ ${s} ${c}}
61
+ `:` ${t.name} (limit: 3, offset: 0) {
62
+ ${s} ${c}}
63
+ `}return ` ${t.name}
64
+ `}function Rn(t,n,e){return t?.attributes.reduce((r,i)=>{let s=n==="default"?"":`${n}
65
+ `;if(ct(i))return `${r}
66
+ ${i.name} {
67
+ ${At}
68
+ }
69
+ `;if(a(i)==="local")return `${r}
70
+ ${i.name} {
71
+ _id
72
+ default
73
+ ${s}
74
+ }
75
+ `;if(a(i)==="relationship"){let o=find(propEq(i.relationship?.entity,"name"))(e),l=find(propEq(i.relationship?.field,"name"))(o?.attributes??[]),c=a(l)==="local"?`{
76
+ _id
77
+ default
78
+ ${s}}
79
+ `:"";if(i.relationship?.mode==="single")return `${r}
80
+ ${i.name} {
81
+ ${i.relationship.field} ${c}}
82
+ `;if(i.relationship?.field)return `${r}
83
+ ${i.name} (limit: ${Kt}, offset: 0) {
84
+ ${i.relationship.field} ${c}}
85
+ `}return `${r}
86
+ ${i.name}
87
+ `},"")??""}function In(t){let n={};for(let e of t)n[e.name]=e;return n}function mt(t){return t?t.name==="url"?true:!(t.hidden===true||t.name==="lqip"):false}function Zn(t,n){if(!Array.isArray(t)||t.length===0)return;let[e]=t;if(!e||typeof e!="object")return;let[r]=Object.keys(e);if(!r||["_id","_createdAt","_updatedAt"].includes(r))return;let i=n?.attributes.find(s=>s.name===r);if(!(!i||a(i)!=="global"||i.dataType==="asset"))return {NOT:{[r]:{eq:null}}}}function at(t,n,e,r){let i=r?.selection??"full",s=i==="display"?"list":i,o=r?.includeCount??true,l=r?.countMode??"aggregate",c="(where: $where, limit: $limit, offset: $offset, sort: $sort)",u=D(e,t),a$2=u?.name??t,d=a$1(u),f=i==="display"?d?[d]:[]:u?.attributes??[],p=In(f),m=`$where: ${a$2}Where, $limit: Int, $offset: Int, $sort: [${a$2}Sort!]`,h=r?.operationName??`Get${x(t)}`;if(!u)throw new Error(`Entity '${a$2}' not found in the schema`);if(f.length===0)throw new Error(`Entity '${a$2}' has no attributes defined in the schema`);let A=L("global",f).filter($=>$==="_updatedAt"?false:s==="list"?i==="display"||mt(p[$]):true).join(`
88
+ `),g=nt(f).filter($=>s!=="list"||i==="display"||mt(p[$])),y=L(["local"],f).filter($=>s!=="list"?true:i==="display"||mt(p[$])),E=y.reduce(($,R)=>`${$}
89
+ ${R} {
90
+ _id
91
+ default
92
+ }
93
+ `,""),C=y.reduce(($,R)=>`${$}
94
+ ${R} {
95
+ _id
96
+ default
97
+ ${n}
98
+ }
99
+ `,""),F=n==="default"?E:C,b=`_id
100
+ path
101
+ url`;s!=="list"&&(b=`_id
102
+ originalFilename
103
+ mimeType
104
+ path
105
+ url
106
+ size
107
+ height
108
+ width
109
+ lqip`);let z=g.reduce(($,R)=>`${$}
110
+ ${R} {
111
+ ${b}
112
+ }
113
+ `,""),J=f.filter($=>a($)==="relationship").reduce(($,R)=>{if(s==="list"&&i!=="display"&&R.hidden===true)return $;if(tt(R))return `${$}
114
+ ${Pt(R.name,Et(R,u),s!=="list",s==="list"?mn:Wt,s==="list")}`;let k=find(propEq(R.relationship?.entity,"name"))(e);if(s==="list"){let v=a$1(k),st=_n(v,n,e,true),ot=R.relationship?.mode==="single"?1:3;return `${$}
115
+ ${R.name} (limit: ${ot}, offset: 0) {
116
+ _id
117
+ ${st} }
118
+ `}let H=Rn(k,n,e);return `${bt(R.name).trim()}${$}
119
+ ${R.name} (limit: 25, offset: 0) { _id ${H}}
120
+ `},"");return {queryEntityName:t,query:`query ${h}(${m}) {
121
+ `+Sn(t,o,l)+` ${t}${c} {
122
+ _id
123
+ _updatedAt
124
+ ${A} ${F} ${z} ${J}}
125
+ }
126
+ `}}function Ht(t,n,e,r){let s=D(r,t)?.attributes??[];if(s.length===0)return {count:0,results:[]};let o=Zt(e,t),l=e[t],c=(a$1,d)=>{let f=d.name;return a$1.slice(0,3).map(p=>{if(a(d)!=="local")return p[f];let m=B(p[f]);return m?.[n]??m?.default}).join(", ")},u=l.map(a$2=>{let{_id:d}=a$2,f=typeof a$2._updatedAt=="string"?a$2._updatedAt:"",p=L("global",s).filter(g=>g!=="_updatedAt").reduce((g,y)=>({...g,[y]:a$2[y]}),{}),m=L("local",s).reduce((g,y)=>{let E=B(a$2[y]);return {...g,[y]:E?.[n]?E[n]:E?.default}},{}),h=nt(s).reduce((g,y)=>({...g,[y]:B(a$2[y])}),{}),A=L(["relationship"],s).reduce((g,y)=>{let E=find(propEq(y,"name"))(s),C=E.relationship?.entity??"",F=find(propEq(C,"name"))(r),b=a$1(F),z=a$2[y];if(tt(E)){let k=Jt(a$2[`${y}Connection`]);return {...g,[y]:k}}if(!b)throw new Error(`There is an error in the schema for the relationship attribute "${y}"`);let V=b.name,J=a(b);if(E.relationship?.mode==="multiple"){let k=Array.isArray(z)?z:[];return {...g,[y]:c(k,b)}}let $=B(z);if(J==="global")return {...g,[y]:$?.[V]};let R=B($?.[V]);return {...g,[y]:R?.[n]??R?.default}},{});return {_id:d,...p,...m,...h,...A,_updatedAt:f}});return {count:o,results:u}}function Yt(t,n,e,r){let s=D(r,t)?.attributes??[];if(s.length===0)return {count:0,results:[]};let o=Zt(e,t),c=e[t].map(u=>{let a$1=L("global",s).reduce((m,h)=>({...m,[h]:{value:u[h],disabled:false,scope:"default",_id:""}}),{}),d=L("local",s).reduce((m,h)=>{let A=find(propEq(h,"name"))(s),g=B(u[h]);return {...m,[h]:{value:g?wn(g,n):null,disabled:!!(g&&g[n]===null&&a(A)==="local"&&n!=="default"),scope:n,_id:g?g._id:null}}},{}),f=nt(s).reduce((m,h)=>({...m,[h]:{value:B(u[h]),disabled:false,scope:"default",_id:""}}),{}),p=L(["relationship"],s).reduce((m,h)=>{let A=find(propEq(h,"name"))(s),g=u[h],y=A.relationship?.mode==="single"?B(g):g,E=y?._id,C=Xt(u[`${h}Connection`]);if(tt(A)){let F=Jt(u[`${h}Connection`]);return {...m,[h]:{count:C,_id:E,knownAssetSortOrders:En(F),value:F,disabled:false,scope:n}}}return {...m,[h]:{count:C,_id:E,value:y,disabled:false,scope:n}}},{});return {...a$1,...d,...f,...p}});return {count:o,results:c}}function wn(t,n){return Array.isArray(t)?t.reduce((e,r)=>{if(r[n]??r.default){let i={_id:r._id,disabled:r.scope===null&&n!=="default",scope:n,value:r[n]??r.default};e.push(i);}return e},[]):t[n]??t.default??null}function Hn(t,n,e,r,i,s,o){let l=D(r,t),c=l?.name??t,u=l?.attributes??[],a=et(t);if(u.length===0)return "";let d=Nt(u,s),f=tn(u,d),p=Fn(n,u,d,e),m=On(u,i,d),h=Cn(u,i,d),A=t,g=o?.responseFields??en(r,t,e);return `mutation ${`Update${x(t)}`}($where: ${c}Where) {
127
+ update${a}(
128
+ where: $where
129
+ update: {${f}${p}${m}${h}
130
+ }
131
+ ) {
132
+ ${A} {
133
+ _id
134
+ ${g} }
135
+ }
136
+ }
137
+ `}function Nt(t,n){let e=t.filter(i=>i.readOnly===true).map(i=>i.name),r=omit(e,n);return pick(t.map(i=>i.name),r)}function L(t,n){return Array.isArray(t)?t.reduce((r,i)=>r.concat(L(i,n)),[]):n.filter(r=>a(r)===t&&r.inputType!=="asset").map(r=>r.name)}function nt(t){return t.filter(ct).map(e=>e.name)}function tn(t,n,e="update"){let r=pick(L("global",t),n);return toPairs(r).reduce((s,[o,l])=>{let c=find(propEq(o,"name"))(t),u=Array.isArray(l?.value)?null:l?.value??null,a=St(c.dataType,u);return e==="create"&&(a===null||a==="")?s:e==="update"?`${s}
138
+ ${o}: { set: ${a} }`:`${s}
139
+ ${o}: ${a}`},"")}function ht(t){return !t?._id||!t.path?"":t._id}function On(t,n,e){let r=pick(nt(t),e);return toPairs(r).reduce((o,[l,c])=>{let u=ht(c.value),a=ht(n[l]?.value);if(u===a)return o;let d=a?` {
140
+ disconnect: [{
141
+ where: {
142
+ node: {
143
+ _id: { eq: ${O(a)} }
144
+ }
145
+ }
146
+ }]
147
+ }
148
+ `:"",f=u?` {
149
+ connect: [{
150
+ where: {
151
+ node: {
152
+ _id: { eq: ${O(u)} }
153
+ }
154
+ }
155
+ }]
156
+ }
157
+ `:"";return `${o}
158
+ ${l}: [
159
+ ${d}${f} ]`},"")}function Ln(t,n){let e=pick(nt(t),n);return toPairs(e).reduce((s,[o,l])=>{let c=ht(l.value);return c?`${s}
160
+ ${o}: {
161
+ connect: [{
162
+ where: {
163
+ node: {
164
+ _id: { eq: ${O(c)} }
165
+ }
166
+ }
167
+ }]
168
+ }`:s},"")}function Fn(t,n,e,r){let i=pick(L("local",n),e);return toPairs(i).reduce((l,[c,u])=>{let a=find(propEq(c,"name"))(n),{dataType:d}=a,f=u.disabled||Array.isArray(u.value)?"null":St(d,u.value);return u._id?`${l}
169
+ ${c}: [{
170
+ update: {
171
+ node: {
172
+ ${r}: { set: ${f} }
173
+ }
174
+ }
175
+ }]`:u.disabled||Array.isArray(u.value)||u.value===void 0||u.value===null||u.value===""||f===null||f===""?l:`${l}
176
+ ${c}: [{
177
+ create: {
178
+ node: {
179
+ _id: ${O(`${t}:${c}`)}
180
+ _type: "${d}"
181
+ ${r}: ${f}
182
+ }
183
+ }
184
+ }]`},"")}function Cn(t,n,e){let r=pick(L("relationship",t),e);return toPairs(r).reduce((o,[l,c])=>{let u=find(propEq(l,"name"))(t),{inputType:a,relationship:d}=u;if(a==="relationship"&&d?.mode==="single"){let f=n[l]._id??"",p=c._id??"";if(f===p)return o;let m=f?` {
185
+ disconnect: [{
186
+ where: {
187
+ node: {
188
+ _id: { eq: ${O(f)} }
189
+ }
190
+ }
191
+ }]
192
+ }
193
+ `:"",h=p?` {
194
+ connect: [{
195
+ where: {
196
+ node: {
197
+ _id: { eq: ${O(p)} }
198
+ }
199
+ }
200
+ }]
201
+ }
202
+ `:"";return `${o}
203
+ ${l}: [
204
+ ${m}${h} ]`}if(a==="relationship"&&d?.mode==="multiple"){if(d.entity==="_asset")return `${o}${Tn(l,n[l],c)}`;let f=uniq(c.relationships?.disconnect??[]).filter(Boolean),m=(c.relationships?.connect??[]).map(g=>O(g._id)).join(", "),h=f.length?` {
205
+ disconnect: [
206
+ ${f.map(g=>` {
207
+ where: {
208
+ node: {
209
+ _id: { eq: ${O(g)} }
210
+ }
211
+ }
212
+ }
213
+ `).join("")} ]
214
+ }
215
+ `:"",A=m?` {
216
+ connect: [{
217
+ where: {
218
+ node: {
219
+ _id: { in: [${m}] }
220
+ }
221
+ }
222
+ }]
223
+ }
224
+ `:"";return !h&&!A?o:`${o}
225
+ ${l}: [
226
+ ${h}${A} ]`}return `${o}
227
+ `},"")}function Tn(t,n,e){let i=(e.relationships?.connect??[]).map((p,m)=>({...p,sortOrder:p.sortOrder??m})),s=i.map(p=>p._id),o={...Mn(n),...n?.knownAssetSortOrders??{},...e.knownAssetSortOrders??{}},l=uniq(e.relationships?.disconnect??[]).filter(p=>p&&!s.includes(p)),c=i.filter(p=>o[p._id]===void 0),u=i.filter(p=>{let m=o[p._id];return m!==void 0&&m!==p.sortOrder}),a=Qn(l),d=qn(c),f=xn(u);return !a&&!d&&!f?"":`
228
+ ${t}: [
229
+ ${a}${d}${f} ]`}function Mn(t){let n=t?.value;return Array.isArray(n)?n.reduce((e,r,i)=>{if(typeof r!="object"||!r||!("_id"in r))return e;let{_id:s}=r;if(typeof s!="string"||s.length===0)return e;let o="sortOrder"in r&&typeof r.sortOrder=="number"?r.sortOrder:i;return {...e,[s]:o}},{}):{}}function Qn(t){return t.length===0?"":` {
230
+ disconnect: [
231
+ ${t.reduce((e,r)=>`${e} {
232
+ where: { node: { _id: { eq: ${O(r)} } } }
233
+ }
234
+ `,"")} ]
235
+ }
236
+ `}function qn(t){return t.length===0?"":` {
237
+ connect: [
238
+ ${nn(t)} ]
239
+ }
240
+ `}function nn(t){return t.reduce((n,e,r)=>{let i=e.sortOrder??r;return `${n} {
241
+ where: { node: { _id: { eq: ${O(e._id)} } } }
242
+ edge: { sortOrder: ${i} }
243
+ }
244
+ `},"")}function xn(t){return t.length===0?"":t.reduce((e,r,i)=>{let s=r.sortOrder??i;return `${e} {
245
+ update: {
246
+ where: { node: { _id: { eq: ${O(r._id)} } } }
247
+ edge: { sortOrder: { set: ${s} } }
248
+ }
249
+ }
250
+ `},"")}function St(t,n){return $n.includes(t)?n?.toString()?O(n.toString()):null:hn.includes(t)?n==null?null:O(n.toString()):n==null||n===""?null:n.toString()}function O(t){return JSON.stringify(t)}function en(t,n,e){let r=D(t,n),i=r?.attributes??[],s=L("global",i),o=L("local",i),l=L("relationship",i),c=s.reduce((u,a)=>`${u}${a}
251
+ `,"");return c+=o.reduce((u,a)=>`${u} ${a} {
252
+ _id
253
+ ${e}
254
+ }
255
+ `,""),c+=l.reduce((u,a$1)=>{let d=find(propEq(a$1,"name"))(i),f=d?.relationship?.mode??"single";if(tt(d))return `${u}${Pt(a$1,Et(d,r))}`;let p=d?.relationship?.entity??"",h=find(propEq(p,"name"))(t)?.attributes??[],A=d?.relationship?.field??"[invalid_relationship_field_name_in_schema]",g=find(propEq(A,"name"))(h),y=a(g),E="";if(f==="single"&&(y==="global"&&(E=` ${a$1} {
256
+ _id
257
+ ${A}
258
+ }
259
+ `),y==="local"&&(E=` ${a$1} {
260
+ _id
261
+ ${A} {
262
+ _id
263
+ default
264
+ ${e}
265
+ }
266
+ }
267
+ `)),f==="multiple"&&h.length){let C=h.reduce((F,b)=>{if(a(b)==="local")return `${F} ${b.name} {
268
+ _id
269
+ default
270
+ ${e}
271
+ }
272
+ `;if(a(b)==="relationship"){let z=e==="default"?"":`${e}
273
+ `,V=find(propEq(b.relationship?.entity,"name"))(t),J=find(propEq(b.relationship?.field,"name"))(V?.attributes??[]),$=a(J)==="local"?`{
274
+ _id
275
+ default
276
+ ${z}}
277
+ `:"";if(b.relationship?.mode==="single")return `${F} ${b.name} {
278
+ ${b.relationship.field} ${$}}
279
+ `;if(b.relationship?.field)return `${F} ${b.name} (limit: ${Kt}, offset: 0) {
280
+ ${b.relationship.field} ${$}}
281
+ `}return ct(b)?`${F} ${b.name} {
282
+ ${At}
283
+ }
284
+ `:`${F} ${b.name}
285
+ `},"");E=bt(a$1)+` ${a$1} (limit: 25, offset: 0) {
286
+ ${C} }
287
+ `;}return `${u}${E}`},""),c}function Yn(t,n,e){let r=typeof e=="string"?[e]:[...e],i=find(propEq(t,"name"))(n),s=i?.attributes??[],o=et(i?.plural??""),l=kn(s,r),c=`Delete${x(i?.plural??t)}`;return t==="_asset"?`mutation ${c}($where: ${t}Where) {
288
+ delete_assets(
289
+ where: $where
290
+ ) {
291
+ nodesDeleted
292
+ relationshipsDeleted
293
+ }
294
+ }
295
+ `:`mutation ${c}($where: ${t}Where) {
296
+ delete${o}(
297
+ where: $where
298
+ ${l?` delete: {
299
+ ${l}
300
+ }
301
+ `:""} ) {
302
+ nodesDeleted
303
+ relationshipsDeleted
304
+ }
305
+ }
306
+ `}function Nn(t){let n=typeof t=="string"?[t]:[...t];return n.length===1?{_id:{eq:n[0]}}:{_id:{in:n}}}function kn(t,n){return L("local",t).reduce((i,s)=>{let o=n.map(c=>O(`${c}:${s}`)).join(", "),l=n.length===1?`_id: { eq: ${o} }`:`_id: { in: [${o}] }`;return `${i}
307
+ ${s}: [{
308
+ where: {
309
+ node: {
310
+ ${l}
311
+ }
312
+ }
313
+ }]`},"")}function te(t,n,e,r,i){let s=D(n,t),o=s?.attributes??[],l=et(s?.plural??"");if(o.length===0)return "";let c=Nt(o,e),u=tn(o,c,"create"),a=vn(o,c,"default",r),d=Ln(o,c),f=jn(o,c),p=t,m=en(n,p,"default");return `mutation ${`Create${x(t)}`} {
314
+ create${l}(
315
+ input: [{
316
+ _id: ${O(r)} ${u} ${a}
317
+ ${d}
318
+ ${f}
319
+ }]
320
+ ) {
321
+ ${p} {
322
+ _id
323
+ ${m} }
324
+ }
325
+ }
326
+ `}function vn(t,n,e,r){let i=pick(L("local",t),n);return toPairs(i).reduce((l,[c,u])=>{if(u?.value===void 0||u.value===null||u.value==="")return l;let a=find(propEq(c,"name"))(t),d=Array.isArray(u.value)?"null":St(a.dataType,u.value);return `${l}
327
+ ${c}: {
328
+ create: [{
329
+ node: {
330
+ _id: ${O(`${r}:${c}`)}
331
+ _type: "${a.dataType}"
332
+ ${e}: ${d}
333
+ }
334
+ }]
335
+ }`},"")}function jn(t,n){let e=pick(L("relationship",t),n);return toPairs(e).reduce((s,[o,l])=>{let c=find(propEq(o,"name"))(t),{inputType:u,relationship:a}=c;if(u==="relationship"&&a?.mode==="single"){if(!l._id)return s;let p=`connect: [{
336
+ where: {
337
+ node: {
338
+ _id: { eq: ${O(l._id)} }
339
+ }
340
+ }
341
+ }]
342
+ `;return `${s}
343
+ ${o}: {
344
+ ${p} }`}let d=u==="relationship"&&a?.mode==="multiple",f=Array.isArray(l.relationships?.connect)&&l.relationships.connect.length>0;if(d&&f){let p=l.relationships?.connect??[];if(a?.entity==="_asset"){let A=nn(p.map((g,y)=>({...g,sortOrder:g.sortOrder??y})));return `${s}
345
+ ${o}: {
346
+ connect: [
347
+ ${A} ]
348
+ }`}let m=p.map(A=>O(A._id)).join(", "),h=m?`connect: {
349
+ where: {
350
+ node: {
351
+ _id: { in: [${m}] }
352
+ }
353
+ }
354
+ }
355
+ `:"";return `${s}
356
+ ${o}: {
357
+ ${h} }`}return `${s}
358
+ `},"")}function ne({relatedEntityName:t,scope:n,schema:e}){let i=find(propEq(t,"name"))(e)?.plural??"";return i?at(i,n,e,{selection:"list",operationName:`GetRelated${x(i)}`}):{queryEntityName:"",query:""}}function ee({attributeName:t,entityName:n,entityNamePlural:e,schema:r}){let i=D(r,e),s=find(propEq(t,"name"))(i?.attributes??[]),o=Et(s,i),l=o?` properties {
359
+ sortOrder
360
+ }
361
+ `:"",c=o?"(first: $first, sort: [{ edge: { sortOrder: ASC } }])":"(first: $first)",u=`Get${x(n)}AssetConnection`;return {queryEntityName:e,query:`query ${u}($where: ${n}Where, $first: Int) {
362
+ ${e}(where: $where) {
363
+ ${t}Connection${c} {
364
+ aggregate {
365
+ count {
366
+ nodes
367
+ }
368
+ }
369
+ edges {
370
+ `+l+` node {
371
+ ${$t}
372
+ }
373
+ }
374
+ }
375
+ }
376
+ }
377
+ `}}var et=t=>t.charAt(0).toUpperCase()+t.slice(1);function x(t){let n=t.split(/[^0-9A-Za-z]+/).filter(Boolean).map(et).join("");return n?/^[A-Za-z_]/.test(n)?n:`Entity${n}`:"Entity"}function D(t,n){return n==="_assets"?b:find(propEq(n,"plural"))(t)}function re(t,n,e){if(!t||typeof t!="object")return {};let r=D(e,n);if(!r)return {};let i=`update${et(n)}`,s=t[i];if(!s||typeof s!="object")return {};let o=s[n],l=Array.isArray(o)?o[0]:void 0;return !l||typeof l!="object"?{}:r.attributes.reduce((c,u)=>{if(a(u)!=="local")return c;let d=B(l[u.name])?._id;return typeof d!="string"||d.length===0?c:{...c,[u.name]:d}},{})}var dt=null,_t=new Set,rn=[],Rt=new Set,It=new Set,wt=new Set;function ue(t,n){if(t==="_asset"||t==="_assets")return `Get${x(b.plural)}`;let e=n.find(s=>s.plural===t),r=n.find(s=>s.name===t),i=e?.plural??r?.plural??t;return `Get${x(i)}`}function sn(t){return Rt.add(t),()=>{Rt.delete(t);}}function on(t){return It.add(t),()=>{It.delete(t);}}function un(t){return wt.add(t),()=>{wt.delete(t);}}function le(t,n,e){let r=new Set(e.filter(Boolean));if(r.size>0)for(let i of It)i(n,r);return Dn(t,n)}function ce(t,n){let e=n.filter(r=>!!r._id);if(e.length!==0)for(let r of wt)r(t,e);}function Dn(t,n){return _t.add(n),new Promise((e,r)=>{rn.push({resolve:e,reject:r}),dt&&clearTimeout(dt),dt=setTimeout(()=>{let i=new Set(_t),s=rn.splice(0);_t.clear(),dt=null,Promise.all([...Rt].map(o=>Promise.resolve(o(i)))).then(()=>{for(let{resolve:o}of s)o();}).catch(o=>{console.error("Error refreshing entity lists:",o);for(let{reject:l}of s)l(o);});},50);})}function Ae({entityNamePlural:t,schema:n,scope:e$1,variables:r,isForm:i,selection:s="full",includeCount:o=true,fetchPolicy:l}){let[c$1,u]=useState({count:0,results:[]}),[a,d$1]=useState(false),[f,p]=useState(false),[m,h]=useState(null),A=useRef(false),g=useRef(false),y=useRef(0),E=useRef(null),C=useRef(null),F=`${t}Total`,b=D(n,t),V=r?.where===void 0&&(b?.spaces?.length??0)===0&&(m?.field!==F||m.schema!==n)?"total":"aggregate",J=useMemo(()=>gql(at(t,e$1,n,{selection:s,countMode:V,includeCount:o}).query),[t,e$1,n,s,V,o]),$=useMemo(()=>gql(at(t,e$1,n,{selection:s,includeCount:false}).query),[t,e$1,n,s]),{schemaErrorMessage:R,setSchemaErrorMessage:k}=e(),{loading:H,data:v,fetchMore:st,refetch:ot,error:Lt,networkStatus:Y}=useQuery(J,{variables:r,notifyOnNetworkStatusChange:true,fetchPolicy:l}),Ft=useRef(st),gt=useRef(ot),Ct=useRef($),Tt=useRef(Y),Mt=useRef(r);Ft.current=st,gt.current=ot,Ct.current=$,Mt.current=r;let yt=o&&d(Lt,F),Qt=V==="total"&&yt,G=yt?void 0:Lt,N=yt&&!v?.[t],qt=a$2(G),P=c(G),{isProjectDisabled:dn,isProjectReadOnly:fn}=(()=>{if(qt?.statusCode===403){let I=b$1(qt.bodyText);if(I&&typeof I.code=="string"){if(I.code==="PROJECT_PAUSED")return {isProjectDisabled:true,isProjectReadOnly:false};if(I.code==="READ_ONLY_MODE")return {isProjectDisabled:false,isProjectReadOnly:true}}return {isProjectDisabled:true,isProjectReadOnly:false}}return {isProjectDisabled:false,isProjectReadOnly:false}})();useEffect(()=>{Qt&&h({field:F,schema:n});},[n,Qt,F]);let pn=useCallback(I=>{if(A.current||g.current)return;A.current=true,d$1(true);let{limit:Q}=I.variables,q=y.current;Ft.current({...I,query:Ct.current,variables:{...Mt.current,...I.variables,offset:q,limit:Q}}).then(({data:X})=>{let M=it({data:X,entityNamePlural:t,isForm:i,schema:n,scope:e$1}),j=M.results.length;y.current=q+(j===0?0:Math.min(j,Q)),u(T=>{let W=uniqBy(prop("_id"),[...T.results,...M.results]);return W.length===T.results.length?{count:T.results.length,results:T.results}:{count:M.count||T.count,results:W}});}).catch(X=>{console.error("Error fetching more data:",X);}).finally(()=>{A.current=false,d$1(false);});},[t,i,n,e$1]),gn=useCallback(I=>{if(g.current)return Promise.resolve();let Q=I?.preserve===true;return g.current=true,A.current=false,d$1(false),Q||(E.current=null,C.current=null,y.current=0,p(true),u({count:0,results:[]})),gt.current().then(({data:q})=>{let X=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),M=it({data:q,entityNamePlural:t,isForm:i,schema:n,scope:e$1});E.current=X,C.current=null,y.current=pt(r)+M.results.length,u(M);}).catch(q=>{console.error("Error reloading data:",q);}).finally(()=>{g.current=false,p(false);})},[t,i,n,e$1,s,o,r]);return useEffect(()=>{if(P){k(P);return}v&&R&&!G&&k(null);},[v,G,R,P,k]),useEffect(()=>{if(G||P||N)return;let I=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r});if(E.current===I)return;if(H&&C.current!==I){C.current=I,y.current=0,u({count:0,results:[]});return}if(H)return;let Q=it({data:v,entityNamePlural:t,isForm:i,schema:n,scope:e$1});E.current=I,C.current=null,y.current=pt(r)+Q.results.length,u(Q);},[v,G,t,i,H,N,n,P,e$1,s,o,r]),useEffect(()=>{let I=Tt.current;if(Tt.current=Y,G||P||g.current||N||I!==NetworkStatus.refetch||Y!==NetworkStatus.ready||!v)return;let Q=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),q=it({data:v,entityNamePlural:t,isForm:i,schema:n,scope:e$1});E.current=Q,C.current=null,y.current=pt(r)+q.results.length,u(q);},[v,G,t,i,N,Y,n,P,e$1,s,o,r]),useEffect(()=>{if(i)return;let I=`Get${x(t)}`,Q=sn(M=>{if(!(!M.has(I)||A.current||g.current))return gt.current().then(({data:j})=>{let T=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),W=it({data:j,entityNamePlural:t,isForm:i,schema:n,scope:e$1});E.current=T,C.current=null,y.current=pt(r)+W.results.length,u(W);}).catch(j=>{console.error("Error soft-refreshing entity list:",j);})}),q=on((M,j)=>{M===I&&u(T=>{let W=T.results.filter(kt=>{let vt=typeof kt._id=="string"?kt._id:void 0;return !vt||!j.has(vt)}),xt=T.results.length-W.length;return xt===0?T:{count:Math.max(0,T.count-xt),results:W}});}),X=un((M,j)=>{M===I&&u(T=>zn(T,j,r?.sort));});return ()=>{Q(),q(),X();}},[t,i,n,e$1,s,o,r]),{isLoading:H&&Y!==NetworkStatus.refetch||f||N,isLoadingMore:a,fetchMore:pn,reload:gn,count:c$1.count,data:c$1.results,isProjectDisabled:dn,isProjectReadOnly:fn,schemaErrorMessage:R}}function pt(t){let n=t?.offset;return typeof n=="number"&&Number.isFinite(n)?n:0}function it(t){let n=t.entityNamePlural;return t.data?.[n]?t.isForm?Yt(t.entityNamePlural,t.scope,t.data,t.schema):Ht(t.entityNamePlural,t.scope,t.data,t.schema):{count:0,results:[]}}function zn(t,n,e){let r=new Map(n.map(o=>[o._id,o])),i=false,s=t.results.map(o=>{let l=typeof o._id=="string"?o._id:void 0;if(!l)return o;let c=r.get(l);return c?(i=true,{...o,...c.attributes}):o});return i?{count:t.count,results:Gn(s,e)}:t}function Gn(t,n){if(!Array.isArray(n)||n.length===0)return t;let[e]=n;if(!e||typeof e!="object")return t;let[r]=Object.entries(e),[i,s]=r??[];if(!i||s!=="ASC"&&s!=="DESC")return t;let o=s==="DESC"?-1:1;return [...t].sort((l,c)=>{let u=l[i],a=c[i],d=typeof u=="string"?u:"",f=typeof a=="string"?a:"";return d.localeCompare(f)*o})}export{Wt as a,Jt as b,En as c,Zn as d,at as e,Ht as f,Hn as g,Yn as h,Nn as i,te as j,ne as k,ee as l,D as m,re as n,ue as o,le as p,ce as q,Dn as r,Ae as s};//# sourceMappingURL=chunk-D76P4TER.js.map
378
+ //# sourceMappingURL=chunk-D76P4TER.js.map