@flexkit/studio 0.2.25 → 0.2.26

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 (62) hide show
  1. package/dist/{chat-page-Z7HA3GSH.js → chat-page-U46RRUKG.js} +3 -3
  2. package/dist/{chat-page-Z7HA3GSH.js.map → chat-page-U46RRUKG.js.map} +1 -1
  3. package/dist/{chunk-2XQHISFR.js → chunk-3L4LYXSR.js} +2 -2
  4. package/dist/{chunk-2XQHISFR.js.map → chunk-3L4LYXSR.js.map} +1 -1
  5. package/dist/{chunk-IPQYDKPP.js → chunk-3YL7XGH5.js} +3 -3
  6. package/dist/{chunk-IPQYDKPP.js.map → chunk-3YL7XGH5.js.map} +1 -1
  7. package/dist/{chunk-QW6H7OZ6.js → chunk-7QHGKOAB.js} +3 -3
  8. package/dist/{chunk-QW6H7OZ6.js.map → chunk-7QHGKOAB.js.map} +1 -1
  9. package/dist/{chunk-OCWM45Z2.js → chunk-BCFG4FXM.js} +3 -3
  10. package/dist/{chunk-OCWM45Z2.js.map → chunk-BCFG4FXM.js.map} +1 -1
  11. package/dist/{chunk-PJ3ZOCQ3.js → chunk-HE7I5LVU.js} +2 -2
  12. package/dist/{chunk-PJ3ZOCQ3.js.map → chunk-HE7I5LVU.js.map} +1 -1
  13. package/dist/{chunk-D6NOMUTD.js → chunk-HPLIQBUP.js} +3 -3
  14. package/dist/{chunk-D6NOMUTD.js.map → chunk-HPLIQBUP.js.map} +1 -1
  15. package/dist/{chunk-WO5OQNAN.js → chunk-NAUY7EN3.js} +2 -2
  16. package/dist/{chunk-WO5OQNAN.js.map → chunk-NAUY7EN3.js.map} +1 -1
  17. package/dist/{chunk-SKHHYRVA.js → chunk-P5YGMKPO.js} +2 -2
  18. package/dist/{chunk-SKHHYRVA.js.map → chunk-P5YGMKPO.js.map} +1 -1
  19. package/dist/{chunk-SRFTSMZD.js → chunk-RARRMN5A.js} +3 -3
  20. package/dist/{chunk-SRFTSMZD.js.map → chunk-RARRMN5A.js.map} +1 -1
  21. package/dist/{chunk-X452A7C3.js → chunk-V45Z7U6J.js} +2 -2
  22. package/dist/{chunk-X452A7C3.js.map → chunk-V45Z7U6J.js.map} +1 -1
  23. package/dist/{chunk-SK7C7CGH.js → chunk-WFJICDCL.js} +3 -3
  24. package/dist/{chunk-SK7C7CGH.js.map → chunk-WFJICDCL.js.map} +1 -1
  25. package/dist/{chunk-T7N3WUV2.js → chunk-Z6WDRVBW.js} +2 -2
  26. package/dist/{chunk-T7N3WUV2.js.map → chunk-Z6WDRVBW.js.map} +1 -1
  27. package/dist/{chunk-JTUOTP5S.js → chunk-ZI22345U.js} +3 -3
  28. package/dist/{chunk-JTUOTP5S.js.map → chunk-ZI22345U.js.map} +1 -1
  29. package/dist/{entry-ZII6ECS5.js → entry-TFSFZ6FA.js} +2 -2
  30. package/dist/{entry-ZII6ECS5.js.map → entry-TFSFZ6FA.js.map} +1 -1
  31. package/dist/index.js +7 -7
  32. package/dist/index.js.map +1 -1
  33. package/dist/{list-76SBWKGF.js → list-ORNZB5HP.js} +2 -2
  34. package/dist/{list-76SBWKGF.js.map → list-ORNZB5HP.js.map} +1 -1
  35. package/dist/{list-YIIXASZF.js → list-Q5R3QLQU.js} +3 -3
  36. package/dist/{list-YIIXASZF.js.map → list-Q5R3QLQU.js.map} +1 -1
  37. package/dist/{pages-N3IGHP7Y.js → pages-IYR7KLDW.js} +3 -3
  38. package/dist/{pages-N3IGHP7Y.js.map → pages-IYR7KLDW.js.map} +1 -1
  39. package/dist/{plugin-pages-MLF2FUBT.js → plugin-pages-QVUZRBF7.js} +2 -2
  40. package/dist/{plugin-pages-MLF2FUBT.js.map → plugin-pages-QVUZRBF7.js.map} +1 -1
  41. package/dist/record-links-XNRXCW3Y.js +2 -0
  42. package/dist/{record-links-66T2CJRM.js.map → record-links-XNRXCW3Y.js.map} +1 -1
  43. package/dist/{root-BRC7XSCT.js → root-2BTH6M5K.js} +3 -3
  44. package/dist/{root-BRC7XSCT.js.map → root-2BTH6M5K.js.map} +1 -1
  45. package/dist/{root-FGVYUZZ6.js → root-5T3UQRUT.js} +2 -2
  46. package/dist/{root-FGVYUZZ6.js.map → root-5T3UQRUT.js.map} +1 -1
  47. package/dist/{root-UKGHRHON.js → root-A76E3Z35.js} +3 -3
  48. package/dist/{root-UKGHRHON.js.map → root-A76E3Z35.js.map} +1 -1
  49. package/dist/{root-RD5VRALH.js → root-LGCOXNRR.js} +2 -2
  50. package/dist/{root-RD5VRALH.js.map → root-LGCOXNRR.js.map} +1 -1
  51. package/dist/{root-MDKGJJB4.js → root-TOTFZUJI.js} +2 -2
  52. package/dist/{root-MDKGJJB4.js.map → root-TOTFZUJI.js.map} +1 -1
  53. package/dist/{root-6Y5RN4PW.js → root-XPFHRGVP.js} +3 -3
  54. package/dist/{root-6Y5RN4PW.js.map → root-XPFHRGVP.js.map} +1 -1
  55. package/dist/{search-IM2VPW6O.js → search-4UVG2IJ5.js} +2 -2
  56. package/dist/{search-IM2VPW6O.js.map → search-4UVG2IJ5.js.map} +1 -1
  57. package/dist/{skills-pages-LZCCHOJB.js → skills-pages-3RFTYQ2K.js} +2 -2
  58. package/dist/{skills-pages-LZCCHOJB.js.map → skills-pages-3RFTYQ2K.js.map} +1 -1
  59. package/dist/{source-ZLZHE7TL.js → source-P5W56BKA.js} +2 -2
  60. package/dist/{source-ZLZHE7TL.js.map → source-P5W56BKA.js.map} +1 -1
  61. package/package.json +4 -4
  62. package/dist/record-links-66T2CJRM.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-SK7C7CGH.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-WO5OQNAN.js.map
