@flexkit/studio 0.2.36 → 0.2.38

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 (75) hide show
  1. package/dist/{chat-page-NDVHLH5Q.js → chat-page-DW3FP4UZ.js} +3 -3
  2. package/dist/{chat-page-NDVHLH5Q.js.map → chat-page-DW3FP4UZ.js.map} +1 -1
  3. package/dist/{chunk-SOA2F7Z6.js → chunk-32B35YDF.js} +3 -3
  4. package/dist/{chunk-SOA2F7Z6.js.map → chunk-32B35YDF.js.map} +1 -1
  5. package/dist/{chunk-MHEFVYKP.js → chunk-377TM7UG.js} +2 -2
  6. package/dist/{chunk-MHEFVYKP.js.map → chunk-377TM7UG.js.map} +1 -1
  7. package/dist/{chunk-GTR4M2BQ.js → chunk-3GXM5SSM.js} +3 -3
  8. package/dist/{chunk-GTR4M2BQ.js.map → chunk-3GXM5SSM.js.map} +1 -1
  9. package/dist/{chunk-474MQNDK.js → chunk-4OGLWOO3.js} +3 -3
  10. package/dist/{chunk-474MQNDK.js.map → chunk-4OGLWOO3.js.map} +1 -1
  11. package/dist/{chunk-27JTWTU6.js → chunk-6J3ZIVDQ.js} +2 -2
  12. package/dist/{chunk-27JTWTU6.js.map → chunk-6J3ZIVDQ.js.map} +1 -1
  13. package/dist/chunk-AQBULUC2.js +10 -0
  14. package/dist/chunk-AQBULUC2.js.map +1 -0
  15. package/dist/{chunk-FXUD4JRG.js → chunk-CCVE7GGO.js} +2 -2
  16. package/dist/{chunk-FXUD4JRG.js.map → chunk-CCVE7GGO.js.map} +1 -1
  17. package/dist/{chunk-2PBDHGRR.js → chunk-DSZJXMN5.js} +2 -2
  18. package/dist/{chunk-2PBDHGRR.js.map → chunk-DSZJXMN5.js.map} +1 -1
  19. package/dist/{chunk-FJS4SN3K.js → chunk-GORBKX24.js} +3 -3
  20. package/dist/{chunk-FJS4SN3K.js.map → chunk-GORBKX24.js.map} +1 -1
  21. package/dist/{chunk-HXPETSXC.js → chunk-GSKQHFQM.js} +3 -3
  22. package/dist/{chunk-HXPETSXC.js.map → chunk-GSKQHFQM.js.map} +1 -1
  23. package/dist/{chunk-VIBGMCLS.js → chunk-IJECATW3.js} +2 -2
  24. package/dist/{chunk-VIBGMCLS.js.map → chunk-IJECATW3.js.map} +1 -1
  25. package/dist/{chunk-TWA6OG5U.js → chunk-INZZOKRC.js} +3 -3
  26. package/dist/{chunk-TWA6OG5U.js.map → chunk-INZZOKRC.js.map} +1 -1
  27. package/dist/{chunk-LTM3MW2D.js → chunk-IUWDNPMY.js} +2 -2
  28. package/dist/{chunk-LTM3MW2D.js.map → chunk-IUWDNPMY.js.map} +1 -1
  29. package/dist/{chunk-FF5EBXYN.js → chunk-JUWAKQPE.js} +3 -3
  30. package/dist/{chunk-FF5EBXYN.js.map → chunk-JUWAKQPE.js.map} +1 -1
  31. package/dist/{chunk-CGMKGENV.js → chunk-KV4OGH5U.js} +2 -2
  32. package/dist/{chunk-CGMKGENV.js.map → chunk-KV4OGH5U.js.map} +1 -1
  33. package/dist/{chunk-LXLEUEWT.js → chunk-LMJEP4VR.js} +2 -2
  34. package/dist/{chunk-LXLEUEWT.js.map → chunk-LMJEP4VR.js.map} +1 -1
  35. package/dist/{chunk-OJ4RI6IQ.js → chunk-UOTVVZPA.js} +3 -3
  36. package/dist/{chunk-OJ4RI6IQ.js.map → chunk-UOTVVZPA.js.map} +1 -1
  37. package/dist/{chunk-NKDQQHCL.js → chunk-WYVXSLB7.js} +2 -2
  38. package/dist/{chunk-NKDQQHCL.js.map → chunk-WYVXSLB7.js.map} +1 -1
  39. package/dist/{entry-XHH3NKN2.js → entry-G2R3W5NU.js} +2 -2
  40. package/dist/{entry-XHH3NKN2.js.map → entry-G2R3W5NU.js.map} +1 -1
  41. package/dist/index.js +2 -2
  42. package/dist/{list-R64THLZD.js → list-IRTUEW55.js} +2 -2
  43. package/dist/{list-R64THLZD.js.map → list-IRTUEW55.js.map} +1 -1
  44. package/dist/{list-XIE55HYD.js → list-LVXMUJHP.js} +3 -3
  45. package/dist/{list-XIE55HYD.js.map → list-LVXMUJHP.js.map} +1 -1
  46. package/dist/{pages-OWXBU64L.js → pages-HJHR7DFO.js} +3 -3
  47. package/dist/{pages-OWXBU64L.js.map → pages-HJHR7DFO.js.map} +1 -1
  48. package/dist/{plugin-pages-JBJQHBIN.js → plugin-pages-ZO3TLUYW.js} +2 -2
  49. package/dist/{plugin-pages-JBJQHBIN.js.map → plugin-pages-ZO3TLUYW.js.map} +1 -1
  50. package/dist/{project-selector-L2WZ3MB5.js → project-selector-OXDEHTJ5.js} +2 -2
  51. package/dist/{project-selector-L2WZ3MB5.js.map → project-selector-OXDEHTJ5.js.map} +1 -1
  52. package/dist/record-links-SZQUATM6.js +2 -0
  53. package/dist/{record-links-BEKOPDDR.js.map → record-links-SZQUATM6.js.map} +1 -1
  54. package/dist/{root-B5XP6VYU.js → root-4ATHF5ZZ.js} +2 -2
  55. package/dist/{root-B5XP6VYU.js.map → root-4ATHF5ZZ.js.map} +1 -1
  56. package/dist/{root-RUOT5OSO.js → root-BIUU3CXY.js} +3 -3
  57. package/dist/{root-RUOT5OSO.js.map → root-BIUU3CXY.js.map} +1 -1
  58. package/dist/{root-DUQULYRX.js → root-BRIEXCDH.js} +2 -2
  59. package/dist/{root-DUQULYRX.js.map → root-BRIEXCDH.js.map} +1 -1
  60. package/dist/{root-I22KNOFC.js → root-E4GIVJYA.js} +3 -3
  61. package/dist/{root-I22KNOFC.js.map → root-E4GIVJYA.js.map} +1 -1
  62. package/dist/{root-VLD6GNZL.js → root-MMGPZ4ZF.js} +3 -3
  63. package/dist/{root-VLD6GNZL.js.map → root-MMGPZ4ZF.js.map} +1 -1
  64. package/dist/{root-O4DMQLEH.js → root-P537YXFS.js} +2 -2
  65. package/dist/{root-O4DMQLEH.js.map → root-P537YXFS.js.map} +1 -1
  66. package/dist/{search-4UQR6ENH.js → search-57W7MXQ3.js} +2 -2
  67. package/dist/{search-4UQR6ENH.js.map → search-57W7MXQ3.js.map} +1 -1
  68. package/dist/{skills-pages-VUIOUEYQ.js → skills-pages-LUOBTEAP.js} +2 -2
  69. package/dist/{skills-pages-VUIOUEYQ.js.map → skills-pages-LUOBTEAP.js.map} +1 -1
  70. package/dist/{source-L54C4T3X.js → source-CJPY5PTU.js} +2 -2
  71. package/dist/{source-L54C4T3X.js.map → source-CJPY5PTU.js.map} +1 -1
  72. package/package.json +5 -5
  73. package/dist/chunk-YJ4NWJCC.js +0 -10
  74. package/dist/chunk-YJ4NWJCC.js.map +0 -1
  75. package/dist/record-links-BEKOPDDR.js +0 -2
