@flexkit/studio 0.2.27 → 0.2.29

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 (76) hide show
  1. package/dist/{activity-nav-button-DIYOSLHR.js → activity-nav-button-E4I4YC3X.js} +2 -2
  2. package/dist/{activity-nav-button-DIYOSLHR.js.map → activity-nav-button-E4I4YC3X.js.map} +1 -1
  3. package/dist/chat-page-UT5M3PM3.js +4 -0
  4. package/dist/{chat-page-4YW4GADV.js.map → chat-page-UT5M3PM3.js.map} +1 -1
  5. package/dist/{chunk-2IFBQNWA.js → chunk-5LGIALCK.js} +2 -2
  6. package/dist/{chunk-2IFBQNWA.js.map → chunk-5LGIALCK.js.map} +1 -1
  7. package/dist/{chunk-I4UFLN53.js → chunk-6A6NT3H3.js} +3 -3
  8. package/dist/{chunk-I4UFLN53.js.map → chunk-6A6NT3H3.js.map} +1 -1
  9. package/dist/{chunk-FVNVNXEV.js → chunk-7AN2E6TU.js} +2 -2
  10. package/dist/{chunk-FVNVNXEV.js.map → chunk-7AN2E6TU.js.map} +1 -1
  11. package/dist/{chunk-RP2CTEIL.js → chunk-AZG72R2F.js} +3 -3
  12. package/dist/{chunk-RP2CTEIL.js.map → chunk-AZG72R2F.js.map} +1 -1
  13. package/dist/{chunk-4ZRVKNBI.js → chunk-BIFQCOZD.js} +2 -2
  14. package/dist/{chunk-4ZRVKNBI.js.map → chunk-BIFQCOZD.js.map} +1 -1
  15. package/dist/{chunk-JPZFJHZP.js → chunk-BRGTUEFL.js} +2 -2
  16. package/dist/{chunk-JPZFJHZP.js.map → chunk-BRGTUEFL.js.map} +1 -1
  17. package/dist/{chunk-DZTBKBD6.js → chunk-BSUCDQYM.js} +3 -3
  18. package/dist/{chunk-DZTBKBD6.js.map → chunk-BSUCDQYM.js.map} +1 -1
  19. package/dist/{chunk-LG2KGSQ4.js → chunk-D3TJCUTA.js} +2 -2
  20. package/dist/{chunk-LG2KGSQ4.js.map → chunk-D3TJCUTA.js.map} +1 -1
  21. package/dist/{chunk-KOAZBC6O.js → chunk-ERCVR23U.js} +2 -2
  22. package/dist/{chunk-KOAZBC6O.js.map → chunk-ERCVR23U.js.map} +1 -1
  23. package/dist/{chunk-54WDEDM4.js → chunk-FRTHKTAS.js} +2 -2
  24. package/dist/{chunk-54WDEDM4.js.map → chunk-FRTHKTAS.js.map} +1 -1
  25. package/dist/{chunk-TWALS64F.js → chunk-H534S4KD.js} +3 -3
  26. package/dist/{chunk-TWALS64F.js.map → chunk-H534S4KD.js.map} +1 -1
  27. package/dist/{chunk-HAU76X63.js → chunk-RZZOOPEF.js} +3 -3
  28. package/dist/{chunk-HAU76X63.js.map → chunk-RZZOOPEF.js.map} +1 -1
  29. package/dist/chunk-T44KNWQD.js +10 -0
  30. package/dist/chunk-T44KNWQD.js.map +1 -0
  31. package/dist/{chunk-IA5Z6LYD.js → chunk-U6VZY3V2.js} +2 -2
  32. package/dist/chunk-U6VZY3V2.js.map +1 -0
  33. package/dist/{chunk-OM2SSOTB.js → chunk-UET5IDEW.js} +3 -3
  34. package/dist/{chunk-OM2SSOTB.js.map → chunk-UET5IDEW.js.map} +1 -1
  35. package/dist/{chunk-ZA2LLGNZ.js → chunk-ZUGTNE5M.js} +2 -2
  36. package/dist/{chunk-ZA2LLGNZ.js.map → chunk-ZUGTNE5M.js.map} +1 -1
  37. package/dist/{entry-XXLNSL6Q.js → entry-QGRB2B7V.js} +2 -2
  38. package/dist/{entry-XXLNSL6Q.js.map → entry-QGRB2B7V.js.map} +1 -1
  39. package/dist/index.css +15 -0
  40. package/dist/index.js +2 -2
  41. package/dist/{list-52ORZRD5.js → list-L6YZSBWF.js} +3 -3
  42. package/dist/{list-52ORZRD5.js.map → list-L6YZSBWF.js.map} +1 -1
  43. package/dist/{list-EFL32GDI.js → list-OPL5OO32.js} +2 -2
  44. package/dist/{list-EFL32GDI.js.map → list-OPL5OO32.js.map} +1 -1
  45. package/dist/{pages-VIE6KUBE.js → pages-K4XZAMXY.js} +3 -3
  46. package/dist/{pages-VIE6KUBE.js.map → pages-K4XZAMXY.js.map} +1 -1
  47. package/dist/{plugin-pages-HTXOLHG2.js → plugin-pages-RCWAF6VC.js} +2 -2
  48. package/dist/{plugin-pages-HTXOLHG2.js.map → plugin-pages-RCWAF6VC.js.map} +1 -1
  49. package/dist/record-links-R7OV4VVH.js +2 -0
  50. package/dist/{record-links-NPBFSAHR.js.map → record-links-R7OV4VVH.js.map} +1 -1
  51. package/dist/{root-2AXD4MNR.js → root-36COMEVE.js} +2 -2
  52. package/dist/{root-2AXD4MNR.js.map → root-36COMEVE.js.map} +1 -1
  53. package/dist/{root-27HUK3RU.js → root-3M4DIRWC.js} +2 -2
  54. package/dist/{root-27HUK3RU.js.map → root-3M4DIRWC.js.map} +1 -1
  55. package/dist/{root-K7JKAYLS.js → root-HETKL6EN.js} +2 -2
  56. package/dist/{root-K7JKAYLS.js.map → root-HETKL6EN.js.map} +1 -1
  57. package/dist/{root-2QPYALTV.js → root-L6Y4PSSA.js} +3 -3
  58. package/dist/{root-2QPYALTV.js.map → root-L6Y4PSSA.js.map} +1 -1
  59. package/dist/{root-M62U2FKR.js → root-R4Y6L62R.js} +3 -3
  60. package/dist/{root-M62U2FKR.js.map → root-R4Y6L62R.js.map} +1 -1
  61. package/dist/{root-7ZAUENIS.js → root-XMZYVO37.js} +3 -3
  62. package/dist/{root-7ZAUENIS.js.map → root-XMZYVO37.js.map} +1 -1
  63. package/dist/{search-FJUNXO53.js → search-UXL3U2EH.js} +2 -2
  64. package/dist/{search-FJUNXO53.js.map → search-UXL3U2EH.js.map} +1 -1
  65. package/dist/skills-pages-KEXNO6DN.js +2 -0
  66. package/dist/skills-pages-KEXNO6DN.js.map +1 -0
  67. package/dist/{source-INDEOHP7.js → source-CWVJGMEZ.js} +2 -2
  68. package/dist/{source-INDEOHP7.js.map → source-CWVJGMEZ.js.map} +1 -1
  69. package/package.json +3 -3
  70. package/dist/chat-page-4YW4GADV.js +0 -4
  71. package/dist/chunk-32M62H3K.js +0 -8
  72. package/dist/chunk-32M62H3K.js.map +0 -1
  73. package/dist/chunk-IA5Z6LYD.js.map +0 -1
  74. package/dist/record-links-NPBFSAHR.js +0 -2
  75. package/dist/skills-pages-Q6NGTRVW.js +0 -2
  76. package/dist/skills-pages-Q6NGTRVW.js.map +0 -1