2
- //# sourceMappingURL=chunk-WO5OQNAN.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-WFJICDCL.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-NAUY7EN3.js.map
2
+ //# sourceMappingURL=chunk-NAUY7EN3.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,CAAN,cAAgC,KAAM,CAC3C,IAAA,CACA,MAAA,CAEA,YAAYC,CAAAA,CAAgBC,CAAAA,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C,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-WO5OQNAN.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,MAAM,IAAIH,CAAAA,CAAaG,CAAAA,CAAS,MAAM,EAGxC,OAAQ,MAAMA,EAAS,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,CAAA,CAAA,CACF,CAAA,CACF,GACF,CAEJ","file":"chunk-NAUY7EN3.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,2 +1,2 @@
1
- import'./index.css';import {c}from'./chunk-XMOSCJOI.js';import {a}from'./chunk-ERDARDGB.js';import {f}from'./chunk-SK7C7CGH.js';import {d}from'./chunk-WPCPL2TQ.js';import {useMemo}from'react';import A from'swr';import {find,propEq}from'ramda';function T(n,o){let{scope:c$1}=c(),{currentProject:r}=f(),a=useMemo(()=>r?.schema??[],[r]),m=r?.scopes?.find(t=>t.isDefault)?.name??"default",e=o?.commonParams.q?JSON.stringify(o):null,{data:s,error:i,isLoading:y}=A(e,()=>fetch(d(n).search,{headers:{"Content-Type":"application/json"},body:JSON.stringify(o),method:"POST",mode:"cors"}).then(t=>t.json()),{keepPreviousData:true});return {results:useMemo(()=>e?E(s?.results??[],n,a,c$1,m)??[]:[],[s,m,n,a,c$1,e]),error:i,isLoading:y}}function E(n,o,c,r,a$1){return n?.filter(l=>l?.hits?.length>0).map(l=>{let m=l,e=m.collection.replace(`${o}_`,"").replace(/_\d+$/,""),s=find(propEq(e,"plural"))(c);if(!s)return [];let i=a(s)?.name??"",y=s?.name??e;return m.hits.map(({document:u})=>{let t=u[i],b=(t&&typeof t!="string"?t[r]??t[a$1]:null)??u[i],N=Object.entries(u).reduce((d,[p,f])=>{if(p!==i&&p!=="id"&&p!=="_updatedAt"){let _=typeof f!="string"?f[r]??f[a$1]:f;d[p]=_;}return d},{});return {_id:u.id,_entityName:y,_entityNamePlural:e,[i]:b,...N}})}).flat()}export{T as a};//# sourceMappingURL=chunk-SKHHYRVA.js.map
2
- //# sourceMappingURL=chunk-SKHHYRVA.js.map
1
+ import'./index.css';import {c}from'./chunk-XMOSCJOI.js';import {a}from'./chunk-ERDARDGB.js';import {f}from'./chunk-WFJICDCL.js';import {d}from'./chunk-WPCPL2TQ.js';import {useMemo}from'react';import A from'swr';import {find,propEq}from'ramda';function T(n,o){let{scope:c$1}=c(),{currentProject:r}=f(),a=useMemo(()=>r?.schema??[],[r]),m=r?.scopes?.find(t=>t.isDefault)?.name??"default",e=o?.commonParams.q?JSON.stringify(o):null,{data:s,error:i,isLoading:y}=A(e,()=>fetch(d(n).search,{headers:{"Content-Type":"application/json"},body:JSON.stringify(o),method:"POST",mode:"cors"}).then(t=>t.json()),{keepPreviousData:true});return {results:useMemo(()=>e?E(s?.results??[],n,a,c$1,m)??[]:[],[s,m,n,a,c$1,e]),error:i,isLoading:y}}function E(n,o,c,r,a$1){return n?.filter(l=>l?.hits?.length>0).map(l=>{let m=l,e=m.collection.replace(`${o}_`,"").replace(/_\d+$/,""),s=find(propEq(e,"plural"))(c);if(!s)return [];let i=a(s)?.name??"",y=s?.name??e;return m.hits.map(({document:u})=>{let t=u[i],b=(t&&typeof t!="string"?t[r]??t[a$1]:null)??u[i],N=Object.entries(u).reduce((d,[p,f])=>{if(p!==i&&p!=="id"&&p!=="_updatedAt"){let _=typeof f!="string"?f[r]??f[a$1]:f;d[p]=_;}return d},{});return {_id:u.id,_entityName:y,_entityNamePlural:e,[i]:b,...N}})}).flat()}export{T as a};//# sourceMappingURL=chunk-P5YGMKPO.js.map
2
+ //# sourceMappingURL=chunk-P5YGMKPO.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/use-search.tsx"],"names":["useSearch","projectId","searchRequest","scope","useAppContext","currentProject","useConfig","schema","useMemo","defaultScope","s","swrKey","data","error","isLoading","useSWR","apiPaths","res","mapResults","results","result","item","entityNamePlural","entitySchema","find","propEq","primaryAttributeName","getDisplayAttribute","entityName","document","primaryAttribute","primaryAttributeValue","attributes","acc","key","value","scopedValue"],"mappings":"mPAWO,SAASA,EACdC,CAAAA,CACAC,CAAAA,CACwE,CACxE,GAAM,CAAE,KAAA,CAAAC,GAAM,CAAA,CAAIC,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AAAA,CAAM1B,GAAY,CAAA,CAAK0B,CAAAA,CAExFF,CAAAA,CAAIC,CAAG,EAAIE,EACb,CAEA,OAAOH,CACT,EACA,EACF,CAAA,CAEA,OAAO,CACL,GAAA,CAAKJ,CAAAA,CAAS,EAAA,CACd,WAAA,CAAaD,CAAAA,CACb,iBAAA,CAAmBN,CAAAA,CACnB,CAACI,CAAoB,EAAGK,CAAAA,CACxB,GAAGC,CACL,CACF,CAAC,CACH,CAAC,CAAA,CACA,MACL","file":"chunk-SKHHYRVA.js","sourcesContent":["'use client';\n\nimport { useMemo } from 'react';\nimport useSWR from 'swr';\nimport { find, propEq } from 'ramda';\nimport { apiPaths } from './api-paths';\nimport { useAppContext } from './app-context';\nimport { useConfig } from './config/config-context';\nimport { getDisplayAttribute } from './get-display-attribute';\nimport type { Entity, RawResultItem, RawSearchResultItems, SearchRequestProps, SearchResultItem } from './types';\n\nexport function useSearch(\n projectId: string,\n searchRequest: SearchRequestProps | null\n): { results: SearchResultItem[] | []; error: Error; isLoading: boolean } {\n const { scope } = useAppContext();\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const scopes = currentProject?.scopes;\n const defaultScope = scopes?.find((s) => s.isDefault)?.name ?? 'default';\n const swrKey = searchRequest?.commonParams.q ? JSON.stringify(searchRequest) : null;\n const { data, error, isLoading } = useSWR(\n swrKey,\n () =>\n fetch(apiPaths(projectId).search, {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(searchRequest),\n method: 'POST',\n mode: 'cors',\n }).then((res) => res.json() as Promise<{ results: RawSearchResultItems }>),\n // Show the previous hits until the next request lands instead of flashing an empty list per keystroke.\n { keepPreviousData: true }\n );\n const results = useMemo(\n // SWR keeps the previous key's data while a new key loads, and also after the key becomes null.\n // Callers treat an empty query as \"no search\", so return no hits once there is nothing to search for.\n () => (swrKey ? (mapResults(data?.results ?? [], projectId, schema, scope, defaultScope) ?? []) : []),\n [data, defaultScope, projectId, schema, scope, swrKey]\n );\n\n return { results, error, isLoading };\n}\n\nfunction mapResults(\n results: RawSearchResultItems | undefined,\n projectId: string,\n schema: Entity[],\n scope: string,\n defaultScope: string\n): SearchResultItem[] | undefined {\n return results\n ?.filter((result) => (result as RawResultItem)?.hits?.length > 0)\n .map((result) => {\n const item = result as RawResultItem;\n const entityNamePlural = item.collection.replace(`${projectId}_`, '').replace(/_\\d+$/, '');\n const entitySchema = find<Entity>(propEq(entityNamePlural, 'plural'))(schema);\n\n if (!entitySchema) {\n return [];\n }\n\n const primaryAttributeName = getDisplayAttribute(entitySchema)?.name ?? '';\n const entityName = entitySchema?.name ?? entityNamePlural;\n\n // iterate over the hits and return an object with the primary attribute value first and then the rest of the attributes.\n return item.hits.map(({ document }) => {\n const primaryAttribute = document[primaryAttributeName];\n const scopedPrimaryAttribute =\n primaryAttribute && typeof primaryAttribute !== 'string'\n ? (primaryAttribute[scope] ?? primaryAttribute[defaultScope])\n : null;\n const primaryAttributeValue = scopedPrimaryAttribute ?? document[primaryAttributeName];\n const attributes = Object.entries(document).reduce(\n (acc: Omit<SearchResultItem, '_id' | '_entityName' | '_entityNamePlural'>, [key, value]) => {\n if (key !== primaryAttributeName && key !== 'id' && key !== '_updatedAt') {\n const scopedValue = typeof value !== 'string' ? (value[scope] ?? value[defaultScope]) : value;\n\n acc[key] = scopedValue;\n }\n\n return acc;\n },\n {}\n );\n\n return {\n _id: document.id,\n _entityName: entityName,\n _entityNamePlural: entityNamePlural,\n [primaryAttributeName]: primaryAttributeValue as string,\n ...attributes,\n };\n });\n })\n .flat();\n}\n"]}
1
+ {"version":3,"sources":["../src/core/use-search.tsx"],"names":["useSearch","projectId","searchRequest","scope","useAppContext","currentProject","useConfig","schema","useMemo","defaultScope","s","swrKey","data","error","isLoading","useSWR","apiPaths","res","mapResults","results","result","item","entityNamePlural","entitySchema","find","propEq","primaryAttributeName","getDisplayAttribute","entityName","document","primaryAttribute","primaryAttributeValue","attributes","acc","key","value","scopedValue"],"mappings":"mP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AAc,CACxE,IAAME,CAAAA,CAAc,OAAOD,CAAAA,EAAU,QAAA,CAAYA,EAAMhC,CAAK,CAAA,EAAKgC,CAAAA,CAAM1B,GAAY,CAAA,CAAK0B,CAAAA,CAExFF,CAAAA,CAAIC,CAAG,EAAIE,EACb,CAEA,OAAOH,CACT,EACA,EACF,CAAA,CAEA,OAAO,CACL,GAAA,CAAKJ,CAAAA,CAAS,EAAA,CACd,WAAA,CAAaD,CAAAA,CACb,iBAAA,CAAmBN,CAAAA,CACnB,CAACI,CAAoB,EAAGK,CAAAA,CACxB,GAAGC,CACL,CACF,CAAC,CACH,CAAC,CAAA,CACA,MACL","file":"chunk-P5YGMKPO.js","sourcesContent":["'use client';\n\nimport { useMemo } from 'react';\nimport useSWR from 'swr';\nimport { find, propEq } from 'ramda';\nimport { apiPaths } from './api-paths';\nimport { useAppContext } from './app-context';\nimport { useConfig } from './config/config-context';\nimport { getDisplayAttribute } from './get-display-attribute';\nimport type { Entity, RawResultItem, RawSearchResultItems, SearchRequestProps, SearchResultItem } from './types';\n\nexport function useSearch(\n projectId: string,\n searchRequest: SearchRequestProps | null\n): { results: SearchResultItem[] | []; error: Error; isLoading: boolean } {\n const { scope } = useAppContext();\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const scopes = currentProject?.scopes;\n const defaultScope = scopes?.find((s) => s.isDefault)?.name ?? 'default';\n const swrKey = searchRequest?.commonParams.q ? JSON.stringify(searchRequest) : null;\n const { data, error, isLoading } = useSWR(\n swrKey,\n () =>\n fetch(apiPaths(projectId).search, {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(searchRequest),\n method: 'POST',\n mode: 'cors',\n }).then((res) => res.json() as Promise<{ results: RawSearchResultItems }>),\n // Show the previous hits until the next request lands instead of flashing an empty list per keystroke.\n { keepPreviousData: true }\n );\n const results = useMemo(\n // SWR keeps the previous key's data while a new key loads, and also after the key becomes null.\n // Callers treat an empty query as \"no search\", so return no hits once there is nothing to search for.\n () => (swrKey ? (mapResults(data?.results ?? [], projectId, schema, scope, defaultScope) ?? []) : []),\n [data, defaultScope, projectId, schema, scope, swrKey]\n );\n\n return { results, error, isLoading };\n}\n\nfunction mapResults(\n results: RawSearchResultItems | undefined,\n projectId: string,\n schema: Entity[],\n scope: string,\n defaultScope: string\n): SearchResultItem[] | undefined {\n return results\n ?.filter((result) => (result as RawResultItem)?.hits?.length > 0)\n .map((result) => {\n const item = result as RawResultItem;\n const entityNamePlural = item.collection.replace(`${projectId}_`, '').replace(/_\\d+$/, '');\n const entitySchema = find<Entity>(propEq(entityNamePlural, 'plural'))(schema);\n\n if (!entitySchema) {\n return [];\n }\n\n const primaryAttributeName = getDisplayAttribute(entitySchema)?.name ?? '';\n const entityName = entitySchema?.name ?? entityNamePlural;\n\n // iterate over the hits and return an object with the primary attribute value first and then the rest of the attributes.\n return item.hits.map(({ document }) => {\n const primaryAttribute = document[primaryAttributeName];\n const scopedPrimaryAttribute =\n primaryAttribute && typeof primaryAttribute !== 'string'\n ? (primaryAttribute[scope] ?? primaryAttribute[defaultScope])\n : null;\n const primaryAttributeValue = scopedPrimaryAttribute ?? document[primaryAttributeName];\n const attributes = Object.entries(document).reduce(\n (acc: Omit<SearchResultItem, '_id' | '_entityName' | '_entityNamePlural'>, [key, value]) => {\n if (key !== primaryAttributeName && key !== 'id' && key !== '_updatedAt') {\n const scopedValue = typeof value !== 'string' ? (value[scope] ?? value[defaultScope]) : value;\n\n acc[key] = scopedValue;\n }\n\n return acc;\n },\n {}\n );\n\n return {\n _id: document.id,\n _entityName: entityName,\n _entityNamePlural: entityNamePlural,\n [primaryAttributeName]: primaryAttributeValue as string,\n ...attributes,\n };\n });\n })\n .flat();\n}\n"]}
@@ -1,4 +1,4 @@
1
- import'./index.css';import {e,d,a as a$2,c,b as b$1}from'./chunk-JTUOTP5S.js';import {a}from'./chunk-YDVO6XWD.js';import {a as a$1}from'./chunk-ERDARDGB.js';import {b,c as c$1}from'./chunk-SK7C7CGH.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 Gt=25,yn=3,Wt=3,mn=["id","string"],hn=["date","datetime","duration","time"],$t=`_id
1
+ import'./index.css';import {e,d,a as a$2,c,b as b$1}from'./chunk-ZI22345U.js';import {a}from'./chunk-YDVO6XWD.js';import {a as a$1}from'./chunk-ERDARDGB.js';import {b,c as c$1}from'./chunk-WFJICDCL.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 Gt=25,yn=3,Wt=3,mn=["id","string"],hn=["date","datetime","duration","time"],$t=`_id
2
2
  originalFilename