@@ -1,4 +1,4 @@
1
- import'./index.css';import {a}from'./chunk-HKN6BX5U.js';import {c}from'./chunk-MBBE4RND.js';import {b,c as c$1}from'./chunk-5CVDMZUI.js';import {useState,useEffect}from'react';var d="0.2.36",L={current:d,latest:d,isCurrent:true};function le(){let e=b(),[t,r]=useState(null);return useEffect(()=>{if(e)return e.onUpdateDownloaded(o=>{r(o.version);})},[e]),e?t===null?{current:e.version,latest:e.version,isCurrent:true}:{current:e.version,latest:t,isCurrent:false,upgrade:()=>e.installUpdate()}:L}var U="flexkit:telemetry",V="flexkit:error-reporting",B=/^(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)$|\.(localhost|test|local)$/i;function M(e){return e.override==="on"?true:e.override==="off"||!e.hosted||e.domain!=="flexkit.io"||e.version==="0.0.0"?false:e.isDesktop||!B.test(e.hostname)}function Y(){try{let e=a();return e?.getItem(U)??e?.getItem(V)??null}catch{return null}}function k({hosted:e}){return typeof window>"u"?false:M({hosted:e,isDesktop:!!b(),domain:c$1,hostname:window.location.hostname,version:d,override:Y()})}async function v(e,t,{keepalive:r=false}={}){return (await fetch(e,{body:t,credentials:"same-origin",headers:{"Content-Type":"application/json"},keepalive:r,method:"POST"})).status}var f={componentStack:4e3,message:2e3,name:200,path:500,stack:8e3,userAgent:500},$=10,G=6e4,K=50,z=5e3,R=/^[a-z0-9]{1,64}$/;function g(e,t){return e.length>t?e.slice(0,t):e}function J(e){let t=e;try{/^[a-z][a-z0-9+.-]*:/i.test(e)&&(t=new URL(e).pathname);}catch{}return g(t.split(/[?#]/)[0]??"",f.path)}function H(e){if(e instanceof Error)return {name:e.name||"Error",message:typeof e.message=="string"?e.message:"",stack:typeof e.stack=="string"?e.stack:void 0};if(typeof e=="string")return {name:"Error",message:e};if(e==null)return {name:"Error",message:`Non-Error thrown: ${String(e)}`};if(typeof e=="object"){let t=e.constructor?.name;return {name:"Error",message:`Non-Error thrown: ${typeof t=="string"&&t?t:"object"}`}}return {name:"Error",message:`Non-Error thrown: ${typeof e}`}}var X=[/ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i,/^Script error\.?$/i,/The (operation|user) (was )?aborted/i,/signal is aborted without reason/i],A=/\b(chrome|moz|safari(-web)?|ms-browser)-extension:\/\//i,F=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi;function Z(e){return e.replace(F,"<email>")}function q(e,t){return e.name==="AbortError"||X.some(r=>r.test(e.message))||t&&A.test(t)?true:!!(e.stack&&A.test(e.stack))}function W(e,t){let r=H(e);if(q(r,t.sourceUrl))return null;let o={source:t.source,name:g(r.name,f.name),message:g(Z(r.message),f.message),occurredAt:(t.now??new Date).toISOString()};return r.stack&&(o.stack=g(r.stack,f.stack)),t.componentStack&&(o.componentStack=g(t.componentStack,f.componentStack)),t.path&&(o.path=J(t.path)),t.projectId&&R.test(t.projectId)&&(o.projectId=t.projectId),o}function Q(e){return `${e.name}
1
+ import'./index.css';import {a}from'./chunk-HKN6BX5U.js';import {c}from'./chunk-MBBE4RND.js';import {b,c as c$1}from'./chunk-5CVDMZUI.js';import {useState,useEffect}from'react';var d="0.2.38",L={current:d,latest:d,isCurrent:true};function le(){let e=b(),[t,r]=useState(null);return useEffect(()=>{if(e)return e.onUpdateDownloaded(o=>{r(o.version);})},[e]),e?t===null?{current:e.version,latest:e.version,isCurrent:true}:{current:e.version,latest:t,isCurrent:false,upgrade:()=>e.installUpdate()}:L}var U="flexkit:telemetry",V="flexkit:error-reporting",B=/^(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)$|\.(localhost|test|local)$/i;function M(e){return e.override==="on"?true:e.override==="off"||!e.hosted||e.domain!=="flexkit.io"||e.version==="0.0.0"?false:e.isDesktop||!B.test(e.hostname)}function Y(){try{let e=a();return e?.getItem(U)??e?.getItem(V)??null}catch{return null}}function k({hosted:e}){return typeof window>"u"?false:M({hosted:e,isDesktop:!!b(),domain:c$1,hostname:window.location.hostname,version:d,override:Y()})}async function v(e,t,{keepalive:r=false}={}){return (await fetch(e,{body:t,credentials:"same-origin",headers:{"Content-Type":"application/json"},keepalive:r,method:"POST"})).status}var f={componentStack:4e3,message:2e3,name:200,path:500,stack:8e3,userAgent:500},$=10,G=6e4,K=50,z=5e3,R=/^[a-z0-9]{1,64}$/;function g(e,t){return e.length>t?e.slice(0,t):e}function J(e){let t=e;try{/^[a-z][a-z0-9+.-]*:/i.test(e)&&(t=new URL(e).pathname);}catch{}return g(t.split(/[?#]/)[0]??"",f.path)}function H(e){if(e instanceof Error)return {name:e.name||"Error",message:typeof e.message=="string"?e.message:"",stack:typeof e.stack=="string"?e.stack:void 0};if(typeof e=="string")return {name:"Error",message:e};if(e==null)return {name:"Error",message:`Non-Error thrown: ${String(e)}`};if(typeof e=="object"){let t=e.constructor?.name;return {name:"Error",message:`Non-Error thrown: ${typeof t=="string"&&t?t:"object"}`}}return {name:"Error",message:`Non-Error thrown: ${typeof e}`}}var X=[/ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i,/^Script error\.?$/i,/The (operation|user) (was )?aborted/i,/signal is aborted without reason/i],A=/\b(chrome|moz|safari(-web)?|ms-browser)-extension:\/\//i,F=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi;function Z(e){return e.replace(F,"<email>")}function q(e,t){return e.name==="AbortError"||X.some(r=>r.test(e.message))||t&&A.test(t)?true:!!(e.stack&&A.test(e.stack))}function W(e,t){let r=H(e);if(q(r,t.sourceUrl))return null;let o={source:t.source,name:g(r.name,f.name),message:g(Z(r.message),f.message),occurredAt:(t.now??new Date).toISOString()};return r.stack&&(o.stack=g(r.stack,f.stack)),t.componentStack&&(o.componentStack=g(t.componentStack,f.componentStack)),t.path&&(o.path=J(t.path)),t.projectId&&R.test(t.projectId)&&(o.projectId=t.projectId),o}function Q(e){return `${e.name}
2
2
  ${e.message}
3
- ${e.stack??""}`}var ee=new TextEncoder;function P(e){return ee.encode(e).length}function te(e,t,r=G){let o=P(JSON.stringify({app:e,errors:[]})),s=[];for(let i of t.slice(0,$)){let n=P(JSON.stringify(i))+(s.length?1:0);if(o+n>r)break;o+=n,s.push(i);}return s.length===0?null:{body:JSON.stringify({app:e,errors:s}),count:s.length}}function re({app:e,send:t,getPath:r,now:o=()=>new Date,setTimer:s=(n,u)=>setTimeout(n,u),clearTimer:i=n=>clearTimeout(n)}){let n=[],u=new Set,_=0,y=null,a=null,E=false;function T(){a===null&&n.length>0&&!E&&(a=s(()=>{a=null,x();},z));}function D(l){let S=te(e,n);return S?(n.splice(0,S.count),t(S.body,{unloading:l}).then(p=>{(p===401||p===403||p===429)&&(E=true,n.length=0);}).catch(()=>{}),n.length>0):(n.shift(),n.length>0)}function x({unloading:l=false}={}){try{if(E)return;a!==null&&l&&(i(a),a=null),n.length>0&&D(l),T();}catch{}}return {report(l,S){try{if(E||_>=K)return;let p=W(l,{...S,now:o(),path:r?.(),projectId:y});if(!p)return;let b=Q(p);if(u.has(b))return;u.add(b),_+=1,n.push(p),T();}catch{}},setProjectId(l){y=l;},flush:x,pending:()=>n,dispose(){a!==null&&(i(a),a=null),E=true,n.length=0;}}}var ne=async(e,{unloading:t})=>{let r=c.clientErrors;if(t&&!b()&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{if(navigator.sendBeacon(r,new Blob([e],{type:"text/plain"})))return null}catch{}return v(r,e,{keepalive:t})},m=null;function we(e,{source:t="manual",componentStack:r}={}){m?.report(e,{source:t,componentStack:r});}function Re(e){m?.setProjectId(e);}function _e({hosted:e}){if(typeof window>"u"||m)return ()=>{};if(!k({hosted:e}))return ()=>{};let t=b(),r=re({app:{platform:t?"desktop":"web",version:d,userAgent:g(navigator.userAgent,f.userAgent)},send:ne,getPath:()=>window.location.pathname});function o(n){r.report(n.error??n.message,{source:"window",sourceUrl:n.filename});}function s(n){r.report(n.reason,{source:"unhandledrejection"});}function i(){r.flush({unloading:true});}return window.addEventListener("error",o),window.addEventListener("unhandledrejection",s),window.addEventListener("pagehide",i),m=r,()=>{window.removeEventListener("error",o),window.removeEventListener("unhandledrejection",s),window.removeEventListener("pagehide",i),r.flush({unloading:true}),r.dispose(),m===r&&(m=null);}}function oe(e){return e.event==="graph_opened"?`graph_opened:${e.projectId}`:e.event}function ie(e){let t=new Set,r=new Set;return {track(o,{onDelivered:s}={}){let i=oe(o);if(t.has(i)||r.has(i))return;t.add(i);let n=u=>{t.delete(i),u!==null&&u>=200&&u<300&&(r.add(i),s?.());};try{e(JSON.stringify(o)).then(n,()=>n(null));}catch{n(null);}}}}var w=null;function Oe(e){e.event==="graph_opened"&&!R.test(e.projectId)||w?.track(e);}var C="flexkit:desktop-launch-recorded";function se(e){try{return sessionStorage.getItem(e)==="1"}catch{return false}}function ae(e){try{sessionStorage.setItem(e,"1");}catch{}}function Ae({hosted:e}){if(!k({hosted:e}))return ()=>{};let t=ie(o=>v(c.productEvents,o,{keepalive:true})),r=b();return w=t,r&&!se(C)&&t.track({appVersion:r.version,event:"desktop_app_opened",os:r.platform},{onDelivered:()=>ae(C)}),()=>{w===t&&(w=null);}}export{le as a,we as b,Re as c,_e as d,Oe as e,Ae as f};//# sourceMappingURL=chunk-SOA2F7Z6.js.map
4
- //# sourceMappingURL=chunk-SOA2F7Z6.js.map
3
+ ${e.stack??""}`}var ee=new TextEncoder;function P(e){return ee.encode(e).length}function te(e,t,r=G){let o=P(JSON.stringify({app:e,errors:[]})),s=[];for(let i of t.slice(0,$)){let n=P(JSON.stringify(i))+(s.length?1:0);if(o+n>r)break;o+=n,s.push(i);}return s.length===0?null:{body:JSON.stringify({app:e,errors:s}),count:s.length}}function re({app:e,send:t,getPath:r,now:o=()=>new Date,setTimer:s=(n,u)=>setTimeout(n,u),clearTimer:i=n=>clearTimeout(n)}){let n=[],u=new Set,_=0,y=null,a=null,E=false;function T(){a===null&&n.length>0&&!E&&(a=s(()=>{a=null,x();},z));}function D(l){let S=te(e,n);return S?(n.splice(0,S.count),t(S.body,{unloading:l}).then(p=>{(p===401||p===403||p===429)&&(E=true,n.length=0);}).catch(()=>{}),n.length>0):(n.shift(),n.length>0)}function x({unloading:l=false}={}){try{if(E)return;a!==null&&l&&(i(a),a=null),n.length>0&&D(l),T();}catch{}}return {report(l,S){try{if(E||_>=K)return;let p=W(l,{...S,now:o(),path:r?.(),projectId:y});if(!p)return;let b=Q(p);if(u.has(b))return;u.add(b),_+=1,n.push(p),T();}catch{}},setProjectId(l){y=l;},flush:x,pending:()=>n,dispose(){a!==null&&(i(a),a=null),E=true,n.length=0;}}}var ne=async(e,{unloading:t})=>{let r=c.clientErrors;if(t&&!b()&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{if(navigator.sendBeacon(r,new Blob([e],{type:"text/plain"})))return null}catch{}return v(r,e,{keepalive:t})},m=null;function we(e,{source:t="manual",componentStack:r}={}){m?.report(e,{source:t,componentStack:r});}function Re(e){m?.setProjectId(e);}function _e({hosted:e}){if(typeof window>"u"||m)return ()=>{};if(!k({hosted:e}))return ()=>{};let t=b(),r=re({app:{platform:t?"desktop":"web",version:d,userAgent:g(navigator.userAgent,f.userAgent)},send:ne,getPath:()=>window.location.pathname});function o(n){r.report(n.error??n.message,{source:"window",sourceUrl:n.filename});}function s(n){r.report(n.reason,{source:"unhandledrejection"});}function i(){r.flush({unloading:true});}return window.addEventListener("error",o),window.addEventListener("unhandledrejection",s),window.addEventListener("pagehide",i),m=r,()=>{window.removeEventListener("error",o),window.removeEventListener("unhandledrejection",s),window.removeEventListener("pagehide",i),r.flush({unloading:true}),r.dispose(),m===r&&(m=null);}}function oe(e){return e.event==="graph_opened"?`graph_opened:${e.projectId}`:e.event}function ie(e){let t=new Set,r=new Set;return {track(o,{onDelivered:s}={}){let i=oe(o);if(t.has(i)||r.has(i))return;t.add(i);let n=u=>{t.delete(i),u!==null&&u>=200&&u<300&&(r.add(i),s?.());};try{e(JSON.stringify(o)).then(n,()=>n(null));}catch{n(null);}}}}var w=null;function Oe(e){e.event==="graph_opened"&&!R.test(e.projectId)||w?.track(e);}var C="flexkit:desktop-launch-recorded";function se(e){try{return sessionStorage.getItem(e)==="1"}catch{return false}}function ae(e){try{sessionStorage.setItem(e,"1");}catch{}}function Ae({hosted:e}){if(!k({hosted:e}))return ()=>{};let t=ie(o=>v(c.productEvents,o,{keepalive:true})),r=b();return w=t,r&&!se(C)&&t.track({appVersion:r.version,event:"desktop_app_opened",os:r.platform},{onDelivered:()=>ae(C)}),()=>{w===t&&(w=null);}}export{le as a,we as b,Re as c,_e as d,Oe as e,Ae as f};//# sourceMappingURL=chunk-32B35YDF.js.map
4
+ //# sourceMappingURL=chunk-32B35YDF.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/use-studio-version.ts","../src/core/telemetry.ts","../src/core/error/error-reporter.ts","../src/core/analytics/product-events.ts"],"names":["STUDIO_VERSION","WEB_VERSION","useStudioVersion","desktop","getDesktop","downloaded","setDownloaded","useState","useEffect","update","TELEMETRY_STORAGE_KEY","LEGACY_TELEMETRY_STORAGE_KEY","LOCAL_HOSTNAME","isTelemetryEnabled","env","readOverride","storage","getLocalStorage","isStudioTelemetryEnabled","hosted","flexkitDomain","postToUserApi","path","body","keepalive","LIMITS","MAX_ERRORS_PER_REPORT","MAX_REPORT_BYTES","MAX_ERRORS_PER_SESSION","FLUSH_INTERVAL_MS","PROJECT_ID_PATTERN","truncate","value","max","toReportPath","pathOrUrl","describeError","error","constructorName","NOISE_MESSAGES","EXTENSION_URL","EMAIL_ADDRESS","maskMessage","message","isNoiseError","details","sourceUrl","pattern","buildClientError","options","entry","errorKey","encoder","byteLength","buildReportBody","app","queue","maxBytes","size","errors","errorSize","createErrorReporter","send","getPath","now","setTimer","callback","ms","clearTimer","timer","seen","accepted","projectId","stopped","schedule","flush","sendNext","unloading","next","status","key","id","sendReportToBff","url","userApiPaths","installed","reportStudioError","source","componentStack","setErrorReportingProjectId","installErrorReporter","reporter","onError","event","onUnhandledRejection","onPageHide","productEventKey","studioEvent","createProductEventTracker","pending","delivered","onDelivered","settle","tracker","trackStudioEvent","DESKTOP_LAUNCH_STORAGE_KEY","readSessionFlag","writeSessionFlag","installProductEvents","current"],"mappings":"gLAeO,IAAMA,CAAAA,CAA0D,QAAA,CACjEC,CAAAA,CAA6B,CAAE,OAAA,CAASD,CAAAA,CAAgB,MAAA,CAAQA,CAAAA,CAAgB,SAAA,CAAW,IAAK,CAAA,CAO/F,SAASE,EAAAA,EAAkC,CAChD,IAAMC,CAAAA,CAAUC,CAAAA,EAAW,CACrB,CAACC,CAAAA,CAAYC,CAAa,CAAA,CAAIC,SAAwB,IAAI,CAAA,CAYhE,OAVAC,SAAAA,CAAU,IAAM,CACd,GAAKL,CAAAA,CAIL,OAAOA,CAAAA,CAAQ,kBAAA,CAAoBM,CAAAA,EAAW,CAC5CH,CAAAA,CAAcG,CAAAA,CAAO,OAAO,EAC9B,CAAC,CACH,CAAA,CAAG,CAACN,CAAO,CAAC,CAAA,CAEPA,CAAAA,CAIDE,CAAAA,GAAe,IAAA,CACV,CAAE,OAAA,CAASF,CAAAA,CAAQ,OAAA,CAAS,MAAA,CAAQA,CAAAA,CAAQ,QAAS,SAAA,CAAW,IAAK,CAAA,CAGvE,CAAE,OAAA,CAASA,CAAAA,CAAQ,OAAA,CAAS,MAAA,CAAQE,CAAAA,CAAY,SAAA,CAAW,KAAA,CAAO,OAAA,CAAS,IAAMF,CAAAA,CAAQ,aAAA,EAAgB,CAAA,CAPvGF,CAQX,CClCO,IAAMS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AAAA,EAAW,CAE3B,OAAAmG,CAAAA,CAAUM,CAAAA,CAEN1G,GAAW,CAACuG,EAAAA,CAAgBD,CAA0B,CAAA,EACxDI,CAAAA,CAAQ,KAAA,CACN,CAAE,UAAA,CAAY1G,CAAAA,CAAQ,QAAS,KAAA,CAAO,oBAAA,CAAsB,GAAIA,CAAAA,CAAQ,QAAS,CAAA,CACjF,CAAE,WAAA,CAAa,IAAMwG,GAAiBF,CAA0B,CAAE,CACpE,CAAA,CAGK,IAAM,CACPF,CAAAA,GAAYM,CAAAA,GACdN,CAAAA,CAAU,IAAA,EAEd,CACF","file":"chunk-SOA2F7Z6.js","sourcesContent":["'use client';\n\nimport { useEffect, useState } from 'react';\nimport { getDesktop } from './desktop';\n\nexport interface StudioVersion {\n current: string;\n latest: string;\n isCurrent: boolean;\n /** Applies the newer version (the desktop app restarts into it); undefined when there is nothing to apply. */\n upgrade?: () => void;\n}\n\n// `@flexkit/studio`'s own version, inlined at build time; a build without the\n// define (tests, tooling) shows a placeholder.\nexport const STUDIO_VERSION = typeof __STUDIO_VERSION__ === 'string' ? __STUDIO_VERSION__ : '0.0.0';\nconst WEB_VERSION: StudioVersion = { current: STUDIO_VERSION, latest: STUDIO_VERSION, isCurrent: true };\n\n/**\n * The Studio version shown in the app bar. The web Studio is always current\n * (the hosted Studio deploys with the packages); the desktop app reports its\n * own version and the update it has downloaded, if any.\n */\nexport function useStudioVersion(): StudioVersion {\n const desktop = getDesktop();\n const [downloaded, setDownloaded] = useState<string | null>(null);\n\n useEffect(() => {\n if (!desktop) {\n return;\n }\n\n return desktop.onUpdateDownloaded((update) => {\n setDownloaded(update.version);\n });\n }, [desktop]);\n\n if (!desktop) {\n return WEB_VERSION;\n }\n\n if (downloaded === null) {\n return { current: desktop.version, latest: desktop.version, isCurrent: true };\n }\n\n return { current: desktop.version, latest: downloaded, isCurrent: false, upgrade: () => desktop.installUpdate() };\n}\n","import { getDesktop } from './desktop';\nimport { flexkitDomain } from './domains';\nimport { getLocalStorage } from './local-storage';\nimport { STUDIO_VERSION } from './use-studio-version';\n\n/**\n * The on/off decision and the transport shared by the Studio's error reports\n * (core/error/error-reporter.ts) and product events\n * (core/analytics/product-events.ts).\n */\n\n/** Turns error reports and product events on (`on`) or off (`off`) in this browser, whatever the environment. */\nexport const TELEMETRY_STORAGE_KEY = 'flexkit:telemetry';\n/** The key error reporting shipped with; still honoured. */\nexport const LEGACY_TELEMETRY_STORAGE_KEY = 'flexkit:error-reporting';\n\nexport interface TelemetryEnvironment {\n /** The Studio lists the signed-in user's projects (hosted Studio, desktop app). */\n hosted: boolean;\n isDesktop: boolean;\n domain: string;\n hostname: string;\n version: string;\n /** The local storage setting in this browser, if any. */\n override: string | null;\n}\n\nconst LOCAL_HOSTNAME = /^(localhost|127\\.0\\.0\\.1|\\[::1\\]|0\\.0\\.0\\.0)$|\\.(localhost|test|local)$/i;\n\n/**\n * On for the hosted Studio and the desktop app against the production\n * backend, and off in development: a local backend (`flexkit.test`), a local\n * host, or a build without a version. The local storage setting forces it\n * `on` or `off`.\n */\nexport function isTelemetryEnabled(env: TelemetryEnvironment): boolean {\n if (env.override === 'on') {\n return true;\n }\n\n if (env.override === 'off') {\n return false;\n }\n\n if (!env.hosted || env.domain !== 'flexkit.io' || env.version === '0.0.0') {\n return false;\n }\n\n return env.isDesktop || !LOCAL_HOSTNAME.test(env.hostname);\n}\n\nfunction readOverride(): string | null {\n try {\n const storage = getLocalStorage();\n\n return storage?.getItem(TELEMETRY_STORAGE_KEY) ?? storage?.getItem(LEGACY_TELEMETRY_STORAGE_KEY) ?? null;\n } catch {\n return null;\n }\n}\n\n/** Whether this Studio sends error reports and product events to Flexkit. */\nexport function isStudioTelemetryEnabled({ hosted }: { hosted: boolean }): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n return isTelemetryEnabled({\n hosted,\n isDesktop: Boolean(getDesktop()),\n domain: flexkitDomain,\n hostname: window.location.hostname,\n version: STUDIO_VERSION,\n override: readOverride(),\n });\n}\n\n/**\n * POSTs JSON to a user-level backend route through the Studio's server proxy,\n * which adds the session. `keepalive` lets the request outlive the page.\n * Returns the response status.\n */\nexport async function postToUserApi(path: string, body: string, { keepalive = false } = {}): Promise<number> {\n const response = await fetch(path, {\n body,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n keepalive,\n method: 'POST',\n });\n\n return response.status;\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { STUDIO_VERSION } from '../use-studio-version';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Reports unexpected Studio errors (uncaught errors, unhandled rejections and\n * errors caught by the error boundaries) to Flexkit through the Studio's own\n * BFF (`/api/flexkit/-/client-errors`), which forwards the session so the\n * report is attributed to the signed-in user.\n *\n * Reports carry the error, the Studio path (no query string or hash) and the\n * current project id; never request bodies, form values or record data.\n */\n\nexport type ClientErrorSource = 'window' | 'unhandledrejection' | 'react' | 'manual';\n\nexport interface ClientError {\n source: ClientErrorSource;\n name: string;\n message: string;\n stack?: string;\n componentStack?: string;\n path?: string;\n projectId?: string;\n occurredAt: string;\n}\n\nexport interface ClientErrorApp {\n platform: 'web' | 'desktop';\n version: string;\n userAgent?: string;\n}\n\nexport interface ClientErrorReport {\n app: ClientErrorApp;\n errors: ClientError[];\n}\n\n/** Field limits of the backend schema. */\nconst LIMITS = {\n componentStack: 4_000,\n message: 2_000,\n name: 200,\n path: 500,\n stack: 8_000,\n userAgent: 500,\n} as const;\n\n/** The backend accepts 1 to 10 errors per report. */\nexport const MAX_ERRORS_PER_REPORT = 10;\n/** The backend refuses bodies over 64 KB; `keepalive` requests share a 64 KB budget too. */\nexport const MAX_REPORT_BYTES = 60_000;\n/** Reports kept per page session; anything after that is dropped. */\nexport const MAX_ERRORS_PER_SESSION = 50;\n/** At most one report is sent per interval; errors in between are batched. */\nexport const FLUSH_INTERVAL_MS = 5_000;\n\n/** Kept for callers and tests that name the gate after error reporting. */\nexport {\n isTelemetryEnabled as isErrorReportingEnabled,\n LEGACY_TELEMETRY_STORAGE_KEY as ERROR_REPORTING_STORAGE_KEY,\n type TelemetryEnvironment as ErrorReportingEnvironment,\n} from '../telemetry';\n\nexport const PROJECT_ID_PATTERN = /^[a-z0-9]{1,64}$/;\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? value.slice(0, max) : value;\n}\n\n/** The pathname of a path or URL, without query string or hash. */\nexport function toReportPath(pathOrUrl: string): string {\n let path = pathOrUrl;\n\n try {\n if (/^[a-z][a-z0-9+.-]*:/i.test(pathOrUrl)) {\n path = new URL(pathOrUrl).pathname;\n }\n } catch {\n // Not a URL; strip by hand below.\n }\n\n return truncate(path.split(/[?#]/)[0] ?? '', LIMITS.path);\n}\n\nexport interface ErrorDetails {\n name: string;\n message: string;\n stack?: string;\n}\n\n/**\n * Name, message and stack of anything thrown. A non-Error value (a rejected\n * promise with a plain object) is described by its type only, so record data\n * someone rejected with never leaves the browser.\n */\nexport function describeError(error: unknown): ErrorDetails {\n if (error instanceof Error) {\n return {\n name: error.name || 'Error',\n message: typeof error.message === 'string' ? error.message : '',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n };\n }\n\n if (typeof error === 'string') {\n return { name: 'Error', message: error };\n }\n\n if (error === null || error === undefined) {\n return { name: 'Error', message: `Non-Error thrown: ${String(error)}` };\n }\n\n if (typeof error === 'object') {\n const constructorName = (error as { constructor?: { name?: unknown } }).constructor?.name;\n\n return {\n name: 'Error',\n message: `Non-Error thrown: ${typeof constructorName === 'string' && constructorName ? constructorName : 'object'}`,\n };\n }\n\n return { name: 'Error', message: `Non-Error thrown: ${typeof error}` };\n}\n\nconst NOISE_MESSAGES = [\n /ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i,\n // Cross-origin script errors carry nothing to act on.\n /^Script error\\.?$/i,\n /The (operation|user) (was )?aborted/i,\n /signal is aborted without reason/i,\n];\n\nconst EXTENSION_URL = /\\b(chrome|moz|safari(-web)?|ms-browser)-extension:\\/\\//i;\n\nconst EMAIL_ADDRESS = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi;\n\n/** Masks email addresses an error message may quote from a record or form. */\nexport function maskMessage(message: string): string {\n return message.replace(EMAIL_ADDRESS, '<email>');\n}\n\n/** Errors that are not Studio bugs: browser quirks, aborted requests, browser extensions. */\nexport function isNoiseError(details: ErrorDetails, sourceUrl?: string): boolean {\n if (details.name === 'AbortError') {\n return true;\n }\n\n if (NOISE_MESSAGES.some((pattern) => pattern.test(details.message))) {\n return true;\n }\n\n if (sourceUrl && EXTENSION_URL.test(sourceUrl)) {\n return true;\n }\n\n return Boolean(details.stack && EXTENSION_URL.test(details.stack));\n}\n\nexport interface BuildClientErrorOptions {\n source: ClientErrorSource;\n componentStack?: string;\n path?: string;\n projectId?: string | null;\n /** The script the error came from (`ErrorEvent.filename`), checked for browser extensions. */\n sourceUrl?: string;\n now?: Date;\n}\n\n/** The report entry for an error, or null when it is noise. */\nexport function buildClientError(error: unknown, options: BuildClientErrorOptions): ClientError | null {\n const details = describeError(error);\n\n if (isNoiseError(details, options.sourceUrl)) {\n return null;\n }\n\n const entry: ClientError = {\n source: options.source,\n name: truncate(details.name, LIMITS.name),\n message: truncate(maskMessage(details.message), LIMITS.message),\n occurredAt: (options.now ?? new Date()).toISOString(),\n };\n\n if (details.stack) {\n entry.stack = truncate(details.stack, LIMITS.stack);\n }\n\n if (options.componentStack) {\n entry.componentStack = truncate(options.componentStack, LIMITS.componentStack);\n }\n\n if (options.path) {\n entry.path = toReportPath(options.path);\n }\n\n if (options.projectId && PROJECT_ID_PATTERN.test(options.projectId)) {\n entry.projectId = options.projectId;\n }\n\n return entry;\n}\n\n/** Identity of an error within a page session: the same message and stack are reported once. */\nexport function errorKey(error: Pick<ClientError, 'message' | 'name' | 'stack'>): string {\n return `${error.name}\\n${error.message}\\n${error.stack ?? ''}`;\n}\n\nconst encoder = new TextEncoder();\n\nfunction byteLength(value: string): number {\n return encoder.encode(value).length;\n}\n\n/**\n * Takes the errors that fit one report (at most 10 and `maxBytes` of JSON)\n * off the front of the queue. Returns the request body and how many errors it holds.\n */\nexport function buildReportBody(\n app: ClientErrorApp,\n queue: readonly ClientError[],\n maxBytes = MAX_REPORT_BYTES\n): { body: string; count: number } | null {\n // The envelope plus each error once, joined by commas.\n let size = byteLength(JSON.stringify({ app, errors: [] } satisfies ClientErrorReport));\n const errors: ClientError[] = [];\n\n for (const error of queue.slice(0, MAX_ERRORS_PER_REPORT)) {\n const errorSize = byteLength(JSON.stringify(error)) + (errors.length ? 1 : 0);\n\n if (size + errorSize > maxBytes) {\n break;\n }\n\n size += errorSize;\n errors.push(error);\n }\n\n if (errors.length === 0) {\n return null;\n }\n\n return { body: JSON.stringify({ app, errors } satisfies ClientErrorReport), count: errors.length };\n}\n\nexport type SendReport = (body: string, options: { unloading: boolean }) => Promise<number | null>;\n\nexport interface ErrorReporterOptions {\n app: ClientErrorApp;\n send: SendReport;\n /** The current Studio path; only its pathname is sent. */\n getPath?: () => string | undefined;\n now?: () => Date;\n setTimer?: (callback: () => void, ms: number) => unknown;\n clearTimer?: (timer: unknown) => void;\n}\n\nexport interface ErrorReporter {\n report: (error: unknown, options: Omit<BuildClientErrorOptions, 'path' | 'projectId' | 'now'>) => void;\n setProjectId: (projectId: string | null) => void;\n /** Sends the next report now; `unloading` uses a beacon or keepalive request that outlives the page. */\n flush: (options?: { unloading?: boolean }) => void;\n /** Errors waiting to be sent (tests). */\n pending: () => readonly ClientError[];\n dispose: () => void;\n}\n\n/** The queue, dedupe, cap and batching; the transport and the clock are injected. */\nexport function createErrorReporter({\n app,\n send,\n getPath,\n now = () => new Date(),\n setTimer = (callback, ms) => setTimeout(callback, ms),\n clearTimer = (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),\n}: ErrorReporterOptions): ErrorReporter {\n const queue: ClientError[] = [];\n const seen = new Set<string>();\n let accepted = 0;\n let projectId: string | null = null;\n let timer: unknown = null;\n let stopped = false;\n\n function schedule(): void {\n if (timer === null && queue.length > 0 && !stopped) {\n timer = setTimer(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n function sendNext(unloading: boolean): boolean {\n const next = buildReportBody(app, queue);\n\n if (!next) {\n // An error that cannot fit a report on its own; drop it.\n queue.shift();\n\n return queue.length > 0;\n }\n\n queue.splice(0, next.count);\n send(next.body, { unloading })\n .then((status) => {\n // Rate limited or not allowed: stop for this page session rather than retry.\n if (status === 401 || status === 403 || status === 429) {\n stopped = true;\n queue.length = 0;\n }\n })\n .catch(() => {\n // Never report the reporter's own failures.\n });\n\n return queue.length > 0;\n }\n\n function flush({ unloading = false }: { unloading?: boolean } = {}): void {\n try {\n if (stopped) {\n return;\n }\n\n if (timer !== null && unloading) {\n clearTimer(timer);\n timer = null;\n }\n\n // One report per flush, also when the page goes away: beacons and\n // keepalive requests share a 64 KB budget, so a second would be refused.\n if (queue.length > 0) {\n sendNext(unloading);\n }\n\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n }\n\n return {\n report(error, options) {\n try {\n if (stopped || accepted >= MAX_ERRORS_PER_SESSION) {\n return;\n }\n\n const entry = buildClientError(error, {\n ...options,\n now: now(),\n path: getPath?.(),\n projectId,\n });\n\n if (!entry) {\n return;\n }\n\n const key = errorKey(entry);\n\n if (seen.has(key)) {\n return;\n }\n\n seen.add(key);\n accepted += 1;\n queue.push(entry);\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n },\n setProjectId(id) {\n projectId = id;\n },\n flush,\n pending: () => queue,\n dispose() {\n if (timer !== null) {\n clearTimer(timer);\n timer = null;\n }\n\n stopped = true;\n queue.length = 0;\n },\n };\n}\n\n/** Sends a report through the BFF; a beacon when the page is going away on the web. */\nexport const sendReportToBff: SendReport = async (body, { unloading }) => {\n const url = userApiPaths.clientErrors;\n\n // A beacon outlives the page. The BFF reads its JSON body like a fetch's\n // and the browser sends the session cookie with it (same origin). The\n // desktop app's BFF only answers script requests, so it uses `keepalive`.\n if (unloading && !getDesktop() && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n try {\n // text/plain is CORS-safelisted, so no browser refuses the beacon; the body is still JSON.\n if (navigator.sendBeacon(url, new Blob([body], { type: 'text/plain' }))) {\n return null;\n }\n } catch {\n // Fall back to a keepalive fetch.\n }\n }\n\n return postToUserApi(url, body, { keepalive: unloading });\n};\n\nlet installed: ErrorReporter | null = null;\n\n/** Reports an error caught by the Studio (an error boundary, for example). Does nothing when reporting is off. */\nexport function reportStudioError(\n error: unknown,\n { source = 'manual', componentStack }: { source?: ClientErrorSource; componentStack?: string } = {}\n): void {\n installed?.report(error, { source, componentStack });\n}\n\n/** The project the Studio shows, added to reports; null outside a project. */\nexport function setErrorReportingProjectId(projectId: string | null): void {\n installed?.setProjectId(projectId);\n}\n\n/**\n * Starts reporting uncaught errors and unhandled rejections when reporting is\n * enabled for this environment. Returns the function that stops it.\n */\nexport function installErrorReporter({ hosted }: { hosted: boolean }): () => void {\n if (typeof window === 'undefined' || installed) {\n return () => undefined;\n }\n\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const desktop = getDesktop();\n\n const reporter = createErrorReporter({\n app: {\n platform: desktop ? 'desktop' : 'web',\n version: STUDIO_VERSION,\n userAgent: truncate(navigator.userAgent, LIMITS.userAgent),\n },\n send: sendReportToBff,\n getPath: () => window.location.pathname,\n });\n\n function onError(event: ErrorEvent): void {\n reporter.report(event.error ?? event.message, { source: 'window', sourceUrl: event.filename });\n }\n\n function onUnhandledRejection(event: PromiseRejectionEvent): void {\n reporter.report(event.reason, { source: 'unhandledrejection' });\n }\n\n function onPageHide(): void {\n reporter.flush({ unloading: true });\n }\n\n window.addEventListener('error', onError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n window.addEventListener('pagehide', onPageHide);\n installed = reporter;\n\n return () => {\n window.removeEventListener('error', onError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n window.removeEventListener('pagehide', onPageHide);\n reporter.flush({ unloading: true });\n reporter.dispose();\n\n if (installed === reporter) {\n installed = null;\n }\n };\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { PROJECT_ID_PATTERN } from '../error/error-reporter';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Product events only the Studio can see, sent to Flexkit through the\n * Studio's own server proxy (`/api/flexkit/-/product-events`) with the\n * session: the Graph app opened, the desktop app launched. They follow the\n * Studio's telemetry setting (see core/telemetry.ts) and carry ids, the\n * desktop app version and the OS only.\n */\nexport type StudioProductEvent =\n | { event: 'graph_opened'; projectId: string }\n | { event: 'desktop_app_opened'; appVersion: string; os: 'darwin' | 'linux' | 'win32' };\n\n/** Identity of an event within a page session; the backend also counts each once per day. */\nexport function productEventKey(studioEvent: StudioProductEvent): string {\n return studioEvent.event === 'graph_opened' ? `graph_opened:${studioEvent.projectId}` : studioEvent.event;\n}\n\n/** Sends the event body; resolves with the response status. */\nexport type SendProductEvent = (body: string) => Promise<number>;\n\nexport interface ProductEventTracker {\n track: (studioEvent: StudioProductEvent, options?: { onDelivered?: () => void }) => void;\n}\n\n/**\n * Sends each event once per page session through `send`. An event counts as\n * sent only once the backend accepted it, so one sent while offline or signed\n * out is sent again next time. Never throws.\n */\nexport function createProductEventTracker(send: SendProductEvent): ProductEventTracker {\n const pending = new Set<string>();\n const delivered = new Set<string>();\n\n return {\n track(studioEvent, { onDelivered } = {}) {\n const key = productEventKey(studioEvent);\n\n if (pending.has(key) || delivered.has(key)) {\n return;\n }\n\n pending.add(key);\n\n const settle = (status: number | null): void => {\n pending.delete(key);\n\n if (status !== null && status >= 200 && status < 300) {\n delivered.add(key);\n onDelivered?.();\n }\n };\n\n try {\n send(JSON.stringify(studioEvent)).then(settle, () => settle(null));\n } catch {\n settle(null);\n }\n },\n };\n}\n\nlet tracker: ProductEventTracker | null = null;\n\n/** Records an event when product events are on (see `installProductEvents`); otherwise does nothing. */\nexport function trackStudioEvent(studioEvent: StudioProductEvent): void {\n if (studioEvent.event === 'graph_opened' && !PROJECT_ID_PATTERN.test(studioEvent.projectId)) {\n return;\n }\n\n tracker?.track(studioEvent);\n}\n\n/** Session storage flag: this desktop app launch was recorded (page reloads keep it, a relaunch does not). */\nexport const DESKTOP_LAUNCH_STORAGE_KEY = 'flexkit:desktop-launch-recorded';\n\nfunction readSessionFlag(key: string): boolean {\n try {\n return sessionStorage.getItem(key) === '1';\n } catch {\n return false;\n }\n}\n\nfunction writeSessionFlag(key: string): void {\n try {\n sessionStorage.setItem(key, '1');\n } catch {\n // Without session storage the backend's once-per-day count still applies.\n }\n}\n\n/**\n * Turns product events on for this environment and records the desktop app\n * launch (once per launch, once the user is signed in). Returns the function\n * that turns them off again.\n */\nexport function installProductEvents({ hosted }: { hosted: boolean }): () => void {\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const current = createProductEventTracker((body) =>\n postToUserApi(userApiPaths.productEvents, body, { keepalive: true })\n );\n const desktop = getDesktop();\n\n tracker = current;\n\n if (desktop && !readSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY)) {\n current.track(\n { appVersion: desktop.version, event: 'desktop_app_opened', os: desktop.platform },\n { onDelivered: () => writeSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY) }\n );\n }\n\n return () => {\n if (tracker === current) {\n tracker = null;\n }\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/core/use-studio-version.ts","../src/core/telemetry.ts","../src/core/error/error-reporter.ts","../src/core/analytics/product-events.ts"],"names":["STUDIO_VERSION","WEB_VERSION","useStudioVersion","desktop","getDesktop","downloaded","setDownloaded","useState","useEffect","update","TELEMETRY_STORAGE_KEY","LEGACY_TELEMETRY_STORAGE_KEY","LOCAL_HOSTNAME","isTelemetryEnabled","env","readOverride","storage","getLocalStorage","isStudioTelemetryEnabled","hosted","flexkitDomain","postToUserApi","path","body","keepalive","LIMITS","MAX_ERRORS_PER_REPORT","MAX_REPORT_BYTES","MAX_ERRORS_PER_SESSION","FLUSH_INTERVAL_MS","PROJECT_ID_PATTERN","truncate","value","max","toReportPath","pathOrUrl","describeError","error","constructorName","NOISE_MESSAGES","EXTENSION_URL","EMAIL_ADDRESS","maskMessage","message","isNoiseError","details","sourceUrl","pattern","buildClientError","options","entry","errorKey","encoder","byteLength","buildReportBody","app","queue","maxBytes","size","errors","errorSize","createErrorReporter","send","getPath","now","setTimer","callback","ms","clearTimer","timer","seen","accepted","projectId","stopped","schedule","flush","sendNext","unloading","next","status","key","id","sendReportToBff","url","userApiPaths","installed","reportStudioError","source","componentStack","setErrorReportingProjectId","installErrorReporter","reporter","onError","event","onUnhandledRejection","onPageHide","productEventKey","studioEvent","createProductEventTracker","pending","delivered","onDelivered","settle","tracker","trackStudioEvent","DESKTOP_LAUNCH_STORAGE_KEY","readSessionFlag","writeSessionFlag","installProductEvents","current"],"mappings":"gLAeO,IAAMA,CAAAA,CAA0D,QAAA,CACjEC,CAAAA,CAA6B,CAAE,OAAA,CAASD,CAAAA,CAAgB,MAAA,CAAQA,CAAAA,CAAgB,SAAA,CAAW,IAAK,CAAA,CAO/F,SAASE,EAAAA,EAAkC,CAChD,IAAMC,CAAAA,CAAUC,CAAAA,EAAW,CACrB,CAACC,CAAAA,CAAYC,CAAa,CAAA,CAAIC,SAAwB,IAAI,CAAA,CAYhE,OAVAC,SAAAA,CAAU,IAAM,CACd,GAAKL,CAAAA,CAIL,OAAOA,CAAAA,CAAQ,kBAAA,CAAoBM,CAAAA,EAAW,CAC5CH,CAAAA,CAAcG,CAAAA,CAAO,OAAO,EAC9B,CAAC,CACH,CAAA,CAAG,CAACN,CAAO,CAAC,CAAA,CAEPA,CAAAA,CAIDE,CAAAA,GAAe,IAAA,CACV,CAAE,OAAA,CAASF,CAAAA,CAAQ,OAAA,CAAS,MAAA,CAAQA,CAAAA,CAAQ,QAAS,SAAA,CAAW,IAAK,CAAA,CAGvE,CAAE,OAAA,CAASA,CAAAA,CAAQ,OAAA,CAAS,MAAA,CAAQE,CA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CAAAA,EACzCF,EAAc+D,CAAAA,CAAa,aAAA,CAAe7D,EAAM,CAAE,SAAA,CAAW,IAAK,CAAC,CACrE,CAAA,CACMpB,EAAUC,CAAAA,EAAW,CAE3B,OAAAmG,CAAAA,CAAUM,CAAAA,CAEN1G,GAAW,CAACuG,EAAAA,CAAgBD,CAA0B,CAAA,EACxDI,CAAAA,CAAQ,KAAA,CACN,CAAE,UAAA,CAAY1G,CAAAA,CAAQ,QAAS,KAAA,CAAO,oBAAA,CAAsB,GAAIA,CAAAA,CAAQ,QAAS,CAAA,CACjF,CAAE,WAAA,CAAa,IAAMwG,GAAiBF,CAA0B,CAAE,CACpE,CAAA,CAGK,IAAM,CACPF,CAAAA,GAAYM,CAAAA,GACdN,CAAAA,CAAU,IAAA,EAEd,CACF","file":"chunk-32B35YDF.js","sourcesContent":["'use client';\n\nimport { useEffect, useState } from 'react';\nimport { getDesktop } from './desktop';\n\nexport interface StudioVersion {\n current: string;\n latest: string;\n isCurrent: boolean;\n /** Applies the newer version (the desktop app restarts into it); undefined when there is nothing to apply. */\n upgrade?: () => void;\n}\n\n// `@flexkit/studio`'s own version, inlined at build time; a build without the\n// define (tests, tooling) shows a placeholder.\nexport const STUDIO_VERSION = typeof __STUDIO_VERSION__ === 'string' ? __STUDIO_VERSION__ : '0.0.0';\nconst WEB_VERSION: StudioVersion = { current: STUDIO_VERSION, latest: STUDIO_VERSION, isCurrent: true };\n\n/**\n * The Studio version shown in the app bar. The web Studio is always current\n * (the hosted Studio deploys with the packages); the desktop app reports its\n * own version and the update it has downloaded, if any.\n */\nexport function useStudioVersion(): StudioVersion {\n const desktop = getDesktop();\n const [downloaded, setDownloaded] = useState<string | null>(null);\n\n useEffect(() => {\n if (!desktop) {\n return;\n }\n\n return desktop.onUpdateDownloaded((update) => {\n setDownloaded(update.version);\n });\n }, [desktop]);\n\n if (!desktop) {\n return WEB_VERSION;\n }\n\n if (downloaded === null) {\n return { current: desktop.version, latest: desktop.version, isCurrent: true };\n }\n\n return { current: desktop.version, latest: downloaded, isCurrent: false, upgrade: () => desktop.installUpdate() };\n}\n","import { getDesktop } from './desktop';\nimport { flexkitDomain } from './domains';\nimport { getLocalStorage } from './local-storage';\nimport { STUDIO_VERSION } from './use-studio-version';\n\n/**\n * The on/off decision and the transport shared by the Studio's error reports\n * (core/error/error-reporter.ts) and product events\n * (core/analytics/product-events.ts).\n */\n\n/** Turns error reports and product events on (`on`) or off (`off`) in this browser, whatever the environment. */\nexport const TELEMETRY_STORAGE_KEY = 'flexkit:telemetry';\n/** The key error reporting shipped with; still honoured. */\nexport const LEGACY_TELEMETRY_STORAGE_KEY = 'flexkit:error-reporting';\n\nexport interface TelemetryEnvironment {\n /** The Studio lists the signed-in user's projects (hosted Studio, desktop app). */\n hosted: boolean;\n isDesktop: boolean;\n domain: string;\n hostname: string;\n version: string;\n /** The local storage setting in this browser, if any. */\n override: string | null;\n}\n\nconst LOCAL_HOSTNAME = /^(localhost|127\\.0\\.0\\.1|\\[::1\\]|0\\.0\\.0\\.0)$|\\.(localhost|test|local)$/i;\n\n/**\n * On for the hosted Studio and the desktop app against the production\n * backend, and off in development: a local backend (`flexkit.test`), a local\n * host, or a build without a version. The local storage setting forces it\n * `on` or `off`.\n */\nexport function isTelemetryEnabled(env: TelemetryEnvironment): boolean {\n if (env.override === 'on') {\n return true;\n }\n\n if (env.override === 'off') {\n return false;\n }\n\n if (!env.hosted || env.domain !== 'flexkit.io' || env.version === '0.0.0') {\n return false;\n }\n\n return env.isDesktop || !LOCAL_HOSTNAME.test(env.hostname);\n}\n\nfunction readOverride(): string | null {\n try {\n const storage = getLocalStorage();\n\n return storage?.getItem(TELEMETRY_STORAGE_KEY) ?? storage?.getItem(LEGACY_TELEMETRY_STORAGE_KEY) ?? null;\n } catch {\n return null;\n }\n}\n\n/** Whether this Studio sends error reports and product events to Flexkit. */\nexport function isStudioTelemetryEnabled({ hosted }: { hosted: boolean }): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n return isTelemetryEnabled({\n hosted,\n isDesktop: Boolean(getDesktop()),\n domain: flexkitDomain,\n hostname: window.location.hostname,\n version: STUDIO_VERSION,\n override: readOverride(),\n });\n}\n\n/**\n * POSTs JSON to a user-level backend route through the Studio's server proxy,\n * which adds the session. `keepalive` lets the request outlive the page.\n * Returns the response status.\n */\nexport async function postToUserApi(path: string, body: string, { keepalive = false } = {}): Promise<number> {\n const response = await fetch(path, {\n body,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n keepalive,\n method: 'POST',\n });\n\n return response.status;\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { STUDIO_VERSION } from '../use-studio-version';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Reports unexpected Studio errors (uncaught errors, unhandled rejections and\n * errors caught by the error boundaries) to Flexkit through the Studio's own\n * BFF (`/api/flexkit/-/client-errors`), which forwards the session so the\n * report is attributed to the signed-in user.\n *\n * Reports carry the error, the Studio path (no query string or hash) and the\n * current project id; never request bodies, form values or record data.\n */\n\nexport type ClientErrorSource = 'window' | 'unhandledrejection' | 'react' | 'manual';\n\nexport interface ClientError {\n source: ClientErrorSource;\n name: string;\n message: string;\n stack?: string;\n componentStack?: string;\n path?: string;\n projectId?: string;\n occurredAt: string;\n}\n\nexport interface ClientErrorApp {\n platform: 'web' | 'desktop';\n version: string;\n userAgent?: string;\n}\n\nexport interface ClientErrorReport {\n app: ClientErrorApp;\n errors: ClientError[];\n}\n\n/** Field limits of the backend schema. */\nconst LIMITS = {\n componentStack: 4_000,\n message: 2_000,\n name: 200,\n path: 500,\n stack: 8_000,\n userAgent: 500,\n} as const;\n\n/** The backend accepts 1 to 10 errors per report. */\nexport const MAX_ERRORS_PER_REPORT = 10;\n/** The backend refuses bodies over 64 KB; `keepalive` requests share a 64 KB budget too. */\nexport const MAX_REPORT_BYTES = 60_000;\n/** Reports kept per page session; anything after that is dropped. */\nexport const MAX_ERRORS_PER_SESSION = 50;\n/** At most one report is sent per interval; errors in between are batched. */\nexport const FLUSH_INTERVAL_MS = 5_000;\n\n/** Kept for callers and tests that name the gate after error reporting. */\nexport {\n isTelemetryEnabled as isErrorReportingEnabled,\n LEGACY_TELEMETRY_STORAGE_KEY as ERROR_REPORTING_STORAGE_KEY,\n type TelemetryEnvironment as ErrorReportingEnvironment,\n} from '../telemetry';\n\nexport const PROJECT_ID_PATTERN = /^[a-z0-9]{1,64}$/;\n\nfunction truncate(value: string, max: number): string {\n return value.length > max ? value.slice(0, max) : value;\n}\n\n/** The pathname of a path or URL, without query string or hash. */\nexport function toReportPath(pathOrUrl: string): string {\n let path = pathOrUrl;\n\n try {\n if (/^[a-z][a-z0-9+.-]*:/i.test(pathOrUrl)) {\n path = new URL(pathOrUrl).pathname;\n }\n } catch {\n // Not a URL; strip by hand below.\n }\n\n return truncate(path.split(/[?#]/)[0] ?? '', LIMITS.path);\n}\n\nexport interface ErrorDetails {\n name: string;\n message: string;\n stack?: string;\n}\n\n/**\n * Name, message and stack of anything thrown. A non-Error value (a rejected\n * promise with a plain object) is described by its type only, so record data\n * someone rejected with never leaves the browser.\n */\nexport function describeError(error: unknown): ErrorDetails {\n if (error instanceof Error) {\n return {\n name: error.name || 'Error',\n message: typeof error.message === 'string' ? error.message : '',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n };\n }\n\n if (typeof error === 'string') {\n return { name: 'Error', message: error };\n }\n\n if (error === null || error === undefined) {\n return { name: 'Error', message: `Non-Error thrown: ${String(error)}` };\n }\n\n if (typeof error === 'object') {\n const constructorName = (error as { constructor?: { name?: unknown } }).constructor?.name;\n\n return {\n name: 'Error',\n message: `Non-Error thrown: ${typeof constructorName === 'string' && constructorName ? constructorName : 'object'}`,\n };\n }\n\n return { name: 'Error', message: `Non-Error thrown: ${typeof error}` };\n}\n\nconst NOISE_MESSAGES = [\n /ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i,\n // Cross-origin script errors carry nothing to act on.\n /^Script error\\.?$/i,\n /The (operation|user) (was )?aborted/i,\n /signal is aborted without reason/i,\n];\n\nconst EXTENSION_URL = /\\b(chrome|moz|safari(-web)?|ms-browser)-extension:\\/\\//i;\n\nconst EMAIL_ADDRESS = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi;\n\n/** Masks email addresses an error message may quote from a record or form. */\nexport function maskMessage(message: string): string {\n return message.replace(EMAIL_ADDRESS, '<email>');\n}\n\n/** Errors that are not Studio bugs: browser quirks, aborted requests, browser extensions. */\nexport function isNoiseError(details: ErrorDetails, sourceUrl?: string): boolean {\n if (details.name === 'AbortError') {\n return true;\n }\n\n if (NOISE_MESSAGES.some((pattern) => pattern.test(details.message))) {\n return true;\n }\n\n if (sourceUrl && EXTENSION_URL.test(sourceUrl)) {\n return true;\n }\n\n return Boolean(details.stack && EXTENSION_URL.test(details.stack));\n}\n\nexport interface BuildClientErrorOptions {\n source: ClientErrorSource;\n componentStack?: string;\n path?: string;\n projectId?: string | null;\n /** The script the error came from (`ErrorEvent.filename`), checked for browser extensions. */\n sourceUrl?: string;\n now?: Date;\n}\n\n/** The report entry for an error, or null when it is noise. */\nexport function buildClientError(error: unknown, options: BuildClientErrorOptions): ClientError | null {\n const details = describeError(error);\n\n if (isNoiseError(details, options.sourceUrl)) {\n return null;\n }\n\n const entry: ClientError = {\n source: options.source,\n name: truncate(details.name, LIMITS.name),\n message: truncate(maskMessage(details.message), LIMITS.message),\n occurredAt: (options.now ?? new Date()).toISOString(),\n };\n\n if (details.stack) {\n entry.stack = truncate(details.stack, LIMITS.stack);\n }\n\n if (options.componentStack) {\n entry.componentStack = truncate(options.componentStack, LIMITS.componentStack);\n }\n\n if (options.path) {\n entry.path = toReportPath(options.path);\n }\n\n if (options.projectId && PROJECT_ID_PATTERN.test(options.projectId)) {\n entry.projectId = options.projectId;\n }\n\n return entry;\n}\n\n/** Identity of an error within a page session: the same message and stack are reported once. */\nexport function errorKey(error: Pick<ClientError, 'message' | 'name' | 'stack'>): string {\n return `${error.name}\\n${error.message}\\n${error.stack ?? ''}`;\n}\n\nconst encoder = new TextEncoder();\n\nfunction byteLength(value: string): number {\n return encoder.encode(value).length;\n}\n\n/**\n * Takes the errors that fit one report (at most 10 and `maxBytes` of JSON)\n * off the front of the queue. Returns the request body and how many errors it holds.\n */\nexport function buildReportBody(\n app: ClientErrorApp,\n queue: readonly ClientError[],\n maxBytes = MAX_REPORT_BYTES\n): { body: string; count: number } | null {\n // The envelope plus each error once, joined by commas.\n let size = byteLength(JSON.stringify({ app, errors: [] } satisfies ClientErrorReport));\n const errors: ClientError[] = [];\n\n for (const error of queue.slice(0, MAX_ERRORS_PER_REPORT)) {\n const errorSize = byteLength(JSON.stringify(error)) + (errors.length ? 1 : 0);\n\n if (size + errorSize > maxBytes) {\n break;\n }\n\n size += errorSize;\n errors.push(error);\n }\n\n if (errors.length === 0) {\n return null;\n }\n\n return { body: JSON.stringify({ app, errors } satisfies ClientErrorReport), count: errors.length };\n}\n\nexport type SendReport = (body: string, options: { unloading: boolean }) => Promise<number | null>;\n\nexport interface ErrorReporterOptions {\n app: ClientErrorApp;\n send: SendReport;\n /** The current Studio path; only its pathname is sent. */\n getPath?: () => string | undefined;\n now?: () => Date;\n setTimer?: (callback: () => void, ms: number) => unknown;\n clearTimer?: (timer: unknown) => void;\n}\n\nexport interface ErrorReporter {\n report: (error: unknown, options: Omit<BuildClientErrorOptions, 'path' | 'projectId' | 'now'>) => void;\n setProjectId: (projectId: string | null) => void;\n /** Sends the next report now; `unloading` uses a beacon or keepalive request that outlives the page. */\n flush: (options?: { unloading?: boolean }) => void;\n /** Errors waiting to be sent (tests). */\n pending: () => readonly ClientError[];\n dispose: () => void;\n}\n\n/** The queue, dedupe, cap and batching; the transport and the clock are injected. */\nexport function createErrorReporter({\n app,\n send,\n getPath,\n now = () => new Date(),\n setTimer = (callback, ms) => setTimeout(callback, ms),\n clearTimer = (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),\n}: ErrorReporterOptions): ErrorReporter {\n const queue: ClientError[] = [];\n const seen = new Set<string>();\n let accepted = 0;\n let projectId: string | null = null;\n let timer: unknown = null;\n let stopped = false;\n\n function schedule(): void {\n if (timer === null && queue.length > 0 && !stopped) {\n timer = setTimer(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n function sendNext(unloading: boolean): boolean {\n const next = buildReportBody(app, queue);\n\n if (!next) {\n // An error that cannot fit a report on its own; drop it.\n queue.shift();\n\n return queue.length > 0;\n }\n\n queue.splice(0, next.count);\n send(next.body, { unloading })\n .then((status) => {\n // Rate limited or not allowed: stop for this page session rather than retry.\n if (status === 401 || status === 403 || status === 429) {\n stopped = true;\n queue.length = 0;\n }\n })\n .catch(() => {\n // Never report the reporter's own failures.\n });\n\n return queue.length > 0;\n }\n\n function flush({ unloading = false }: { unloading?: boolean } = {}): void {\n try {\n if (stopped) {\n return;\n }\n\n if (timer !== null && unloading) {\n clearTimer(timer);\n timer = null;\n }\n\n // One report per flush, also when the page goes away: beacons and\n // keepalive requests share a 64 KB budget, so a second would be refused.\n if (queue.length > 0) {\n sendNext(unloading);\n }\n\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n }\n\n return {\n report(error, options) {\n try {\n if (stopped || accepted >= MAX_ERRORS_PER_SESSION) {\n return;\n }\n\n const entry = buildClientError(error, {\n ...options,\n now: now(),\n path: getPath?.(),\n projectId,\n });\n\n if (!entry) {\n return;\n }\n\n const key = errorKey(entry);\n\n if (seen.has(key)) {\n return;\n }\n\n seen.add(key);\n accepted += 1;\n queue.push(entry);\n schedule();\n } catch {\n // Error reporting must never break the Studio.\n }\n },\n setProjectId(id) {\n projectId = id;\n },\n flush,\n pending: () => queue,\n dispose() {\n if (timer !== null) {\n clearTimer(timer);\n timer = null;\n }\n\n stopped = true;\n queue.length = 0;\n },\n };\n}\n\n/** Sends a report through the BFF; a beacon when the page is going away on the web. */\nexport const sendReportToBff: SendReport = async (body, { unloading }) => {\n const url = userApiPaths.clientErrors;\n\n // A beacon outlives the page. The BFF reads its JSON body like a fetch's\n // and the browser sends the session cookie with it (same origin). The\n // desktop app's BFF only answers script requests, so it uses `keepalive`.\n if (unloading && !getDesktop() && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n try {\n // text/plain is CORS-safelisted, so no browser refuses the beacon; the body is still JSON.\n if (navigator.sendBeacon(url, new Blob([body], { type: 'text/plain' }))) {\n return null;\n }\n } catch {\n // Fall back to a keepalive fetch.\n }\n }\n\n return postToUserApi(url, body, { keepalive: unloading });\n};\n\nlet installed: ErrorReporter | null = null;\n\n/** Reports an error caught by the Studio (an error boundary, for example). Does nothing when reporting is off. */\nexport function reportStudioError(\n error: unknown,\n { source = 'manual', componentStack }: { source?: ClientErrorSource; componentStack?: string } = {}\n): void {\n installed?.report(error, { source, componentStack });\n}\n\n/** The project the Studio shows, added to reports; null outside a project. */\nexport function setErrorReportingProjectId(projectId: string | null): void {\n installed?.setProjectId(projectId);\n}\n\n/**\n * Starts reporting uncaught errors and unhandled rejections when reporting is\n * enabled for this environment. Returns the function that stops it.\n */\nexport function installErrorReporter({ hosted }: { hosted: boolean }): () => void {\n if (typeof window === 'undefined' || installed) {\n return () => undefined;\n }\n\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const desktop = getDesktop();\n\n const reporter = createErrorReporter({\n app: {\n platform: desktop ? 'desktop' : 'web',\n version: STUDIO_VERSION,\n userAgent: truncate(navigator.userAgent, LIMITS.userAgent),\n },\n send: sendReportToBff,\n getPath: () => window.location.pathname,\n });\n\n function onError(event: ErrorEvent): void {\n reporter.report(event.error ?? event.message, { source: 'window', sourceUrl: event.filename });\n }\n\n function onUnhandledRejection(event: PromiseRejectionEvent): void {\n reporter.report(event.reason, { source: 'unhandledrejection' });\n }\n\n function onPageHide(): void {\n reporter.flush({ unloading: true });\n }\n\n window.addEventListener('error', onError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n window.addEventListener('pagehide', onPageHide);\n installed = reporter;\n\n return () => {\n window.removeEventListener('error', onError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n window.removeEventListener('pagehide', onPageHide);\n reporter.flush({ unloading: true });\n reporter.dispose();\n\n if (installed === reporter) {\n installed = null;\n }\n };\n}\n","import { userApiPaths } from '../api-paths';\nimport { getDesktop } from '../desktop';\nimport { PROJECT_ID_PATTERN } from '../error/error-reporter';\nimport { isStudioTelemetryEnabled, postToUserApi } from '../telemetry';\n\n/**\n * Product events only the Studio can see, sent to Flexkit through the\n * Studio's own server proxy (`/api/flexkit/-/product-events`) with the\n * session: the Graph app opened, the desktop app launched. They follow the\n * Studio's telemetry setting (see core/telemetry.ts) and carry ids, the\n * desktop app version and the OS only.\n */\nexport type StudioProductEvent =\n | { event: 'graph_opened'; projectId: string }\n | { event: 'desktop_app_opened'; appVersion: string; os: 'darwin' | 'linux' | 'win32' };\n\n/** Identity of an event within a page session; the backend also counts each once per day. */\nexport function productEventKey(studioEvent: StudioProductEvent): string {\n return studioEvent.event === 'graph_opened' ? `graph_opened:${studioEvent.projectId}` : studioEvent.event;\n}\n\n/** Sends the event body; resolves with the response status. */\nexport type SendProductEvent = (body: string) => Promise<number>;\n\nexport interface ProductEventTracker {\n track: (studioEvent: StudioProductEvent, options?: { onDelivered?: () => void }) => void;\n}\n\n/**\n * Sends each event once per page session through `send`. An event counts as\n * sent only once the backend accepted it, so one sent while offline or signed\n * out is sent again next time. Never throws.\n */\nexport function createProductEventTracker(send: SendProductEvent): ProductEventTracker {\n const pending = new Set<string>();\n const delivered = new Set<string>();\n\n return {\n track(studioEvent, { onDelivered } = {}) {\n const key = productEventKey(studioEvent);\n\n if (pending.has(key) || delivered.has(key)) {\n return;\n }\n\n pending.add(key);\n\n const settle = (status: number | null): void => {\n pending.delete(key);\n\n if (status !== null && status >= 200 && status < 300) {\n delivered.add(key);\n onDelivered?.();\n }\n };\n\n try {\n send(JSON.stringify(studioEvent)).then(settle, () => settle(null));\n } catch {\n settle(null);\n }\n },\n };\n}\n\nlet tracker: ProductEventTracker | null = null;\n\n/** Records an event when product events are on (see `installProductEvents`); otherwise does nothing. */\nexport function trackStudioEvent(studioEvent: StudioProductEvent): void {\n if (studioEvent.event === 'graph_opened' && !PROJECT_ID_PATTERN.test(studioEvent.projectId)) {\n return;\n }\n\n tracker?.track(studioEvent);\n}\n\n/** Session storage flag: this desktop app launch was recorded (page reloads keep it, a relaunch does not). */\nexport const DESKTOP_LAUNCH_STORAGE_KEY = 'flexkit:desktop-launch-recorded';\n\nfunction readSessionFlag(key: string): boolean {\n try {\n return sessionStorage.getItem(key) === '1';\n } catch {\n return false;\n }\n}\n\nfunction writeSessionFlag(key: string): void {\n try {\n sessionStorage.setItem(key, '1');\n } catch {\n // Without session storage the backend's once-per-day count still applies.\n }\n}\n\n/**\n * Turns product events on for this environment and records the desktop app\n * launch (once per launch, once the user is signed in). Returns the function\n * that turns them off again.\n */\nexport function installProductEvents({ hosted }: { hosted: boolean }): () => void {\n if (!isStudioTelemetryEnabled({ hosted })) {\n return () => undefined;\n }\n\n const current = createProductEventTracker((body) =>\n postToUserApi(userApiPaths.productEvents, body, { keepalive: true })\n );\n const desktop = getDesktop();\n\n tracker = current;\n\n if (desktop && !readSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY)) {\n current.track(\n { appVersion: desktop.version, event: 'desktop_app_opened', os: desktop.platform },\n { onDelivered: () => writeSessionFlag(DESKTOP_LAUNCH_STORAGE_KEY) }\n );\n }\n\n return () => {\n if (tracker === current) {\n tracker = null;\n }\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- import'./index.css';import {c,e}from'./chunk-2PBDHGRR.js';import {b}from'./chunk-FJS4SN3K.js';import {f}from'./chunk-TWA6OG5U.js';import {d}from'./chunk-MBBE4RND.js';import {useMemo}from'react';import I from'swr';import {find,propEq}from'ramda';function $(n,o){let{scope:l}=c(),{currentProject:e$1}=f(),a=useMemo(()=>e$1?.schema??[],[e$1]),m=e$1?.scopes,u=e(m),t=o?.commonParams.q?JSON.stringify(o):null,{data:r,error:s,isLoading:y}=I(t,()=>fetch(d(n).search,{headers:{"Content-Type":"application/json"},body:JSON.stringify(o),method:"POST",mode:"cors"}).then(i=>i.json()),{keepPreviousData:true});return {results:useMemo(()=>t?O(r?.results??[],n,a,l,u)??[]:[],[r,u,n,a,l,t]),error:s,isLoading:y}}function O(n,o,l,e,a){return n?.filter(m=>m?.hits?.length>0).map(m=>{let u=m,t=u.collection.replace(`${o}_`,"").replace(/_\d+$/,""),r=find(propEq(t,"plural"))(l);if(!r)return [];let s=b(r)?.name??"",y=r?.name??t;return u.hits.map(({document:c})=>{let i=c[s],N=(i&&typeof i!="string"?i[e]??i[a]:null)??c[s],_=Object.entries(c).reduce((h,[p,f])=>{if(p!==s&&p!=="id"&&p!=="_updatedAt"){let A=typeof f!="string"?f[e]??f[a]:f;h[p]=A;}return h},{});return {_id:c.id,_entityName:y,_entityNamePlural:t,[s]:N,..._}})}).flat()}export{$ as a};//# sourceMappingURL=chunk-MHEFVYKP.js.map
2
- //# sourceMappingURL=chunk-MHEFVYKP.js.map
1
+ import'./index.css';import {c,e}from'./chunk-DSZJXMN5.js';import {b}from'./chunk-GORBKX24.js';import {f}from'./chunk-INZZOKRC.js';import {d}from'./chunk-MBBE4RND.js';import {useMemo}from'react';import I from'swr';import {find,propEq}from'ramda';function $(n,o){let{scope:l}=c(),{currentProject:e$1}=f(),a=useMemo(()=>e$1?.schema??[],[e$1]),m=e$1?.scopes,u=e(m),t=o?.commonParams.q?JSON.stringify(o):null,{data:r,error:s,isLoading:y}=I(t,()=>fetch(d(n).search,{headers:{"Content-Type":"application/json"},body:JSON.stringify(o),method:"POST",mode:"cors"}).then(i=>i.json()),{keepPreviousData:true});return {results:useMemo(()=>t?O(r?.results??[],n,a,l,u)??[]:[],[r,u,n,a,l,t]),error:s,isLoading:y}}function O(n,o,l,e,a){return n?.filter(m=>m?.hits?.length>0).map(m=>{let u=m,t=u.collection.replace(`${o}_`,"").replace(/_\d+$/,""),r=find(propEq(t,"plural"))(l);if(!r)return [];let s=b(r)?.name??"",y=r?.name??t;return u.hits.map(({document:c})=>{let i=c[s],N=(i&&typeof i!="string"?i[e]??i[a]:null)??c[s],_=Object.entries(c).reduce((h,[p,f])=>{if(p!==s&&p!=="id"&&p!=="_updatedAt"){let A=typeof f!="string"?f[e]??f[a]:f;h[p]=A;}return h},{});return {_id:c.id,_entityName:y,_entityNamePlural:t,[s]:N,..._}})}).flat()}export{$ as a};//# sourceMappingURL=chunk-377TM7UG.js.map
2
+ //# sourceMappingURL=chunk-377TM7UG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/use-search.tsx"],"names":["useSearch","projectId","searchRequest","scope","useAppContext","currentProject","useConfig","schema","useMemo","scopes","defaultScope","defaultScopeName","swrKey","data","error","isLoading","useSWR","apiPaths","res","mapResults","results","result","item","entityNamePlural","entitySchema","find","propEq","primaryAttributeName","getDisplayAttribute","entityName","document","primaryAttribute","primaryAttributeValue","attributes","acc","key","value","scopedValue"],"mappings":"qPAYO,SAASA,EACdC,CAAAA,CACAC,CAAAA,CACwE,CACxE,GAAM,CAAE,KAAA,CAAAC,CAAM,CAAA,CAAIC,GAAc,CAC1B,CAAE,cAAA,CAAAC,GAAe,EAAIC,CAAAA,EAAU,CAC/BC,CAAAA,CAASC,OAAAA,CAAQ,IAAMH,GAAAA,EAAgB,MAAA,EAAU,EAAC,CAAG,CAACA,GAAc,CAAC,CAAA,CACrEI,EAASJ,GAAAA,EAAgB,MAAA,CACzBK,CAAAA,CAAeC,CAAAA,CAAiBF,CAAM,CAAA,CACtCG,CAAAA,CAASV,CAAAA,EAAe,aAAa,CAAA,CAAI,IAAA,CAAK,SAAA,CAAUA,CAAa,CAAA,CAAI,IAAA,CACzE,CAAE,IAAA,CAAAW,EAAM,KAAA,CAAAC,CAAAA,CAAO,SAAA,CAAAC,CAAU,EAAIC,CAAAA,CACjCJ,CAAAA,CACA,IACE,KAAA,CAAMK,EAAShB,CAAS,CA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Y,CAAA,EAAG,IAAA,EAAQ,EAAA,CAClEK,CAAAA,CAAaL,CAAAA,EAAc,IAAA,EAAQD,CAAAA,CAGzC,OAAOD,CAAAA,CAAK,IAAA,CAAK,GAAA,CAAI,CAAC,CAAE,QAAA,CAAAQ,CAAS,CAAA,GAAM,CACrC,IAAMC,CAAAA,CAAmBD,CAAAA,CAASH,CAAoB,EAKhDK,CAAAA,CAAAA,CAHJD,CAAAA,EAAoB,OAAOA,CAAAA,EAAqB,SAC3CA,CAAAA,CAAiB5B,CAAK,CAAA,EAAK4B,CAAAA,CAAiBrB,CAAY,CAAA,CACzD,IAAA,GACkDoB,CAAAA,CAASH,CAAoB,CAAA,CAC/EM,CAAAA,CAAa,MAAA,CAAO,OAAA,CAAQH,CAAQ,CAAA,CAAE,MAAA,CAC1C,CAACI,EAA0E,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAM,CAC1F,GAAID,CAAAA,GAAQR,CAAAA,EAAwBQ,IAAQ,IAAA,EAAQA,CAAAA,GAAQ,YAAA,CAAc,CACxE,IAAME,CAAAA,CAAc,OAAOD,CAAAA,EAAU,QAAA,CAAYA,EAAMjC,CAAK,CAAA,EAAKiC,CAAAA,CAAM1B,CAAY,CAAA,CAAK0B,CAAAA,CAExFF,CAAAA,CAAIC,CAAG,EAAIE,EACb,CAEA,OAAOH,CACT,EACA,EACF,CAAA,CAEA,OAAO,CACL,GAAA,CAAKJ,CAAAA,CAAS,EAAA,CACd,WAAA,CAAaD,CAAAA,CACb,iBAAA,CAAmBN,CAAAA,CACnB,CAACI,CAAoB,EAAGK,CAAAA,CACxB,GAAGC,CACL,CACF,CAAC,CACH,CAAC,CAAA,CACA,MACL","file":"chunk-MHEFVYKP.js","sourcesContent":["'use client';\n\nimport { useMemo } from 'react';\nimport { defaultScopeName } from './default-scope';\nimport useSWR from 'swr';\nimport { find, propEq } from 'ramda';\nimport { apiPaths } from './api-paths';\nimport { useAppContext } from './app-context';\nimport { useConfig } from './config/config-context';\nimport { getDisplayAttribute } from './get-display-attribute';\nimport type { Entity, RawResultItem, RawSearchResultItems, SearchRequestProps, SearchResultItem } from './types';\n\nexport function useSearch(\n projectId: string,\n searchRequest: SearchRequestProps | null\n): { results: SearchResultItem[] | []; error: Error; isLoading: boolean } {\n const { scope } = useAppContext();\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const scopes = currentProject?.scopes;\n const defaultScope = defaultScopeName(scopes);\n const swrKey = searchRequest?.commonParams.q ? JSON.stringify(searchRequest) : null;\n const { data, error, isLoading } = useSWR(\n swrKey,\n () =>\n fetch(apiPaths(projectId).search, {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(searchRequest),\n method: 'POST',\n mode: 'cors',\n }).then((res) => res.json() as Promise<{ results: RawSearchResultItems }>),\n // Show the previous hits until the next request lands instead of flashing an empty list per keystroke.\n { keepPreviousData: true }\n );\n const results = useMemo(\n // SWR keeps the previous key's data while a new key loads, and also after the key becomes null.\n // Callers treat an empty query as \"no search\", so return no hits once there is nothing to search for.\n () => (swrKey ? (mapResults(data?.results ?? [], projectId, schema, scope, defaultScope) ?? []) : []),\n [data, defaultScope, projectId, schema, scope, swrKey]\n );\n\n return { results, error, isLoading };\n}\n\nfunction mapResults(\n results: RawSearchResultItems | undefined,\n projectId: string,\n schema: Entity[],\n scope: string,\n defaultScope: string\n): SearchResultItem[] | undefined {\n return results\n ?.filter((result) => (result as RawResultItem)?.hits?.length > 0)\n .map((result) => {\n const item = result as RawResultItem;\n const entityNamePlural = item.collection.replace(`${projectId}_`, '').replace(/_\\d+$/, '');\n const entitySchema = find<Entity>(propEq(entityNamePlural, 'plural'))(schema);\n\n if (!entitySchema) {\n return [];\n }\n\n const primaryAttributeName = getDisplayAttribute(entitySchema)?.name ?? '';\n const entityName = entitySchema?.name ?? entityNamePlural;\n\n // iterate over the hits and return an object with the primary attribute value first and then the rest of the attributes.\n return item.hits.map(({ document }) => {\n const primaryAttribute = document[primaryAttributeName];\n const scopedPrimaryAttribute =\n primaryAttribute && typeof primaryAttribute !== 'string'\n ? (primaryAttribute[scope] ?? primaryAttribute[defaultScope])\n : null;\n const primaryAttributeValue = scopedPrimaryAttribute ?? document[primaryAttributeName];\n const attributes = Object.entries(document).reduce(\n (acc: Omit<SearchResultItem, '_id' | '_entityName' | '_entityNamePlural'>, [key, value]) => {\n if (key !== primaryAttributeName && key !== 'id' && key !== '_updatedAt') {\n const scopedValue = typeof value !== 'string' ? (value[scope] ?? value[defaultScope]) : value;\n\n acc[key] = scopedValue;\n }\n\n return acc;\n },\n {}\n );\n\n return {\n _id: document.id,\n _entityName: entityName,\n _entityNamePlural: entityNamePlural,\n [primaryAttributeName]: primaryAttributeValue as string,\n ...attributes,\n };\n });\n })\n .flat();\n}\n"]}
1
+ {"version":3,"sources":["../src/core/use-search.tsx"],"names":["useSearch","projectId","searchRequest","scope","useAppContext","currentProject","useConfig","schema","useMemo","scopes","defaultScope","defaultScopeName","swrKey","data","error","isLoading","useSWR","apiPaths","res","mapResults","results","result","item","entityNamePlural","entitySchema","find","propEq","primaryAttributeName","getDisplayAttribute","entityName","document","primaryAttribute","primaryAttributeValue","attributes","acc","key","value","scopedValue"],"mappings":"qPAYO,SAASA,EACdC,CAAAA,CACAC,CAAAA,CACwE,CACxE,GAAM,CAAE,KAAA,CAAAC,CAAM,CAAA,CAAIC,GAAc,CAC1B,CAAE,cAAA,CAAAC,GAAe,EAAIC,CAAAA,EAAU,CAC/BC,CAAAA,CAASC,OAAAA,CAAQ,IAAMH,GAAAA,EAAgB,MAAA,EAAU,EAAC,CAAG,CAACA,GAAc,CAAC,CAAA,CACrEI,EAASJ,GAAAA,EAAgB,MAAA,CACzBK,CAAAA,CAAeC,CAAAA,CAAiBF,CAAM,CAAA,CACtCG,CAAAA,CAASV,CAAAA,EAAe,aAAa,CAAA,CAAI,IAAA,CAAK,SAAA,CAAUA,CAAa,CAAA,CAAI,IAAA,CACzE,CAAE,IAAA,CAAAW,EAAM,KAAA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C,CAAA,CAAEhB,CAAM,EAE5E,GAAI,CAACiB,CAAAA,CACH,OAAO,EAAC,CAGV,IAAMG,CAAAA,CAAuBC,EAAoBJ,CAAY,CAAA,EAAG,IAAA,EAAQ,EAAA,CAClEK,CAAAA,CAAaL,CAAAA,EAAc,IAAA,EAAQD,CAAAA,CAGzC,OAAOD,CAAAA,CAAK,IAAA,CAAK,GAAA,CAAI,CAAC,CAAE,QAAA,CAAAQ,CAAS,CAAA,GAAM,CACrC,IAAMC,CAAAA,CAAmBD,CAAAA,CAASH,CAAoB,EAKhDK,CAAAA,CAAAA,CAHJD,CAAAA,EAAoB,OAAOA,CAAAA,EAAqB,SAC3CA,CAAAA,CAAiB5B,CAAK,CAAA,EAAK4B,CAAAA,CAAiBrB,CAAY,CAAA,CACzD,IAAA,GACkDoB,CAAAA,CAASH,CAAoB,CAAA,CAC/EM,CAAAA,CAAa,MAAA,CAAO,OAAA,CAAQH,CAAQ,CAAA,CAAE,MAAA,CAC1C,CAACI,EAA0E,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAM,CAC1F,GAAID,CAAAA,GAAQR,CAAAA,EAAwBQ,IAAQ,IAAA,EAAQA,CAAAA,GAAQ,YAAA,CAAc,CACxE,IAAME,CAAAA,CAAc,OAAOD,CAAAA,EAAU,QAAA,CAAYA,EAAMjC,CAAK,CAAA,EAAKiC,CAAAA,CAAM1B,CAAY,CAAA,CAAK0B,CAAAA,CAExFF,CAAAA,CAAIC,CAAG,EAAIE,EACb,CAEA,OAAOH,CACT,EACA,EACF,CAAA,CAEA,OAAO,CACL,GAAA,CAAKJ,CAAAA,CAAS,EAAA,CACd,WAAA,CAAaD,CAAAA,CACb,iBAAA,CAAmBN,CAAAA,CACnB,CAACI,CAAoB,EAAGK,CAAAA,CACxB,GAAGC,CACL,CACF,CAAC,CACH,CAAC,CAAA,CACA,MACL","file":"chunk-377TM7UG.js","sourcesContent":["'use client';\n\nimport { useMemo } from 'react';\nimport { defaultScopeName } from './default-scope';\nimport useSWR from 'swr';\nimport { find, propEq } from 'ramda';\nimport { apiPaths } from './api-paths';\nimport { useAppContext } from './app-context';\nimport { useConfig } from './config/config-context';\nimport { getDisplayAttribute } from './get-display-attribute';\nimport type { Entity, RawResultItem, RawSearchResultItems, SearchRequestProps, SearchResultItem } from './types';\n\nexport function useSearch(\n projectId: string,\n searchRequest: SearchRequestProps | null\n): { results: SearchResultItem[] | []; error: Error; isLoading: boolean } {\n const { scope } = useAppContext();\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const scopes = currentProject?.scopes;\n const defaultScope = defaultScopeName(scopes);\n const swrKey = searchRequest?.commonParams.q ? JSON.stringify(searchRequest) : null;\n const { data, error, isLoading } = useSWR(\n swrKey,\n () =>\n fetch(apiPaths(projectId).search, {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(searchRequest),\n method: 'POST',\n mode: 'cors',\n }).then((res) => res.json() as Promise<{ results: RawSearchResultItems }>),\n // Show the previous hits until the next request lands instead of flashing an empty list per keystroke.\n { keepPreviousData: true }\n );\n const results = useMemo(\n // SWR keeps the previous key's data while a new key loads, and also after the key becomes null.\n // Callers treat an empty query as \"no search\", so return no hits once there is nothing to search for.\n () => (swrKey ? (mapResults(data?.results ?? [], projectId, schema, scope, defaultScope) ?? []) : []),\n [data, defaultScope, projectId, schema, scope, swrKey]\n );\n\n return { results, error, isLoading };\n}\n\nfunction mapResults(\n results: RawSearchResultItems | undefined,\n projectId: string,\n schema: Entity[],\n scope: string,\n defaultScope: string\n): SearchResultItem[] | undefined {\n return results\n ?.filter((result) => (result as RawResultItem)?.hits?.length > 0)\n .map((result) => {\n const item = result as RawResultItem;\n const entityNamePlural = item.collection.replace(`${projectId}_`, '').replace(/_\\d+$/, '');\n const entitySchema = find<Entity>(propEq(entityNamePlural, 'plural'))(schema);\n\n if (!entitySchema) {\n return [];\n }\n\n const primaryAttributeName = getDisplayAttribute(entitySchema)?.name ?? '';\n const entityName = entitySchema?.name ?? entityNamePlural;\n\n // iterate over the hits and return an object with the primary attribute value first and then the rest of the attributes.\n return item.hits.map(({ document }) => {\n const primaryAttribute = document[primaryAttributeName];\n const scopedPrimaryAttribute =\n primaryAttribute && typeof primaryAttribute !== 'string'\n ? (primaryAttribute[scope] ?? primaryAttribute[defaultScope])\n : null;\n const primaryAttributeValue = scopedPrimaryAttribute ?? document[primaryAttributeName];\n const attributes = Object.entries(document).reduce(\n (acc: Omit<SearchResultItem, '_id' | '_entityName' | '_entityNamePlural'>, [key, value]) => {\n if (key !== primaryAttributeName && key !== 'id' && key !== '_updatedAt') {\n const scopedValue = typeof value !== 'string' ? (value[scope] ?? value[defaultScope]) : value;\n\n acc[key] = scopedValue;\n }\n\n return acc;\n },\n {}\n );\n\n return {\n _id: document.id,\n _entityName: entityName,\n _entityNamePlural: entityNamePlural,\n [primaryAttributeName]: primaryAttributeValue as string,\n ...attributes,\n };\n });\n })\n .flat();\n}\n"]}
@@ -1,3 +1,3 @@
1
- import'./index.css';import {d as d$1}from'./chunk-TWA6OG5U.js';import {c}from'./chunk-MBBE4RND.js';import {mutate}from'swr';function i(t){return `/api/flexkit/${t}/starter`}async function d(t,e,a,c="Something went wrong. Please try again."){try{let s=await fetch(t,{method:e,credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),r=await s.json().catch(()=>({}));return s.ok?{...r,ok:!0}:{ok:!1,code:r.code??"unknown_error",message:r.error??c}}catch{return {ok:false,code:"network_error",message:"Flexkit is not reachable. Check your connection and try again."}}}function w(t){return d(c.me,"PATCH",{displayName:t})}function b(t,e){return d(i(t),"POST",e)}function g(t){return t?.state==="queued"||t?.state==="deploying"||t?.state==="seeding"}function T(t){return [`I'm setting up Flexkit for my business: ${t.trim()}`,"","Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records."].join(`
2
- `)}var x=["Which variants are running low on stock, and what is already on order?","Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.","Which products are missing prices, titles or SEO copy in the UK or US?","Show last month\u2019s revenue by market and sales channel.","Which open support tickets need attention today?"],v=["Design a schema for my business. Ask me what you need to know first.","Set up a product catalog with variants, prices per market and stock per warehouse.","Help me import my products from a spreadsheet."];function _(t){let e=t.trim();return e?e.length>48?"Project names can be up to 48 characters.":null:"Give your project a name."}function O(t,e,a){switch(t){case "starter":return {kind:"starter",template:"commerce",sampleData:e};case "describe":return {kind:"describe",description:a};case "empty":return {kind:"empty"}}}var h=2e3,f=300,u=new Set;async function y(t){let e=await fetch(i(t),{credentials:"include"});return e.ok?(await e.json()).starter??"missing":null}function k(t){return t.state==="seeding"||t.state==="completed"}function F({fetchStatus:t,projectId:e,publish:a=r=>mutate(i(e),{starter:r},{revalidate:false}),revalidate:c=d$1,sleep:s=r=>new Promise(o=>setTimeout(o,r))}){if(u.has(e))return;u.add(e);let r=t??(()=>y(e));(async()=>{let o=false;try{for(let l=0;l<f;l+=1){await s(h);let n=null;try{n=await r();}catch{n=null;}if(n==="missing")return;if(n!==null&&(await a(n),!o&&k(n)&&(o=!0,await c(e)),!g(n)))return}}finally{u.delete(e);}})();}export{i as a,d as b,w as c,b as d,g as e,T as f,x as g,v as h,_ as i,O as j,k,F as l};//# sourceMappingURL=chunk-GTR4M2BQ.js.map
3
- //# sourceMappingURL=chunk-GTR4M2BQ.js.map
1
+ import'./index.css';import {d as d$1}from'./chunk-INZZOKRC.js';import {c}from'./chunk-MBBE4RND.js';import {mutate}from'swr';function i(t){return `/api/flexkit/${t}/starter`}async function d(t,e,a,c="Something went wrong. Please try again."){try{let s=await fetch(t,{method:e,credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),r=await s.json().catch(()=>({}));return s.ok?{...r,ok:!0}:{ok:!1,code:r.code??"unknown_error",message:r.error??c}}catch{return {ok:false,code:"network_error",message:"Flexkit is not reachable. Check your connection and try again."}}}function w(t){return d(c.me,"PATCH",{displayName:t})}function b(t,e){return d(i(t),"POST",e)}function g(t){return t?.state==="queued"||t?.state==="deploying"||t?.state==="seeding"}function T(t){return [`I'm setting up Flexkit for my business: ${t.trim()}`,"","Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records."].join(`
2
+ `)}var x=["Which variants are running low on stock, and what is already on order?","Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.","Which products are missing prices, titles or SEO copy in the UK or US?","Show last month\u2019s revenue by market and sales channel.","Which open support tickets need attention today?"],v=["Design a schema for my business. Ask me what you need to know first.","Set up a product catalog with variants, prices per market and stock per warehouse.","Help me import my products from a spreadsheet."];function _(t){let e=t.trim();return e?e.length>48?"Project names can be up to 48 characters.":null:"Give your project a name."}function O(t,e,a){switch(t){case "starter":return {kind:"starter",template:"commerce",sampleData:e};case "describe":return {kind:"describe",description:a};case "empty":return {kind:"empty"}}}var h=2e3,f=300,u=new Set;async function y(t){let e=await fetch(i(t),{credentials:"include"});return e.ok?(await e.json()).starter??"missing":null}function k(t){return t.state==="seeding"||t.state==="completed"}function F({fetchStatus:t,projectId:e,publish:a=r=>mutate(i(e),{starter:r},{revalidate:false}),revalidate:c=d$1,sleep:s=r=>new Promise(o=>setTimeout(o,r))}){if(u.has(e))return;u.add(e);let r=t??(()=>y(e));(async()=>{let o=false;try{for(let l=0;l<f;l+=1){await s(h);let n=null;try{n=await r();}catch{n=null;}if(n==="missing")return;if(n!==null&&(await a(n),!o&&k(n)&&(o=!0,await c(e)),!g(n)))return}}finally{u.delete(e);}})();}export{i as a,d as b,w as c,b as d,g as e,T as f,x as g,v as h,_ as i,O as j,k,F as l};//# sourceMappingURL=chunk-3GXM5SSM.js.map
3
+ //# sourceMappingURL=chunk-3GXM5SSM.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/config/onboarding.ts","../src/apps/ai/starter-watch.ts"],"names":["starterPath","projectId","send","url","method","body","fallbackMessage","response","json","saveDisplayName","displayName","userApiPaths","applyStarter","starter","isStarterRunning","status","describeBusinessPrompt","description","COMMERCE_STARTER_PROMPTS","EMPTY_STARTER_PROMPTS","validateProjectName","name","trimmed","toProjectStart","kind","sampleData","POLL_INTERVAL_MS","POLL_LIMIT","watching","fetchStarter","starterSchemaDeployed","watchStarter","fetchStatus","publish","mutate","revalidate","revalidateProjectSchema","sleep","ms","resolve","load","schemaLoaded","attempt"],"mappings":"4HAuBO,SAASA,CAAAA,CAAYC,CAAAA,CAA2B,CACrD,OAAO,gBAAgBA,CAAS,CAAA,QAAA,CAClC,CAKA,eAAsBC,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,EAAkB,yCAAA,CACqB,CACvC,GAAI,CACF,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAMJ,EAAK,CAChC,MAAA,CAAAC,CAAAA,CACA,WAAA,CAAa,aAAA,CACb,OAAA,CAAS,CAAE,cAAA,CAAgB,kBAAmB,CAAA,CAC9C,IAAA,CAAM,IAAA,CAAK,SAAA,CAAUC,CAAI,CAC3B,CAAC,CAAA,CACKG,EAAQ,MAAMD,CAAAA,CAAS,IAAA,EAAK,CAAE,KAAA,CAAM,KAAO,EAAC,CAAE,EAEpD,OAAIA,CAAAA,CAAS,EAAA,CACJ,CAAE,GAAGC,CAAAA,CAAM,EAAA,CAAI,CAAA,CAAK,EAGtB,CACL,EAAA,CAAI,CAAA,CAAA,CACJ,IAAA,CAAMA,EAAK,IAAA,EAAQ,eAAA,CACnB,OAAA,CAASA,CAAAA,CAAK,OAASF,CACzB,CACF,CAAA,KAAQ,CACN,OAAO,CACL,EAAA,CAAI,KAAA,CACJ,KAAM,eAAA,CACN,OAAA,CAAS,gEACX,CACF,CACF,CAGO,SAASG,CAAAA,CAAgBC,EAAsD,CACpF,OAAOR,CAAAA,CAAKS,CAAAA,CAAa,EAAA,CAAI,OAAA,CAAS,CAAE,WAAA,CAAAD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D,MAAML,CAAAA,CAAMX,CAAgB,CAAA,CAE5B,IAAIX,CAAAA,CAA2C,IAAA,CAE/C,GAAI,CACFA,CAAAA,CAAS,MAAMyB,CAAAA,GACjB,CAAA,KAAQ,CACNzB,CAAAA,CAAS,KACX,CAEA,GAAIA,CAAAA,GAAW,SAAA,CACb,OAGF,GAAIA,CAAAA,GAAW,IAAA,GAIf,MAAMkB,CAAAA,CAAQlB,CAAM,CAAA,CAEhB,CAAC0B,CAAAA,EAAgBX,CAAAA,CAAsBf,CAAM,CAAA,GAC/C0B,CAAAA,CAAe,CAAA,CAAA,CACf,MAAMN,CAAAA,CAAWlC,CAAS,CAAA,CAAA,CAGxB,CAACa,CAAAA,CAAiBC,CAAM,CAAA,CAAA,CAC1B,MAEJ,CACF,CAAA,OAAE,CACAa,CAAAA,CAAS,MAAA,CAAO3B,CAAS,EAC3B,CACF,CAAA,IACF","file":"chunk-GTR4M2BQ.js","sourcesContent":["import { userApiPaths } from '../api-paths';\n\n/** Starter templates a new project can begin from; the backend owns their schema and sample data. */\nexport type StarterTemplate = 'commerce';\n\nexport type StarterStatus = {\n template: StarterTemplate;\n sampleData: boolean;\n state: 'queued' | 'deploying' | 'seeding' | 'completed' | 'failed';\n progress?: { done: number; total: number };\n error?: string;\n completedAt?: string;\n};\n\n/** How the user chose to start a new project, carried to its AI chat in the navigation state. */\nexport type ProjectStart =\n | { kind: 'starter'; template: StarterTemplate; sampleData: boolean }\n | { kind: 'describe'; description: string }\n | { kind: 'empty' };\n\n/** Navigation state the onboarding hands the AI chat of a new project. */\nexport type OnboardingNavigationState = { onboardingPrompt?: string };\n\nexport function starterPath(projectId: string): string {\n return `/api/flexkit/${projectId}/starter`;\n}\n\nexport type Failure = { ok: false; code: string; message: string };\n\n/** A JSON request to the hosted BFF, with its failures mapped to a message the UI can show. */\nexport async function send<T>(\n url: string,\n method: 'PATCH' | 'POST',\n body: unknown,\n fallbackMessage = 'Something went wrong. Please try again.'\n): Promise<({ ok: true } & T) | Failure> {\n try {\n const response = await fetch(url, {\n method,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n const json = (await response.json().catch(() => ({}))) as { code?: string; error?: string } & T;\n\n if (response.ok) {\n return { ...json, ok: true };\n }\n\n return {\n ok: false,\n code: json.code ?? 'unknown_error',\n message: json.error ?? fallbackMessage,\n };\n } catch {\n return {\n ok: false,\n code: 'network_error',\n message: 'Flexkit is not reachable. Check your connection and try again.',\n };\n }\n}\n\n/** Hosted mode: saves the signed-in user's display name. */\nexport function saveDisplayName(displayName: string): Promise<{ ok: true } | Failure> {\n return send(userApiPaths.me, 'PATCH', { displayName });\n}\n\n/** Applies a starter template to a new, empty project; the schema and sample data arrive in the background. */\nexport function applyStarter(\n projectId: string,\n starter: { template: StarterTemplate; sampleData: boolean }\n): Promise<({ ok: true } & { starter: StarterStatus }) | Failure> {\n return send<{ starter: StarterStatus }>(starterPath(projectId), 'POST', starter);\n}\n\nexport function isStarterRunning(status: StarterStatus | null | undefined): boolean {\n return status?.state === 'queued' || status?.state === 'deploying' || status?.state === 'seeding';\n}\n\n/** The first message of a project whose owner described the business instead of picking a template. */\nexport function describeBusinessPrompt(description: string): string {\n return [\n `I'm setting up Flexkit for my business: ${description.trim()}`,\n '',\n 'Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records.',\n ].join('\\n');\n}\n\n/** Questions the commerce sample store can answer; each one finds a problem planted in the data. */\nexport const COMMERCE_STARTER_PROMPTS = [\n 'Which variants are running low on stock, and what is already on order?',\n 'Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.',\n 'Which products are missing prices, titles or SEO copy in the UK or US?',\n 'Show last month’s revenue by market and sales channel.',\n 'Which open support tickets need attention today?',\n] as const;\n\nexport const EMPTY_STARTER_PROMPTS = [\n 'Design a schema for my business. Ask me what you need to know first.',\n 'Set up a product catalog with variants, prices per market and stock per warehouse.',\n 'Help me import my products from a spreadsheet.',\n] as const;\n\n/** Only what the field can tell; the backend owns the character rules and says what it refuses. */\nexport function validateProjectName(name: string): string | null {\n const trimmed = name.trim();\n\n if (!trimmed) {\n return 'Give your project a name.';\n }\n\n if (trimmed.length > 48) {\n return 'Project names can be up to 48 characters.';\n }\n\n return null;\n}\n\n/** The choice on the last step, as sent to the backend and the AI chat. */\nexport function toProjectStart(kind: ProjectStart['kind'], sampleData: boolean, description: string): ProjectStart {\n switch (kind) {\n case 'starter':\n return { kind: 'starter', template: 'commerce', sampleData };\n case 'describe':\n return { kind: 'describe', description };\n case 'empty':\n return { kind: 'empty' };\n }\n}\n","import { mutate } from 'swr';\nimport { isStarterRunning, starterPath, type StarterStatus } from '../../core/config/onboarding';\nimport { revalidateProjectSchema } from '../../core/config/use-project-schemas';\n\nconst POLL_INTERVAL_MS = 2_000;\n/** About ten minutes; a starter usually finishes in two. */\nconst POLL_LIMIT = 300;\nconst watching = new Set<string>();\n\n/** `null` = transient failure (keep polling). */\nexport type StarterFetcher = () => Promise<StarterStatus | null | 'missing'>;\n\nasync function fetchStarter(projectId: string): Promise<StarterStatus | null | 'missing'> {\n const response = await fetch(starterPath(projectId), { credentials: 'include' });\n\n if (!response.ok) {\n return null;\n }\n\n const body = (await response.json()) as { starter?: StarterStatus | null };\n\n return body.starter ?? 'missing';\n}\n\n/** The schema is live once the starter got past its deploy. */\nexport function starterSchemaDeployed(status: StarterStatus): boolean {\n return status.state === 'seeding' || status.state === 'completed';\n}\n\n/**\n * Follows a running starter until it settles, independently of which\n * component started it and of navigation inside the Studio. Shares its\n * results through the SWR cache of `starterPath`, and reloads the project\n * schema once, as soon as the starter's schema is deployed.\n */\nexport function watchStarter({\n fetchStatus,\n projectId,\n publish = (status) => mutate(starterPath(projectId), { starter: status }, { revalidate: false }),\n revalidate = revalidateProjectSchema,\n sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n}: {\n fetchStatus?: StarterFetcher;\n projectId: string;\n publish?: (_status: StarterStatus) => Promise<unknown>;\n revalidate?: (_projectId: string) => Promise<unknown>;\n sleep?: (_ms: number) => Promise<void>;\n}): void {\n if (watching.has(projectId)) {\n return;\n }\n\n watching.add(projectId);\n\n const load = fetchStatus ?? (() => fetchStarter(projectId));\n\n void (async () => {\n let schemaLoaded = false;\n\n try {\n for (let attempt = 0; attempt < POLL_LIMIT; attempt += 1) {\n await sleep(POLL_INTERVAL_MS);\n\n let status: StarterStatus | null | 'missing' = null;\n\n try {\n status = await load();\n } catch {\n status = null;\n }\n\n if (status === 'missing') {\n return;\n }\n\n if (status === null) {\n continue;\n }\n\n await publish(status);\n\n if (!schemaLoaded && starterSchemaDeployed(status)) {\n schemaLoaded = true;\n await revalidate(projectId);\n }\n\n if (!isStarterRunning(status)) {\n return;\n }\n }\n } finally {\n watching.delete(projectId);\n }\n })();\n}\n"]}
1
+ {"version":3,"sources":["../src/core/config/onboarding.ts","../src/apps/ai/starter-watch.ts"],"names":["starterPath","projectId","send","url","method","body","fallbackMessage","response","json","saveDisplayName","displayName","userApiPaths","applyStarter","starter","isStarterRunning","status","describeBusinessPrompt","description","COMMERCE_STARTER_PROMPTS","EMPTY_STARTER_PROMPTS","validateProjectName","name","trimmed","toProjectStart","kind","sampleData","POLL_INTERVAL_MS","POLL_LIMIT","watching","fetchStarter","starterSchemaDeployed","watchStarter","fetchStatus","publish","mutate","revalidate","revalidateProjectSchema","sleep","ms","resolve","load","schemaLoaded","attempt"],"mappings":"4HAuBO,SAASA,CAAAA,CAAYC,CAAAA,CAA2B,CACrD,OAAO,gBAAgBA,CAAS,CAAA,QAAA,CAClC,CAKA,eAAsBC,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,EAAkB,yCAAA,CACqB,CACvC,GAAI,CACF,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAMJ,EAAK,CAChC,MAAA,CAAAC,CAAAA,CACA,WAAA,CAAa,aAAA,CACb,OA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-paths';\n\n/** Starter templates a new project can begin from; the backend owns their schema and sample data. */\nexport type StarterTemplate = 'commerce';\n\nexport type StarterStatus = {\n template: StarterTemplate;\n sampleData: boolean;\n state: 'queued' | 'deploying' | 'seeding' | 'completed' | 'failed';\n progress?: { done: number; total: number };\n error?: string;\n completedAt?: string;\n};\n\n/** How the user chose to start a new project, carried to its AI chat in the navigation state. */\nexport type ProjectStart =\n | { kind: 'starter'; template: StarterTemplate; sampleData: boolean }\n | { kind: 'describe'; description: string }\n | { kind: 'empty' };\n\n/** Navigation state the onboarding hands the AI chat of a new project. */\nexport type OnboardingNavigationState = { onboardingPrompt?: string };\n\nexport function starterPath(projectId: string): string {\n return `/api/flexkit/${projectId}/starter`;\n}\n\nexport type Failure = { ok: false; code: string; message: string };\n\n/** A JSON request to the hosted BFF, with its failures mapped to a message the UI can show. */\nexport async function send<T>(\n url: string,\n method: 'PATCH' | 'POST',\n body: unknown,\n fallbackMessage = 'Something went wrong. Please try again.'\n): Promise<({ ok: true } & T) | Failure> {\n try {\n const response = await fetch(url, {\n method,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n const json = (await response.json().catch(() => ({}))) as { code?: string; error?: string } & T;\n\n if (response.ok) {\n return { ...json, ok: true };\n }\n\n return {\n ok: false,\n code: json.code ?? 'unknown_error',\n message: json.error ?? fallbackMessage,\n };\n } catch {\n return {\n ok: false,\n code: 'network_error',\n message: 'Flexkit is not reachable. Check your connection and try again.',\n };\n }\n}\n\n/** Hosted mode: saves the signed-in user's display name. */\nexport function saveDisplayName(displayName: string): Promise<{ ok: true } | Failure> {\n return send(userApiPaths.me, 'PATCH', { displayName });\n}\n\n/** Applies a starter template to a new, empty project; the schema and sample data arrive in the background. */\nexport function applyStarter(\n projectId: string,\n starter: { template: StarterTemplate; sampleData: boolean }\n): Promise<({ ok: true } & { starter: StarterStatus }) | Failure> {\n return send<{ starter: StarterStatus }>(starterPath(projectId), 'POST', starter);\n}\n\nexport function isStarterRunning(status: StarterStatus | null | undefined): boolean {\n return status?.state === 'queued' || status?.state === 'deploying' || status?.state === 'seeding';\n}\n\n/** The first message of a project whose owner described the business instead of picking a template. */\nexport function describeBusinessPrompt(description: string): string {\n return [\n `I'm setting up Flexkit for my business: ${description.trim()}`,\n '',\n 'Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records.',\n ].join('\\n');\n}\n\n/** Questions the commerce sample store can answer; each one finds a problem planted in the data. */\nexport const COMMERCE_STARTER_PROMPTS = [\n 'Which variants are running low on stock, and what is already on order?',\n 'Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.',\n 'Which products are missing prices, titles or SEO copy in the UK or US?',\n 'Show last month’s revenue by market and sales channel.',\n 'Which open support tickets need attention today?',\n] as const;\n\nexport const EMPTY_STARTER_PROMPTS = [\n 'Design a schema for my business. Ask me what you need to know first.',\n 'Set up a product catalog with variants, prices per market and stock per warehouse.',\n 'Help me import my products from a spreadsheet.',\n] as const;\n\n/** Only what the field can tell; the backend owns the character rules and says what it refuses. */\nexport function validateProjectName(name: string): string | null {\n const trimmed = name.trim();\n\n if (!trimmed) {\n return 'Give your project a name.';\n }\n\n if (trimmed.length > 48) {\n return 'Project names can be up to 48 characters.';\n }\n\n return null;\n}\n\n/** The choice on the last step, as sent to the backend and the AI chat. */\nexport function toProjectStart(kind: ProjectStart['kind'], sampleData: boolean, description: string): ProjectStart {\n switch (kind) {\n case 'starter':\n return { kind: 'starter', template: 'commerce', sampleData };\n case 'describe':\n return { kind: 'describe', description };\n case 'empty':\n return { kind: 'empty' };\n }\n}\n","import { mutate } from 'swr';\nimport { isStarterRunning, starterPath, type StarterStatus } from '../../core/config/onboarding';\nimport { revalidateProjectSchema } from '../../core/config/use-project-schemas';\n\nconst POLL_INTERVAL_MS = 2_000;\n/** About ten minutes; a starter usually finishes in two. */\nconst POLL_LIMIT = 300;\nconst watching = new Set<string>();\n\n/** `null` = transient failure (keep polling). */\nexport type StarterFetcher = () => Promise<StarterStatus | null | 'missing'>;\n\nasync function fetchStarter(projectId: string): Promise<StarterStatus | null | 'missing'> {\n const response = await fetch(starterPath(projectId), { credentials: 'include' });\n\n if (!response.ok) {\n return null;\n }\n\n const body = (await response.json()) as { starter?: StarterStatus | null };\n\n return body.starter ?? 'missing';\n}\n\n/** The schema is live once the starter got past its deploy. */\nexport function starterSchemaDeployed(status: StarterStatus): boolean {\n return status.state === 'seeding' || status.state === 'completed';\n}\n\n/**\n * Follows a running starter until it settles, independently of which\n * component started it and of navigation inside the Studio. Shares its\n * results through the SWR cache of `starterPath`, and reloads the project\n * schema once, as soon as the starter's schema is deployed.\n */\nexport function watchStarter({\n fetchStatus,\n projectId,\n publish = (status) => mutate(starterPath(projectId), { starter: status }, { revalidate: false }),\n revalidate = revalidateProjectSchema,\n sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n}: {\n fetchStatus?: StarterFetcher;\n projectId: string;\n publish?: (_status: StarterStatus) => Promise<unknown>;\n revalidate?: (_projectId: string) => Promise<unknown>;\n sleep?: (_ms: number) => Promise<void>;\n}): void {\n if (watching.has(projectId)) {\n return;\n }\n\n watching.add(projectId);\n\n const load = fetchStatus ?? (() => fetchStarter(projectId));\n\n void (async () => {\n let schemaLoaded = false;\n\n try {\n for (let attempt = 0; attempt < POLL_LIMIT; attempt += 1) {\n await sleep(POLL_INTERVAL_MS);\n\n let status: StarterStatus | null | 'missing' = null;\n\n try {\n status = await load();\n } catch {\n status = null;\n }\n\n if (status === 'missing') {\n return;\n }\n\n if (status === null) {\n continue;\n }\n\n await publish(status);\n\n if (!schemaLoaded && starterSchemaDeployed(status)) {\n schemaLoaded = true;\n await revalidate(projectId);\n }\n\n if (!isStarterRunning(status)) {\n return;\n }\n }\n } finally {\n watching.delete(projectId);\n }\n })();\n}\n"]}
@@ -1,3 +1,3 @@
1
- import'./index.css';import {f as f$1}from'./chunk-TWA6OG5U.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-474MQNDK.js.map
3
- //# sourceMappingURL=chunk-474MQNDK.js.map
1
+ import'./index.css';import {f as f$1}from'./chunk-INZZOKRC.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-4OGLWOO3.js.map
3
+ //# sourceMappingURL=chunk-4OGLWOO3.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,MAAA,CAAQK,CAAA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AG,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-474MQNDK.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,CAAAA,CAAkC,CAChF,G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K,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-4OGLWOO3.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 {c,a,d as d$1}from'./chunk-FXUD4JRG.js';import {f}from'./chunk-TWA6OG5U.js';import {d}from'./chunk-MBBE4RND.js';import {useCallback}from'react';import {toast}from'sonner';import {useApolloClient}from'@apollo/client/react';function E(i){let{currentProjectSchema:t}=f();return useCallback(a$1=>{t&&c(a(i,t),a$1);},[i,t])}var g=["image/jpeg","image/png","image/webp","image/vnd.microsoft.icon","image/bmp","image/gif","image/tiff","image/svg+xml","image/avif","image/heic","image/heif","image/heic-sequence","image/heif-sequence","image/apng","audio/aac","audio/mpeg","audio/wav","audio/webm","audio/midi","audio/x-midi","audio/ogg","video/x-msvideo","video/mp4","video/mpeg","video/webm","video/quicktime","video/ogg","video/mp2t","video/3gpp","video/3gpp2","application/x-7z-compressed","application/zip","application/vnd.amazon.ebook","application/octet-stream","application/epub+zip","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-fontobject","application/gzip","application/x-gzip","application/java-archive","application/json","application/ld+json","text/javascript","application/vnd.oasis.opendocument.presentation","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.text","application/ogg","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.rar","application/x-tar","application/vnd.visio","application/xhtml+xml","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/xml"];function F(i,t){if(!i.type)return true;let a=t?t.split(",").map(e=>e.trim()).filter(Boolean):g;return a.length===0?true:a.some(e=>e.endsWith("/*")?i.type.startsWith(e.slice(0,-1)):i.type===e)}async function x(i,t){let a=new URLSearchParams({filename:i.name}),e=await fetch(`${d(t).assets}?${a.toString()}`,{method:"POST",headers:{"Content-Type":i.type||"application/octet-stream"},body:i});if(!e.ok)throw new Error(`Upload failed for ${i.name}`);let n=await e.json(),o={_id:n._id,path:n.path??"",originalFilename:n.originalFilename??i.name,size:n.size??i.size,mimeType:n.mimeType??i.type,lqip:n.lqip??"",width:n.width??0,height:n.height??0};return {pathname:o.path,lqip:o.lqip||void 0,originalFilename:o.originalFilename,size:o.size,mimeType:o.mimeType,width:o.width||void 0,height:o.height||void 0,_id:o._id,asset:o}}async function h(i,t){let{projectId:a,accept:e,maxBytes:n=4*1024*1024,onUploadStart:o}=t,l=[];for(let p of Array.from(i)){if(p.size>n){toast.error(`File size too big (max ${(n/(1024*1024)).toFixed(0)}MB): ${p.name}`);continue}if(!F(p,e)){toast.error(`Unsupported file type: ${p.name}`);continue}l.push(p);}if(l.length===0)return [];o?.();try{let p=await Promise.all(l.map(async f=>x(f,a)));return p.length>0&&toast.success(`Uploaded ${p.length} file${p.length>1?"s":""}`),p}catch(p){return console.error(p),toast.error("Upload failed. Please try again."),[]}}async function b(i){let{accept:t,multiple:a=true}=i,e=document.createElement("input");e.type="file",e.accept=t??g.join(","),e.multiple=a,e.style.display="none",document.body.appendChild(e);try{let n=await new Promise(o=>{e.addEventListener("change",()=>o(e.files),{once:!0}),e.addEventListener("cancel",()=>o(null),{once:!0}),e.click();});return !n||n.length===0?[]:h(n,i)}finally{document.body.removeChild(e);}}function q(){let i=useApolloClient();return useCallback(async t=>{let a=t.files?await h(t.files,t):await b(t);return a.length>0&&await d$1(i,"GetAssets").catch(e=>{console.error("Error refreshing asset lists after upload:",e);}),a},[i])}export{E as a,x as b,q as c};//# sourceMappingURL=chunk-27JTWTU6.js.map
2
- //# sourceMappingURL=chunk-27JTWTU6.js.map
1
+ import'./index.css';import {c,a,d as d$1}from'./chunk-CCVE7GGO.js';import {f}from'./chunk-INZZOKRC.js';import {d}from'./chunk-MBBE4RND.js';import {useCallback}from'react';import {toast}from'sonner';import {useApolloClient}from'@apollo/client/react';function E(i){let{currentProjectSchema:t}=f();return useCallback(a$1=>{t&&c(a(i,t),a$1);},[i,t])}var g=["image/jpeg","image/png","image/webp","image/vnd.microsoft.icon","image/bmp","image/gif","image/tiff","image/svg+xml","image/avif","image/heic","image/heif","image/heic-sequence","image/heif-sequence","image/apng","audio/aac","audio/mpeg","audio/wav","audio/webm","audio/midi","audio/x-midi","audio/ogg","video/x-msvideo","video/mp4","video/mpeg","video/webm","video/quicktime","video/ogg","video/mp2t","video/3gpp","video/3gpp2","application/x-7z-compressed","application/zip","application/vnd.amazon.ebook","application/octet-stream","application/epub+zip","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-fontobject","application/gzip","application/x-gzip","application/java-archive","application/json","application/ld+json","text/javascript","application/vnd.oasis.opendocument.presentation","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.text","application/ogg","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.rar","application/x-tar","application/vnd.visio","application/xhtml+xml","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/xml"];function F(i,t){if(!i.type)return true;let a=t?t.split(",").map(e=>e.trim()).filter(Boolean):g;return a.length===0?true:a.some(e=>e.endsWith("/*")?i.type.startsWith(e.slice(0,-1)):i.type===e)}async function x(i,t){let a=new URLSearchParams({filename:i.name}),e=await fetch(`${d(t).assets}?${a.toString()}`,{method:"POST",headers:{"Content-Type":i.type||"application/octet-stream"},body:i});if(!e.ok)throw new Error(`Upload failed for ${i.name}`);let n=await e.json(),o={_id:n._id,path:n.path??"",originalFilename:n.originalFilename??i.name,size:n.size??i.size,mimeType:n.mimeType??i.type,lqip:n.lqip??"",width:n.width??0,height:n.height??0};return {pathname:o.path,lqip:o.lqip||void 0,originalFilename:o.originalFilename,size:o.size,mimeType:o.mimeType,width:o.width||void 0,height:o.height||void 0,_id:o._id,asset:o}}async function h(i,t){let{projectId:a,accept:e,maxBytes:n=4*1024*1024,onUploadStart:o}=t,l=[];for(let p of Array.from(i)){if(p.size>n){toast.error(`File size too big (max ${(n/(1024*1024)).toFixed(0)}MB): ${p.name}`);continue}if(!F(p,e)){toast.error(`Unsupported file type: ${p.name}`);continue}l.push(p);}if(l.length===0)return [];o?.();try{let p=await Promise.all(l.map(async f=>x(f,a)));return p.length>0&&toast.success(`Uploaded ${p.length} file${p.length>1?"s":""}`),p}catch(p){return console.error(p),toast.error("Upload failed. Please try again."),[]}}async function b(i){let{accept:t,multiple:a=true}=i,e=document.createElement("input");e.type="file",e.accept=t??g.join(","),e.multiple=a,e.style.display="none",document.body.appendChild(e);try{let n=await new Promise(o=>{e.addEventListener("change",()=>o(e.files),{once:!0}),e.addEventListener("cancel",()=>o(null),{once:!0}),e.click();});return !n||n.length===0?[]:h(n,i)}finally{document.body.removeChild(e);}}function q(){let i=useApolloClient();return useCallback(async t=>{let a=t.files?await h(t.files,t):await b(t);return a.length>0&&await d$1(i,"GetAssets").catch(e=>{console.error("Error refreshing asset lists after upload:",e);}),a},[i])}export{E as a,x as b,q as c};//# sourceMappingURL=chunk-6J3ZIVDQ.js.map
2
+ //# sourceMappingURL=chunk-6J3ZIVDQ.js.map