@@ -1,2 +1,2 @@
1
- import'./index.css';import {b as b$1}from'./chunk-IA5Z6LYD.js';import {s}from'./chunk-DGIY4SKN.js';import {c,h,i,k,l,j}from'./chunk-32ZU4MLE.js';import {b}from'./chunk-6NRQMG26.js';import {useSyncExternalStore,useId,useState}from'react';import {LoaderCircle,ExternalLinkIcon}from'lucide-react';import {jsx,jsxs}from'react/jsx-runtime';var K="/plugins/oauth/start",R=class extends Error{code="account_mismatch";constructor(){super('You signed in with a different account. Use "Connect another account" to add it.'),this.name="PluginAccountMismatchError";}};function U(t){let e;try{e=new URL(t);}catch{return null}return e.protocol!=="https:"||e.username!==""||e.password!==""?null:e}function Q(t,e){let n=b$1(),r=U(t),o=U(e);return !r||!o||r.origin!==n||r.pathname!==K||o.origin!==n||o.pathname!=="/"?null:{href:r.href,origin:n}}async function O(t,e,n,r){let o=window.open("about:blank",`flexkit-plugin-${crypto.randomUUID()}`,"popup,width=560,height=720");if(!o)throw new Error("Allow popups for Studio, then connect again.");let a;try{a=await t.connectPlugins({pluginId:e,scope:n,studioOrigin:window.location.origin,...r?.connectionId?{connectionId:r.connectionId}:{}});}catch(u){throw o.close(),u}let d=Q(a.authorizeUrl,a.completionOrigin);if(!d)throw o.close(),new Error("Connection could not be started.");let g=d.origin;await new Promise((u,m)=>{let c=false,f=false,k=false,h=i=>{if(!f){if(f=true,window.clearInterval(l),window.clearTimeout(C),window.removeEventListener("message",P),o.close(),i){m(i);return}u();}},v=async()=>{if(c||f)return;c=true;let i;try{i=await t.pluginOAuthStatus(a.transactionId);}catch{c=false;return}if(c=false,i.status==="complete"){h();return}if(!k&&o.closed&&i.status==="pending"){h(new Error("Connection window was closed."));return}(i.status==="failed"||new Date(i.expires_at).getTime()<Date.now())&&h(new Error("Connection was not completed. Please try again."));},P=i=>{if(i.origin!==g||i.source!==o||!i.data||typeof i.data!="object")return;let y=i.data;if(y.type==="flexkit:plugin-oauth-ready"&&y.transactionId===a.transactionId){k=true,o.postMessage({type:"flexkit:plugin-oauth-start",transactionId:a.transactionId,ticket:a.launchTicket},g);return}if(y.type==="flexkit:plugin-oauth"&&y.transactionId===a.transactionId){if(y.status==="failed"&&y.error==="account_mismatch"){h(new R);return}v();}},l=window.setInterval(()=>{v();},2e3),C=window.setTimeout(()=>h(new Error("Connection timed out. Please try again.")),6e5);window.addEventListener("message",P),o.location.href=d.href;});}function W(t){let{connect:e}=t;return e?.type==="api-token"?e.pattern?[{label:e.tokenLabel,pattern:e.pattern}]:[]:e?.type==="credentials"?[...e.fields,...e.methods.flatMap(n=>n.fields)].filter(n=>n.kind==="secret"&&n.detect).map(n=>({label:n.label,pattern:n.detect})):[]}function M(t,e){let n=t.methods.find(r=>r.key===e);return [...t.fields,...n?.fields??[]]}function z(t,e){return t.every(n=>!n.required||!!e[n.key]?.trim())}function X(t,e){for(let n of t){let r=e[n.key]?.trim()??"";if(!r){if(n.required)return {field:n.key,message:`Enter the ${n.label}.`};continue}if(r.length>4096)return {field:n.key,message:`The ${n.label} is too long; paste only the value.`};if(!S(r,n.pattern))return {field:n.key,message:`That is not a valid ${n.label}.`}}return null}function S(t,e){if(!e)return true;try{return new RegExp(e,"u").test(t)}catch{return true}}function Z(t){if(!t)return null;try{return new RegExp(t,"u")}catch{return null}}function ae(t,e){let n=t.split(/[\s"'`()<>[\]{},;:=!?&]+/).map(a=>a.replace(/\.+$/,"")).filter(Boolean),r=null,o=new Set;for(let a of e)for(let d of W(a)){let g=Z(d.pattern);for(let u of g?n:[])g.test(u)&&(r??={plugin:a,label:d.label},o.add(u));}return r?{...r,tokens:[...o]}:null}var _=null,q=0,L=null,N=new Set;function B(t){_=t,N.forEach(e=>e());}function ne(t){return N.add(t),()=>N.delete(t)}function me(t,e,n,r){let{connect:o}=e;if(o?.type!=="api-token"&&o?.type!=="credentials")return O(t,e.id,n,r).then(()=>true);L?.();let a=++q,d=r?.connectionId?{connectionId:r.connectionId}:{};return new Promise(g=>{let u=c=>{_?.id===a&&B(null),q===a&&(L=null),g(c);},m=o.type==="api-token"?{kind:"token",id:a,plugin:{...e,connect:o},submit:async c=>{await t.connectPluginToken({pluginId:e.id,scope:n,token:c,...d});},settle:u}:{kind:"credentials",id:a,plugin:{...e,connect:o},submit:async(c,f)=>{await t.connectPluginCredentials({pluginId:e.id,scope:n,method:c,values:f,...d});},settle:u};L=()=>u(false),setTimeout(()=>{q===a&&B(m);});})}function oe(t){if(!t)return null;try{let e=new URL(t);return e.protocol==="https:"?e.href:null}catch{return null}}function ke(){let t=useSyncExternalStore(ne,()=>_,()=>null);return t?t.kind==="token"?jsx(le,{request:t},t.id):jsx(re,{request:t},t.id):null}function $({id:t,message:e}){return e?jsx("p",{className:"fk:text-sm fk:text-destructive",id:t,children:e}):null}function V({href:t,label:e}){let n=oe(t);return n?jsxs("a",{className:"fk:inline-flex fk:items-center fk:gap-1 fk:text-sm fk:text-muted-foreground fk:underline-offset-4 fk:hover:underline",href:n,rel:"noreferrer",target:"_blank",children:[e,jsx(ExternalLinkIcon,{className:"fk:size-3.5"})]}):null}function re({request:t}){let{connect:e,name:n}=t.plugin,r=useId(),[o,a]=useState(e.methods[0]?.key??null),[d,g]=useState({}),[u,m]=useState(null),[c$1,f]=useState(false),k$1=M(e,o),h$1=e.methods.find(l=>l.key===o)??null,v=z(k$1,d);async function P(l){if(l.preventDefault(),c$1)return;let C=X(k$1,d);if(C){m(C);return}f(true),m(null);try{await t.submit(o??void 0,Object.fromEntries(k$1.map(i=>[i.key,d[i.key]?.trim()??""]).filter(([,i])=>i))),g({}),t.settle(!0);}catch(i){m({field:null,message:i instanceof Error?i.message:`${n} could not be connected.`});}finally{f(false);}}return jsx(c,{open:true,onOpenChange:l=>{!l&&!c$1&&t.settle(false);},children:jsx(h,{children:jsxs("form",{className:"fk:flex fk:flex-col fk:gap-4",onSubmit:l=>{P(l);},children:[jsxs(i,{children:[jsxs(k,{children:["Connect ",n]}),jsxs(l,{children:[e.description," Flexkit checks the credentials with ",n,", stores them encrypted and sends them only to Flexkit's own ",n," server; the agent can use the tools but never sees them."]})]}),e.methods.length>1?jsx("div",{className:"fk:space-y-1.5",role:"group","aria-label":"How to connect",children:e.methods.map(l=>jsxs("button",{"aria-pressed":o===l.key,className:`fk:flex fk:w-full fk:flex-col fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:corner-squircle ${o===l.key?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,disabled:c$1,onClick:()=>{a(l.key),m(null);},type:"button",children:[jsx("span",{className:"fk:text-sm fk:font-medium",children:l.label}),l.description?jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:l.description}):null]},l.key))}):h$1?.description?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:h$1.description}):null,k$1.map((l,C)=>{let i=`${r}-${l.key}`,y=u?.field===l.key?u.message:null;return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-2",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:i,children:l.label}),jsx(s,{"aria-describedby":y?`${i}-error`:l.help?`${i}-help`:void 0,"aria-invalid":y?true:void 0,autoComplete:"off",autoFocus:C===0,disabled:c$1,id:i,placeholder:l.placeholder??void 0,spellCheck:false,type:l.kind==="secret"?"password":"text",value:d[l.key]??"",onChange:j=>{g(Y=>({...Y,[l.key]:j.target.value})),m(null);}}),l.help&&!y?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",id:`${i}-help`,children:l.help}):null,jsx($,{id:`${i}-error`,message:y})]},l.key)}),jsx($,{id:`${r}-error`,message:u?.field===null?u.message:null}),jsx(V,{href:e.helpUrl,label:`How to set up ${n}`}),jsxs(j,{children:[jsx(b,{disabled:c$1,size:"sm",type:"button",variant:"outline",onClick:()=>t.settle(false),children:"Cancel"}),jsxs(b,{disabled:c$1||!v,size:"sm",type:"submit",children:[c$1?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):null,"Connect"]})]})]})})})}function le({request:t}){let{connect:e,name:n}=t.plugin,r=useId(),[o,a]=useState(""),[d,g]=useState(null),[u,m]=useState(false);async function c$1(f){f.preventDefault();let k=o.trim();if(!(u||!k)){if(!S(k,e.pattern)){g(`That does not look like a ${e.tokenLabel}.`);return}m(true),g(null);try{await t.submit(k),a(""),t.settle(!0);}catch(h){g(h instanceof Error?h.message:`${n} could not be connected.`);}finally{m(false);}}}return jsx(c,{open:true,onOpenChange:f=>{!f&&!u&&t.settle(false);},children:jsx(h,{children:jsxs("form",{className:"fk:flex fk:flex-col fk:gap-4",onSubmit:f=>{c$1(f);},children:[jsxs(i,{children:[jsxs(k,{children:["Connect ",n]}),jsxs(l,{children:["Paste a ",e.tokenLabel,". Flexkit stores it encrypted and sends it only to ",n,"; the agent can use"," ",n,"'s tools but never sees the token. Give it read access only, unless the agent should change things in ",n,"."]})]}),jsxs("div",{className:"fk:flex fk:flex-col fk:gap-2",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:r,children:e.tokenLabel}),jsx(s,{"aria-describedby":d?`${r}-error`:void 0,"aria-invalid":d?true:void 0,autoComplete:"off",autoFocus:true,disabled:u,id:r,placeholder:e.placeholder??void 0,spellCheck:false,type:"password",value:o,onChange:f=>{a(f.target.value),g(null);}}),jsx($,{id:`${r}-error`,message:d}),jsx(V,{href:e.helpUrl,label:`How to create a ${e.tokenLabel}`})]}),jsxs(j,{children:[jsx(b,{disabled:u,size:"sm",type:"button",variant:"outline",onClick:()=>t.settle(false),children:"Cancel"}),jsxs(b,{disabled:u||!o.trim(),size:"sm",type:"submit",children:[u?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):null,"Connect"]})]})]})})})}export{R as a,O as b,ae as c,me as d,ke as e};//# sourceMappingURL=chunk-2IFBQNWA.js.map
2
- //# sourceMappingURL=chunk-2IFBQNWA.js.map
1
+ import'./index.css';import {b as b$1}from'./chunk-U6VZY3V2.js';import {s}from'./chunk-DGIY4SKN.js';import {c,h,i,k,l,j}from'./chunk-32ZU4MLE.js';import {b}from'./chunk-6NRQMG26.js';import {useSyncExternalStore,useId,useState}from'react';import {LoaderCircle,ExternalLinkIcon}from'lucide-react';import {jsx,jsxs}from'react/jsx-runtime';var K="/plugins/oauth/start",R=class extends Error{code="account_mismatch";constructor(){super('You signed in with a different account. Use "Connect another account" to add it.'),this.name="PluginAccountMismatchError";}};function U(t){let e;try{e=new URL(t);}catch{return null}return e.protocol!=="https:"||e.username!==""||e.password!==""?null:e}function Q(t,e){let n=b$1(),r=U(t),o=U(e);return !r||!o||r.origin!==n||r.pathname!==K||o.origin!==n||o.pathname!=="/"?null:{href:r.href,origin:n}}async function O(t,e,n,r){let o=window.open("about:blank",`flexkit-plugin-${crypto.randomUUID()}`,"popup,width=560,height=720");if(!o)throw new Error("Allow popups for Studio, then connect again.");let a;try{a=await t.connectPlugins({pluginId:e,scope:n,studioOrigin:window.location.origin,...r?.connectionId?{connectionId:r.connectionId}:{}});}catch(u){throw o.close(),u}let d=Q(a.authorizeUrl,a.completionOrigin);if(!d)throw o.close(),new Error("Connection could not be started.");let g=d.origin;await new Promise((u,m)=>{let c=false,f=false,k=false,h=i=>{if(!f){if(f=true,window.clearInterval(l),window.clearTimeout(C),window.removeEventListener("message",P),o.close(),i){m(i);return}u();}},v=async()=>{if(c||f)return;c=true;let i;try{i=await t.pluginOAuthStatus(a.transactionId);}catch{c=false;return}if(c=false,i.status==="complete"){h();return}if(!k&&o.closed&&i.status==="pending"){h(new Error("Connection window was closed."));return}(i.status==="failed"||new Date(i.expires_at).getTime()<Date.now())&&h(new Error("Connection was not completed. Please try again."));},P=i=>{if(i.origin!==g||i.source!==o||!i.data||typeof i.data!="object")return;let y=i.data;if(y.type==="flexkit:plugin-oauth-ready"&&y.transactionId===a.transactionId){k=true,o.postMessage({type:"flexkit:plugin-oauth-start",transactionId:a.transactionId,ticket:a.launchTicket},g);return}if(y.type==="flexkit:plugin-oauth"&&y.transactionId===a.transactionId){if(y.status==="failed"&&y.error==="account_mismatch"){h(new R);return}v();}},l=window.setInterval(()=>{v();},2e3),C=window.setTimeout(()=>h(new Error("Connection timed out. Please try again.")),6e5);window.addEventListener("message",P),o.location.href=d.href;});}function W(t){let{connect:e}=t;return e?.type==="api-token"?e.pattern?[{label:e.tokenLabel,pattern:e.pattern}]:[]:e?.type==="credentials"?[...e.fields,...e.methods.flatMap(n=>n.fields)].filter(n=>n.kind==="secret"&&n.detect).map(n=>({label:n.label,pattern:n.detect})):[]}function M(t,e){let n=t.methods.find(r=>r.key===e);return [...t.fields,...n?.fields??[]]}function z(t,e){return t.every(n=>!n.required||!!e[n.key]?.trim())}function X(t,e){for(let n of t){let r=e[n.key]?.trim()??"";if(!r){if(n.required)return {field:n.key,message:`Enter the ${n.label}.`};continue}if(r.length>4096)return {field:n.key,message:`The ${n.label} is too long; paste only the value.`};if(!S(r,n.pattern))return {field:n.key,message:`That is not a valid ${n.label}.`}}return null}function S(t,e){if(!e)return true;try{return new RegExp(e,"u").test(t)}catch{return true}}function Z(t){if(!t)return null;try{return new RegExp(t,"u")}catch{return null}}function ae(t,e){let n=t.split(/[\s"'`()<>[\]{},;:=!?&]+/).map(a=>a.replace(/\.+$/,"")).filter(Boolean),r=null,o=new Set;for(let a of e)for(let d of W(a)){let g=Z(d.pattern);for(let u of g?n:[])g.test(u)&&(r??={plugin:a,label:d.label},o.add(u));}return r?{...r,tokens:[...o]}:null}var _=null,q=0,L=null,N=new Set;function B(t){_=t,N.forEach(e=>e());}function ne(t){return N.add(t),()=>N.delete(t)}function me(t,e,n,r){let{connect:o}=e;if(o?.type!=="api-token"&&o?.type!=="credentials")return O(t,e.id,n,r).then(()=>true);L?.();let a=++q,d=r?.connectionId?{connectionId:r.connectionId}:{};return new Promise(g=>{let u=c=>{_?.id===a&&B(null),q===a&&(L=null),g(c);},m=o.type==="api-token"?{kind:"token",id:a,plugin:{...e,connect:o},submit:async c=>{await t.connectPluginToken({pluginId:e.id,scope:n,token:c,...d});},settle:u}:{kind:"credentials",id:a,plugin:{...e,connect:o},submit:async(c,f)=>{await t.connectPluginCredentials({pluginId:e.id,scope:n,method:c,values:f,...d});},settle:u};L=()=>u(false),setTimeout(()=>{q===a&&B(m);});})}function oe(t){if(!t)return null;try{let e=new URL(t);return e.protocol==="https:"?e.href:null}catch{return null}}function ke(){let t=useSyncExternalStore(ne,()=>_,()=>null);return t?t.kind==="token"?jsx(le,{request:t},t.id):jsx(re,{request:t},t.id):null}function $({id:t,message:e}){return e?jsx("p",{className:"fk:text-sm fk:text-destructive",id:t,children:e}):null}function V({href:t,label:e}){let n=oe(t);return n?jsxs("a",{className:"fk:inline-flex fk:items-center fk:gap-1 fk:text-sm fk:text-muted-foreground fk:underline-offset-4 fk:hover:underline",href:n,rel:"noreferrer",target:"_blank",children:[e,jsx(ExternalLinkIcon,{className:"fk:size-3.5"})]}):null}function re({request:t}){let{connect:e,name:n}=t.plugin,r=useId(),[o,a]=useState(e.methods[0]?.key??null),[d,g]=useState({}),[u,m]=useState(null),[c$1,f]=useState(false),k$1=M(e,o),h$1=e.methods.find(l=>l.key===o)??null,v=z(k$1,d);async function P(l){if(l.preventDefault(),c$1)return;let C=X(k$1,d);if(C){m(C);return}f(true),m(null);try{await t.submit(o??void 0,Object.fromEntries(k$1.map(i=>[i.key,d[i.key]?.trim()??""]).filter(([,i])=>i))),g({}),t.settle(!0);}catch(i){m({field:null,message:i instanceof Error?i.message:`${n} could not be connected.`});}finally{f(false);}}return jsx(c,{open:true,onOpenChange:l=>{!l&&!c$1&&t.settle(false);},children:jsx(h,{children:jsxs("form",{className:"fk:flex fk:flex-col fk:gap-4",onSubmit:l=>{P(l);},children:[jsxs(i,{children:[jsxs(k,{children:["Connect ",n]}),jsxs(l,{children:[e.description," Flexkit checks the credentials with ",n,", stores them encrypted and sends them only to Flexkit's own ",n," server; the agent can use the tools but never sees them."]})]}),e.methods.length>1?jsx("div",{className:"fk:space-y-1.5",role:"group","aria-label":"How to connect",children:e.methods.map(l=>jsxs("button",{"aria-pressed":o===l.key,className:`fk:flex fk:w-full fk:flex-col fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:corner-squircle ${o===l.key?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,disabled:c$1,onClick:()=>{a(l.key),m(null);},type:"button",children:[jsx("span",{className:"fk:text-sm fk:font-medium",children:l.label}),l.description?jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:l.description}):null]},l.key))}):h$1?.description?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:h$1.description}):null,k$1.map((l,C)=>{let i=`${r}-${l.key}`,y=u?.field===l.key?u.message:null;return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-2",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:i,children:l.label}),jsx(s,{"aria-describedby":y?`${i}-error`:l.help?`${i}-help`:void 0,"aria-invalid":y?true:void 0,autoComplete:"off",autoFocus:C===0,disabled:c$1,id:i,placeholder:l.placeholder??void 0,spellCheck:false,type:l.kind==="secret"?"password":"text",value:d[l.key]??"",onChange:j=>{g(Y=>({...Y,[l.key]:j.target.value})),m(null);}}),l.help&&!y?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",id:`${i}-help`,children:l.help}):null,jsx($,{id:`${i}-error`,message:y})]},l.key)}),jsx($,{id:`${r}-error`,message:u?.field===null?u.message:null}),jsx(V,{href:e.helpUrl,label:`How to set up ${n}`}),jsxs(j,{children:[jsx(b,{disabled:c$1,size:"sm",type:"button",variant:"outline",onClick:()=>t.settle(false),children:"Cancel"}),jsxs(b,{disabled:c$1||!v,size:"sm",type:"submit",children:[c$1?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):null,"Connect"]})]})]})})})}function le({request:t}){let{connect:e,name:n}=t.plugin,r=useId(),[o,a]=useState(""),[d,g]=useState(null),[u,m]=useState(false);async function c$1(f){f.preventDefault();let k=o.trim();if(!(u||!k)){if(!S(k,e.pattern)){g(`That does not look like a ${e.tokenLabel}.`);return}m(true),g(null);try{await t.submit(k),a(""),t.settle(!0);}catch(h){g(h instanceof Error?h.message:`${n} could not be connected.`);}finally{m(false);}}}return jsx(c,{open:true,onOpenChange:f=>{!f&&!u&&t.settle(false);},children:jsx(h,{children:jsxs("form",{className:"fk:flex fk:flex-col fk:gap-4",onSubmit:f=>{c$1(f);},children:[jsxs(i,{children:[jsxs(k,{children:["Connect ",n]}),jsxs(l,{children:["Paste a ",e.tokenLabel,". Flexkit stores it encrypted and sends it only to ",n,"; the agent can use"," ",n,"'s tools but never sees the token. Give it read access only, unless the agent should change things in ",n,"."]})]}),jsxs("div",{className:"fk:flex fk:flex-col fk:gap-2",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:r,children:e.tokenLabel}),jsx(s,{"aria-describedby":d?`${r}-error`:void 0,"aria-invalid":d?true:void 0,autoComplete:"off",autoFocus:true,disabled:u,id:r,placeholder:e.placeholder??void 0,spellCheck:false,type:"password",value:o,onChange:f=>{a(f.target.value),g(null);}}),jsx($,{id:`${r}-error`,message:d}),jsx(V,{href:e.helpUrl,label:`How to create a ${e.tokenLabel}`})]}),jsxs(j,{children:[jsx(b,{disabled:u,size:"sm",type:"button",variant:"outline",onClick:()=>t.settle(false),children:"Cancel"}),jsxs(b,{disabled:u||!o.trim(),size:"sm",type:"submit",children:[u?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):null,"Connect"]})]})]})})})}export{R as a,O as b,ae as c,me as d,ke as e};//# sourceMappingURL=chunk-5LGIALCK.js.map
2
+ //# sourceMappingURL=chunk-5LGIALCK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apps/ai/plugin-oauth.ts","../src/apps/ai/plugin-token-format.ts","../src/apps/ai/plugin-token.tsx"],"names":["OAUTH_START_PATH","PluginAccountMismatchError","httpsUrl","value","url","trustedPluginOAuthTargets","authorizeUrl","completionOrigin","origin","getPlatformOrigin","authorize","completion","connectPluginPopup","api","pluginId","scope","options","popup","transaction","error","targets","expectedOrigin","resolve","reject","polling","finished","handedOff","finish","interval","timeout","onMessage","poll","status","event","payload","pluginSecretFormats","plugin","connect","method","field","credentialFormFields","selected","item","credentialFormComplete","fields","values","credentialFormError","matchesTokenPattern","token","pattern","compileTokenPattern","findPastedPluginToken","text","plugins","words","word","found","tokens","format","request","lastRequestId","cancelLatest","listeners","setRequest","next","listener","subscribe","connectPlugin","id","connectionId","settle","connected","httpsHref","PluginTokenDialogHost","current","useSyncExternalStore","jsx","PluginTokenDialog","PluginCredentialsDialog","FieldError","message","HelpLink","href","label","safeHref","jsxs","ExternalLinkIcon","name","formId","useId","setMethod","useState","setValues","setError","saving","setSaving","selectedMethod","ready","save","problem","failure","Dialog","open","DialogContent","DialogHeader","DialogTitle","DialogDescription","index","inputId","fieldError","Input","previous","DialogFooter","Button","LoaderCircle","setToken"],"mappings":"+UAGA,IAAMA,CAAAA,CAAmB,sBAAA,CAGZC,CAAAA,CAAN,cAAyC,KAAM,CAC3C,IAAA,CAAO,kBAAA,CAEhB,WAAA,EAAc,CACZ,KAAA,CAAM,kFAAkF,EACxF,IAAA,CAAK,IAAA,CAAO,6BACd,CACF,EAEA,SAASC,CAAAA,CAASC,CAAAA,CAA2B,CAC3C,IAAIC,CAAAA,CAEJ,GAAI,CACFA,CAAAA,CAAM,IAAI,GAAA,CAAID,CAAK,EACrB,CAAA,KAAQ,CACN,OAAO,IACT,CAEA,OAAIC,CAAAA,CAAI,QAAA,GAAa,QAAA,EAAYA,CAAAA,CAAI,QAAA,GAAa,IAAMA,CAAAA,CAAI,QAAA,GAAa,EAAA,CAChE,IAAA,CAGFA,CACT,CAGA,SAASC,CAAAA,CACPC,CAAAA,CACAC,CAAAA,CACyC,CACzC,IAAMC,CAAAA,CAASC,GAAAA,GACTC,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AAA,CAE1G,EACAW,IAAAA,CAAC4B,CAAAA,CAAA,CAAO,QAAA,CAAUnB,CAAAA,EAAU,CAAC9C,CAAAA,CAAM,IAAA,EAAK,CAAG,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,QAAA,CACvD,QAAA,CAAA,CAAA8C,EAASlB,GAAAA,CAACsC,YAAAA,CAAA,CAAa,SAAA,CAAU,2BAAA,CAA4B,CAAA,CAAK,IAAA,CAAK,SAAA,CAAA,CAE1E,CAAA,CAAA,CACF,CAAA,CAAA,CACF,CAAA,CACF,CAAA,CACF,CAEJ","file":"chunk-2IFBQNWA.js","sourcesContent":["import { getPlatformOrigin, type ApiClient } from './api';\nimport type { PluginScope } from './plugin-types';\n\nconst OAUTH_START_PATH = '/plugins/oauth/start';\n\n/** A Reconnect was completed with a different provider account than the one being reconnected. */\nexport class PluginAccountMismatchError extends Error {\n readonly code = 'account_mismatch';\n\n constructor() {\n super('You signed in with a different account. Use \"Connect another account\" to add it.');\n this.name = 'PluginAccountMismatchError';\n }\n}\n\nfunction httpsUrl(value: string): URL | null {\n let url: URL;\n\n try {\n url = new URL(value);\n } catch {\n return null;\n }\n\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '') {\n return null;\n }\n\n return url;\n}\n\n/** Popup navigation and postMessage stay on the platform OAuth start page. */\nfunction trustedPluginOAuthTargets(\n authorizeUrl: string,\n completionOrigin: string\n): { href: string; origin: string } | null {\n const origin = getPlatformOrigin();\n const authorize = httpsUrl(authorizeUrl);\n const completion = httpsUrl(completionOrigin);\n\n if (!authorize || !completion) {\n return null;\n }\n\n if (authorize.origin !== origin || authorize.pathname !== OAUTH_START_PATH) {\n return null;\n }\n\n if (completion.origin !== origin || completion.pathname !== '/') {\n return null;\n }\n\n return { href: authorize.href, origin };\n}\n\n/** Must be called directly from the click handler so browsers allow the popup. */\nexport async function connectPluginPopup(\n api: ApiClient,\n pluginId: string,\n scope: PluginScope,\n options?: { connectionId?: string }\n): Promise<void> {\n const popup = window.open('about:blank', `flexkit-plugin-${crypto.randomUUID()}`, 'popup,width=560,height=720');\n\n if (!popup) {\n throw new Error('Allow popups for Studio, then connect again.');\n }\n\n let transaction: Awaited<ReturnType<ApiClient['connectPlugins']>>;\n\n try {\n transaction = await api.connectPlugins({\n pluginId,\n scope,\n studioOrigin: window.location.origin,\n ...(options?.connectionId ? { connectionId: options.connectionId } : {}),\n });\n } catch (error) {\n popup.close();\n throw error;\n }\n\n const targets = trustedPluginOAuthTargets(transaction.authorizeUrl, transaction.completionOrigin);\n\n if (!targets) {\n popup.close();\n throw new Error('Connection could not be started.');\n }\n\n const expectedOrigin = targets.origin;\n\n await new Promise<void>((resolve, reject) => {\n let polling = false;\n let finished = false;\n // Once the popup leaves for the provider, `popup.closed` says nothing:\n // providers isolate their pages (Cross-Origin-Opener-Policy), which severs\n // the opener and reports the window as closed while it is open. From then\n // on only the transaction's status (and the timeout) ends the wait.\n let handedOff = false;\n const finish = (error?: Error) => {\n if (finished) {\n return;\n }\n\n finished = true;\n window.clearInterval(interval);\n window.clearTimeout(timeout);\n window.removeEventListener('message', onMessage);\n popup.close();\n\n if (error) {\n reject(error);\n\n return;\n }\n\n resolve();\n };\n const poll = async () => {\n if (polling || finished) {\n return;\n }\n\n polling = true;\n let status: Awaited<ReturnType<ApiClient['pluginOAuthStatus']>>;\n\n try {\n status = await api.pluginOAuthStatus(transaction.transactionId);\n } catch {\n polling = false;\n\n return;\n }\n\n polling = false;\n\n if (status.status === 'complete') {\n finish();\n\n return;\n }\n\n if (!handedOff && popup.closed && status.status === 'pending') {\n finish(new Error('Connection window was closed.'));\n\n return;\n }\n\n if (status.status === 'failed' || new Date(status.expires_at).getTime() < Date.now()) {\n finish(new Error('Connection was not completed. Please try again.'));\n }\n };\n const onMessage = (event: MessageEvent<unknown>) => {\n if (event.origin !== expectedOrigin || event.source !== popup || !event.data || typeof event.data !== 'object') {\n return;\n }\n\n const payload = event.data as { type?: string; transactionId?: string; status?: string; error?: string };\n\n if (payload.type === 'flexkit:plugin-oauth-ready' && payload.transactionId === transaction.transactionId) {\n handedOff = true;\n popup.postMessage(\n {\n type: 'flexkit:plugin-oauth-start',\n transactionId: transaction.transactionId,\n ticket: transaction.launchTicket,\n },\n expectedOrigin\n );\n\n return;\n }\n\n if (payload.type === 'flexkit:plugin-oauth' && payload.transactionId === transaction.transactionId) {\n if (payload.status === 'failed' && payload.error === 'account_mismatch') {\n finish(new PluginAccountMismatchError());\n\n return;\n }\n\n void poll();\n }\n };\n const interval = window.setInterval(() => {\n void poll();\n }, 2000);\n const timeout = window.setTimeout(() => finish(new Error('Connection timed out. Please try again.')), 600_000);\n window.addEventListener('message', onMessage);\n popup.location.href = targets.href;\n });\n}\n","import type { MarketplacePlugin, PluginCredentialField, PluginCredentialsConnect } from './plugin-types';\n\nexport type ConnectablePlugin = Pick<MarketplacePlugin, 'connect' | 'id' | 'name'>;\n\n/** Longer than any credential a provider issues; the server rejects more. */\nexport const MAX_CREDENTIAL_VALUE_LENGTH = 4096;\n\n/**\n * The secrets a plugin's connect form takes that can be recognized on their\n * own (a distinctive prefix, say), each with that pattern and what to call it.\n */\nexport function pluginSecretFormats(plugin: ConnectablePlugin): Array<{ label: string; pattern: string }> {\n const { connect } = plugin;\n\n if (connect?.type === 'api-token') {\n return connect.pattern ? [{ label: connect.tokenLabel, pattern: connect.pattern }] : [];\n }\n\n if (connect?.type === 'credentials') {\n return [...connect.fields, ...connect.methods.flatMap((method) => method.fields)]\n .filter((field) => field.kind === 'secret' && field.detect)\n .map((field) => ({ label: field.label, pattern: field.detect! }));\n }\n\n return [];\n}\n\n/** The fields a credentials form shows: the shared ones, then those of the chosen method. */\nexport function credentialFormFields(connect: PluginCredentialsConnect, method: string | null): PluginCredentialField[] {\n const selected = connect.methods.find((item) => item.key === method);\n\n return [...connect.fields, ...(selected?.fields ?? [])];\n}\n\n/** Whether every required field has a value: what the Connect button waits for. */\nexport function credentialFormComplete(\n fields: readonly PluginCredentialField[],\n values: { [key: string]: string }\n): boolean {\n return fields.every((field) => !field.required || Boolean(values[field.key]?.trim()));\n}\n\n/** The first problem with the values entered, or null when they can be submitted. */\nexport function credentialFormError(\n fields: readonly PluginCredentialField[],\n values: { [key: string]: string }\n): { field: string; message: string } | null {\n for (const field of fields) {\n const value = values[field.key]?.trim() ?? '';\n\n if (!value) {\n if (field.required) {\n return { field: field.key, message: `Enter the ${field.label}.` };\n }\n\n continue;\n }\n\n if (value.length > MAX_CREDENTIAL_VALUE_LENGTH) {\n return { field: field.key, message: `The ${field.label} is too long; paste only the value.` };\n }\n\n if (!matchesTokenPattern(value, field.pattern)) {\n return { field: field.key, message: `That is not a valid ${field.label}.` };\n }\n }\n\n return null;\n}\n\nexport function matchesTokenPattern(token: string, pattern: string | null): boolean {\n if (!pattern) {\n return true;\n }\n\n try {\n return new RegExp(pattern, 'u').test(token);\n } catch {\n // The server validates the pattern when it admits the plugin; never block on a bad one here.\n return true;\n }\n}\n\n/** A pattern that compiles; an empty or broken one detects nothing rather than every word. */\nfunction compileTokenPattern(pattern: string | null): RegExp | null {\n if (!pattern) {\n return null;\n }\n\n try {\n return new RegExp(pattern, 'u');\n } catch {\n return null;\n }\n}\n\n/**\n * The first plugin whose secret format `text` contains, if any, with every\n * secret-shaped word in the message and what the plugin calls that secret: a\n * token pasted into the chat would be stored in the conversation and sent to\n * the model.\n */\nexport function findPastedPluginToken(\n text: string,\n plugins: readonly ConnectablePlugin[]\n): { plugin: ConnectablePlugin; tokens: string[]; label: string } | null {\n // A token is often glued to a label (`token=…`, `key: …`) or wrapped in\n // brackets, quotes or a sentence's punctuation; none of those are part of it.\n const words = text\n .split(/[\\s\"'`()<>[\\]{},;:=!?&]+/)\n .map((word) => word.replace(/\\.+$/, ''))\n .filter(Boolean);\n let found: { plugin: ConnectablePlugin; label: string } | null = null;\n const tokens = new Set<string>();\n\n for (const plugin of plugins) {\n for (const format of pluginSecretFormats(plugin)) {\n const pattern = compileTokenPattern(format.pattern);\n\n for (const word of pattern ? words : []) {\n if (pattern!.test(word)) {\n found ??= { plugin, label: format.label };\n tokens.add(word);\n }\n }\n }\n }\n\n return found ? { ...found, tokens: [...tokens] } : null;\n}\n","import type { FormEvent, JSX } from 'react';\nimport { useId, useState, useSyncExternalStore } from 'react';\nimport { ExternalLinkIcon, LoaderCircle } from 'lucide-react';\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Input,\n} from '../../ui';\nimport type { ApiClient } from './api';\nimport { connectPluginPopup } from './plugin-oauth';\nimport {\n credentialFormComplete,\n credentialFormError,\n credentialFormFields,\n matchesTokenPattern,\n type ConnectablePlugin,\n} from './plugin-token-format';\nimport type { PluginApiTokenConnect, PluginCredentialsConnect, PluginScope } from './plugin-types';\n\ninterface TokenRequest {\n id: number;\n plugin: ConnectablePlugin & { connect: PluginApiTokenConnect };\n /** Saves the token; rejects with a message the dialog shows next to the field. */\n submit: (_token: string) => Promise<void>;\n settle: (_connected: boolean) => void;\n}\n\ninterface CredentialsRequest {\n id: number;\n plugin: ConnectablePlugin & { connect: PluginCredentialsConnect };\n /** Saves the form; rejects with a message the dialog shows under the fields. */\n submit: (_method: string | undefined, _values: { [key: string]: string }) => Promise<void>;\n settle: (_connected: boolean) => void;\n}\n\ntype FormRequest = ({ kind: 'token' } & TokenRequest) | ({ kind: 'credentials' } & CredentialsRequest);\n\n/** The one open connect form, outside React so any connect button can open it. */\nlet request: FormRequest | null = null;\nlet lastRequestId = 0;\n/** Cancels the latest request, whether its dialog has opened yet or not. */\nlet cancelLatest: (() => void) | null = null;\nconst listeners = new Set<() => void>();\n\nfunction setRequest(next: FormRequest | null): void {\n request = next;\n listeners.forEach((listener) => listener());\n}\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener);\n\n return () => listeners.delete(listener);\n}\n\n/**\n * Connects a plugin: a sign-in popup for OAuth plugins, the token dialog for\n * plugins that take a pasted token, the credentials dialog for plugins that\n * take the credentials of an app the user created at the provider. Resolves\n * `false` when the user closes a dialog without connecting.\n *\n * Call it straight from a click handler: browsers only allow the popup there.\n */\nexport function connectPlugin(\n api: ApiClient,\n plugin: ConnectablePlugin,\n scope: PluginScope,\n options?: { connectionId?: string }\n): Promise<boolean> {\n const { connect } = plugin;\n\n if (connect?.type !== 'api-token' && connect?.type !== 'credentials') {\n return connectPluginPopup(api, plugin.id, scope, options).then(() => true);\n }\n\n // Opening a second dialog closes the first, as if cancelled.\n cancelLatest?.();\n\n const id = ++lastRequestId;\n const connectionId = options?.connectionId ? { connectionId: options.connectionId } : {};\n\n return new Promise<boolean>((resolve) => {\n const settle = (connected: boolean): void => {\n // A save still running for a replaced dialog must not close its successor.\n if (request?.id === id) {\n setRequest(null);\n }\n\n if (lastRequestId === id) {\n cancelLatest = null;\n }\n\n resolve(connected);\n };\n const next: FormRequest =\n connect.type === 'api-token'\n ? {\n kind: 'token',\n id,\n plugin: { ...plugin, connect },\n submit: async (token) => {\n await api.connectPluginToken({ pluginId: plugin.id, scope, token, ...connectionId });\n },\n settle,\n }\n : {\n kind: 'credentials',\n id,\n plugin: { ...plugin, connect },\n submit: async (method, values) => {\n await api.connectPluginCredentials({ pluginId: plugin.id, scope, method, values, ...connectionId });\n },\n settle,\n };\n\n cancelLatest = () => settle(false);\n\n // Open after the current event: a menu item that started this closes first\n // and returns focus to its trigger, which would take it from the first field.\n setTimeout(() => {\n if (lastRequestId === id) {\n setRequest(next);\n }\n });\n });\n}\n\nfunction httpsHref(value: string | null): string | null {\n if (!value) {\n return null;\n }\n\n try {\n const url = new URL(value);\n\n return url.protocol === 'https:' ? url.href : null;\n } catch {\n return null;\n }\n}\n\n/** Mounted once by the Studio layout; renders the dialog `connectPlugin` opens for token and credentials plugins. */\nexport function PluginTokenDialogHost(): JSX.Element | null {\n const current = useSyncExternalStore(\n subscribe,\n () => request,\n () => null\n );\n\n if (!current) {\n return null;\n }\n\n // A new key per request resets the fields, so a secret never outlives its dialog.\n return current.kind === 'token' ? (\n <PluginTokenDialog key={current.id} request={current} />\n ) : (\n <PluginCredentialsDialog key={current.id} request={current} />\n );\n}\n\nfunction FieldError({ id, message }: { id: string; message: string | null }): JSX.Element | null {\n return message ? (\n <p className=\"fk:text-sm fk:text-destructive\" id={id}>\n {message}\n </p>\n ) : null;\n}\n\nfunction HelpLink({ href, label }: { href: string | null; label: string }): JSX.Element | null {\n const safeHref = httpsHref(href);\n\n return safeHref ? (\n <a\n className=\"fk:inline-flex fk:items-center fk:gap-1 fk:text-sm fk:text-muted-foreground fk:underline-offset-4 fk:hover:underline\"\n href={safeHref}\n rel=\"noreferrer\"\n target=\"_blank\"\n >\n {label}\n <ExternalLinkIcon className=\"fk:size-3.5\" />\n </a>\n ) : null;\n}\n\nfunction PluginCredentialsDialog({ request: current }: { request: CredentialsRequest }): JSX.Element {\n const { connect, name } = current.plugin;\n const formId = useId();\n const [method, setMethod] = useState<string | null>(connect.methods[0]?.key ?? null);\n const [values, setValues] = useState<{ [key: string]: string }>({});\n const [error, setError] = useState<{ field: string | null; message: string } | null>(null);\n const [saving, setSaving] = useState(false);\n const fields = credentialFormFields(connect, method);\n const selectedMethod = connect.methods.find((item) => item.key === method) ?? null;\n // Submitting surfaces which field is malformed; the button only waits for the required values.\n const ready = credentialFormComplete(fields, values);\n\n async function save(event: FormEvent): Promise<void> {\n event.preventDefault();\n\n if (saving) {\n return;\n }\n\n const problem = credentialFormError(fields, values);\n\n if (problem) {\n setError(problem);\n\n return;\n }\n\n setSaving(true);\n setError(null);\n\n try {\n await current.submit(\n method ?? undefined,\n Object.fromEntries(fields.map((field) => [field.key, values[field.key]?.trim() ?? '']).filter(([, value]) => value))\n );\n setValues({});\n current.settle(true);\n } catch (failure) {\n setError({ field: null, message: failure instanceof Error ? failure.message : `${name} could not be connected.` });\n } finally {\n setSaving(false);\n }\n }\n\n return (\n <Dialog\n open\n onOpenChange={(open) => {\n if (!open && !saving) {\n current.settle(false);\n }\n }}\n >\n <DialogContent>\n <form className=\"fk:flex fk:flex-col fk:gap-4\" onSubmit={(event) => void save(event)}>\n <DialogHeader>\n <DialogTitle>Connect {name}</DialogTitle>\n <DialogDescription>\n {connect.description} Flexkit checks the credentials with {name}, stores them encrypted and sends them\n only to Flexkit&apos;s own {name} server; the agent can use the tools but never sees them.\n </DialogDescription>\n </DialogHeader>\n {connect.methods.length > 1 ? (\n <div className=\"fk:space-y-1.5\" role=\"group\" aria-label=\"How to connect\">\n {connect.methods.map((item) => (\n <button\n aria-pressed={method === item.key}\n className={`fk:flex fk:w-full fk:flex-col fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:corner-squircle ${\n method === item.key ? 'fk:border-primary fk:bg-primary/5' : 'fk:border-border fk:hover:bg-muted/60'\n }`}\n disabled={saving}\n key={item.key}\n onClick={() => {\n setMethod(item.key);\n setError(null);\n }}\n type=\"button\"\n >\n <span className=\"fk:text-sm fk:font-medium\">{item.label}</span>\n {item.description ? (\n <span className=\"fk:text-xs fk:text-muted-foreground\">{item.description}</span>\n ) : null}\n </button>\n ))}\n </div>\n ) : selectedMethod?.description ? (\n <p className=\"fk:text-sm fk:text-muted-foreground\">{selectedMethod.description}</p>\n ) : null}\n {fields.map((field, index) => {\n const inputId = `${formId}-${field.key}`;\n const fieldError = error?.field === field.key ? error.message : null;\n\n return (\n <div className=\"fk:flex fk:flex-col fk:gap-2\" key={field.key}>\n <label className=\"fk:text-sm fk:font-medium\" htmlFor={inputId}>\n {field.label}\n </label>\n <Input\n aria-describedby={fieldError ? `${inputId}-error` : field.help ? `${inputId}-help` : undefined}\n aria-invalid={fieldError ? true : undefined}\n autoComplete=\"off\"\n autoFocus={index === 0}\n disabled={saving}\n id={inputId}\n placeholder={field.placeholder ?? undefined}\n spellCheck={false}\n type={field.kind === 'secret' ? 'password' : 'text'}\n value={values[field.key] ?? ''}\n onChange={(event) => {\n setValues((previous) => ({ ...previous, [field.key]: event.target.value }));\n setError(null);\n }}\n />\n {field.help && !fieldError ? (\n <p className=\"fk:text-sm fk:text-muted-foreground\" id={`${inputId}-help`}>\n {field.help}\n </p>\n ) : null}\n <FieldError id={`${inputId}-error`} message={fieldError} />\n </div>\n );\n })}\n <FieldError id={`${formId}-error`} message={error?.field === null ? error.message : null} />\n <HelpLink href={connect.helpUrl} label={`How to set up ${name}`} />\n <DialogFooter>\n <Button disabled={saving} size=\"sm\" type=\"button\" variant=\"outline\" onClick={() => current.settle(false)}>\n Cancel\n </Button>\n <Button disabled={saving || !ready} size=\"sm\" type=\"submit\">\n {saving ? <LoaderCircle className=\"fk:size-4 fk:animate-spin\" /> : null}\n Connect\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n\nfunction PluginTokenDialog({ request: current }: { request: TokenRequest }): JSX.Element {\n const { connect, name } = current.plugin;\n const inputId = useId();\n const [token, setToken] = useState('');\n const [error, setError] = useState<string | null>(null);\n const [saving, setSaving] = useState(false);\n\n async function save(event: FormEvent): Promise<void> {\n event.preventDefault();\n const value = token.trim();\n\n if (saving || !value) {\n return;\n }\n\n if (!matchesTokenPattern(value, connect.pattern)) {\n setError(`That does not look like a ${connect.tokenLabel}.`);\n\n return;\n }\n\n setSaving(true);\n setError(null);\n\n try {\n await current.submit(value);\n setToken('');\n current.settle(true);\n } catch (failure) {\n setError(failure instanceof Error ? failure.message : `${name} could not be connected.`);\n } finally {\n setSaving(false);\n }\n }\n\n return (\n <Dialog\n open\n onOpenChange={(open) => {\n if (!open && !saving) {\n current.settle(false);\n }\n }}\n >\n <DialogContent>\n <form className=\"fk:flex fk:flex-col fk:gap-4\" onSubmit={(event) => void save(event)}>\n <DialogHeader>\n <DialogTitle>Connect {name}</DialogTitle>\n <DialogDescription>\n Paste a {connect.tokenLabel}. Flexkit stores it encrypted and sends it only to {name}; the agent can use{' '}\n {name}&apos;s tools but never sees the token. Give it read access only, unless the agent should change\n things in {name}.\n </DialogDescription>\n </DialogHeader>\n <div className=\"fk:flex fk:flex-col fk:gap-2\">\n <label className=\"fk:text-sm fk:font-medium\" htmlFor={inputId}>\n {connect.tokenLabel}\n </label>\n <Input\n aria-describedby={error ? `${inputId}-error` : undefined}\n aria-invalid={error ? true : undefined}\n autoComplete=\"off\"\n autoFocus\n disabled={saving}\n id={inputId}\n placeholder={connect.placeholder ?? undefined}\n spellCheck={false}\n type=\"password\"\n value={token}\n onChange={(event) => {\n setToken(event.target.value);\n setError(null);\n }}\n />\n <FieldError id={`${inputId}-error`} message={error} />\n <HelpLink href={connect.helpUrl} label={`How to create a ${connect.tokenLabel}`} />\n </div>\n <DialogFooter>\n <Button disabled={saving} size=\"sm\" type=\"button\" variant=\"outline\" onClick={() => current.settle(false)}>\n Cancel\n </Button>\n <Button disabled={saving || !token.trim()} size=\"sm\" type=\"submit\">\n {saving ? <LoaderCircle className=\"fk:size-4 fk:animate-spin\" /> : null}\n Connect\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/apps/ai/plugin-oauth.ts","../src/apps/ai/plugin-token-format.ts","../src/apps/ai/plugin-token.tsx"],"names":["OAUTH_START_PATH","PluginAccountMismatchError","httpsUrl","value","url","trustedPluginOAuthTargets","authorizeUrl","completionOrigin","origin","getPlatformOrigin","authorize","completion","connectPluginPopup","api","pluginId","scope","options","popup","transaction","error","targets","expectedOrigin","resolve","reject","polling","finished","handedOff","finish","interval","timeout","onMessage","poll","status","event","payload","pluginSecretFormats","plugin","connect","method","field","credentialFormFields","selected","item","credentialFormComplete","fields","values","credentialFormError","matchesTokenPattern","token","pattern","compileTokenPattern","findPastedPluginToken","text","plugins","words","word","found","tokens","format","request","lastRequestId","cancelLatest","listeners","setRequest","next","listener","subscribe","connectPlugin","id","connectionId","settle","connected","httpsHref","PluginTokenDialogHost","current","useSyncExternalStore","jsx","PluginTokenDialog","PluginCredentialsDialog","FieldError","message","HelpLink","href","label","safeHref","jsxs","ExternalLinkIcon","name","formId","useId","setMethod","useState","setValues","setError","saving","setSaving","selectedMethod","ready","save","problem","failure","Dialog","open","DialogContent","DialogHeader","DialogTitle","DialogDescription","index","inputId","fieldError","Input","previous","DialogFooter","Button","LoaderCircle","setToken"],"mappings":"+UAGA,IAAMA,CAAAA,CAAmB,sBAAA,CAGZC,CAAAA,CAAN,cAAyC,KAAM,CAC3C,IAAA,CAAO,kBAAA,CAEhB,WAAA,EAAc,CACZ,KAAA,CAAM,kFAAkF,EACxF,IAAA,CAAK,IAAA,CAAO,6BACd,CACF,EAEA,SAASC,CAAAA,CAASC,CAAAA,CAA2B,CAC3C,IAAIC,CAAAA,CAEJ,GAAI,CACFA,CAAAA,CAAM,IAAI,GAAA,CAAID,CAAK,EACrB,CAAA,KAAQ,CACN,OAAO,IACT,CAEA,OAAIC,CAAAA,CAAI,QAAA,GAAa,QAAA,EAAYA,CAAAA,CAAI,QAAA,GAAa,IAAMA,CAAAA,CAAI,QAAA,GAAa,EAAA,CAChE,IAAA,CAGFA,CACT,CAGA,SAASC,CAAAA,CACPC,CAAAA,CACAC,CAAAA,CACyC,CACzC,IAAMC,CAAAA,CAASC,GAAAA,GACTC,CAAAA,CAAYR,CAAAA,CAASI,CAAY,CAAA,CACjCK,CAAAA,CAAaT,CAAAA,CAASK,CAAgB,CAAA,CAU5C,OARI,CAACG,CAAAA,EAAa,CAACC,CAAAA,EAIfD,CAAAA,CAAU,SAAWF,CAAAA,EAAUE,CAAAA,CAAU,QAAA,GAAaV,CAAAA,EAItDW,CAAAA,CAAW,MAAA,GAAWH,CAAAA,EAAUG,CAAAA,CAAW,QAAA,GAAa,GAAA,CACnD,IAAA,CAGF,CAAE,IAAA,CAAMD,CAAAA,CAAU,KAAM,MAAA,CAAAF,CAAO,CACxC,CAGA,eAAsBI,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACe,CACf,IAAMC,CAAAA,CAAQ,MAAA,CAAO,KAAK,aAAA,CAAe,CAAA,eAAA,EAAkB,MAAA,CAAO,UAAA,EAAY,CAAA,CAAA,CAAI,4BAA4B,CAAA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,CAAAA,CAAM,MAAA,CAAO,KAAK,CAAA,CAC3B4D,CAAAA,CAAS,IAAI,EACf,CAAA,CACF,CAAA,CACAjB,IAACG,CAAAA,CAAA,CAAW,EAAA,CAAI,CAAA,EAAG6B,CAAO,CAAA,MAAA,CAAA,CAAU,OAAA,CAASzF,CAAAA,CAAO,CAAA,CACpDyD,GAAAA,CAACK,CAAAA,CAAA,CAAS,IAAA,CAAM5C,CAAAA,CAAQ,QAAS,KAAA,CAAO,CAAA,gBAAA,EAAmBA,CAAAA,CAAQ,UAAU,CAAA,CAAA,CAAI,CAAA,CAAA,CACnF,CAAA,CACAgD,IAAAA,CAAC2B,CAAAA,CAAA,CACC,QAAA,CAAA,CAAApC,GAAAA,CAACqC,CAAAA,CAAA,CAAO,SAAUnB,CAAAA,CAAQ,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQ,SAAA,CAAU,OAAA,CAAS,IAAMpB,CAAAA,CAAQ,MAAA,CAAO,KAAK,CAAA,CAAG,QAAA,CAAA,QAAA,CAE1G,EACAW,IAAAA,CAAC4B,CAAAA,CAAA,CAAO,QAAA,CAAUnB,CAAAA,EAAU,CAAC9C,CAAAA,CAAM,IAAA,EAAK,CAAG,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,QAAA,CACvD,QAAA,CAAA,CAAA8C,EAASlB,GAAAA,CAACsC,YAAAA,CAAA,CAAa,SAAA,CAAU,2BAAA,CAA4B,CAAA,CAAK,IAAA,CAAK,SAAA,CAAA,CAE1E,CAAA,CAAA,CACF,CAAA,CAAA,CACF,CAAA,CACF,CAAA,CACF,CAEJ","file":"chunk-5LGIALCK.js","sourcesContent":["import { getPlatformOrigin, type ApiClient } from './api';\nimport type { PluginScope } from './plugin-types';\n\nconst OAUTH_START_PATH = '/plugins/oauth/start';\n\n/** A Reconnect was completed with a different provider account than the one being reconnected. */\nexport class PluginAccountMismatchError extends Error {\n readonly code = 'account_mismatch';\n\n constructor() {\n super('You signed in with a different account. Use \"Connect another account\" to add it.');\n this.name = 'PluginAccountMismatchError';\n }\n}\n\nfunction httpsUrl(value: string): URL | null {\n let url: URL;\n\n try {\n url = new URL(value);\n } catch {\n return null;\n }\n\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '') {\n return null;\n }\n\n return url;\n}\n\n/** Popup navigation and postMessage stay on the platform OAuth start page. */\nfunction trustedPluginOAuthTargets(\n authorizeUrl: string,\n completionOrigin: string\n): { href: string; origin: string } | null {\n const origin = getPlatformOrigin();\n const authorize = httpsUrl(authorizeUrl);\n const completion = httpsUrl(completionOrigin);\n\n if (!authorize || !completion) {\n return null;\n }\n\n if (authorize.origin !== origin || authorize.pathname !== OAUTH_START_PATH) {\n return null;\n }\n\n if (completion.origin !== origin || completion.pathname !== '/') {\n return null;\n }\n\n return { href: authorize.href, origin };\n}\n\n/** Must be called directly from the click handler so browsers allow the popup. */\nexport async function connectPluginPopup(\n api: ApiClient,\n pluginId: string,\n scope: PluginScope,\n options?: { connectionId?: string }\n): Promise<void> {\n const popup = window.open('about:blank', `flexkit-plugin-${crypto.randomUUID()}`, 'popup,width=560,height=720');\n\n if (!popup) {\n throw new Error('Allow popups for Studio, then connect again.');\n }\n\n let transaction: Awaited<ReturnType<ApiClient['connectPlugins']>>;\n\n try {\n transaction = await api.connectPlugins({\n pluginId,\n scope,\n studioOrigin: window.location.origin,\n ...(options?.connectionId ? { connectionId: options.connectionId } : {}),\n });\n } catch (error) {\n popup.close();\n throw error;\n }\n\n const targets = trustedPluginOAuthTargets(transaction.authorizeUrl, transaction.completionOrigin);\n\n if (!targets) {\n popup.close();\n throw new Error('Connection could not be started.');\n }\n\n const expectedOrigin = targets.origin;\n\n await new Promise<void>((resolve, reject) => {\n let polling = false;\n let finished = false;\n // Once the popup leaves for the provider, `popup.closed` says nothing:\n // providers isolate their pages (Cross-Origin-Opener-Policy), which severs\n // the opener and reports the window as closed while it is open. From then\n // on only the transaction's status (and the timeout) ends the wait.\n let handedOff = false;\n const finish = (error?: Error) => {\n if (finished) {\n return;\n }\n\n finished = true;\n window.clearInterval(interval);\n window.clearTimeout(timeout);\n window.removeEventListener('message', onMessage);\n popup.close();\n\n if (error) {\n reject(error);\n\n return;\n }\n\n resolve();\n };\n const poll = async () => {\n if (polling || finished) {\n return;\n }\n\n polling = true;\n let status: Awaited<ReturnType<ApiClient['pluginOAuthStatus']>>;\n\n try {\n status = await api.pluginOAuthStatus(transaction.transactionId);\n } catch {\n polling = false;\n\n return;\n }\n\n polling = false;\n\n if (status.status === 'complete') {\n finish();\n\n return;\n }\n\n if (!handedOff && popup.closed && status.status === 'pending') {\n finish(new Error('Connection window was closed.'));\n\n return;\n }\n\n if (status.status === 'failed' || new Date(status.expires_at).getTime() < Date.now()) {\n finish(new Error('Connection was not completed. Please try again.'));\n }\n };\n const onMessage = (event: MessageEvent<unknown>) => {\n if (event.origin !== expectedOrigin || event.source !== popup || !event.data || typeof event.data !== 'object') {\n return;\n }\n\n const payload = event.data as { type?: string; transactionId?: string; status?: string; error?: string };\n\n if (payload.type === 'flexkit:plugin-oauth-ready' && payload.transactionId === transaction.transactionId) {\n handedOff = true;\n popup.postMessage(\n {\n type: 'flexkit:plugin-oauth-start',\n transactionId: transaction.transactionId,\n ticket: transaction.launchTicket,\n },\n expectedOrigin\n );\n\n return;\n }\n\n if (payload.type === 'flexkit:plugin-oauth' && payload.transactionId === transaction.transactionId) {\n if (payload.status === 'failed' && payload.error === 'account_mismatch') {\n finish(new PluginAccountMismatchError());\n\n return;\n }\n\n void poll();\n }\n };\n const interval = window.setInterval(() => {\n void poll();\n }, 2000);\n const timeout = window.setTimeout(() => finish(new Error('Connection timed out. Please try again.')), 600_000);\n window.addEventListener('message', onMessage);\n popup.location.href = targets.href;\n });\n}\n","import type { MarketplacePlugin, PluginCredentialField, PluginCredentialsConnect } from './plugin-types';\n\nexport type ConnectablePlugin = Pick<MarketplacePlugin, 'connect' | 'id' | 'name'>;\n\n/** Longer than any credential a provider issues; the server rejects more. */\nexport const MAX_CREDENTIAL_VALUE_LENGTH = 4096;\n\n/**\n * The secrets a plugin's connect form takes that can be recognized on their\n * own (a distinctive prefix, say), each with that pattern and what to call it.\n */\nexport function pluginSecretFormats(plugin: ConnectablePlugin): Array<{ label: string; pattern: string }> {\n const { connect } = plugin;\n\n if (connect?.type === 'api-token') {\n return connect.pattern ? [{ label: connect.tokenLabel, pattern: connect.pattern }] : [];\n }\n\n if (connect?.type === 'credentials') {\n return [...connect.fields, ...connect.methods.flatMap((method) => method.fields)]\n .filter((field) => field.kind === 'secret' && field.detect)\n .map((field) => ({ label: field.label, pattern: field.detect! }));\n }\n\n return [];\n}\n\n/** The fields a credentials form shows: the shared ones, then those of the chosen method. */\nexport function credentialFormFields(connect: PluginCredentialsConnect, method: string | null): PluginCredentialField[] {\n const selected = connect.methods.find((item) => item.key === method);\n\n return [...connect.fields, ...(selected?.fields ?? [])];\n}\n\n/** Whether every required field has a value: what the Connect button waits for. */\nexport function credentialFormComplete(\n fields: readonly PluginCredentialField[],\n values: { [key: string]: string }\n): boolean {\n return fields.every((field) => !field.required || Boolean(values[field.key]?.trim()));\n}\n\n/** The first problem with the values entered, or null when they can be submitted. */\nexport function credentialFormError(\n fields: readonly PluginCredentialField[],\n values: { [key: string]: string }\n): { field: string; message: string } | null {\n for (const field of fields) {\n const value = values[field.key]?.trim() ?? '';\n\n if (!value) {\n if (field.required) {\n return { field: field.key, message: `Enter the ${field.label}.` };\n }\n\n continue;\n }\n\n if (value.length > MAX_CREDENTIAL_VALUE_LENGTH) {\n return { field: field.key, message: `The ${field.label} is too long; paste only the value.` };\n }\n\n if (!matchesTokenPattern(value, field.pattern)) {\n return { field: field.key, message: `That is not a valid ${field.label}.` };\n }\n }\n\n return null;\n}\n\nexport function matchesTokenPattern(token: string, pattern: string | null): boolean {\n if (!pattern) {\n return true;\n }\n\n try {\n return new RegExp(pattern, 'u').test(token);\n } catch {\n // The server validates the pattern when it admits the plugin; never block on a bad one here.\n return true;\n }\n}\n\n/** A pattern that compiles; an empty or broken one detects nothing rather than every word. */\nfunction compileTokenPattern(pattern: string | null): RegExp | null {\n if (!pattern) {\n return null;\n }\n\n try {\n return new RegExp(pattern, 'u');\n } catch {\n return null;\n }\n}\n\n/**\n * The first plugin whose secret format `text` contains, if any, with every\n * secret-shaped word in the message and what the plugin calls that secret: a\n * token pasted into the chat would be stored in the conversation and sent to\n * the model.\n */\nexport function findPastedPluginToken(\n text: string,\n plugins: readonly ConnectablePlugin[]\n): { plugin: ConnectablePlugin; tokens: string[]; label: string } | null {\n // A token is often glued to a label (`token=…`, `key: …`) or wrapped in\n // brackets, quotes or a sentence's punctuation; none of those are part of it.\n const words = text\n .split(/[\\s\"'`()<>[\\]{},;:=!?&]+/)\n .map((word) => word.replace(/\\.+$/, ''))\n .filter(Boolean);\n let found: { plugin: ConnectablePlugin; label: string } | null = null;\n const tokens = new Set<string>();\n\n for (const plugin of plugins) {\n for (const format of pluginSecretFormats(plugin)) {\n const pattern = compileTokenPattern(format.pattern);\n\n for (const word of pattern ? words : []) {\n if (pattern!.test(word)) {\n found ??= { plugin, label: format.label };\n tokens.add(word);\n }\n }\n }\n }\n\n return found ? { ...found, tokens: [...tokens] } : null;\n}\n","import type { FormEvent, JSX } from 'react';\nimport { useId, useState, useSyncExternalStore } from 'react';\nimport { ExternalLinkIcon, LoaderCircle } from 'lucide-react';\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Input,\n} from '../../ui';\nimport type { ApiClient } from './api';\nimport { connectPluginPopup } from './plugin-oauth';\nimport {\n credentialFormComplete,\n credentialFormError,\n credentialFormFields,\n matchesTokenPattern,\n type ConnectablePlugin,\n} from './plugin-token-format';\nimport type { PluginApiTokenConnect, PluginCredentialsConnect, PluginScope } from './plugin-types';\n\ninterface TokenRequest {\n id: number;\n plugin: ConnectablePlugin & { connect: PluginApiTokenConnect };\n /** Saves the token; rejects with a message the dialog shows next to the field. */\n submit: (_token: string) => Promise<void>;\n settle: (_connected: boolean) => void;\n}\n\ninterface CredentialsRequest {\n id: number;\n plugin: ConnectablePlugin & { connect: PluginCredentialsConnect };\n /** Saves the form; rejects with a message the dialog shows under the fields. */\n submit: (_method: string | undefined, _values: { [key: string]: string }) => Promise<void>;\n settle: (_connected: boolean) => void;\n}\n\ntype FormRequest = ({ kind: 'token' } & TokenRequest) | ({ kind: 'credentials' } & CredentialsRequest);\n\n/** The one open connect form, outside React so any connect button can open it. */\nlet request: FormRequest | null = null;\nlet lastRequestId = 0;\n/** Cancels the latest request, whether its dialog has opened yet or not. */\nlet cancelLatest: (() => void) | null = null;\nconst listeners = new Set<() => void>();\n\nfunction setRequest(next: FormRequest | null): void {\n request = next;\n listeners.forEach((listener) => listener());\n}\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener);\n\n return () => listeners.delete(listener);\n}\n\n/**\n * Connects a plugin: a sign-in popup for OAuth plugins, the token dialog for\n * plugins that take a pasted token, the credentials dialog for plugins that\n * take the credentials of an app the user created at the provider. Resolves\n * `false` when the user closes a dialog without connecting.\n *\n * Call it straight from a click handler: browsers only allow the popup there.\n */\nexport function connectPlugin(\n api: ApiClient,\n plugin: ConnectablePlugin,\n scope: PluginScope,\n options?: { connectionId?: string }\n): Promise<boolean> {\n const { connect } = plugin;\n\n if (connect?.type !== 'api-token' && connect?.type !== 'credentials') {\n return connectPluginPopup(api, plugin.id, scope, options).then(() => true);\n }\n\n // Opening a second dialog closes the first, as if cancelled.\n cancelLatest?.();\n\n const id = ++lastRequestId;\n const connectionId = options?.connectionId ? { connectionId: options.connectionId } : {};\n\n return new Promise<boolean>((resolve) => {\n const settle = (connected: boolean): void => {\n // A save still running for a replaced dialog must not close its successor.\n if (request?.id === id) {\n setRequest(null);\n }\n\n if (lastRequestId === id) {\n cancelLatest = null;\n }\n\n resolve(connected);\n };\n const next: FormRequest =\n connect.type === 'api-token'\n ? {\n kind: 'token',\n id,\n plugin: { ...plugin, connect },\n submit: async (token) => {\n await api.connectPluginToken({ pluginId: plugin.id, scope, token, ...connectionId });\n },\n settle,\n }\n : {\n kind: 'credentials',\n id,\n plugin: { ...plugin, connect },\n submit: async (method, values) => {\n await api.connectPluginCredentials({ pluginId: plugin.id, scope, method, values, ...connectionId });\n },\n settle,\n };\n\n cancelLatest = () => settle(false);\n\n // Open after the current event: a menu item that started this closes first\n // and returns focus to its trigger, which would take it from the first field.\n setTimeout(() => {\n if (lastRequestId === id) {\n setRequest(next);\n }\n });\n });\n}\n\nfunction httpsHref(value: string | null): string | null {\n if (!value) {\n return null;\n }\n\n try {\n const url = new URL(value);\n\n return url.protocol === 'https:' ? url.href : null;\n } catch {\n return null;\n }\n}\n\n/** Mounted once by the Studio layout; renders the dialog `connectPlugin` opens for token and credentials plugins. */\nexport function PluginTokenDialogHost(): JSX.Element | null {\n const current = useSyncExternalStore(\n subscribe,\n () => request,\n () => null\n );\n\n if (!current) {\n return null;\n }\n\n // A new key per request resets the fields, so a secret never outlives its dialog.\n return current.kind === 'token' ? (\n <PluginTokenDialog key={current.id} request={current} />\n ) : (\n <PluginCredentialsDialog key={current.id} request={current} />\n );\n}\n\nfunction FieldError({ id, message }: { id: string; message: string | null }): JSX.Element | null {\n return message ? (\n <p className=\"fk:text-sm fk:text-destructive\" id={id}>\n {message}\n </p>\n ) : null;\n}\n\nfunction HelpLink({ href, label }: { href: string | null; label: string }): JSX.Element | null {\n const safeHref = httpsHref(href);\n\n return safeHref ? (\n <a\n className=\"fk:inline-flex fk:items-center fk:gap-1 fk:text-sm fk:text-muted-foreground fk:underline-offset-4 fk:hover:underline\"\n href={safeHref}\n rel=\"noreferrer\"\n target=\"_blank\"\n >\n {label}\n <ExternalLinkIcon className=\"fk:size-3.5\" />\n </a>\n ) : null;\n}\n\nfunction PluginCredentialsDialog({ request: current }: { request: CredentialsRequest }): JSX.Element {\n const { connect, name } = current.plugin;\n const formId = useId();\n const [method, setMethod] = useState<string | null>(connect.methods[0]?.key ?? null);\n const [values, setValues] = useState<{ [key: string]: string }>({});\n const [error, setError] = useState<{ field: string | null; message: string } | null>(null);\n const [saving, setSaving] = useState(false);\n const fields = credentialFormFields(connect, method);\n const selectedMethod = connect.methods.find((item) => item.key === method) ?? null;\n // Submitting surfaces which field is malformed; the button only waits for the required values.\n const ready = credentialFormComplete(fields, values);\n\n async function save(event: FormEvent): Promise<void> {\n event.preventDefault();\n\n if (saving) {\n return;\n }\n\n const problem = credentialFormError(fields, values);\n\n if (problem) {\n setError(problem);\n\n return;\n }\n\n setSaving(true);\n setError(null);\n\n try {\n await current.submit(\n method ?? undefined,\n Object.fromEntries(fields.map((field) => [field.key, values[field.key]?.trim() ?? '']).filter(([, value]) => value))\n );\n setValues({});\n current.settle(true);\n } catch (failure) {\n setError({ field: null, message: failure instanceof Error ? failure.message : `${name} could not be connected.` });\n } finally {\n setSaving(false);\n }\n }\n\n return (\n <Dialog\n open\n onOpenChange={(open) => {\n if (!open && !saving) {\n current.settle(false);\n }\n }}\n >\n <DialogContent>\n <form className=\"fk:flex fk:flex-col fk:gap-4\" onSubmit={(event) => void save(event)}>\n <DialogHeader>\n <DialogTitle>Connect {name}</DialogTitle>\n <DialogDescription>\n {connect.description} Flexkit checks the credentials with {name}, stores them encrypted and sends them\n only to Flexkit&apos;s own {name} server; the agent can use the tools but never sees them.\n </DialogDescription>\n </DialogHeader>\n {connect.methods.length > 1 ? (\n <div className=\"fk:space-y-1.5\" role=\"group\" aria-label=\"How to connect\">\n {connect.methods.map((item) => (\n <button\n aria-pressed={method === item.key}\n className={`fk:flex fk:w-full fk:flex-col fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:corner-squircle ${\n method === item.key ? 'fk:border-primary fk:bg-primary/5' : 'fk:border-border fk:hover:bg-muted/60'\n }`}\n disabled={saving}\n key={item.key}\n onClick={() => {\n setMethod(item.key);\n setError(null);\n }}\n type=\"button\"\n >\n <span className=\"fk:text-sm fk:font-medium\">{item.label}</span>\n {item.description ? (\n <span className=\"fk:text-xs fk:text-muted-foreground\">{item.description}</span>\n ) : null}\n </button>\n ))}\n </div>\n ) : selectedMethod?.description ? (\n <p className=\"fk:text-sm fk:text-muted-foreground\">{selectedMethod.description}</p>\n ) : null}\n {fields.map((field, index) => {\n const inputId = `${formId}-${field.key}`;\n const fieldError = error?.field === field.key ? error.message : null;\n\n return (\n <div className=\"fk:flex fk:flex-col fk:gap-2\" key={field.key}>\n <label className=\"fk:text-sm fk:font-medium\" htmlFor={inputId}>\n {field.label}\n </label>\n <Input\n aria-describedby={fieldError ? `${inputId}-error` : field.help ? `${inputId}-help` : undefined}\n aria-invalid={fieldError ? true : undefined}\n autoComplete=\"off\"\n autoFocus={index === 0}\n disabled={saving}\n id={inputId}\n placeholder={field.placeholder ?? undefined}\n spellCheck={false}\n type={field.kind === 'secret' ? 'password' : 'text'}\n value={values[field.key] ?? ''}\n onChange={(event) => {\n setValues((previous) => ({ ...previous, [field.key]: event.target.value }));\n setError(null);\n }}\n />\n {field.help && !fieldError ? (\n <p className=\"fk:text-sm fk:text-muted-foreground\" id={`${inputId}-help`}>\n {field.help}\n </p>\n ) : null}\n <FieldError id={`${inputId}-error`} message={fieldError} />\n </div>\n );\n })}\n <FieldError id={`${formId}-error`} message={error?.field === null ? error.message : null} />\n <HelpLink href={connect.helpUrl} label={`How to set up ${name}`} />\n <DialogFooter>\n <Button disabled={saving} size=\"sm\" type=\"button\" variant=\"outline\" onClick={() => current.settle(false)}>\n Cancel\n </Button>\n <Button disabled={saving || !ready} size=\"sm\" type=\"submit\">\n {saving ? <LoaderCircle className=\"fk:size-4 fk:animate-spin\" /> : null}\n Connect\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n\nfunction PluginTokenDialog({ request: current }: { request: TokenRequest }): JSX.Element {\n const { connect, name } = current.plugin;\n const inputId = useId();\n const [token, setToken] = useState('');\n const [error, setError] = useState<string | null>(null);\n const [saving, setSaving] = useState(false);\n\n async function save(event: FormEvent): Promise<void> {\n event.preventDefault();\n const value = token.trim();\n\n if (saving || !value) {\n return;\n }\n\n if (!matchesTokenPattern(value, connect.pattern)) {\n setError(`That does not look like a ${connect.tokenLabel}.`);\n\n return;\n }\n\n setSaving(true);\n setError(null);\n\n try {\n await current.submit(value);\n setToken('');\n current.settle(true);\n } catch (failure) {\n setError(failure instanceof Error ? failure.message : `${name} could not be connected.`);\n } finally {\n setSaving(false);\n }\n }\n\n return (\n <Dialog\n open\n onOpenChange={(open) => {\n if (!open && !saving) {\n current.settle(false);\n }\n }}\n >\n <DialogContent>\n <form className=\"fk:flex fk:flex-col fk:gap-4\" onSubmit={(event) => void save(event)}>\n <DialogHeader>\n <DialogTitle>Connect {name}</DialogTitle>\n <DialogDescription>\n Paste a {connect.tokenLabel}. Flexkit stores it encrypted and sends it only to {name}; the agent can use{' '}\n {name}&apos;s tools but never sees the token. Give it read access only, unless the agent should change\n things in {name}.\n </DialogDescription>\n </DialogHeader>\n <div className=\"fk:flex fk:flex-col fk:gap-2\">\n <label className=\"fk:text-sm fk:font-medium\" htmlFor={inputId}>\n {connect.tokenLabel}\n </label>\n <Input\n aria-describedby={error ? `${inputId}-error` : undefined}\n aria-invalid={error ? true : undefined}\n autoComplete=\"off\"\n autoFocus\n disabled={saving}\n id={inputId}\n placeholder={connect.placeholder ?? undefined}\n spellCheck={false}\n type=\"password\"\n value={token}\n onChange={(event) => {\n setToken(event.target.value);\n setError(null);\n }}\n />\n <FieldError id={`${inputId}-error`} message={error} />\n <HelpLink href={connect.helpUrl} label={`How to create a ${connect.tokenLabel}`} />\n </div>\n <DialogFooter>\n <Button disabled={saving} size=\"sm\" type=\"button\" variant=\"outline\" onClick={() => current.settle(false)}>\n Cancel\n </Button>\n <Button disabled={saving || !token.trim()} size=\"sm\" type=\"submit\">\n {saving ? <LoaderCircle className=\"fk:size-4 fk:animate-spin\" /> : null}\n Connect\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n"]}
@@ -1,3 +1,3 @@
1
- import'./index.css';import {f as f$1}from'./chunk-TWALS64F.js';import {ApolloClient,InMemoryCache,defaultDataIdFromObject,from,HttpLink}from'@apollo/client';import {ApolloProvider}from'@apollo/client/react';import {ErrorLink}from'@apollo/client/link/error';import {ServerError,CombinedGraphQLErrors,CombinedProtocolErrors}from'@apollo/client/errors';import {createContext,useContext,useState,useMemo,useReducer}from'react';import {jsx}from'react/jsx-runtime';import {uniqBy,props}from'ramda';function A(r){return r?"cause"in r:false}function f(r){if(!r)return null;if(ServerError.is(r))return r;if(A(r)){let e=r.cause;if(ServerError.is(e))return e}return null}function L(r){if(!r||typeof r!="object")return null;let{message:e}=r;return typeof e=="string"?e:null}function d(r){if(!r)return null;try{return JSON.parse(r)}catch{return null}}function k(r){if(!r)return null;let e=C(r).filter(t=>!I(t));return e.length===0?null:["The deployed schema is out of sync with your local Flexkit schema.","Run `flexkit deploy` using the CLI to apply your latest schema changes.",...e.map(t=>`- ${t}`)].join(`
2
- `)}function er(r,e){return r?C(r).some(t=>t.includes(`Cannot query field "${e}"`)):false}function C(r){if(CombinedGraphQLErrors.is(r))return r.errors.filter(y).map(({message:o})=>o);let e=L(r);if(e&&a(e))return [e];let t=f(r);if(t?.statusCode!==400)return [];let n=d(t.bodyText)??P(t)??b(r);return n?Array.isArray(n.errors)?n.errors.filter(y).map(o=>o.message):typeof n.message=="string"&&a(n.message)?[n.message]:typeof n.error=="string"&&a(n.error)?[n.error]:[]:[]}function P(r){let{result:e}=r;return !e||typeof e!="object"?null:e}function b(r){if(!A(r))return null;let{cause:e}=r,t=L(e);if(t&&a(t))return {message:t};if(!e||typeof e!="object")return null;let{result:n}=e;return n&&typeof n=="object"?n:null}function y(r){if(!r||typeof r!="object")return false;let{extensions:e,message:t}=r;return e?.code==="GRAPHQL_VALIDATION_FAILED"&&typeof t=="string"?true:typeof t=="string"&&a(t)}function a(r){return r.startsWith("Cannot query field ")||r.startsWith("Unknown type ")||r.startsWith('Cannot query field "')||r.includes("GRAPHQL_VALIDATION_FAILED")}function I(r){return /Cannot query field "[_A-Za-z][_0-9A-Za-z]*Total" on type "Query"/.test(r)}var U=ApolloProvider,v=createContext(void 0);function pr(){let r=useContext(v);if(!r)throw new Error("useGraphQLError must be used within GraphQLProvider");return r}var fr={userQuery:true};function H(r){return new ErrorLink(({error:e,operation:t})=>{if(t.getContext().userQuery===true)return;let n=k(e);if(n){r(n);return}CombinedGraphQLErrors.is(e)?e.errors.forEach(({message:s,locations:i,path:c})=>{console.warn(`[GraphQL error]: Message: ${s}, Location: ${i}, Path: ${c}`);}):CombinedProtocolErrors.is(e)&&e.errors.forEach(({message:s,extensions:i})=>{console.warn(`[Protocol error]: Message: ${s}, Extensions: ${JSON.stringify(i)}`);});let o=f(e);if(o?.statusCode===400){let s=d(o.bodyText),i=null;if(s&&typeof s=="object"){let{error:c,errors:g,message:E}=s;if(typeof E=="string")i=E;else if(Array.isArray(g)){let[p]=g;if(p&&typeof p.message=="string"){let{message:D}=p;i=D;}}else typeof c=="string"?i=c:i=JSON.stringify(s);}else i=o.bodyText;r(i??"There is an error in the deployed Flexkit schema. Fix flexkit.config.ts and run flexkit deploy.");}if(o){console.warn(`[Network error]: ${o.message}`);return}e&&console.warn(`[Network error]: ${e.message}`);})}function z(r,e){return from([H(e),new HttpLink({uri:`/api/flexkit/${r}/graphql`})])}function Z(r,e){return new ApolloClient({link:z(r??"",e),cache:new InMemoryCache({dataIdFromObject:t=>t._id?t._id:defaultDataIdFromObject(t)})})}function dr({children:r}){let{currentProjectId:e}=f$1(),[t,n]=useState(null),o=useMemo(()=>({schemaErrorMessage:t,setSchemaErrorMessage:n}),[t]),s=useMemo(()=>Z(e,n),[e]);return jsx(v.Provider,{value:o,children:jsx(U,{client:s,children:r})})}var G=createContext([]),M=createContext(()=>{});function K(r,e){let t=e.type;switch(e._id||(e._id=Date.now().toString()),t){case "DeleteEntity":return uniqBy(props(["type","_id"]),[...r,e]);case "AddEntity":return uniqBy(props(["type","_id"]),[...r,e]);case "EditEntity":return uniqBy(props(["type","_id"]),[...r,e]);case "EditRelationship":return uniqBy(props(["type","_id"]),[...r,e]);case "AlertDialog":return uniqBy(props(["type","_id"]),[...r,e]);case "Dismiss":return r.filter(n=>n._id!==e._id);default:throw Error(`Unknown action: ${t}`)}}function yr({children:r}){let[e,t]=useReducer(K,[]);return jsx(G.Provider,{value:e,children:jsx(M.Provider,{value:t,children:r})})}function Ar(){return useContext(G)}function Lr(){return useContext(M)}export{f as a,d as b,k as c,er as d,pr as e,fr as f,dr as g,yr as h,Ar as i,Lr as j};//# sourceMappingURL=chunk-I4UFLN53.js.map
3
- //# sourceMappingURL=chunk-I4UFLN53.js.map
1
+ import'./index.css';import {f as f$1}from'./chunk-H534S4KD.js';import {ApolloClient,InMemoryCache,defaultDataIdFromObject,from,HttpLink}from'@apollo/client';import {ApolloProvider}from'@apollo/client/react';import {ErrorLink}from'@apollo/client/link/error';import {ServerError,CombinedGraphQLErrors,CombinedProtocolErrors}from'@apollo/client/errors';import {createContext,useContext,useState,useMemo,useReducer}from'react';import {jsx}from'react/jsx-runtime';import {uniqBy,props}from'ramda';function A(r){return r?"cause"in r:false}function f(r){if(!r)return null;if(ServerError.is(r))return r;if(A(r)){let e=r.cause;if(ServerError.is(e))return e}return null}function L(r){if(!r||typeof r!="object")return null;let{message:e}=r;return typeof e=="string"?e:null}function d(r){if(!r)return null;try{return JSON.parse(r)}catch{return null}}function k(r){if(!r)return null;let e=C(r).filter(t=>!I(t));return e.length===0?null:["The deployed schema is out of sync with your local Flexkit schema.","Run `flexkit deploy` using the CLI to apply your latest schema changes.",...e.map(t=>`- ${t}`)].join(`
2
+ `)}function er(r,e){return r?C(r).some(t=>t.includes(`Cannot query field "${e}"`)):false}function C(r){if(CombinedGraphQLErrors.is(r))return r.errors.filter(y).map(({message:o})=>o);let e=L(r);if(e&&a(e))return [e];let t=f(r);if(t?.statusCode!==400)return [];let n=d(t.bodyText)??P(t)??b(r);return n?Array.isArray(n.errors)?n.errors.filter(y).map(o=>o.message):typeof n.message=="string"&&a(n.message)?[n.message]:typeof n.error=="string"&&a(n.error)?[n.error]:[]:[]}function P(r){let{result:e}=r;return !e||typeof e!="object"?null:e}function b(r){if(!A(r))return null;let{cause:e}=r,t=L(e);if(t&&a(t))return {message:t};if(!e||typeof e!="object")return null;let{result:n}=e;return n&&typeof n=="object"?n:null}function y(r){if(!r||typeof r!="object")return false;let{extensions:e,message:t}=r;return e?.code==="GRAPHQL_VALIDATION_FAILED"&&typeof t=="string"?true:typeof t=="string"&&a(t)}function a(r){return r.startsWith("Cannot query field ")||r.startsWith("Unknown type ")||r.startsWith('Cannot query field "')||r.includes("GRAPHQL_VALIDATION_FAILED")}function I(r){return /Cannot query field "[_A-Za-z][_0-9A-Za-z]*Total" on type "Query"/.test(r)}var U=ApolloProvider,v=createContext(void 0);function pr(){let r=useContext(v);if(!r)throw new Error("useGraphQLError must be used within GraphQLProvider");return r}var fr={userQuery:true};function H(r){return new ErrorLink(({error:e,operation:t})=>{if(t.getContext().userQuery===true)return;let n=k(e);if(n){r(n);return}CombinedGraphQLErrors.is(e)?e.errors.forEach(({message:s,locations:i,path:c})=>{console.warn(`[GraphQL error]: Message: ${s}, Location: ${i}, Path: ${c}`);}):CombinedProtocolErrors.is(e)&&e.errors.forEach(({message:s,extensions:i})=>{console.warn(`[Protocol error]: Message: ${s}, Extensions: ${JSON.stringify(i)}`);});let o=f(e);if(o?.statusCode===400){let s=d(o.bodyText),i=null;if(s&&typeof s=="object"){let{error:c,errors:g,message:E}=s;if(typeof E=="string")i=E;else if(Array.isArray(g)){let[p]=g;if(p&&typeof p.message=="string"){let{message:D}=p;i=D;}}else typeof c=="string"?i=c:i=JSON.stringify(s);}else i=o.bodyText;r(i??"There is an error in the deployed Flexkit schema. Fix flexkit.config.ts and run flexkit deploy.");}if(o){console.warn(`[Network error]: ${o.message}`);return}e&&console.warn(`[Network error]: ${e.message}`);})}function z(r,e){return from([H(e),new HttpLink({uri:`/api/flexkit/${r}/graphql`})])}function Z(r,e){return new ApolloClient({link:z(r??"",e),cache:new InMemoryCache({dataIdFromObject:t=>t._id?t._id:defaultDataIdFromObject(t)})})}function dr({children:r}){let{currentProjectId:e}=f$1(),[t,n]=useState(null),o=useMemo(()=>({schemaErrorMessage:t,setSchemaErrorMessage:n}),[t]),s=useMemo(()=>Z(e,n),[e]);return jsx(v.Provider,{value:o,children:jsx(U,{client:s,children:r})})}var G=createContext([]),M=createContext(()=>{});function K(r,e){let t=e.type;switch(e._id||(e._id=Date.now().toString()),t){case "DeleteEntity":return uniqBy(props(["type","_id"]),[...r,e]);case "AddEntity":return uniqBy(props(["type","_id"]),[...r,e]);case "EditEntity":return uniqBy(props(["type","_id"]),[...r,e]);case "EditRelationship":return uniqBy(props(["type","_id"]),[...r,e]);case "AlertDialog":return uniqBy(props(["type","_id"]),[...r,e]);case "Dismiss":return r.filter(n=>n._id!==e._id);default:throw Error(`Unknown action: ${t}`)}}function yr({children:r}){let[e,t]=useReducer(K,[]);return jsx(G.Provider,{value:e,children:jsx(M.Provider,{value:t,children:r})})}function Ar(){return useContext(G)}function Lr(){return useContext(M)}export{f as a,d as b,k as c,er as d,pr as e,fr as f,dr as g,yr as h,Ar as i,Lr as j};//# sourceMappingURL=chunk-6A6NT3H3.js.map
3
+ //# sourceMappingURL=chunk-6A6NT3H3.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graphql-client/error-utils.ts","../src/graphql-client/graphql-context.tsx","../src/entities/actions-context.tsx"],"names":["hasCause","error","getServerError","ServerError","possibleServerError","getErrorMessage","message","parseErrorBody","bodyText","getGraphQLSchemaMismatchMessage","messages","getGraphQLValidationMessages","isMissingCountStoreFieldMessage","isMissingGraphQLFieldError","fieldName","CombinedGraphQLErrors","isSchemaValidationError","directMessage","isSchemaValidationMessage","serverError","responseBody","getServerErrorResult","getErrorCauseResponse","item","result","cause","causeMessage","extensions","ApolloProviderCompat","ApolloProvider","GraphQLErrorContext","createContext","useGraphQLError","ctx","useContext","USER_QUERY_CONTEXT","createErrorLink","setSchemaErrorMessage","ErrorLink","operation","schemaMismatchMessage","locations","path","CombinedProtocolErrors","responseError","errors","responseMessage","firstError","firstErrorMessage","additiveLink","currentProjectId","from","HttpLink","client","ApolloClient","InMemoryCache","responseObject","defaultDataIdFromObject","GraphQLProvider","children","useConfig","schemaErrorMessage","useState","useMemo","apolloClient","jsx","ActionsContext","EntityDispatchContext","actionsReducer","actions","action","actionType","uniqBy","props","ActionsProvider","entityActions","dispatchEntityActions","useReducer","useActions","useDispatch"],"mappings":"4eAsBA,SAASA,CAAAA,CAASC,EAA2C,CAC3D,OAAKA,EAIE,OAAA,GAAYA,CAAAA,CAHV,KAIX,CAEO,SAASC,CAAAA,CAAeD,CAAAA,CAAuC,CACpE,GAAI,CAACA,CAAAA,CACH,OAAO,IAAA,CAGT,GAAIE,YAAY,EAAA,CAAGF,CAAK,EACtB,OAAOA,CAAAA,CAGT,GAAID,CAAAA,CAASC,CAAK,CAAA,CAAG,CACnB,IAAMG,CAAAA,CAAsBH,CAAAA,CAAM,KAAA,CAElC,GAAIE,YAAY,EAAA,CAAGC,CAAmB,CAAA,CACpC,OAAOA,CAEX,CAEA,OAAO,IACT,CAEA,SAASC,EAAgBJ,CAAAA,CAA+B,CACtD,GAAI,CAACA,GAAS,OAAOA,CAAAA,EAAU,QAAA,CAC7B,OAAO,KAGT,GAAM,CAAE,OAAA,CAAAK,CAAQ,EAAIL,CAAAA,CAEpB,OAAO,OAAOK,CAAAA,EAAY,SAAWA,CAAAA,CAAU,IACjD,CAEO,SAASC,EAAkBC,CAAAA,CAAwC,CACxE,GAAI,CAACA,EACH,OAAO,IAAA,CAGT,GAAI,CACF,OAAO,IAAA,CAAK,KAAA,CAAMA,CAAQ,CAC5B,CAAA,KAAQ,CACN,OAAO,IACT,CACF,CAEO,SAASC,CAAAA,CAAgCR,CAAAA,CAAkC,CAChF,GAAI,CAACA,CAAAA,CACH,OAAO,IAAA,CAGT,IAAMS,EAAWC,CAAAA,CAA6BV,CAAK,EAAE,M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,CAAAA,CAAO,GAAG,CAAA,CAEzD,QACE,MAAM,KAAA,CAAM,CAAA,gBAAA,EAAmBC,CAAoB,CAAA,CAAE,CAEzD,CACF,CAEA,SAASG,EAAAA,CAAgB,CAAE,QAAA,CAAAf,CAAS,EAAyC,CAC3E,GAAM,CAACgB,CAAAA,CAAeC,CAAqB,CAAA,CAAIC,WAAWT,CAAAA,CAAgB,EAAE,CAAA,CAE5E,OACEH,IAACC,CAAAA,CAAe,QAAA,CAAf,CAAwB,KAAA,CAAOS,CAAAA,CAC9B,QAAA,CAAAV,IAACE,CAAAA,CAAsB,QAAA,CAAtB,CAA+B,KAAA,CAAOS,CAAAA,CAAwB,SAAAjB,CAAAA,CAAS,CAAA,CAC1E,CAEJ,CAEA,SAASmB,EAAAA,EAAuB,CAC9B,OAAO5C,UAAAA,CAAWgC,CAAc,CAClC,CAEA,SAASa,IAAgC,CACvC,OAAO7C,UAAAA,CAAWiC,CAAqB,CACzC","file":"chunk-I4UFLN53.js","sourcesContent":["import type { ErrorLike } from '@apollo/client';\nimport { CombinedGraphQLErrors, ServerError } from '@apollo/client/errors';\n\ntype ErrorWithCause = ErrorLike & { cause?: unknown };\ntype ErrorWithMessage = {\n message?: unknown;\n};\ntype ServerErrorWithResult = ServerError & {\n result?: unknown;\n};\ntype GraphQLErrorResponse = {\n error?: unknown;\n errors?: unknown;\n message?: unknown;\n};\ntype GraphQLErrorItem = {\n extensions?: {\n code?: unknown;\n };\n message?: unknown;\n};\n\nfunction hasCause(error: ErrorLike): error is ErrorWithCause {\n if (!error) {\n return false;\n }\n\n return 'cause' in (error as ErrorWithCause);\n}\n\nexport function getServerError(error?: ErrorLike): ServerError | null {\n if (!error) {\n return null;\n }\n\n if (ServerError.is(error)) {\n return error;\n }\n\n if (hasCause(error)) {\n const possibleServerError = error.cause;\n\n if (ServerError.is(possibleServerError)) {\n return possibleServerError;\n }\n }\n\n return null;\n}\n\nfunction getErrorMessage(error: unknown): string | null {\n if (!error || typeof error !== 'object') {\n return null;\n }\n\n const { message } = error as ErrorWithMessage;\n\n return typeof message === 'string' ? message : null;\n}\n\nexport function parseErrorBody<T>(bodyText: string | undefined): T | null {\n if (!bodyText) {\n return null;\n }\n\n try {\n return JSON.parse(bodyText) as T;\n } catch {\n return null;\n }\n}\n\nexport function getGraphQLSchemaMismatchMessage(error?: ErrorLike): string | null {\n if (!error) {\n return null;\n }\n\n const messages = getGraphQLValidationMessages(error).filter((message) => !isMissingCountStoreFieldMessage(message));\n\n if (messages.length === 0) {\n return null;\n }\n\n return [\n 'The deployed schema is out of sync with your local Flexkit schema.',\n 'Run `flexkit deploy` using the CLI to apply your latest schema changes.',\n ...messages.map((message) => `- ${message}`),\n ].join('\\n');\n}\n\nexport function isMissingGraphQLFieldError(error: ErrorLike | undefined, fieldName: string): boolean {\n if (!error) {\n return false;\n }\n\n return getGraphQLValidationMessages(error).some((message) => {\n return message.includes(`Cannot query field \"${fieldName}\"`);\n });\n}\n\nfunction getGraphQLValidationMessages(error: ErrorLike): string[] {\n if (CombinedGraphQLErrors.is(error)) {\n return error.errors.filter(isSchemaValidationError).map(({ message }) => message);\n }\n\n const directMessage = getErrorMessage(error);\n\n if (directMessage && isSchemaValidationMessage(directMessage)) {\n return [directMessage];\n }\n\n const serverError = getServerError(error);\n\n if (serverError?.statusCode !== 400) {\n return [];\n }\n\n const responseBody =\n parseErrorBody<GraphQLErrorResponse>(serverError.bodyText) ??\n getServerErrorResult(serverError) ??\n getErrorCauseResponse(error);\n\n if (!responseBody) {\n return [];\n }\n\n if (Array.isArray(responseBody.errors)) {\n return responseBody.errors.filter(isSchemaValidationError).map((item) => item.message);\n }\n\n if (typeof responseBody.message === 'string' && isSchemaValidationMessage(responseBody.message)) {\n return [responseBody.message];\n }\n\n if (typeof responseBody.error === 'string' && isSchemaValidationMessage(responseBody.error)) {\n return [responseBody.error];\n }\n\n return [];\n}\n\nfunction getServerErrorResult(serverError: ServerError): GraphQLErrorResponse | null {\n const { result } = serverError as ServerErrorWithResult;\n\n if (!result || typeof result !== 'object') {\n return null;\n }\n\n return result as GraphQLErrorResponse;\n}\n\nfunction getErrorCauseResponse(error: ErrorLike): GraphQLErrorResponse | null {\n if (!hasCause(error)) {\n return null;\n }\n\n const { cause } = error;\n const causeMessage = getErrorMessage(cause);\n\n if (causeMessage && isSchemaValidationMessage(causeMessage)) {\n return { message: causeMessage };\n }\n\n if (!cause || typeof cause !== 'object') {\n return null;\n }\n\n const { result } = cause as { result?: unknown };\n\n if (result && typeof result === 'object') {\n return result as GraphQLErrorResponse;\n }\n\n return null;\n}\n\nfunction isSchemaValidationError(error: unknown): error is GraphQLErrorItem & { message: string } {\n if (!error || typeof error !== 'object') {\n return false;\n }\n\n const { extensions, message } = error as GraphQLErrorItem;\n const code = extensions?.code;\n\n if (code === 'GRAPHQL_VALIDATION_FAILED' && typeof message === 'string') {\n return true;\n }\n\n return typeof message === 'string' && isSchemaValidationMessage(message);\n}\n\nfunction isSchemaValidationMessage(message: string): boolean {\n return (\n message.startsWith('Cannot query field ') ||\n message.startsWith('Unknown type ') ||\n message.startsWith('Cannot query field \"') ||\n message.includes('GRAPHQL_VALIDATION_FAILED')\n );\n}\n\nfunction isMissingCountStoreFieldMessage(message: string): boolean {\n return /Cannot query field \"[_A-Za-z][_0-9A-Za-z]*Total\" on type \"Query\"/.test(message);\n}\n","'use client';\n\nimport type { JSX } from 'react';\nimport { ApolloClient, InMemoryCache, defaultDataIdFromObject, from, HttpLink } from '@apollo/client';\nimport type { ApolloLink } from '@apollo/client';\nimport { ApolloProvider } from '@apollo/client/react';\nimport { ErrorLink } from '@apollo/client/link/error';\nimport { CombinedGraphQLErrors, CombinedProtocolErrors } from '@apollo/client/errors';\nimport { getGraphQLSchemaMismatchMessage, getServerError, parseErrorBody } from './error-utils';\nimport { useConfig } from '../core/config/config-context';\nimport React, { createContext, useContext, useMemo, useState } from 'react';\n\nconst ApolloProviderCompat = ApolloProvider as unknown as React.ComponentType<{\n children?: React.ReactNode;\n client: ApolloClient;\n}>;\n\ntype GraphQLErrorContextValue = {\n schemaErrorMessage: string | null;\n setSchemaErrorMessage: React.Dispatch<React.SetStateAction<string | null>>;\n};\n\nconst GraphQLErrorContext = createContext<GraphQLErrorContextValue | undefined>(undefined);\n\nfunction useGraphQLError(): GraphQLErrorContextValue {\n const ctx = useContext(GraphQLErrorContext);\n\n if (!ctx) {\n throw new Error('useGraphQLError must be used within GraphQLProvider');\n }\n\n return ctx;\n}\n\n/**\n * Context flag for operations the user writes themselves (the Graph app's\n * Query view): any error there, a mismatch or a 400, is a typo, not a\n * deployment that drifted from the local schema, so it must not raise the\n * schema banner. The caller shows the error itself.\n */\nexport const USER_QUERY_CONTEXT = { userQuery: true } as const;\n\nfunction createErrorLink(setSchemaErrorMessage: (msg: string | null) => void): ApolloLink {\n return new ErrorLink(({ error, operation }) => {\n if (operation.getContext().userQuery === true) {\n return;\n }\n\n const schemaMismatchMessage = getGraphQLSchemaMismatchMessage(error);\n\n if (schemaMismatchMessage) {\n setSchemaErrorMessage(schemaMismatchMessage);\n\n return;\n }\n\n if (CombinedGraphQLErrors.is(error)) {\n error.errors.forEach(({ message, locations, path }) => {\n console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);\n });\n } else if (CombinedProtocolErrors.is(error)) {\n error.errors.forEach(({ message, extensions }) => {\n console.warn(`[Protocol error]: Message: ${message}, Extensions: ${JSON.stringify(extensions)}`);\n });\n }\n\n const serverError = getServerError(error);\n\n if (serverError?.statusCode === 400) {\n const responseBody = parseErrorBody<Record<string, unknown>>(serverError.bodyText);\n let message: string | null = null;\n\n if (responseBody && typeof responseBody === 'object') {\n const {\n error: responseError,\n errors,\n message: responseMessage,\n } = responseBody as {\n error?: unknown;\n errors?: unknown;\n message?: unknown;\n };\n\n if (typeof responseMessage === 'string') {\n message = responseMessage;\n } else if (Array.isArray(errors)) {\n const [firstError] = errors as { message?: unknown }[];\n\n if (firstError && typeof firstError.message === 'string') {\n const { message: firstErrorMessage } = firstError;\n message = firstErrorMessage;\n }\n } else if (typeof responseError === 'string') {\n message = responseError;\n } else {\n message = JSON.stringify(responseBody);\n }\n } else {\n message = serverError.bodyText;\n }\n\n setSchemaErrorMessage(\n message ?? 'There is an error in the deployed Flexkit schema. Fix flexkit.config.ts and run flexkit deploy.'\n );\n }\n\n if (serverError) {\n console.warn(`[Network error]: ${serverError.message}`);\n\n return;\n }\n\n if (error) {\n console.warn(`[Network error]: ${error.message}`);\n }\n });\n}\n\nfunction additiveLink(currentProjectId: string, setSchemaErrorMessage: (msg: string | null) => void): ApolloLink {\n return from([\n createErrorLink(setSchemaErrorMessage),\n new HttpLink({ uri: `/api/flexkit/${currentProjectId}/graphql` }),\n ]);\n}\n\nfunction client(\n currentProjectId: string | undefined,\n setSchemaErrorMessage: (msg: string | null) => void\n): ApolloClient {\n return new ApolloClient({\n link: additiveLink(currentProjectId ?? '', setSchemaErrorMessage),\n cache: new InMemoryCache({\n dataIdFromObject: (responseObject) => {\n return responseObject._id ? (responseObject._id as string) : defaultDataIdFromObject(responseObject);\n },\n }),\n });\n}\n\nexport function GraphQLProvider({ children }: { children: React.ReactNode }): JSX.Element {\n const { currentProjectId } = useConfig();\n const [schemaErrorMessage, setSchemaErrorMessage] = useState<string | null>(null);\n const ctx = useMemo(() => ({ schemaErrorMessage, setSchemaErrorMessage }), [schemaErrorMessage]);\n const apolloClient = useMemo(() => client(currentProjectId, setSchemaErrorMessage), [currentProjectId]);\n\n return (\n <GraphQLErrorContext.Provider value={ctx}>\n <ApolloProviderCompat client={apolloClient}>{children}</ApolloProviderCompat>\n </GraphQLErrorContext.Provider>\n );\n}\n\nexport { useGraphQLError };\n","'use client';\n\nimport { createContext, useContext, useReducer } from 'react';\nimport type { Dispatch, JSX, ReactNode } from 'react';\nimport { props, uniqBy } from 'ramda';\nimport type {\n Action,\n ActionAddEntity,\n ActionAlertDialog,\n ActionDeleteEntity,\n ActionEditEntity,\n ActionEditRelationship,\n} from './types';\n\nconst ActionsContext = createContext<Action[] | []>([]);\nconst EntityDispatchContext = createContext<Dispatch<Action>>(() => undefined);\n\nfunction actionsReducer(actions: Action[], action: Action): Action[] {\n const actionType = action.type;\n\n if (!action._id) {\n action._id = Date.now().toString();\n }\n\n switch (actionType) {\n case 'DeleteEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionDeleteEntity[]), action]);\n }\n case 'AddEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionAddEntity[]), action]);\n }\n case 'EditEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionEditEntity[]), action]);\n }\n case 'EditRelationship': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionEditRelationship[]), action]);\n }\n case 'AlertDialog': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionAlertDialog[]), action]);\n }\n case 'Dismiss': {\n return actions.filter((item) => item._id !== action._id);\n }\n default: {\n throw Error(`Unknown action: ${actionType as string}`);\n }\n }\n}\n\nfunction ActionsProvider({ children }: { children: ReactNode }): JSX.Element {\n const [entityActions, dispatchEntityActions] = useReducer(actionsReducer, []);\n\n return (\n <ActionsContext.Provider value={entityActions}>\n <EntityDispatchContext.Provider value={dispatchEntityActions}>{children}</EntityDispatchContext.Provider>\n </ActionsContext.Provider>\n );\n}\n\nfunction useActions(): Action[] {\n return useContext(ActionsContext);\n}\n\nfunction useDispatch(): Dispatch<Action> {\n return useContext(EntityDispatchContext);\n}\n\nexport { ActionsProvider, useActions, useDispatch };\n"]}
1
+ {"version":3,"sources":["../src/graphql-client/error-utils.ts","../src/graphql-client/graphql-context.tsx","../src/entities/actions-context.tsx"],"names":["hasCause","error","getServerError","ServerError","possibleServerError","getErrorMessage","message","parseErrorBody","bodyText","getGraphQLSchemaMismatchMessage","messages","getGraphQLValidationMessages","isMissingCountStoreFieldMessage","isMissingGraphQLFieldError","fieldName","CombinedGraphQLErrors","isSchemaValidationError","directMessage","isSchemaValidationMessage","serverError","responseBody","getServerErrorResult","getErrorCauseResponse","item","result","cause","causeMessage","extensions","ApolloProviderCompat","ApolloProvider","GraphQLErrorContext","createContext","useGraphQLError","ctx","useContext","USER_QUERY_CONTEXT","createErrorLink","setSchemaErrorMessage","ErrorLink","operation","schemaMismatchMessage","locations","path","CombinedProtocolErrors","responseError","errors","responseMessage","firstError","firstErrorMessage","additiveLink","currentProjectId","from","HttpLink","client","ApolloClient","InMemoryCache","responseObject","defaultDataIdFromObject","GraphQLProvider","children","useConfig","schemaErrorMessage","useState","useMemo","apolloClient","jsx","ActionsContext","EntityDispatchContext","actionsReducer","actions","action","actionType","uniqBy","props","ActionsProvider","entityActions","dispatchEntityActions","useReducer","useActions","useDispatch"],"mappings":"4eAsBA,SAASA,CAAAA,CAASC,EAA2C,CAC3D,OAAKA,EAIE,OAAA,GAAYA,CAAAA,CAHV,KAIX,CAEO,SAASC,CAAAA,CAAeD,CAAAA,CAAuC,CACpE,GAAI,CAACA,CAAAA,CACH,OAAO,IAAA,CAGT,GAAIE,YAAY,EAAA,CAAGF,CAAK,EACtB,OAAOA,CAAAA,CAGT,GAAID,CAAAA,CAASC,CAAK,CAAA,CAAG,CACnB,IAAMG,CAAAA,CAAsBH,CAAAA,CAAM,KAAA,CAElC,GAAIE,YAAY,EAAA,CAAGC,CAAmB,CAAA,CACpC,OAAOA,CAEX,CAEA,OAAO,IACT,CAEA,SAASC,EAAgBJ,CAAAA,CAA+B,CACtD,GAAI,CAACA,GAAS,OAAOA,CAAAA,EAAU,QAAA,CAC7B,OAAO,KAGT,GAAM,CAAE,OAAA,CAAAK,CAAQ,EAAIL,CAAAA,CAEpB,OAAO,OAAOK,CAAAA,EAAY,SAAWA,CAAAA,CAAU,IACjD,CAEO,SAASC,EAAkBC,CAAAA,CAAwC,CACxE,GAAI,CAACA,EACH,OAAO,IAAA,CAGT,GAAI,CACF,OAAO,IAAA,CAAK,KAAA,CAAMA,CAAQ,CAC5B,CAAA,KAAQ,CACN,OAAO,IACT,CACF,CAEO,SAASC,CAAAA,CAAgCR,CAA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,CAAC,EAE/F,KAAK,SAAA,CACH,OAAOD,CAAAA,CAAQ,MAAA,CAAQ9C,CAAAA,EAASA,EAAK,GAAA,GAAQ+C,CAAAA,CAAO,GAAG,CAAA,CAEzD,QACE,MAAM,KAAA,CAAM,CAAA,gBAAA,EAAmBC,CAAoB,CAAA,CAAE,CAEzD,CACF,CAEA,SAASG,EAAAA,CAAgB,CAAE,QAAA,CAAAf,CAAS,EAAyC,CAC3E,GAAM,CAACgB,CAAAA,CAAeC,CAAqB,CAAA,CAAIC,WAAWT,CAAAA,CAAgB,EAAE,CAAA,CAE5E,OACEH,IAACC,CAAAA,CAAe,QAAA,CAAf,CAAwB,KAAA,CAAOS,CAAAA,CAC9B,QAAA,CAAAV,IAACE,CAAAA,CAAsB,QAAA,CAAtB,CAA+B,KAAA,CAAOS,CAAAA,CAAwB,SAAAjB,CAAAA,CAAS,CAAA,CAC1E,CAEJ,CAEA,SAASmB,EAAAA,EAAuB,CAC9B,OAAO5C,UAAAA,CAAWgC,CAAc,CAClC,CAEA,SAASa,IAAgC,CACvC,OAAO7C,UAAAA,CAAWiC,CAAqB,CACzC","file":"chunk-6A6NT3H3.js","sourcesContent":["import type { ErrorLike } from '@apollo/client';\nimport { CombinedGraphQLErrors, ServerError } from '@apollo/client/errors';\n\ntype ErrorWithCause = ErrorLike & { cause?: unknown };\ntype ErrorWithMessage = {\n message?: unknown;\n};\ntype ServerErrorWithResult = ServerError & {\n result?: unknown;\n};\ntype GraphQLErrorResponse = {\n error?: unknown;\n errors?: unknown;\n message?: unknown;\n};\ntype GraphQLErrorItem = {\n extensions?: {\n code?: unknown;\n };\n message?: unknown;\n};\n\nfunction hasCause(error: ErrorLike): error is ErrorWithCause {\n if (!error) {\n return false;\n }\n\n return 'cause' in (error as ErrorWithCause);\n}\n\nexport function getServerError(error?: ErrorLike): ServerError | null {\n if (!error) {\n return null;\n }\n\n if (ServerError.is(error)) {\n return error;\n }\n\n if (hasCause(error)) {\n const possibleServerError = error.cause;\n\n if (ServerError.is(possibleServerError)) {\n return possibleServerError;\n }\n }\n\n return null;\n}\n\nfunction getErrorMessage(error: unknown): string | null {\n if (!error || typeof error !== 'object') {\n return null;\n }\n\n const { message } = error as ErrorWithMessage;\n\n return typeof message === 'string' ? message : null;\n}\n\nexport function parseErrorBody<T>(bodyText: string | undefined): T | null {\n if (!bodyText) {\n return null;\n }\n\n try {\n return JSON.parse(bodyText) as T;\n } catch {\n return null;\n }\n}\n\nexport function getGraphQLSchemaMismatchMessage(error?: ErrorLike): string | null {\n if (!error) {\n return null;\n }\n\n const messages = getGraphQLValidationMessages(error).filter((message) => !isMissingCountStoreFieldMessage(message));\n\n if (messages.length === 0) {\n return null;\n }\n\n return [\n 'The deployed schema is out of sync with your local Flexkit schema.',\n 'Run `flexkit deploy` using the CLI to apply your latest schema changes.',\n ...messages.map((message) => `- ${message}`),\n ].join('\\n');\n}\n\nexport function isMissingGraphQLFieldError(error: ErrorLike | undefined, fieldName: string): boolean {\n if (!error) {\n return false;\n }\n\n return getGraphQLValidationMessages(error).some((message) => {\n return message.includes(`Cannot query field \"${fieldName}\"`);\n });\n}\n\nfunction getGraphQLValidationMessages(error: ErrorLike): string[] {\n if (CombinedGraphQLErrors.is(error)) {\n return error.errors.filter(isSchemaValidationError).map(({ message }) => message);\n }\n\n const directMessage = getErrorMessage(error);\n\n if (directMessage && isSchemaValidationMessage(directMessage)) {\n return [directMessage];\n }\n\n const serverError = getServerError(error);\n\n if (serverError?.statusCode !== 400) {\n return [];\n }\n\n const responseBody =\n parseErrorBody<GraphQLErrorResponse>(serverError.bodyText) ??\n getServerErrorResult(serverError) ??\n getErrorCauseResponse(error);\n\n if (!responseBody) {\n return [];\n }\n\n if (Array.isArray(responseBody.errors)) {\n return responseBody.errors.filter(isSchemaValidationError).map((item) => item.message);\n }\n\n if (typeof responseBody.message === 'string' && isSchemaValidationMessage(responseBody.message)) {\n return [responseBody.message];\n }\n\n if (typeof responseBody.error === 'string' && isSchemaValidationMessage(responseBody.error)) {\n return [responseBody.error];\n }\n\n return [];\n}\n\nfunction getServerErrorResult(serverError: ServerError): GraphQLErrorResponse | null {\n const { result } = serverError as ServerErrorWithResult;\n\n if (!result || typeof result !== 'object') {\n return null;\n }\n\n return result as GraphQLErrorResponse;\n}\n\nfunction getErrorCauseResponse(error: ErrorLike): GraphQLErrorResponse | null {\n if (!hasCause(error)) {\n return null;\n }\n\n const { cause } = error;\n const causeMessage = getErrorMessage(cause);\n\n if (causeMessage && isSchemaValidationMessage(causeMessage)) {\n return { message: causeMessage };\n }\n\n if (!cause || typeof cause !== 'object') {\n return null;\n }\n\n const { result } = cause as { result?: unknown };\n\n if (result && typeof result === 'object') {\n return result as GraphQLErrorResponse;\n }\n\n return null;\n}\n\nfunction isSchemaValidationError(error: unknown): error is GraphQLErrorItem & { message: string } {\n if (!error || typeof error !== 'object') {\n return false;\n }\n\n const { extensions, message } = error as GraphQLErrorItem;\n const code = extensions?.code;\n\n if (code === 'GRAPHQL_VALIDATION_FAILED' && typeof message === 'string') {\n return true;\n }\n\n return typeof message === 'string' && isSchemaValidationMessage(message);\n}\n\nfunction isSchemaValidationMessage(message: string): boolean {\n return (\n message.startsWith('Cannot query field ') ||\n message.startsWith('Unknown type ') ||\n message.startsWith('Cannot query field \"') ||\n message.includes('GRAPHQL_VALIDATION_FAILED')\n );\n}\n\nfunction isMissingCountStoreFieldMessage(message: string): boolean {\n return /Cannot query field \"[_A-Za-z][_0-9A-Za-z]*Total\" on type \"Query\"/.test(message);\n}\n","'use client';\n\nimport type { JSX } from 'react';\nimport { ApolloClient, InMemoryCache, defaultDataIdFromObject, from, HttpLink } from '@apollo/client';\nimport type { ApolloLink } from '@apollo/client';\nimport { ApolloProvider } from '@apollo/client/react';\nimport { ErrorLink } from '@apollo/client/link/error';\nimport { CombinedGraphQLErrors, CombinedProtocolErrors } from '@apollo/client/errors';\nimport { getGraphQLSchemaMismatchMessage, getServerError, parseErrorBody } from './error-utils';\nimport { useConfig } from '../core/config/config-context';\nimport React, { createContext, useContext, useMemo, useState } from 'react';\n\nconst ApolloProviderCompat = ApolloProvider as unknown as React.ComponentType<{\n children?: React.ReactNode;\n client: ApolloClient;\n}>;\n\ntype GraphQLErrorContextValue = {\n schemaErrorMessage: string | null;\n setSchemaErrorMessage: React.Dispatch<React.SetStateAction<string | null>>;\n};\n\nconst GraphQLErrorContext = createContext<GraphQLErrorContextValue | undefined>(undefined);\n\nfunction useGraphQLError(): GraphQLErrorContextValue {\n const ctx = useContext(GraphQLErrorContext);\n\n if (!ctx) {\n throw new Error('useGraphQLError must be used within GraphQLProvider');\n }\n\n return ctx;\n}\n\n/**\n * Context flag for operations the user writes themselves (the Graph app's\n * Query view): any error there, a mismatch or a 400, is a typo, not a\n * deployment that drifted from the local schema, so it must not raise the\n * schema banner. The caller shows the error itself.\n */\nexport const USER_QUERY_CONTEXT = { userQuery: true } as const;\n\nfunction createErrorLink(setSchemaErrorMessage: (msg: string | null) => void): ApolloLink {\n return new ErrorLink(({ error, operation }) => {\n if (operation.getContext().userQuery === true) {\n return;\n }\n\n const schemaMismatchMessage = getGraphQLSchemaMismatchMessage(error);\n\n if (schemaMismatchMessage) {\n setSchemaErrorMessage(schemaMismatchMessage);\n\n return;\n }\n\n if (CombinedGraphQLErrors.is(error)) {\n error.errors.forEach(({ message, locations, path }) => {\n console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);\n });\n } else if (CombinedProtocolErrors.is(error)) {\n error.errors.forEach(({ message, extensions }) => {\n console.warn(`[Protocol error]: Message: ${message}, Extensions: ${JSON.stringify(extensions)}`);\n });\n }\n\n const serverError = getServerError(error);\n\n if (serverError?.statusCode === 400) {\n const responseBody = parseErrorBody<Record<string, unknown>>(serverError.bodyText);\n let message: string | null = null;\n\n if (responseBody && typeof responseBody === 'object') {\n const {\n error: responseError,\n errors,\n message: responseMessage,\n } = responseBody as {\n error?: unknown;\n errors?: unknown;\n message?: unknown;\n };\n\n if (typeof responseMessage === 'string') {\n message = responseMessage;\n } else if (Array.isArray(errors)) {\n const [firstError] = errors as { message?: unknown }[];\n\n if (firstError && typeof firstError.message === 'string') {\n const { message: firstErrorMessage } = firstError;\n message = firstErrorMessage;\n }\n } else if (typeof responseError === 'string') {\n message = responseError;\n } else {\n message = JSON.stringify(responseBody);\n }\n } else {\n message = serverError.bodyText;\n }\n\n setSchemaErrorMessage(\n message ?? 'There is an error in the deployed Flexkit schema. Fix flexkit.config.ts and run flexkit deploy.'\n );\n }\n\n if (serverError) {\n console.warn(`[Network error]: ${serverError.message}`);\n\n return;\n }\n\n if (error) {\n console.warn(`[Network error]: ${error.message}`);\n }\n });\n}\n\nfunction additiveLink(currentProjectId: string, setSchemaErrorMessage: (msg: string | null) => void): ApolloLink {\n return from([\n createErrorLink(setSchemaErrorMessage),\n new HttpLink({ uri: `/api/flexkit/${currentProjectId}/graphql` }),\n ]);\n}\n\nfunction client(\n currentProjectId: string | undefined,\n setSchemaErrorMessage: (msg: string | null) => void\n): ApolloClient {\n return new ApolloClient({\n link: additiveLink(currentProjectId ?? '', setSchemaErrorMessage),\n cache: new InMemoryCache({\n dataIdFromObject: (responseObject) => {\n return responseObject._id ? (responseObject._id as string) : defaultDataIdFromObject(responseObject);\n },\n }),\n });\n}\n\nexport function GraphQLProvider({ children }: { children: React.ReactNode }): JSX.Element {\n const { currentProjectId } = useConfig();\n const [schemaErrorMessage, setSchemaErrorMessage] = useState<string | null>(null);\n const ctx = useMemo(() => ({ schemaErrorMessage, setSchemaErrorMessage }), [schemaErrorMessage]);\n const apolloClient = useMemo(() => client(currentProjectId, setSchemaErrorMessage), [currentProjectId]);\n\n return (\n <GraphQLErrorContext.Provider value={ctx}>\n <ApolloProviderCompat client={apolloClient}>{children}</ApolloProviderCompat>\n </GraphQLErrorContext.Provider>\n );\n}\n\nexport { useGraphQLError };\n","'use client';\n\nimport { createContext, useContext, useReducer } from 'react';\nimport type { Dispatch, JSX, ReactNode } from 'react';\nimport { props, uniqBy } from 'ramda';\nimport type {\n Action,\n ActionAddEntity,\n ActionAlertDialog,\n ActionDeleteEntity,\n ActionEditEntity,\n ActionEditRelationship,\n} from './types';\n\nconst ActionsContext = createContext<Action[] | []>([]);\nconst EntityDispatchContext = createContext<Dispatch<Action>>(() => undefined);\n\nfunction actionsReducer(actions: Action[], action: Action): Action[] {\n const actionType = action.type;\n\n if (!action._id) {\n action._id = Date.now().toString();\n }\n\n switch (actionType) {\n case 'DeleteEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionDeleteEntity[]), action]);\n }\n case 'AddEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionAddEntity[]), action]);\n }\n case 'EditEntity': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionEditEntity[]), action]);\n }\n case 'EditRelationship': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionEditRelationship[]), action]);\n }\n case 'AlertDialog': {\n return uniqBy(props(['type' as string, '_id']), [...(actions as ActionAlertDialog[]), action]);\n }\n case 'Dismiss': {\n return actions.filter((item) => item._id !== action._id);\n }\n default: {\n throw Error(`Unknown action: ${actionType as string}`);\n }\n }\n}\n\nfunction ActionsProvider({ children }: { children: ReactNode }): JSX.Element {\n const [entityActions, dispatchEntityActions] = useReducer(actionsReducer, []);\n\n return (\n <ActionsContext.Provider value={entityActions}>\n <EntityDispatchContext.Provider value={dispatchEntityActions}>{children}</EntityDispatchContext.Provider>\n </ActionsContext.Provider>\n );\n}\n\nfunction useActions(): Action[] {\n return useContext(ActionsContext);\n}\n\nfunction useDispatch(): Dispatch<Action> {\n return useContext(EntityDispatchContext);\n}\n\nexport { ActionsProvider, useActions, useDispatch };\n"]}
@@ -1,2 +1,2 @@
1
- import'./index.css';import {e,c,b,a,g,h as h$1,m as m$1,k as k$2,n}from'./chunk-LG2KGSQ4.js';import {m as m$2,s as s$2}from'./chunk-HAU76X63.js';import {b as b$3}from'./chunk-V7C4EHK3.js';import {j}from'./chunk-I4UFLN53.js';import {c as c$3}from'./chunk-XMOSCJOI.js';import {t,s,u,q as q$1,v,k as k$1,i as i$1,o as o$1,r as r$2,p as p$2}from'./chunk-7KLXWCDS.js';import {a as a$2}from'./chunk-ERDARDGB.js';import {f}from'./chunk-TWALS64F.js';import {na,p,q,r,t as t$2,u as u$1,v as v$1,qa,s as s$1}from'./chunk-DGIY4SKN.js';import {t as t$1}from'./chunk-SZEGGBOC.js';import {b as b$2,c as c$1,h,i,k,l,m,o,p as p$1,q as q$2,r as r$1,t as t$3}from'./chunk-32ZU4MLE.js';import {a as a$1,b as b$4,c as c$2,e as e$1}from'./chunk-USNXQOMJ.js';import {b as b$1}from'./chunk-6NRQMG26.js';import {useState,useMemo,useDeferredValue}from'react';import {BookOpenTextIcon,PaperclipIcon,ChevronRightIcon,LayersIcon,XIcon,PlusIcon,Unlink2Icon,LoaderCircle,SearchIcon}from'lucide-react';import {Link}from'react-router-dom';import H from'swr';import Qe from'swr/infinite';import {jsxs,Fragment,jsx}from'react/jsx-runtime';var Be=50;function fe({disabled:n,label:l,onClick:o}){return jsxs(b$4,{children:[jsx(c$2,{asChild:true,children:jsx(b$1,{"aria-label":l,className:"fk:size-7 fk:shrink-0",disabled:n,size:"icon",variant:"ghost",onClick:o,children:jsx(Unlink2Icon,{className:"fk:size-4"})})}),jsx(e$1,{children:l})]})}function Xe({api:n$1,attachedIds:l$1,onAttached:o,onOpenChange:a,open:s,projectId:u,target:r,targetLabel:c$2}){let[p,h$2]=useState(""),m=useDeferredValue(p.trim()),[y,f]=useState(null),b$1=(k,K)=>!s||K&&!K.hasMore?null:c(u).sources({limit:Be,offset:k*Be,search:m||void 0}),{data:v,error:w,isLoading:x,setSize:i$2,size:d}=Qe(b$1,b,{keepPreviousData:true}),g=useMemo(()=>r$2(v?.flatMap(k=>k.sources)??[],l$1),[l$1,v]),L=v?.[v.length-1]?.hasMore??false,C=v!==void 0&&d>v.length;async function A(k){f(k.id);try{let K=await n$1.linkSource(k.id,r);qa.success(K.linked?`Attached "${k.title}".`:`"${k.title}" was already attached.`),o(k),a(!1);}catch(K){qa.error(h$1(K,"The document could not be attached."));}finally{f(null);}}let R;return w?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):x&&!v?R=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-3 fk:py-2",children:[jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"})]}):g.length===0&&!L?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-muted-foreground",children:m?"No documents match your search.":"Every document is attached already, or there are none yet. Add documents in Knowledge first."}):R=jsxs("ul",{className:"fk:flex fk:max-h-80 fk:flex-col fk:overflow-y-auto fk:-mx-2",children:[g.map(k=>{let K=k$1(k),B=y===k.id;return jsx("li",{children:jsxs("button",{className:"fk:flex fk:w-full fk:min-w-0 fk:items-center fk:gap-3 fk:rounded-lg fk:px-2 fk:py-2 fk:text-left fk:transition-colors fk:hover:bg-accent fk:focus-visible:bg-accent fk:focus-visible:outline-none fk:disabled:opacity-60 fk:corner-squircle",disabled:y!==null,type:"button",onClick:()=>{A(k);},children:[jsx(m$1,{source:k}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:k.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i$1(k)," \xB7 ",K.detail]})]}),B?jsx(LoaderCircle,{className:"fk:size-4 fk:shrink-0 fk:animate-spin fk:text-muted-foreground"}):jsx(k$2,{label:K.label,tone:K.tone})]})},k.id)}),L&&!C?jsx("li",{"aria-hidden":true,children:jsx(n,{onVisible:()=>{i$2(k=>k+1);}})}):null,C?jsx("li",{className:"fk:flex fk:justify-center fk:py-2",children:jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin fk:text-muted-foreground"})}):null]}),jsx(c$1,{open:s,onOpenChange:a,children:jsxs(h,{className:"fk:sm:max-w-lg",children:[jsxs(i,{children:[jsx(k,{children:"Attach a document"}),jsx(l,{children:r.recordId===void 0?`Documents attached to every ${c$2} are searched before the rest of Knowledge when a question is about one of them, or about ${c$2} in general.`:`Documents attached to ${c$2} are searched before the rest of Knowledge when a question is about it.`})]}),jsxs("div",{className:"fk:relative",children:[jsx(SearchIcon,{className:"fk:pointer-events-none fk:absolute fk:left-2.5 fk:top-1/2 fk:size-4 fk:-translate-y-1/2 fk:text-muted-foreground"}),jsx(s$1,{"aria-label":"Search documents",autoFocus:true,className:"fk:pl-8",placeholder:"Search documents by title",value:p,onChange:k=>h$2(k.target.value)})]}),R]})})}function re({projectId:n,renderAction:l,sources:o}){return jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1 fk:-mx-2",children:o.map(a=>{let s=k$1(a);return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1.5 fk:corner-squircle",children:[jsxs(Link,{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-3 fk:rounded-md fk:hover:underline fk:underline-offset-2",to:o$1(n,a.id),children:[jsx(m$1,{source:a}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:a.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i$1(a)," \xB7 ",s.detail]})]})]}),jsx(k$2,{label:s.label,tone:s.tone}),l?.(a)]},a.id)})})}function yt({entityName:n}){let{api:l,projectId:o}=e(),{currentProject:a$1}=f(),[s$1,u$1]=useState(false),r=t(a$1?.schema??[],n),c$1=!!r&&s(n),{data:p,error:h}=H(o&&c$1?c(o).entitySources(n):null,b);if(!l||!o||!r||!c$1||h instanceof a&&h.status===404)return null;let m=p?.sources.length??0;return jsxs(Fragment,{children:[jsxs(b$1,{"aria-label":`Knowledge for every ${u(r)}`,className:"fk:mr-2 fk:h-8","data-knowledge-entity-button":true,size:"sm",variant:"outline",onClick:()=>u$1(true),children:[jsx(BookOpenTextIcon,{}),"Knowledge",m>0?jsx(b$2,{className:"fk:corner-squircle",variant:"secondary",children:m}):null]}),jsx(Ue,{api:l,entityLabel:u(r),entityName:n,open:s$1,projectId:o,onOpenChange:u$1})]})}function Ue({api:n,entityLabel:l$1,entityName:o,onOpenChange:a,open:s,projectId:u}){let r=b$3(),[c$2,p]=useState(false),[h$2,m]=useState(null),{data:y,error:f,isLoading:b$4,mutate:v}=H(c(u).entitySources(o),b),w=y?.sources??[],x=useMemo(()=>({entity:o}),[o]);async function i$1(g$1){m(g$1.id);try{await n.unlinkSource(g$1.id,x),qa.success(`"${g$1.title}" no longer applies to every ${l$1}.`),await v({sources:w.filter(L=>L.id!==g$1.id)},{revalidate:!1}),g();}catch(L){qa.error(h$1(L,"The document could not be detached."));}finally{m(null);}}let d;return f?d=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):b$4&&!y?d=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):w.length===0?d=jsxs("p",{className:"fk:text-sm fk:text-muted-foreground",children:["No documents apply to every ",l$1," yet. Attach a guide, a policy or a spec that holds for all of them and the agent searches it first when asked about any ",l$1,", or about ",l$1," in general."]}):d=jsx(re,{projectId:u,sources:w,renderAction:g=>r?jsx(fe,{disabled:h$2!==null,label:`Detach ${g.title}`,onClick:()=>{i$1(g);}}):null}),jsx(c$1,{open:s,onOpenChange:a,children:jsxs(h,{className:"fk:sm:max-w-lg","data-knowledge-entity-dialog":true,children:[jsxs(i,{children:[jsxs(k,{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(BookOpenTextIcon,{className:"fk:size-4 fk:text-muted-foreground"}),"Knowledge for every ",l$1,y?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:w.length}):null]}),jsxs(l,{children:["Documents attached here apply to every ",l$1,"; each record can hold its own on top."]})]}),jsx("div",{className:"fk:max-h-80 fk:overflow-y-auto",children:d}),jsx("div",{className:"fk:flex fk:justify-end",children:jsx(na,{disabled:!r,children:jsxs(b$1,{disabled:!r,size:"sm",variant:"outline",onClick:()=>p(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})})}),jsx(Xe,{api:n,attachedIds:w.map(g=>g.id),open:c$2,projectId:u,target:x,targetLabel:l$1,onAttached:g$1=>{v({sources:w.some(L=>L.id===g$1.id)?w:[...w,g$1]},{revalidate:false}),g();},onOpenChange:p})]})})}function bt({entityName:n,recordId:l,recordLabel:o}){let{api:a$2,projectId:s$1}=e(),{currentProject:u$1}=f(),r$1=b$3(),[c$1,p$1]=useState(false),[h,m]=useState(false),[y,f$1]=useState(null),b$4=useMemo(()=>({entity:n,recordId:l}),[n,l]),v=t(u$1?.schema??[],n),w=v?u(v):n,x=s(n),{data:i,error:d,isLoading:g$1,mutate:L}=H(s$1&&x?c(s$1).recordSources(b$4):null,b);if(!a$2||!s$1||!x||d instanceof a&&d.status===404)return null;let C=i?.sources??[],A=i?.inherited??[],R=C.map(N=>N.id),k=a$2;async function K(N){f$1(N.id);try{await k.unlinkSource(N.id,b$4),qa.success(`Detached "${N.title}".`),await L({sources:C.filter($=>$.id!==N.id),inherited:A},{revalidate:!1}),g();}catch($){qa.error(h$1($,"The document could not be detached."));}finally{f$1(null);}}let B;return d?B=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The attached documents could not be loaded."}):g$1&&!i?B=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):B=jsxs("div",{className:"fk:flex fk:flex-col fk:gap-4",children:[C.length===0?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:A.length>0?"No documents attached to this record itself; the ones below apply to every record of its type.":"No documents attached. Attach a manual, spec or contract and the agent will use it alongside the record's data when asked about this record."}):jsx(re,{projectId:s$1,sources:C,renderAction:N=>r$1?jsx(fe,{disabled:y!==null,label:`Detach ${N.title}`,onClick:()=>{K(N);}}):null}),A.length>0?jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1","data-knowledge-inherited":true,children:[jsxs("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:["Applies to every ",w]}),jsx(re,{projectId:s$1,sources:A})]}):null]}),jsx(a$1,{children:jsxs(p,{className:`fk:z-10 fk:flex fk:shrink-0 fk:flex-col fk:border-t fk:bg-background ${c$1?"fk:h-1/2":""}`,"data-knowledge-record-panel":true,open:c$1,onOpenChange:p$1,children:[jsxs("div",{className:"fk:flex fk:shrink-0 fk:items-center fk:gap-2 fk:pl-4 fk:pr-10 fk:py-2",children:[jsx(q,{asChild:true,children:jsxs("button",{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-2 fk:rounded-md fk:py-1 fk:text-left fk:text-sm fk:font-semibold fk:tracking-tight fk:hover:text-foreground/80 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",type:"button",children:[jsx(ChevronRightIcon,{className:`fk:size-4 fk:shrink-0 fk:text-muted-foreground fk:transition-transform ${c$1?"fk:rotate-90":""}`}),jsx(BookOpenTextIcon,{className:"fk:size-4 fk:shrink-0 fk:text-muted-foreground"}),"Knowledge",i?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:C.length+A.length}):null]})}),c$1?jsx(na,{disabled:!r$1,children:jsxs(b$1,{disabled:!r$1,size:"sm",variant:"outline",onClick:()=>m(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})}):null]}),jsx(r,{className:"fk:min-h-0 fk:flex-1 fk:overflow-y-auto fk:px-10 fk:pb-6",children:B}),jsx(Xe,{api:a$2,attachedIds:R,open:h,projectId:s$1,target:b$4,targetLabel:o||`this ${n}`,onAttached:N=>{L({sources:C.some($=>$.id===N.id)?C:[...C,N],inherited:A.filter($=>$.id!==N.id)},{revalidate:false}),g();},onOpenChange:m})]})})}function Ze(n,l,o){let{scope:a}=c$3(),s=n.links.map(r=>r.recordId),{data:u}=s$2({entityNamePlural:n.entityPlural,schema:l,scope:a,selection:"display",includeCount:false,variables:{where:{_id:{in:s}},limit:s.length}});return useMemo(()=>{let r={};for(let c of u??[]){let p=c[o.name];typeof p=="string"&&p.trim()&&(r[c._id]=p);}return r},[u,o])}function Ye(n){let{currentProject:l}=f(),o=useMemo(()=>l?.schema??[],[l]),a=m$2(o,n.group.entityPlural),s=a$2(a);return !a||!s?jsx(Je,{...n,entityLabel:a?u(a):n.group.entityPlural,labels:{}}):jsx(et,{...n,displayAttribute:s,schema:o,entityLabel:u(a)})}function et({displayAttribute:n,entityLabel:l,schema:o,...a}){let s=Ze(a.group,o,n);return jsx(Je,{...a,entityLabel:l,labels:s})}function Je({canMutate:n,detachingKey:l,entityLabel:o,group:a,labels:s,onDetach:u}){let r=j();return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1",children:[jsx("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:o}),jsx("ul",{className:"fk:flex fk:flex-col fk:-mx-2",children:a.links.map(c=>{let p=p$2(c,s[c.recordId]),h=`${c.entity}:${c.recordId}`;return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1 fk:corner-squircle",children:[jsx("button",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:text-left fk:text-sm fk:hover:underline fk:underline-offset-2",title:c.recordId,type:"button",onClick:()=>r({type:"EditEntity",payload:{entityId:c.recordId,entityNamePlural:a.entityPlural}}),children:p}),n?jsx(fe,{disabled:l!==null,label:`Detach from ${p}`,onClick:()=>u(c)}):null]},h)})})]})}function vt({api:n,projectId:l,source:o}){let a=b$3(),[s,u$1]=useState(null),{data:r,error:c$1,isLoading:p,mutate:h}=H(c(l).links(o.id),b),m=useMemo(()=>r?.links??[],[r]),y=useMemo(()=>r?.entities??[],[r]),f=useMemo(()=>q$1(m),[m]);async function b$1(i){u$1(`${i.entity}:${i.recordId}`);try{await n.unlinkSource(o.id,{entity:i.entity,recordId:i.recordId}),qa.success("Detached."),await h({links:m.filter(d=>d.entity!==i.entity||d.recordId!==i.recordId),entities:y},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function v(i){u$1(`${i.entity}:*`);try{await n.unlinkSource(o.id,{entity:i.entity}),qa.success("Detached."),await h({links:m,entities:y.filter(d=>d.entity!==i.entity)},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function w(i){u$1(`${i.name}:+`);try{let d=await n.linkSource(o.id,{entity:i.name});qa.success(d.linked?`Applies to every ${u(i)} now.`:`Already applied to every ${u(i)}.`),await h({links:m,entities:y.some(g=>g.entity===i.name)?y:[...y,{entity:i.name,entityPlural:i.plural}]},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be attached."));}finally{u$1(null);}}let x;return c$1?x=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The linked records could not be loaded."}):p&&!r?x=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-6 fk:w-1/2"}),jsx(t$1,{className:"fk:h-6 fk:w-1/3"})]}):f.length===0?x=jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:'Not attached to any record. Open a record in the Desk and use "Attach document" so the agent searches this document before the rest of Knowledge when asked about that record.'}):x=jsx("div",{className:"fk:flex fk:flex-col fk:gap-4",children:f.map(i=>jsx(Ye,{canMutate:a,detachingKey:s,group:i,onDetach:d=>{b$1(d);}},i.entityPlural))}),jsxs(Fragment,{children:[jsx(tt,{busy:s!==null,canMutate:a,entities:y,isLoading:p&&!r,onAttach:i=>{w(i);},onDetach:i=>{v(i);}}),jsxs("div",{className:"fk:mt-2 fk:flex fk:items-center fk:gap-2",children:[jsx(PaperclipIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Linked records"}),m.length>0?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:m.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"When a question is about one of these records, the agent searches this document before the rest."}),x]})}function tt({busy:n,canMutate:l,entities:o$1,isLoading:a,onAttach:s,onDetach:u$2}){let{currentProject:r}=f(),c=useMemo(()=>r?.schema??[],[r]),[p,h]=useState(false),m$1=useMemo(()=>v(c,o$1),[o$1,c]),y=f=>{let b=t(c,f.entity);return b?u(b):f.entityPlural};return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-3","data-knowledge-applies-to":true,children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(LayersIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Applies to"}),o$1.length>0?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:o$1.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"Attach this document to a whole entity type and the agent searches it before the rest of Knowledge for every record of that type, and for questions about the type in general."}),a?jsx(t$1,{className:"fk:h-7 fk:w-1/3"}):jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[o$1.map(f=>{let b=y(f);return jsxs(b$2,{className:"fk:gap-1 fk:py-1 fk:pl-2.5 fk:pr-1 fk:corner-squircle",variant:"secondary",children:[jsx("span",{className:"fk:capitalize",children:b}),l?jsxs(b$4,{children:[jsx(c$2,{asChild:true,children:jsx("button",{"aria-label":`No longer apply to every ${b}`,className:"fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:hover:text-foreground fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:disabled:opacity-50",disabled:n,type:"button",onClick:()=>u$2(f),children:jsx(XIcon,{className:"fk:size-3"})})}),jsxs(e$1,{children:["No longer apply to every ",b]})]}):null]},f.entity)}),jsxs(t$2,{open:p,onOpenChange:h,children:[jsx(na,{disabled:!l,children:jsx(u$1,{asChild:true,children:jsxs(b$1,{className:"fk:h-7",disabled:!l||m$1.length===0,size:"sm",variant:"outline",children:[jsx(PlusIcon,{}),"Add entity type"]})})}),jsx(v$1,{align:"start",className:"fk:w-64 fk:p-0",children:jsxs(m,{children:[jsx(o,{placeholder:"Search entity types"}),jsxs(p$1,{children:[jsx(q$2,{children:"No entity type matches."}),jsx(r$1,{children:m$1.map(f=>jsx(t$3,{keywords:[u(f),f.name,f.plural],value:f.name,onSelect:()=>{h(false),s(f);},children:jsx("span",{className:"fk:capitalize",children:u(f)})},f.name))})]})]})})]})]})]})}export{yt as a,bt as b,vt as c};//# sourceMappingURL=chunk-FVNVNXEV.js.map
2
- //# sourceMappingURL=chunk-FVNVNXEV.js.map
1
+ import'./index.css';import {e,c,b,a,g,h as h$1,m as m$1,k as k$2,n}from'./chunk-D3TJCUTA.js';import {m as m$2,s as s$2}from'./chunk-RZZOOPEF.js';import {b as b$3}from'./chunk-V7C4EHK3.js';import {j}from'./chunk-6A6NT3H3.js';import {c as c$3}from'./chunk-XMOSCJOI.js';import {t,s,u,q as q$1,v,k as k$1,i as i$1,o as o$1,r as r$2,p as p$2}from'./chunk-7KLXWCDS.js';import {a as a$2}from'./chunk-ERDARDGB.js';import {f}from'./chunk-H534S4KD.js';import {na,p,q,r,t as t$2,u as u$1,v as v$1,qa,s as s$1}from'./chunk-DGIY4SKN.js';import {t as t$1}from'./chunk-SZEGGBOC.js';import {b as b$2,c as c$1,h,i,k,l,m,o,p as p$1,q as q$2,r as r$1,t as t$3}from'./chunk-32ZU4MLE.js';import {a as a$1,b as b$4,c as c$2,e as e$1}from'./chunk-USNXQOMJ.js';import {b as b$1}from'./chunk-6NRQMG26.js';import {useState,useMemo,useDeferredValue}from'react';import {BookOpenTextIcon,PaperclipIcon,ChevronRightIcon,LayersIcon,XIcon,PlusIcon,Unlink2Icon,LoaderCircle,SearchIcon}from'lucide-react';import {Link}from'react-router-dom';import H from'swr';import Qe from'swr/infinite';import {jsxs,Fragment,jsx}from'react/jsx-runtime';var Be=50;function fe({disabled:n,label:l,onClick:o}){return jsxs(b$4,{children:[jsx(c$2,{asChild:true,children:jsx(b$1,{"aria-label":l,className:"fk:size-7 fk:shrink-0",disabled:n,size:"icon",variant:"ghost",onClick:o,children:jsx(Unlink2Icon,{className:"fk:size-4"})})}),jsx(e$1,{children:l})]})}function Xe({api:n$1,attachedIds:l$1,onAttached:o,onOpenChange:a,open:s,projectId:u,target:r,targetLabel:c$2}){let[p,h$2]=useState(""),m=useDeferredValue(p.trim()),[y,f]=useState(null),b$1=(k,K)=>!s||K&&!K.hasMore?null:c(u).sources({limit:Be,offset:k*Be,search:m||void 0}),{data:v,error:w,isLoading:x,setSize:i$2,size:d}=Qe(b$1,b,{keepPreviousData:true}),g=useMemo(()=>r$2(v?.flatMap(k=>k.sources)??[],l$1),[l$1,v]),L=v?.[v.length-1]?.hasMore??false,C=v!==void 0&&d>v.length;async function A(k){f(k.id);try{let K=await n$1.linkSource(k.id,r);qa.success(K.linked?`Attached "${k.title}".`:`"${k.title}" was already attached.`),o(k),a(!1);}catch(K){qa.error(h$1(K,"The document could not be attached."));}finally{f(null);}}let R;return w?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):x&&!v?R=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-3 fk:py-2",children:[jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"})]}):g.length===0&&!L?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-muted-foreground",children:m?"No documents match your search.":"Every document is attached already, or there are none yet. Add documents in Knowledge first."}):R=jsxs("ul",{className:"fk:flex fk:max-h-80 fk:flex-col fk:overflow-y-auto fk:-mx-2",children:[g.map(k=>{let K=k$1(k),B=y===k.id;return jsx("li",{children:jsxs("button",{className:"fk:flex fk:w-full fk:min-w-0 fk:items-center fk:gap-3 fk:rounded-lg fk:px-2 fk:py-2 fk:text-left fk:transition-colors fk:hover:bg-accent fk:focus-visible:bg-accent fk:focus-visible:outline-none fk:disabled:opacity-60 fk:corner-squircle",disabled:y!==null,type:"button",onClick:()=>{A(k);},children:[jsx(m$1,{source:k}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:k.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i$1(k)," \xB7 ",K.detail]})]}),B?jsx(LoaderCircle,{className:"fk:size-4 fk:shrink-0 fk:animate-spin fk:text-muted-foreground"}):jsx(k$2,{label:K.label,tone:K.tone})]})},k.id)}),L&&!C?jsx("li",{"aria-hidden":true,children:jsx(n,{onVisible:()=>{i$2(k=>k+1);}})}):null,C?jsx("li",{className:"fk:flex fk:justify-center fk:py-2",children:jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin fk:text-muted-foreground"})}):null]}),jsx(c$1,{open:s,onOpenChange:a,children:jsxs(h,{className:"fk:sm:max-w-lg",children:[jsxs(i,{children:[jsx(k,{children:"Attach a document"}),jsx(l,{children:r.recordId===void 0?`Documents attached to every ${c$2} are searched before the rest of Knowledge when a question is about one of them, or about ${c$2} in general.`:`Documents attached to ${c$2} are searched before the rest of Knowledge when a question is about it.`})]}),jsxs("div",{className:"fk:relative",children:[jsx(SearchIcon,{className:"fk:pointer-events-none fk:absolute fk:left-2.5 fk:top-1/2 fk:size-4 fk:-translate-y-1/2 fk:text-muted-foreground"}),jsx(s$1,{"aria-label":"Search documents",autoFocus:true,className:"fk:pl-8",placeholder:"Search documents by title",value:p,onChange:k=>h$2(k.target.value)})]}),R]})})}function re({projectId:n,renderAction:l,sources:o}){return jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1 fk:-mx-2",children:o.map(a=>{let s=k$1(a);return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1.5 fk:corner-squircle",children:[jsxs(Link,{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-3 fk:rounded-md fk:hover:underline fk:underline-offset-2",to:o$1(n,a.id),children:[jsx(m$1,{source:a}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:a.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i$1(a)," \xB7 ",s.detail]})]})]}),jsx(k$2,{label:s.label,tone:s.tone}),l?.(a)]},a.id)})})}function yt({entityName:n}){let{api:l,projectId:o}=e(),{currentProject:a$1}=f(),[s$1,u$1]=useState(false),r=t(a$1?.schema??[],n),c$1=!!r&&s(n),{data:p,error:h}=H(o&&c$1?c(o).entitySources(n):null,b);if(!l||!o||!r||!c$1||h instanceof a&&h.status===404)return null;let m=p?.sources.length??0;return jsxs(Fragment,{children:[jsxs(b$1,{"aria-label":`Knowledge for every ${u(r)}`,className:"fk:mr-2 fk:h-8","data-knowledge-entity-button":true,size:"sm",variant:"outline",onClick:()=>u$1(true),children:[jsx(BookOpenTextIcon,{}),"Knowledge",m>0?jsx(b$2,{className:"fk:corner-squircle",variant:"secondary",children:m}):null]}),jsx(Ue,{api:l,entityLabel:u(r),entityName:n,open:s$1,projectId:o,onOpenChange:u$1})]})}function Ue({api:n,entityLabel:l$1,entityName:o,onOpenChange:a,open:s,projectId:u}){let r=b$3(),[c$2,p]=useState(false),[h$2,m]=useState(null),{data:y,error:f,isLoading:b$4,mutate:v}=H(c(u).entitySources(o),b),w=y?.sources??[],x=useMemo(()=>({entity:o}),[o]);async function i$1(g$1){m(g$1.id);try{await n.unlinkSource(g$1.id,x),qa.success(`"${g$1.title}" no longer applies to every ${l$1}.`),await v({sources:w.filter(L=>L.id!==g$1.id)},{revalidate:!1}),g();}catch(L){qa.error(h$1(L,"The document could not be detached."));}finally{m(null);}}let d;return f?d=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):b$4&&!y?d=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):w.length===0?d=jsxs("p",{className:"fk:text-sm fk:text-muted-foreground",children:["No documents apply to every ",l$1," yet. Attach a guide, a policy or a spec that holds for all of them and the agent searches it first when asked about any ",l$1,", or about ",l$1," in general."]}):d=jsx(re,{projectId:u,sources:w,renderAction:g=>r?jsx(fe,{disabled:h$2!==null,label:`Detach ${g.title}`,onClick:()=>{i$1(g);}}):null}),jsx(c$1,{open:s,onOpenChange:a,children:jsxs(h,{className:"fk:sm:max-w-lg","data-knowledge-entity-dialog":true,children:[jsxs(i,{children:[jsxs(k,{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(BookOpenTextIcon,{className:"fk:size-4 fk:text-muted-foreground"}),"Knowledge for every ",l$1,y?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:w.length}):null]}),jsxs(l,{children:["Documents attached here apply to every ",l$1,"; each record can hold its own on top."]})]}),jsx("div",{className:"fk:max-h-80 fk:overflow-y-auto",children:d}),jsx("div",{className:"fk:flex fk:justify-end",children:jsx(na,{disabled:!r,children:jsxs(b$1,{disabled:!r,size:"sm",variant:"outline",onClick:()=>p(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})})}),jsx(Xe,{api:n,attachedIds:w.map(g=>g.id),open:c$2,projectId:u,target:x,targetLabel:l$1,onAttached:g$1=>{v({sources:w.some(L=>L.id===g$1.id)?w:[...w,g$1]},{revalidate:false}),g();},onOpenChange:p})]})})}function bt({entityName:n,recordId:l,recordLabel:o}){let{api:a$2,projectId:s$1}=e(),{currentProject:u$1}=f(),r$1=b$3(),[c$1,p$1]=useState(false),[h,m]=useState(false),[y,f$1]=useState(null),b$4=useMemo(()=>({entity:n,recordId:l}),[n,l]),v=t(u$1?.schema??[],n),w=v?u(v):n,x=s(n),{data:i,error:d,isLoading:g$1,mutate:L}=H(s$1&&x?c(s$1).recordSources(b$4):null,b);if(!a$2||!s$1||!x||d instanceof a&&d.status===404)return null;let C=i?.sources??[],A=i?.inherited??[],R=C.map(N=>N.id),k=a$2;async function K(N){f$1(N.id);try{await k.unlinkSource(N.id,b$4),qa.success(`Detached "${N.title}".`),await L({sources:C.filter($=>$.id!==N.id),inherited:A},{revalidate:!1}),g();}catch($){qa.error(h$1($,"The document could not be detached."));}finally{f$1(null);}}let B;return d?B=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The attached documents could not be loaded."}):g$1&&!i?B=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):B=jsxs("div",{className:"fk:flex fk:flex-col fk:gap-4",children:[C.length===0?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:A.length>0?"No documents attached to this record itself; the ones below apply to every record of its type.":"No documents attached. Attach a manual, spec or contract and the agent will use it alongside the record's data when asked about this record."}):jsx(re,{projectId:s$1,sources:C,renderAction:N=>r$1?jsx(fe,{disabled:y!==null,label:`Detach ${N.title}`,onClick:()=>{K(N);}}):null}),A.length>0?jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1","data-knowledge-inherited":true,children:[jsxs("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:["Applies to every ",w]}),jsx(re,{projectId:s$1,sources:A})]}):null]}),jsx(a$1,{children:jsxs(p,{className:`fk:z-10 fk:flex fk:shrink-0 fk:flex-col fk:border-t fk:bg-background ${c$1?"fk:h-1/2":""}`,"data-knowledge-record-panel":true,open:c$1,onOpenChange:p$1,children:[jsxs("div",{className:"fk:flex fk:shrink-0 fk:items-center fk:gap-2 fk:pl-4 fk:pr-10 fk:py-2",children:[jsx(q,{asChild:true,children:jsxs("button",{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-2 fk:rounded-md fk:py-1 fk:text-left fk:text-sm fk:font-semibold fk:tracking-tight fk:hover:text-foreground/80 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",type:"button",children:[jsx(ChevronRightIcon,{className:`fk:size-4 fk:shrink-0 fk:text-muted-foreground fk:transition-transform ${c$1?"fk:rotate-90":""}`}),jsx(BookOpenTextIcon,{className:"fk:size-4 fk:shrink-0 fk:text-muted-foreground"}),"Knowledge",i?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:C.length+A.length}):null]})}),c$1?jsx(na,{disabled:!r$1,children:jsxs(b$1,{disabled:!r$1,size:"sm",variant:"outline",onClick:()=>m(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})}):null]}),jsx(r,{className:"fk:min-h-0 fk:flex-1 fk:overflow-y-auto fk:px-10 fk:pb-6",children:B}),jsx(Xe,{api:a$2,attachedIds:R,open:h,projectId:s$1,target:b$4,targetLabel:o||`this ${n}`,onAttached:N=>{L({sources:C.some($=>$.id===N.id)?C:[...C,N],inherited:A.filter($=>$.id!==N.id)},{revalidate:false}),g();},onOpenChange:m})]})})}function Ze(n,l,o){let{scope:a}=c$3(),s=n.links.map(r=>r.recordId),{data:u}=s$2({entityNamePlural:n.entityPlural,schema:l,scope:a,selection:"display",includeCount:false,variables:{where:{_id:{in:s}},limit:s.length}});return useMemo(()=>{let r={};for(let c of u??[]){let p=c[o.name];typeof p=="string"&&p.trim()&&(r[c._id]=p);}return r},[u,o])}function Ye(n){let{currentProject:l}=f(),o=useMemo(()=>l?.schema??[],[l]),a=m$2(o,n.group.entityPlural),s=a$2(a);return !a||!s?jsx(Je,{...n,entityLabel:a?u(a):n.group.entityPlural,labels:{}}):jsx(et,{...n,displayAttribute:s,schema:o,entityLabel:u(a)})}function et({displayAttribute:n,entityLabel:l,schema:o,...a}){let s=Ze(a.group,o,n);return jsx(Je,{...a,entityLabel:l,labels:s})}function Je({canMutate:n,detachingKey:l,entityLabel:o,group:a,labels:s,onDetach:u}){let r=j();return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1",children:[jsx("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:o}),jsx("ul",{className:"fk:flex fk:flex-col fk:-mx-2",children:a.links.map(c=>{let p=p$2(c,s[c.recordId]),h=`${c.entity}:${c.recordId}`;return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1 fk:corner-squircle",children:[jsx("button",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:text-left fk:text-sm fk:hover:underline fk:underline-offset-2",title:c.recordId,type:"button",onClick:()=>r({type:"EditEntity",payload:{entityId:c.recordId,entityNamePlural:a.entityPlural}}),children:p}),n?jsx(fe,{disabled:l!==null,label:`Detach from ${p}`,onClick:()=>u(c)}):null]},h)})})]})}function vt({api:n,projectId:l,source:o}){let a=b$3(),[s,u$1]=useState(null),{data:r,error:c$1,isLoading:p,mutate:h}=H(c(l).links(o.id),b),m=useMemo(()=>r?.links??[],[r]),y=useMemo(()=>r?.entities??[],[r]),f=useMemo(()=>q$1(m),[m]);async function b$1(i){u$1(`${i.entity}:${i.recordId}`);try{await n.unlinkSource(o.id,{entity:i.entity,recordId:i.recordId}),qa.success("Detached."),await h({links:m.filter(d=>d.entity!==i.entity||d.recordId!==i.recordId),entities:y},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function v(i){u$1(`${i.entity}:*`);try{await n.unlinkSource(o.id,{entity:i.entity}),qa.success("Detached."),await h({links:m,entities:y.filter(d=>d.entity!==i.entity)},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function w(i){u$1(`${i.name}:+`);try{let d=await n.linkSource(o.id,{entity:i.name});qa.success(d.linked?`Applies to every ${u(i)} now.`:`Already applied to every ${u(i)}.`),await h({links:m,entities:y.some(g=>g.entity===i.name)?y:[...y,{entity:i.name,entityPlural:i.plural}]},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be attached."));}finally{u$1(null);}}let x;return c$1?x=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The linked records could not be loaded."}):p&&!r?x=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-6 fk:w-1/2"}),jsx(t$1,{className:"fk:h-6 fk:w-1/3"})]}):f.length===0?x=jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:'Not attached to any record. Open a record in the Desk and use "Attach document" so the agent searches this document before the rest of Knowledge when asked about that record.'}):x=jsx("div",{className:"fk:flex fk:flex-col fk:gap-4",children:f.map(i=>jsx(Ye,{canMutate:a,detachingKey:s,group:i,onDetach:d=>{b$1(d);}},i.entityPlural))}),jsxs(Fragment,{children:[jsx(tt,{busy:s!==null,canMutate:a,entities:y,isLoading:p&&!r,onAttach:i=>{w(i);},onDetach:i=>{v(i);}}),jsxs("div",{className:"fk:mt-2 fk:flex fk:items-center fk:gap-2",children:[jsx(PaperclipIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Linked records"}),m.length>0?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:m.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"When a question is about one of these records, the agent searches this document before the rest."}),x]})}function tt({busy:n,canMutate:l,entities:o$1,isLoading:a,onAttach:s,onDetach:u$2}){let{currentProject:r}=f(),c=useMemo(()=>r?.schema??[],[r]),[p,h]=useState(false),m$1=useMemo(()=>v(c,o$1),[o$1,c]),y=f=>{let b=t(c,f.entity);return b?u(b):f.entityPlural};return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-3","data-knowledge-applies-to":true,children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(LayersIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Applies to"}),o$1.length>0?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:o$1.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"Attach this document to a whole entity type and the agent searches it before the rest of Knowledge for every record of that type, and for questions about the type in general."}),a?jsx(t$1,{className:"fk:h-7 fk:w-1/3"}):jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[o$1.map(f=>{let b=y(f);return jsxs(b$2,{className:"fk:gap-1 fk:py-1 fk:pl-2.5 fk:pr-1 fk:corner-squircle",variant:"secondary",children:[jsx("span",{className:"fk:capitalize",children:b}),l?jsxs(b$4,{children:[jsx(c$2,{asChild:true,children:jsx("button",{"aria-label":`No longer apply to every ${b}`,className:"fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:hover:text-foreground fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:disabled:opacity-50",disabled:n,type:"button",onClick:()=>u$2(f),children:jsx(XIcon,{className:"fk:size-3"})})}),jsxs(e$1,{children:["No longer apply to every ",b]})]}):null]},f.entity)}),jsxs(t$2,{open:p,onOpenChange:h,children:[jsx(na,{disabled:!l,children:jsx(u$1,{asChild:true,children:jsxs(b$1,{className:"fk:h-7",disabled:!l||m$1.length===0,size:"sm",variant:"outline",children:[jsx(PlusIcon,{}),"Add entity type"]})})}),jsx(v$1,{align:"start",className:"fk:w-64 fk:p-0",children:jsxs(m,{children:[jsx(o,{placeholder:"Search entity types"}),jsxs(p$1,{children:[jsx(q$2,{children:"No entity type matches."}),jsx(r$1,{children:m$1.map(f=>jsx(t$3,{keywords:[u(f),f.name,f.plural],value:f.name,onSelect:()=>{h(false),s(f);},children:jsx("span",{className:"fk:capitalize",children:u(f)})},f.name))})]})]})})]})]})]})}export{yt as a,bt as b,vt as c};//# sourceMappingURL=chunk-7AN2E6TU.js.map
2
+ //# sourceMappingURL=chunk-7AN2E6TU.js.map