3
3
  mimeType
4
4
  path
@@ -374,5 +374,5 @@ ${A} ]
374
374
  }
375
375
  }
376
376
  }
377
- `}}var nt=t=>t.charAt(0).toUpperCase()+t.slice(1);function v(t){let n=t.split(/[^0-9A-Za-z]+/).filter(Boolean).map(nt).join("");return n?/^[A-Za-z_]/.test(n)?n:`Entity${n}`:"Entity"}function U(t,n){return n==="_assets"?b:find(propEq(n,"plural"))(t)}function ee(t,n,e){if(!t||typeof t!="object")return {};let r=U(e,n);if(!r)return {};let i=`update${nt(n)}`,s=t[i];if(!s||typeof s!="object")return {};let o=s[n],c=Array.isArray(o)?o[0]:void 0;return !c||typeof c!="object"?{}:r.attributes.reduce((u,l)=>{if(a(l)!=="local")return u;let d=B(c[l.name])?._id;return typeof d!="string"||d.length===0?u:{...u,[l.name]:d}},{})}var dt=null,_t=new Set,en=[],Rt=new Set,It=new Set,wt=new Set;function oe(t,n){if(t==="_asset"||t==="_assets")return `Get${v(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${v(i)}`}function rn(t){return Rt.add(t),()=>{Rt.delete(t);}}function sn(t){return It.add(t),()=>{It.delete(t);}}function on(t){return wt.add(t),()=>{wt.delete(t);}}function ue(t,n,e){let r=new Set(e.filter(Boolean));if(r.size>0)for(let i of It)i(n,r);return jn(t,n)}function le(t,n){let e=n.filter(r=>!!r._id);if(e.length!==0)for(let r of wt)r(t,e);}function jn(t,n){return _t.add(n),new Promise((e,r)=>{en.push({resolve:e,reject:r}),dt&&clearTimeout(dt),dt=setTimeout(()=>{let i=new Set(_t),s=en.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:c}of s)c(o);});},50);})}function $e({entityNamePlural:t,schema:n,scope:e$1,variables:r,isForm:i,selection:s="full",includeCount:o=true}){let[c$1,u]=useState({count:0,results:[]}),[l,a]=useState(false),[d$1,f]=useState(false),[g,h]=useState(null),y=useRef(false),A=useRef(false),p=useRef(0),m=useRef(null),E=useRef(null),T=`${t}Total`,F=U(n,t),Q=r?.where===void 0&&(F?.spaces?.length??0)===0&&(g?.field!==T||g.schema!==n)?"total":"aggregate",J=useMemo(()=>gql(at(t,e$1,n,{selection:s,countMode:Q,includeCount:o}).query),[t,e$1,n,s,Q,o]),z=useMemo(()=>gql(at(t,e$1,n,{selection:s,includeCount:false}).query),[t,e$1,n,s]),{schemaErrorMessage:$,setSchemaErrorMessage:R}=e(),{loading:q,data:j,fetchMore:it,refetch:st,error:ot,networkStatus:H}=useQuery(J,{variables:r,notifyOnNetworkStatusChange:true}),Lt=useRef(it),gt=useRef(st),Ft=useRef(z),Ct=useRef(H),Tt=useRef(r);Lt.current=it,gt.current=st,Ft.current=z,Tt.current=r;let yt=o&&d(ot,T),Mt=Q==="total"&&yt,G=yt?void 0:ot,Y=yt&&!j?.[t],Qt=a$2(G),P=c(G),{isProjectDisabled:an,isProjectReadOnly:dn}=(()=>{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(()=>{Mt&&h({field:T,schema:n});},[n,Mt,T]);let fn=useCallback(I=>{if(y.current||A.current)return;y.current=true,a(true);let{limit:x}=I.variables,k=p.current;Lt.current({...I,query:Ft.current,variables:{...Tt.current,...I.variables,offset:k,limit:x}}).then(({data:X})=>{let M=rt({data:X,entityNamePlural:t,isForm:i,schema:n,scope:e$1}),D=M.results.length;p.current=k+(D===0?0:Math.min(D,x)),u(C=>{let W=uniqBy(prop("_id"),[...C.results,...M.results]);return W.length===C.results.length?{count:C.results.length,results:C.results}:{count:M.count||C.count,results:W}});}).catch(X=>{console.error("Error fetching more data:",X);}).finally(()=>{y.current=false,a(false);});},[t,i,n,e$1]),pn=useCallback(I=>{if(A.current)return Promise.resolve();let x=I?.preserve===true;return A.current=true,y.current=false,a(false),x||(m.current=null,E.current=null,p.current=0,f(true),u({count:0,results:[]})),gt.current().then(({data:k})=>{let X=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),M=rt({data:k,entityNamePlural:t,isForm:i,schema:n,scope:e$1});m.current=X,E.current=null,p.current=pt(r)+M.results.length,u(M);}).catch(k=>{console.error("Error reloading data:",k);}).finally(()=>{A.current=false,f(false);})},[t,i,n,e$1,s,o,r]);return useEffect(()=>{if(P){R(P);return}j&&$&&!G&&R(null);},[j,G,$,P,R]),useEffect(()=>{if(G||P||Y)return;let I=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r});if(m.current===I)return;if(q&&E.current!==I){E.current=I,p.current=0,u({count:0,results:[]});return}if(q)return;let x=rt({data:j,entityNamePlural:t,isForm:i,schema:n,scope:e$1});m.current=I,E.current=null,p.current=pt(r)+x.results.length,u(x);},[j,G,t,i,q,Y,n,P,e$1,s,o,r]),useEffect(()=>{let I=Ct.current;if(Ct.current=H,G||P||A.current||Y||I!==NetworkStatus.refetch||H!==NetworkStatus.ready||!j)return;let x=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),k=rt({data:j,entityNamePlural:t,isForm:i,schema:n,scope:e$1});m.current=x,E.current=null,p.current=pt(r)+k.results.length,u(k);},[j,G,t,i,Y,H,n,P,e$1,s,o,r]),useEffect(()=>{if(i)return;let I=`Get${v(t)}`,x=rn(M=>{if(!(!M.has(I)||y.current||A.current))return gt.current().then(({data:D})=>{let C=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),W=rt({data:D,entityNamePlural:t,isForm:i,schema:n,scope:e$1});m.current=C,E.current=null,p.current=pt(r)+W.results.length,u(W);}).catch(D=>{console.error("Error soft-refreshing entity list:",D);})}),k=sn((M,D)=>{M===I&&u(C=>{let W=C.results.filter(xt=>{let kt=typeof xt._id=="string"?xt._id:void 0;return !kt||!D.has(kt)}),qt=C.results.length-W.length;return qt===0?C:{count:Math.max(0,C.count-qt),results:W}});}),X=on((M,D)=>{M===I&&u(C=>Bn(C,D,r?.sort));});return ()=>{x(),k(),X();}},[t,i,n,e$1,s,o,r]),{isLoading:q&&H!==NetworkStatus.refetch||d$1||Y,isLoadingMore:l,fetchMore:fn,reload:pn,count:c$1.count,data:c$1.results,isProjectDisabled:an,isProjectReadOnly:dn,schemaErrorMessage:$}}function pt(t){let n=t?.offset;return typeof n=="number"&&Number.isFinite(n)?n:0}function rt(t){let n=t.entityNamePlural;return t.data?.[n]?t.isForm?Ht(t.entityNamePlural,t.scope,t.data,t.schema):Zt(t.entityNamePlural,t.scope,t.data,t.schema):{count:0,results:[]}}function Bn(t,n,e){let r=new Map(n.map(o=>[o._id,o])),i=false,s=t.results.map(o=>{let c=typeof o._id=="string"?o._id:void 0;if(!c)return o;let u=r.get(c);return u?(i=true,{...o,...u.attributes}):o});return i?{count:t.count,results:zn(s,e)}:t}function zn(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((c,u)=>{let l=c[i],a=u[i],d=typeof l=="string"?l:"",f=typeof a=="string"?a:"";return d.localeCompare(f)*o})}export{Gt as a,Kt as b,An as c,Xn as d,at as e,Zt as f,Zn as g,Hn as h,Yn as i,Nn as j,te as k,ne as l,U as m,ee as n,oe as o,ue as p,le as q,jn as r,$e as s};//# sourceMappingURL=chunk-SRFTSMZD.js.map
378
- //# sourceMappingURL=chunk-SRFTSMZD.js.map
377
+ `}}var nt=t=>t.charAt(0).toUpperCase()+t.slice(1);function v(t){let n=t.split(/[^0-9A-Za-z]+/).filter(Boolean).map(nt).join("");return n?/^[A-Za-z_]/.test(n)?n:`Entity${n}`:"Entity"}function U(t,n){return n==="_assets"?b:find(propEq(n,"plural"))(t)}function ee(t,n,e){if(!t||typeof t!="object")return {};let r=U(e,n);if(!r)return {};let i=`update${nt(n)}`,s=t[i];if(!s||typeof s!="object")return {};let o=s[n],c=Array.isArray(o)?o[0]:void 0;return !c||typeof c!="object"?{}:r.attributes.reduce((u,l)=>{if(a(l)!=="local")return u;let d=B(c[l.name])?._id;return typeof d!="string"||d.length===0?u:{...u,[l.name]:d}},{})}var dt=null,_t=new Set,en=[],Rt=new Set,It=new Set,wt=new Set;function oe(t,n){if(t==="_asset"||t==="_assets")return `Get${v(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${v(i)}`}function rn(t){return Rt.add(t),()=>{Rt.delete(t);}}function sn(t){return It.add(t),()=>{It.delete(t);}}function on(t){return wt.add(t),()=>{wt.delete(t);}}function ue(t,n,e){let r=new Set(e.filter(Boolean));if(r.size>0)for(let i of It)i(n,r);return jn(t,n)}function le(t,n){let e=n.filter(r=>!!r._id);if(e.length!==0)for(let r of wt)r(t,e);}function jn(t,n){return _t.add(n),new Promise((e,r)=>{en.push({resolve:e,reject:r}),dt&&clearTimeout(dt),dt=setTimeout(()=>{let i=new Set(_t),s=en.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:c}of s)c(o);});},50);})}function $e({entityNamePlural:t,schema:n,scope:e$1,variables:r,isForm:i,selection:s="full",includeCount:o=true}){let[c$1,u]=useState({count:0,results:[]}),[l,a]=useState(false),[d$1,f]=useState(false),[g,h]=useState(null),y=useRef(false),A=useRef(false),p=useRef(0),m=useRef(null),E=useRef(null),T=`${t}Total`,F=U(n,t),Q=r?.where===void 0&&(F?.spaces?.length??0)===0&&(g?.field!==T||g.schema!==n)?"total":"aggregate",J=useMemo(()=>gql(at(t,e$1,n,{selection:s,countMode:Q,includeCount:o}).query),[t,e$1,n,s,Q,o]),z=useMemo(()=>gql(at(t,e$1,n,{selection:s,includeCount:false}).query),[t,e$1,n,s]),{schemaErrorMessage:$,setSchemaErrorMessage:R}=e(),{loading:q,data:j,fetchMore:it,refetch:st,error:ot,networkStatus:H}=useQuery(J,{variables:r,notifyOnNetworkStatusChange:true}),Lt=useRef(it),gt=useRef(st),Ft=useRef(z),Ct=useRef(H),Tt=useRef(r);Lt.current=it,gt.current=st,Ft.current=z,Tt.current=r;let yt=o&&d(ot,T),Mt=Q==="total"&&yt,G=yt?void 0:ot,Y=yt&&!j?.[t],Qt=a$2(G),P=c(G),{isProjectDisabled:an,isProjectReadOnly:dn}=(()=>{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(()=>{Mt&&h({field:T,schema:n});},[n,Mt,T]);let fn=useCallback(I=>{if(y.current||A.current)return;y.current=true,a(true);let{limit:x}=I.variables,k=p.current;Lt.current({...I,query:Ft.current,variables:{...Tt.current,...I.variables,offset:k,limit:x}}).then(({data:X})=>{let M=rt({data:X,entityNamePlural:t,isForm:i,schema:n,scope:e$1}),D=M.results.length;p.current=k+(D===0?0:Math.min(D,x)),u(C=>{let W=uniqBy(prop("_id"),[...C.results,...M.results]);return W.length===C.results.length?{count:C.results.length,results:C.results}:{count:M.count||C.count,results:W}});}).catch(X=>{console.error("Error fetching more data:",X);}).finally(()=>{y.current=false,a(false);});},[t,i,n,e$1]),pn=useCallback(I=>{if(A.current)return Promise.resolve();let x=I?.preserve===true;return A.current=true,y.current=false,a(false),x||(m.current=null,E.current=null,p.current=0,f(true),u({count:0,results:[]})),gt.current().then(({data:k})=>{let X=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),M=rt({data:k,entityNamePlural:t,isForm:i,schema:n,scope:e$1});m.current=X,E.current=null,p.current=pt(r)+M.results.length,u(M);}).catch(k=>{console.error("Error reloading data:",k);}).finally(()=>{A.current=false,f(false);})},[t,i,n,e$1,s,o,r]);return useEffect(()=>{if(P){R(P);return}j&&$&&!G&&R(null);},[j,G,$,P,R]),useEffect(()=>{if(G||P||Y)return;let I=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r});if(m.current===I)return;if(q&&E.current!==I){E.current=I,p.current=0,u({count:0,results:[]});return}if(q)return;let x=rt({data:j,entityNamePlural:t,isForm:i,schema:n,scope:e$1});m.current=I,E.current=null,p.current=pt(r)+x.results.length,u(x);},[j,G,t,i,q,Y,n,P,e$1,s,o,r]),useEffect(()=>{let I=Ct.current;if(Ct.current=H,G||P||A.current||Y||I!==NetworkStatus.refetch||H!==NetworkStatus.ready||!j)return;let x=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),k=rt({data:j,entityNamePlural:t,isForm:i,schema:n,scope:e$1});m.current=x,E.current=null,p.current=pt(r)+k.results.length,u(k);},[j,G,t,i,Y,H,n,P,e$1,s,o,r]),useEffect(()=>{if(i)return;let I=`Get${v(t)}`,x=rn(M=>{if(!(!M.has(I)||y.current||A.current))return gt.current().then(({data:D})=>{let C=JSON.stringify({entityNamePlural:t,scope:e$1,selection:s,includeCount:o,variables:r}),W=rt({data:D,entityNamePlural:t,isForm:i,schema:n,scope:e$1});m.current=C,E.current=null,p.current=pt(r)+W.results.length,u(W);}).catch(D=>{console.error("Error soft-refreshing entity list:",D);})}),k=sn((M,D)=>{M===I&&u(C=>{let W=C.results.filter(xt=>{let kt=typeof xt._id=="string"?xt._id:void 0;return !kt||!D.has(kt)}),qt=C.results.length-W.length;return qt===0?C:{count:Math.max(0,C.count-qt),results:W}});}),X=on((M,D)=>{M===I&&u(C=>Bn(C,D,r?.sort));});return ()=>{x(),k(),X();}},[t,i,n,e$1,s,o,r]),{isLoading:q&&H!==NetworkStatus.refetch||d$1||Y,isLoadingMore:l,fetchMore:fn,reload:pn,count:c$1.count,data:c$1.results,isProjectDisabled:an,isProjectReadOnly:dn,schemaErrorMessage:$}}function pt(t){let n=t?.offset;return typeof n=="number"&&Number.isFinite(n)?n:0}function rt(t){let n=t.entityNamePlural;return t.data?.[n]?t.isForm?Ht(t.entityNamePlural,t.scope,t.data,t.schema):Zt(t.entityNamePlural,t.scope,t.data,t.schema):{count:0,results:[]}}function Bn(t,n,e){let r=new Map(n.map(o=>[o._id,o])),i=false,s=t.results.map(o=>{let c=typeof o._id=="string"?o._id:void 0;if(!c)return o;let u=r.get(c);return u?(i=true,{...o,...u.attributes}):o});return i?{count:t.count,results:zn(s,e)}:t}function zn(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((c,u)=>{let l=c[i],a=u[i],d=typeof l=="string"?l:"",f=typeof a=="string"?a:"";return d.localeCompare(f)*o})}export{Gt as a,Kt as b,An as c,Xn as d,at as e,Zt as f,Zn as g,Hn as h,Yn as i,Nn as j,te as k,ne as l,U as m,ee as n,oe as o,ue as p,le as q,jn as r,$e as s};//# sourceMappingURL=chunk-RARRMN5A.js.map
378
+ //# sourceMappingURL=chunk-RARRMN5A.js.map