orbitchat 2.3.2 → 2.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{_basePickBy-C3-QE0dl-iFJM37t-.js → _basePickBy-C3-QE0dl-CBItb41O.js} +1 -1
- package/dist/assets/{_baseUniq-CstiM9Lp-mfwAZxz7.js → _baseUniq-CstiM9Lp-Vrkvfrsq.js} +1 -1
- package/dist/assets/{api-LelnGrLi.js → api-CvFCgVm7.js} +1 -1
- package/dist/assets/{arc-W3NKKXLI-BSMC_lFa.js → arc-W3NKKXLI-BLXqQVy9.js} +1 -1
- package/dist/assets/{architectureDiagram-VXUJARFQ-zzJsgPC6-BsU11BG-.js → architectureDiagram-VXUJARFQ-zzJsgPC6-DHQldRFY.js} +1 -1
- package/dist/assets/{blockDiagram-VD42YOAC-D-In4h7h-CMLKJ02L.js → blockDiagram-VD42YOAC-D-In4h7h-QH2TogI4.js} +1 -1
- package/dist/assets/{c4Diagram-YG6GDRKO-DBs8r9gh-cdf9XHrR.js → c4Diagram-YG6GDRKO-DBs8r9gh-DC_egmCX.js} +1 -1
- package/dist/assets/channel-RBWQyMSg-B7EgkQfa.js +1 -0
- package/dist/assets/{chunk-4BX2VUAB-BqD7w0AR-CqSCJfba.js → chunk-4BX2VUAB-BqD7w0AR-pdODcPr_.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-D8pvDVEJ-D61_Ok8Q.js → chunk-55IACEB6-D8pvDVEJ-BDgpw68Q.js} +1 -1
- package/dist/assets/{chunk-B4BG7PRW-Dwma1pSy-z58jzoiB.js → chunk-B4BG7PRW-Dwma1pSy-BLbPnUzX.js} +1 -1
- package/dist/assets/{chunk-DI55MBZ5-BY2XXvZz-CHzq07Hh.js → chunk-DI55MBZ5-BY2XXvZz-WCPjnK5U.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-BeiLbQ8U-DVReJLpg.js → chunk-FMBD7UC4-BeiLbQ8U-PPDuhvL_.js} +1 -1
- package/dist/assets/{chunk-QN33PNHL-BkO3hOeq-SQ3cFeMx.js → chunk-QN33PNHL-BkO3hOeq-BxbTTNC7.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-Cwlo2qTG-BKM38KSm.js → chunk-QZHKN3VN-Cwlo2qTG-CcNoRHZC.js} +1 -1
- package/dist/assets/{chunk-TZMSLE5B-BnXK-OiF-DjwcKkV-.js → chunk-TZMSLE5B-BnXK-OiF-ggUp8YXR.js} +1 -1
- package/dist/assets/{classDiagram-2ON5EDUG-Crd6O69V-CTb_giLj.js → classDiagram-2ON5EDUG-Crd6O69V-Chm9m1T4.js} +1 -1
- package/dist/assets/{classDiagram-v2-WZHVMYZB-Crd6O69V-CTb_giLj.js → classDiagram-v2-WZHVMYZB-Crd6O69V-Chm9m1T4.js} +1 -1
- package/dist/assets/clone-CfLgyC8S-D-j0r5Pr.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-DKeVcPDK-C49Ve4bT.js → cose-bilkent-S5V4N54A-DKeVcPDK-DzjcbsIY.js} +1 -1
- package/dist/assets/{dagre-6UL2VRFP-BPf604Df-D7VW3CmU.js → dagre-6UL2VRFP-BPf604Df-C0WwjL5r.js} +1 -1
- package/dist/assets/{diagram-PSM6KHXK-DeLcpEV3-H60fPqtK.js → diagram-PSM6KHXK-DeLcpEV3-Bj0ToVQD.js} +1 -1
- package/dist/assets/{diagram-QEK2KX5R-C_5RR1NJ-CyBWBLkl.js → diagram-QEK2KX5R-C_5RR1NJ-CTdkvrxF.js} +1 -1
- package/dist/assets/{diagram-S2PKOQOG-DVx43aon-DETWtBuT.js → diagram-S2PKOQOG-DVx43aon-Du-jFDIt.js} +1 -1
- package/dist/assets/{erDiagram-Q2GNP2WA-DgUeO5_h-BNJGcHpr.js → erDiagram-Q2GNP2WA-DgUeO5_h-D8uM7AsV.js} +1 -1
- package/dist/assets/{flowDiagram-NV44I4VS-C5HQUzU9-BNXI-d2R.js → flowDiagram-NV44I4VS-C5HQUzU9-66FPNpP3.js} +1 -1
- package/dist/assets/{ganttDiagram-JELNMOA3-DgSZ1ixF-CqqwgL-1.js → ganttDiagram-JELNMOA3-DgSZ1ixF-B9F9GbD_.js} +1 -1
- package/dist/assets/{gitGraphDiagram-NY62KEGX-DY5loT9K-LIsl5uZ3.js → gitGraphDiagram-NY62KEGX-DY5loT9K-B22n5mHi.js} +1 -1
- package/dist/assets/{graph-BfwqPHx6-DFBd6FGE.js → graph-BfwqPHx6-DXOEeCjL.js} +1 -1
- package/dist/assets/{index-BAOVR-xx-7Y8chteW.js → index-BAOVR-xx-CgGkM_kf.js} +1 -1
- package/dist/assets/{index-bTMd1n3H.js → index-Bkkyccnk.js} +27 -27
- package/dist/assets/{infoDiagram-WHAUD3N6-DIqQ6vCk-CgIZNz5k.js → infoDiagram-WHAUD3N6-DIqQ6vCk-xD2zIyk6.js} +1 -1
- package/dist/assets/{journeyDiagram-XKPGCS4Q-DXjg3S3r-BFSr5Y_O.js → journeyDiagram-XKPGCS4Q-DXjg3S3r-BUFxCU2Q.js} +1 -1
- package/dist/assets/{kanban-definition-3W4ZIXB7-Uxt7Am6n-B2sQ_4KY.js → kanban-definition-3W4ZIXB7-Uxt7Am6n-Csei5eOU.js} +1 -1
- package/dist/assets/{layout-CSfkE668-DqEfFpaV.js → layout-CSfkE668-CekMakW-.js} +1 -1
- package/dist/assets/{mindmap-definition-VGOIOE7T-DXwVuAPE-CqSxawNn.js → mindmap-definition-VGOIOE7T-DXwVuAPE-8H0GPPLn.js} +1 -1
- package/dist/assets/{pieDiagram-ADFJNKIX-Cj0EHHtj-DoZkugbn.js → pieDiagram-ADFJNKIX-Cj0EHHtj-dX98b0XZ.js} +1 -1
- package/dist/assets/{quadrantDiagram-AYHSOK5B-CnLDz007-B5oIgb5_.js → quadrantDiagram-AYHSOK5B-CnLDz007-CdAKZqPT.js} +1 -1
- package/dist/assets/{requirementDiagram-UZGBJVZJ-rDaI-8Be-CxOGR1Zn.js → requirementDiagram-UZGBJVZJ-rDaI-8Be-BJPCvjkD.js} +1 -1
- package/dist/assets/{sankeyDiagram-TZEHDZUN-A0YO8ixs-C5PgwN-q.js → sankeyDiagram-TZEHDZUN-A0YO8ixs-DvqHljpO.js} +1 -1
- package/dist/assets/{sequenceDiagram-WL72ISMW-BFF7TtP7-hG33hfBF.js → sequenceDiagram-WL72ISMW-BFF7TtP7-BSpeW2is.js} +1 -1
- package/dist/assets/{stateDiagram-FKZM4ZOC-ofFsB7HJ-DTDtfvGY.js → stateDiagram-FKZM4ZOC-ofFsB7HJ-CebwML_S.js} +1 -1
- package/dist/assets/{stateDiagram-v2-4FDKWEC3-CEZFbksU-N2nGVIZ8.js → stateDiagram-v2-4FDKWEC3-CEZFbksU-DblRbnEz.js} +1 -1
- package/dist/assets/{timeline-definition-IT6M3QCI-5W361ZNm-BJCAmQPf.js → timeline-definition-IT6M3QCI-5W361ZNm-DWTb5GU0.js} +1 -1
- package/dist/assets/{treemap-KMMF4GRG-pGRoYcSn-Bqd_b8O9.js → treemap-KMMF4GRG-pGRoYcSn-C629biGV.js} +1 -1
- package/dist/assets/{xychartDiagram-PRI3JC2R-CSr0GxaP-CvHeGt3A.js → xychartDiagram-PRI3JC2R-CSr0GxaP-xg5Sy4er.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/channel-RBWQyMSg-Bm1y8qn4.js +0 -1
- package/dist/assets/clone-CfLgyC8S-DcNkVsiB.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dagre-6UL2VRFP-BPf604Df-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dagre-6UL2VRFP-BPf604Df-C0WwjL5r.js","assets/graph-BfwqPHx6-DXOEeCjL.js","assets/_baseUniq-CstiM9Lp-Vrkvfrsq.js","assets/layout-CSfkE668-CekMakW-.js","assets/_basePickBy-C3-QE0dl-CBItb41O.js","assets/clone-CfLgyC8S-D-j0r5Pr.js","assets/cose-bilkent-S5V4N54A-DKeVcPDK-DzjcbsIY.js","assets/cytoscape.esm-CjI2IsL8-Da6dFVsf.js","assets/c4Diagram-YG6GDRKO-DBs8r9gh-DC_egmCX.js","assets/chunk-TZMSLE5B-BnXK-OiF-ggUp8YXR.js","assets/flowDiagram-NV44I4VS-C5HQUzU9-66FPNpP3.js","assets/chunk-FMBD7UC4-BeiLbQ8U-PPDuhvL_.js","assets/chunk-55IACEB6-D8pvDVEJ-BDgpw68Q.js","assets/chunk-QN33PNHL-BkO3hOeq-BxbTTNC7.js","assets/channel-RBWQyMSg-B7EgkQfa.js","assets/erDiagram-Q2GNP2WA-DgUeO5_h-D8uM7AsV.js","assets/gitGraphDiagram-NY62KEGX-DY5loT9K-B22n5mHi.js","assets/chunk-4BX2VUAB-BqD7w0AR-pdODcPr_.js","assets/chunk-QZHKN3VN-Cwlo2qTG-CcNoRHZC.js","assets/treemap-KMMF4GRG-pGRoYcSn-C629biGV.js","assets/infoDiagram-WHAUD3N6-DIqQ6vCk-xD2zIyk6.js","assets/pieDiagram-ADFJNKIX-Cj0EHHtj-dX98b0XZ.js","assets/arc-W3NKKXLI-BLXqQVy9.js","assets/requirementDiagram-UZGBJVZJ-rDaI-8Be-BJPCvjkD.js","assets/sequenceDiagram-WL72ISMW-BFF7TtP7-BSpeW2is.js","assets/classDiagram-2ON5EDUG-Crd6O69V-Chm9m1T4.js","assets/chunk-B4BG7PRW-Dwma1pSy-BLbPnUzX.js","assets/classDiagram-v2-WZHVMYZB-Crd6O69V-Chm9m1T4.js","assets/stateDiagram-FKZM4ZOC-ofFsB7HJ-CebwML_S.js","assets/chunk-DI55MBZ5-BY2XXvZz-WCPjnK5U.js","assets/stateDiagram-v2-4FDKWEC3-CEZFbksU-DblRbnEz.js","assets/journeyDiagram-XKPGCS4Q-DXjg3S3r-BUFxCU2Q.js","assets/timeline-definition-IT6M3QCI-5W361ZNm-DWTb5GU0.js","assets/mindmap-definition-VGOIOE7T-DXwVuAPE-8H0GPPLn.js","assets/kanban-definition-3W4ZIXB7-Uxt7Am6n-Csei5eOU.js","assets/diagram-S2PKOQOG-DVx43aon-Du-jFDIt.js","assets/diagram-QEK2KX5R-C_5RR1NJ-CTdkvrxF.js","assets/blockDiagram-VD42YOAC-D-In4h7h-QH2TogI4.js","assets/architectureDiagram-VXUJARFQ-zzJsgPC6-DHQldRFY.js","assets/diagram-PSM6KHXK-DeLcpEV3-Bj0ToVQD.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var kce=Object.defineProperty;var Sce=(e,t,r)=>t in e?kce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var gA=(e,t,r)=>Sce(e,typeof t!="symbol"?t+"":t,r);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const A of i)if(A.type==="childList")for(const a of A.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function r(i){const A={};return i.integrity&&(A.integrity=i.integrity),i.referrerPolicy&&(A.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?A.credentials="include":i.crossOrigin==="anonymous"?A.credentials="omit":A.credentials="same-origin",A}function n(i){if(i.ep)return;i.ep=!0;const A=r(i);fetch(i.href,A)}})();function Uce(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var sV={exports:{}},Kf={},oV={exports:{}},_t={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -1078,8 +1078,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error
|
|
|
1078
1078
|
node : x:${e.x} y:${e.y} w:${e.width} h:${e.height}`);const n=e.x,i=e.y,A=Math.abs(n-r.x),a=e.width/2;let s=r.x<t.x?a-A:a+A;const o=e.height/2,l=Math.abs(t.y-r.y),c=Math.abs(t.x-r.x);if(Math.abs(i-t.y)*a>Math.abs(n-t.x)*o){let u=r.y<t.y?t.y-o-i:i-o-t.y;s=c*u/l;const g={x:r.x<t.x?r.x+s:r.x-c+s,y:r.y<t.y?r.y+l-u:r.y-l+u};return s===0&&(g.x=t.x,g.y=t.y),c===0&&(g.x=t.x),l===0&&(g.y=t.y),ve.debug(`abc89 top/bottom calc, Q ${l}, q ${u}, R ${c}, r ${s}`,g),g}else{r.x<t.x?s=t.x-a-n:s=n-a-t.x;let u=l*s/c,g=r.x<t.x?r.x+c-s:r.x-c+s,h=r.y<t.y?r.y+u:r.y-u;return ve.debug(`sides calc abc89, Q ${l}, q ${u}, R ${c}, r ${s}`,{_x:g,_y:h}),s===0&&(g=t.x,h=t.y),c===0&&(g=t.x),l===0&&(h=t.y),{x:g,y:h}}},"intersection"),xJ=k((e,t)=>{ve.warn("abc88 cutPathAtIntersect",e,t);let r=[],n=e[0],i=!1;return e.forEach(A=>{if(ve.info("abc88 checking point",A,t),!wTe(t,A)&&!i){const a=fTe(t,n,A);ve.debug("abc88 inside",A,n,a),ve.debug("abc88 intersection",a,t);let s=!1;r.forEach(o=>{s=s||o.x===a.x&&o.y===a.y}),r.some(o=>o.x===a.x&&o.y===a.y)?ve.warn("abc88 no intersect",a,r):r.push(a),i=!0}else ve.warn("abc88 outside",A,n),n=A,i||r.push(A)}),ve.debug("returning points",r),r},"cutPathAtIntersect");function sie(e){const t=[],r=[];for(let n=1;n<e.length-1;n++){const i=e[n-1],A=e[n],a=e[n+1];(i.x===A.x&&A.y===a.y&&Math.abs(A.x-a.x)>5&&Math.abs(A.y-i.y)>5||i.y===A.y&&A.x===a.x&&Math.abs(A.x-i.x)>5&&Math.abs(A.y-a.y)>5)&&(t.push(A),r.push(n))}return{cornerPoints:t,cornerPointPositions:r}}k(sie,"extractCornerPoints");var NJ=k(function(e,t,r){const n=t.x-e.x,i=t.y-e.y,A=Math.sqrt(n*n+i*i),a=r/A;return{x:t.x-a*n,y:t.y-a*i}},"findAdjacentPoint"),yTe=k(function(e){const{cornerPointPositions:t}=sie(e),r=[];for(let n=0;n<e.length;n++)if(t.includes(n)){const i=e[n-1],A=e[n+1],a=e[n],s=NJ(i,a,5),o=NJ(A,a,5),l=o.x-s.x,c=o.y-s.y;r.push(s);const u=Math.sqrt(2)*2;let g={x:a.x,y:a.y};if(Math.abs(A.x-i.x)>10&&Math.abs(A.y-i.y)>=10){ve.debug("Corner point fixing",Math.abs(A.x-i.x),Math.abs(A.y-i.y));const h=5;a.x===s.x?g={x:l<0?s.x-h+u:s.x+h-u,y:c<0?s.y-u:s.y+u}:g={x:l<0?s.x-u:s.x+u,y:c<0?s.y-h+u:s.y+h-u}}else ve.debug("Corner point skipping fixing",Math.abs(A.x-i.x),Math.abs(A.y-i.y));r.push(g,o)}else r.push(e[n]);return r},"fixCorners"),ETe=k((e,t,r)=>{const n=e-t-r,i=2,A=2,a=i+A,s=Math.floor(n/a),o=Array(s).fill(`${i} ${A}`).join(" ");return`0 ${t} ${o} ${r}`},"generateDashArray"),ITe=k(function(e,t,r,n,i,A,a,s=!1){var o;const{handDrawnSeed:l}=Ir();let c=t.points,u=!1;const g=i;var h=A;const d=[];for(const Z in t.cssCompiledStyles)zte(Z)||d.push(t.cssCompiledStyles[Z]);ve.debug("UIO intersect check",t.points,h.x,g.x),h.intersect&&g.intersect&&!s&&(c=c.slice(1,t.points.length-1),c.unshift(g.intersect(c[0])),ve.debug("Last point UIO",t.start,"-->",t.end,c[c.length-1],h,h.intersect(c[c.length-1])),c.push(h.intersect(c[c.length-1])));const B=btoa(JSON.stringify(c));t.toCluster&&(ve.info("to cluster abc88",r.get(t.toCluster)),c=xJ(t.points,r.get(t.toCluster).node),u=!0),t.fromCluster&&(ve.debug("from cluster abc88",r.get(t.fromCluster),JSON.stringify(c,null,2)),c=xJ(c.reverse(),r.get(t.fromCluster).node).reverse(),u=!0);let y=c.filter(Z=>!Number.isNaN(Z.y));y=yTe(y);let w=vh;switch(w=zc,t.curve){case"linear":w=zc;break;case"basis":w=vh;break;case"cardinal":w=K$;break;case"bumpX":w=pS;break;case"bumpY":w=mS;break;case"catmullRom":w=X$;break;case"monotoneX":w=CS;break;case"monotoneY":w=QS;break;case"natural":w=MS;break;case"step":w=FS;break;case"stepAfter":w=bS;break;case"stepBefore":w=YS;break;default:w=vh}const{x:f,y:I}=y3e(t),Y=BS().x(f).y(I).curve(w);let Q;switch(t.thickness){case"normal":Q="edge-thickness-normal";break;case"thick":Q="edge-thickness-thick";break;case"invisible":Q="edge-thickness-invisible";break;default:Q="edge-thickness-normal"}switch(t.pattern){case"solid":Q+=" edge-pattern-solid";break;case"dotted":Q+=" edge-pattern-dotted";break;case"dashed":Q+=" edge-pattern-dashed";break;default:Q+=" edge-pattern-solid"}let M,D=t.curve==="rounded"?oie(lie(y,t),5):Y(y);const G=Array.isArray(t.style)?t.style:[t.style];let z=G.find(Z=>Z==null?void 0:Z.startsWith("stroke:")),R=!1;if(t.look==="handDrawn"){const Z=ht.svg(e);Object.assign([],y);const ee=Z.path(D,{roughness:.3,seed:l});Q+=" transition",M=ir(ee).select("path").attr("id",t.id).attr("class"," "+Q+(t.classes?" "+t.classes:"")).attr("style",G?G.reduce((K,$)=>K+";"+$,""):"");let Ae=M.attr("d");M.attr("d",Ae),e.node().appendChild(M.node())}else{const Z=d.join(";"),ee=G?G.reduce((P,Be)=>P+Be+";",""):"";let Ae="";t.animate&&(Ae=" edge-animation-fast"),t.animation&&(Ae=" edge-animation-"+t.animation);const K=(Z?Z+";"+ee+";":ee)+";"+(G?G.reduce((P,Be)=>P+";"+Be,""):"");M=e.append("path").attr("d",D).attr("id",t.id).attr("class"," "+Q+(t.classes?" "+t.classes:"")+(Ae??"")).attr("style",K),z=(o=K.match(/stroke:([^;]+)/))==null?void 0:o[1],R=t.animate===!0||!!t.animation||Z.includes("animation");const $=M.node(),L=typeof $.getTotalLength=="function"?$.getTotalLength():0,ne=P6[t.arrowTypeStart]||0,ge=P6[t.arrowTypeEnd]||0;if(t.look==="neo"&&!R){const P=`stroke-dasharray: ${t.pattern==="dotted"||t.pattern==="dashed"?ETe(L,ne,ge):`0 ${ne} ${L-ne-ge} ${ge}`}; stroke-dashoffset: 0;`;M.attr("style",P+M.attr("style"))}}M.attr("data-edge",!0),M.attr("data-et","edge"),M.attr("data-id",t.id),M.attr("data-points",B),t.showPoints&&y.forEach(Z=>{e.append("circle").style("stroke","red").style("fill","red").attr("r",1).attr("cx",Z.x).attr("cy",Z.y)});let j="";(Ir().flowchart.arrowMarkerAbsolute||Ir().state.arrowMarkerAbsolute)&&(j=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search,j=j.replace(/\(/g,"\\(").replace(/\)/g,"\\)")),ve.info("arrowTypeStart",t.arrowTypeStart),ve.info("arrowTypeEnd",t.arrowTypeEnd),dTe(M,t,j,a,n,z);const W=Math.floor(c.length/2),te=c[W];Ta.isLabelCoordinateInPath(te,M.attr("d"))||(u=!0);let X={};return u&&(X.updatedPath=c),X.originalPath=t.points,X},"insertEdge");function oie(e,t){if(e.length<2)return"";let r="";const n=e.length,i=1e-5;for(let A=0;A<n;A++){const a=e[A],s=e[A-1],o=e[A+1];if(A===0)r+=`M${a.x},${a.y}`;else if(A===n-1)r+=`L${a.x},${a.y}`;else{const l=a.x-s.x,c=a.y-s.y,u=o.x-a.x,g=o.y-a.y,h=Math.hypot(l,c),d=Math.hypot(u,g);if(h<i||d<i){r+=`L${a.x},${a.y}`;continue}const B=l/h,y=c/h,w=u/d,f=g/d,I=B*w+y*f,Y=Math.max(-1,Math.min(1,I)),Q=Math.acos(Y);if(Q<i||Math.abs(Math.PI-Q)<i){r+=`L${a.x},${a.y}`;continue}const M=Math.min(t/Math.sin(Q/2),h/2,d/2),D=a.x-B*M,G=a.y-y*M,z=a.x+w*M,R=a.y+f*M;r+=`L${D},${G}`,r+=`Q${a.x},${a.y} ${z},${R}`}}return r}k(oie,"generateRoundedPath");function G2(e,t){if(!e||!t)return{angle:0,deltaX:0,deltaY:0};const r=t.x-e.x,n=t.y-e.y;return{angle:Math.atan2(n,r),deltaX:r,deltaY:n}}k(G2,"calculateDeltaAndAngle");function lie(e,t){const r=e.map(i=>({...i}));if(e.length>=2&&ki[t.arrowTypeStart]){const i=ki[t.arrowTypeStart],A=e[0],a=e[1],{angle:s}=G2(A,a),o=i*Math.cos(s),l=i*Math.sin(s);r[0].x=A.x+o,r[0].y=A.y+l}const n=e.length;if(n>=2&&ki[t.arrowTypeEnd]){const i=ki[t.arrowTypeEnd],A=e[n-1],a=e[n-2],{angle:s}=G2(a,A),o=i*Math.cos(s),l=i*Math.sin(s);r[n-1].x=A.x-o,r[n-1].y=A.y-l}return r}k(lie,"applyMarkerOffsetsToPoints");var CTe=k((e,t,r,n)=>{t.forEach(i=>{TTe[i](e,r,n)})},"insertMarkers"),QTe=k((e,t,r)=>{ve.trace("Making markers for ",r),e.append("defs").append("marker").attr("id",r+"_"+t+"-extensionStart").attr("class","marker extension "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 1,7 L18,13 V 1 Z"),e.append("defs").append("marker").attr("id",r+"_"+t+"-extensionEnd").attr("class","marker extension "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 1,1 V 13 L18,7 Z")},"extension"),MTe=k((e,t,r)=>{e.append("defs").append("marker").attr("id",r+"_"+t+"-compositionStart").attr("class","marker composition "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),e.append("defs").append("marker").attr("id",r+"_"+t+"-compositionEnd").attr("class","marker composition "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"composition"),FTe=k((e,t,r)=>{e.append("defs").append("marker").attr("id",r+"_"+t+"-aggregationStart").attr("class","marker aggregation "+t).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),e.append("defs").append("marker").attr("id",r+"_"+t+"-aggregationEnd").attr("class","marker aggregation "+t).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"aggregation"),YTe=k((e,t,r)=>{e.append("defs").append("marker").attr("id",r+"_"+t+"-dependencyStart").attr("class","marker dependency "+t).attr("refX",6).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 5,7 L9,13 L1,7 L9,1 Z"),e.append("defs").append("marker").attr("id",r+"_"+t+"-dependencyEnd").attr("class","marker dependency "+t).attr("refX",13).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z")},"dependency"),bTe=k((e,t,r)=>{e.append("defs").append("marker").attr("id",r+"_"+t+"-lollipopStart").attr("class","marker lollipop "+t).attr("refX",13).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6),e.append("defs").append("marker").attr("id",r+"_"+t+"-lollipopEnd").attr("class","marker lollipop "+t).attr("refX",1).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6)},"lollipop"),xTe=k((e,t,r)=>{e.append("marker").attr("id",r+"_"+t+"-pointEnd").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",5).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",8).attr("markerHeight",8).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),e.append("marker").attr("id",r+"_"+t+"-pointStart").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",4.5).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",8).attr("markerHeight",8).attr("orient","auto").append("path").attr("d","M 0 5 L 10 10 L 10 0 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0")},"point"),NTe=k((e,t,r)=>{e.append("marker").attr("id",r+"_"+t+"-circleEnd").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",11).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),e.append("marker").attr("id",r+"_"+t+"-circleStart").attr("class","marker "+t).attr("viewBox","0 0 10 10").attr("refX",-1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0")},"circle"),DTe=k((e,t,r)=>{e.append("marker").attr("id",r+"_"+t+"-crossEnd").attr("class","marker cross "+t).attr("viewBox","0 0 11 11").attr("refX",12).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0"),e.append("marker").attr("id",r+"_"+t+"-crossStart").attr("class","marker cross "+t).attr("viewBox","0 0 11 11").attr("refX",-1).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0")},"cross"),kTe=k((e,t,r)=>{e.append("defs").append("marker").attr("id",r+"_"+t+"-barbEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",14).attr("markerUnits","userSpaceOnUse").attr("orient","auto").append("path").attr("d","M 19,7 L9,13 L14,7 L9,1 Z")},"barb"),STe=k((e,t,r)=>{e.append("defs").append("marker").attr("id",r+"_"+t+"-onlyOneStart").attr("class","marker onlyOne "+t).attr("refX",0).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").append("path").attr("d","M9,0 L9,18 M15,0 L15,18"),e.append("defs").append("marker").attr("id",r+"_"+t+"-onlyOneEnd").attr("class","marker onlyOne "+t).attr("refX",18).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").append("path").attr("d","M3,0 L3,18 M9,0 L9,18")},"only_one"),UTe=k((e,t,r)=>{const n=e.append("defs").append("marker").attr("id",r+"_"+t+"-zeroOrOneStart").attr("class","marker zeroOrOne "+t).attr("refX",0).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto");n.append("circle").attr("fill","white").attr("cx",21).attr("cy",9).attr("r",6),n.append("path").attr("d","M9,0 L9,18");const i=e.append("defs").append("marker").attr("id",r+"_"+t+"-zeroOrOneEnd").attr("class","marker zeroOrOne "+t).attr("refX",30).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto");i.append("circle").attr("fill","white").attr("cx",9).attr("cy",9).attr("r",6),i.append("path").attr("d","M21,0 L21,18")},"zero_or_one"),vTe=k((e,t,r)=>{e.append("defs").append("marker").attr("id",r+"_"+t+"-oneOrMoreStart").attr("class","marker oneOrMore "+t).attr("refX",18).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").append("path").attr("d","M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27"),e.append("defs").append("marker").attr("id",r+"_"+t+"-oneOrMoreEnd").attr("class","marker oneOrMore "+t).attr("refX",27).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").append("path").attr("d","M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18")},"one_or_more"),GTe=k((e,t,r)=>{const n=e.append("defs").append("marker").attr("id",r+"_"+t+"-zeroOrMoreStart").attr("class","marker zeroOrMore "+t).attr("refX",18).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto");n.append("circle").attr("fill","white").attr("cx",48).attr("cy",18).attr("r",6),n.append("path").attr("d","M0,18 Q18,0 36,18 Q18,36 0,18");const i=e.append("defs").append("marker").attr("id",r+"_"+t+"-zeroOrMoreEnd").attr("class","marker zeroOrMore "+t).attr("refX",39).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto");i.append("circle").attr("fill","white").attr("cx",9).attr("cy",18).attr("r",6),i.append("path").attr("d","M21,18 Q39,0 57,18 Q39,36 21,18")},"zero_or_more"),RTe=k((e,t,r)=>{e.append("defs").append("marker").attr("id",r+"_"+t+"-requirement_arrowEnd").attr("refX",20).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").append("path").attr("d",`M0,0
|
|
1079
1079
|
L20,10
|
|
1080
1080
|
M20,10
|
|
1081
|
-
L0,20`)},"requirement_arrow"),zTe=k((e,t,r)=>{const n=e.append("defs").append("marker").attr("id",r+"_"+t+"-requirement_containsStart").attr("refX",0).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").append("g");n.append("circle").attr("cx",10).attr("cy",10).attr("r",9).attr("fill","none"),n.append("line").attr("x1",1).attr("x2",19).attr("y1",10).attr("y2",10),n.append("line").attr("y1",1).attr("y2",19).attr("x1",10).attr("x2",10)},"requirement_contains"),TTe={extension:QTe,composition:MTe,aggregation:FTe,dependency:YTe,lollipop:bTe,point:xTe,circle:NTe,cross:DTe,barb:kTe,only_one:STe,zero_or_one:UTe,one_or_more:vTe,zero_or_more:GTe,requirement_arrow:RTe,requirement_contains:zTe},jTe=CTe,LTe={common:Pg,getConfig:Ri,insertCluster:Xze,insertEdge:ITe,insertEdgeLabel:pTe,insertMarkers:jTe,insertNode:aie,interpolateToCurve:LS,labelHelper:Ft,log:ve,positionEdgeLabel:mTe},Id={},cie=k(e=>{for(const t of e)Id[t.name]=t},"registerLayoutLoaders"),HTe=k(()=>{cie([{name:"dagre",loader:k(async()=>await rr(()=>import("./dagre-6UL2VRFP-BPf604Df-D7VW3CmU.js"),__vite__mapDeps([0,1,2,3,4,5])),"loader")},{name:"cose-bilkent",loader:k(async()=>await rr(()=>import("./cose-bilkent-S5V4N54A-DKeVcPDK-C49Ve4bT.js"),__vite__mapDeps([6,7])),"loader")}])},"registerDefaultLayoutLoaders");HTe();var pnt=k(async(e,t)=>{if(!(e.layoutAlgorithm in Id))throw new Error(`Unknown layout algorithm: ${e.layoutAlgorithm}`);const r=Id[e.layoutAlgorithm];return(await r.loader()).render(e,t,LTe,{algorithm:r.algorithm})},"render"),mnt=k((e="",{fallback:t="dagre"}={})=>{if(e in Id)return e;if(t in Id)return ve.warn(`Layout algorithm ${e} is not registered. Using ${t} as fallback.`),t;throw new Error(`Both layout algorithms ${e} and ${t} are not registered.`)},"getRegisteredLayoutAlgorithm"),uie="comm",gie="rule",hie="decl",JTe="@import",OTe="@namespace",WTe="@keyframes",PTe="@layer",die=Math.abs,sU=String.fromCharCode;function Bie(e){return e.trim()}function km(e,t,r){return e.replace(t,r)}function KTe(e,t,r){return e.indexOf(t,r)}function lg(e,t){return e.charCodeAt(t)|0}function Dg(e,t,r){return e.slice(t,r)}function gs(e){return e.length}function VTe(e){return e.length}function Lp(e,t){return t.push(e),e}var aE=1,kg=1,pie=0,ya=0,Gn=0,_g="";function oU(e,t,r,n,i,A,a,s){return{value:e,root:t,parent:r,type:n,props:i,children:A,line:aE,column:kg,length:a,return:"",siblings:s}}function XTe(){return Gn}function ZTe(){return Gn=ya>0?lg(_g,--ya):0,kg--,Gn===10&&(kg=1,aE--),Gn}function Pa(){return Gn=ya<pie?lg(_g,ya++):0,kg++,Gn===10&&(kg=1,aE++),Gn}function cl(){return lg(_g,ya)}function Sm(){return ya}function sE(e,t){return Dg(_g,e,t)}function Cd(e){switch(e){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function qTe(e){return aE=kg=1,pie=gs(_g=e),ya=0,[]}function _Te(e){return _g="",e}function Zx(e){return Bie(sE(ya-1,R2(e===91?e+2:e===40?e+1:e)))}function $Te(e){for(;(Gn=cl())&&Gn<33;)Pa();return Cd(e)>2||Cd(Gn)>3?"":" "}function eje(e,t){for(;--t&&Pa()&&!(Gn<48||Gn>102||Gn>57&&Gn<65||Gn>70&&Gn<97););return sE(e,Sm()+(t<6&&cl()==32&&Pa()==32))}function R2(e){for(;Pa();)switch(Gn){case e:return ya;case 34:case 39:e!==34&&e!==39&&R2(Gn);break;case 40:e===41&&R2(e);break;case 92:Pa();break}return ya}function tje(e,t){for(;Pa()&&e+Gn!==57&&!(e+Gn===84&&cl()===47););return"/*"+sE(t,ya-1)+"*"+sU(e===47?e:Pa())}function rje(e){for(;!Cd(cl());)Pa();return sE(e,ya)}function nje(e){return _Te(Um("",null,null,null,[""],e=qTe(e),0,[0],e))}function Um(e,t,r,n,i,A,a,s,o){for(var l=0,c=0,u=a,g=0,h=0,d=0,B=1,y=1,w=1,f=0,I="",Y=i,Q=A,M=n,D=I;y;)switch(d=f,f=Pa()){case 40:if(d!=108&&lg(D,u-1)==58){KTe(D+=km(Zx(f),"&","&\f"),"&\f",die(l?s[l-1]:0))!=-1&&(w=-1);break}case 34:case 39:case 91:D+=Zx(f);break;case 9:case 10:case 13:case 32:D+=$Te(d);break;case 92:D+=eje(Sm()-1,7);continue;case 47:switch(cl()){case 42:case 47:Lp(ije(tje(Pa(),Sm()),t,r,o),o),(Cd(d||1)==5||Cd(cl()||1)==5)&&gs(D)&&Dg(D,-1,void 0)!==" "&&(D+=" ");break;default:D+="/"}break;case 123*B:s[l++]=gs(D)*w;case 125*B:case 59:case 0:switch(f){case 0:case 125:y=0;case 59+c:w==-1&&(D=km(D,/\f/g,"")),h>0&&(gs(D)-u||B===0&&d===47)&&Lp(h>32?kJ(D+";",n,r,u-1,o):kJ(km(D," ","")+";",n,r,u-2,o),o);break;case 59:D+=";";default:if(Lp(M=DJ(D,t,r,l,c,i,s,I,Y=[],Q=[],u,A),A),f===123)if(c===0)Um(D,t,M,M,Y,A,u,s,Q);else{switch(g){case 99:if(lg(D,3)===110)break;case 108:if(lg(D,2)===97)break;default:c=0;case 100:case 109:case 115:}c?Um(e,M,M,n&&Lp(DJ(e,M,M,0,0,i,s,I,i,Y=[],u,Q),Q),i,Q,u,s,n?Y:Q):Um(D,M,M,M,[""],Q,0,s,Q)}}l=c=h=0,B=w=1,I=D="",u=a;break;case 58:u=1+gs(D),h=d;default:if(B<1){if(f==123)--B;else if(f==125&&B++==0&&ZTe()==125)continue}switch(D+=sU(f),f*B){case 38:w=c>0?1:(D+="\f",-1);break;case 44:s[l++]=(gs(D)-1)*w,w=1;break;case 64:cl()===45&&(D+=Zx(Pa())),g=cl(),c=u=gs(I=D+=rje(Sm())),f++;break;case 45:d===45&&gs(D)==2&&(B=0)}}return A}function DJ(e,t,r,n,i,A,a,s,o,l,c,u){for(var g=i-1,h=i===0?A:[""],d=VTe(h),B=0,y=0,w=0;B<n;++B)for(var f=0,I=Dg(e,g+1,g=die(y=a[B])),Y=e;f<d;++f)(Y=Bie(y>0?h[f]+" "+I:km(I,/&\f/g,h[f])))&&(o[w++]=Y);return oU(e,t,r,i===0?gie:s,o,l,c,u)}function ije(e,t,r,n){return oU(e,t,r,uie,sU(XTe()),Dg(e,2,-2),0,n)}function kJ(e,t,r,n,i){return oU(e,t,r,hie,Dg(e,0,n),Dg(e,n+1,-1),n,i)}function z2(e,t){for(var r="",n=0;n<e.length;n++)r+=t(e[n],n,e,t)||"";return r}function Aje(e,t,r,n){switch(e.type){case PTe:if(e.children.length)break;case JTe:case OTe:case hie:return e.return=e.return||e.value;case uie:return"";case WTe:return e.return=e.value+"{"+z2(e.children,n)+"}";case gie:if(!gs(e.value=e.props.join(",")))return""}return gs(r=z2(e.children,n))?e.return=e.value+"{"+r+"}":""}var aje=Hte(Object.keys,Object),sje=Object.prototype,oje=sje.hasOwnProperty;function lje(e){if(!Zy(e))return aje(e);var t=[];for(var r in Object(e))oje.call(e,r)&&r!="constructor"&&t.push(r);return t}var T2=ou(ks,"DataView"),j2=ou(ks,"Promise"),L2=ou(ks,"Set"),H2=ou(ks,"WeakMap"),SJ="[object Map]",cje="[object Object]",UJ="[object Promise]",vJ="[object Set]",GJ="[object WeakMap]",RJ="[object DataView]",uje=su(T2),gje=su(yd),hje=su(j2),dje=su(L2),Bje=su(H2),nc=Xg;(T2&&nc(new T2(new ArrayBuffer(1)))!=RJ||yd&&nc(new yd)!=SJ||j2&&nc(j2.resolve())!=UJ||L2&&nc(new L2)!=vJ||H2&&nc(new H2)!=GJ)&&(nc=function(e){var t=Xg(e),r=t==cje?e.constructor:void 0,n=r?su(r):"";if(n)switch(n){case uje:return RJ;case gje:return SJ;case hje:return UJ;case dje:return vJ;case Bje:return GJ}return t});var pje="[object Map]",mje="[object Set]",wje=Object.prototype,fje=wje.hasOwnProperty;function zJ(e){if(e==null)return!0;if(qy(e)&&($w(e)||typeof e=="string"||typeof e.splice=="function"||TS(e)||jS(e)||_w(e)))return!e.length;var t=nc(e);if(t==pje||t==mje)return!e.size;if(Zy(e))return!lje(e).length;for(var r in e)if(fje.call(e,r))return!1;return!0}var mie="c4",yje=k(e=>/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(e),"detector"),Eje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./c4Diagram-YG6GDRKO-DBs8r9gh-cdf9XHrR.js");return{diagram:t}},__vite__mapDeps([8,9]));return{id:mie,diagram:e}},"loader"),Ije={id:mie,detector:yje,loader:Eje},Cje=Ije,wie="flowchart",Qje=k((e,t)=>{var r,n;return((r=t==null?void 0:t.flowchart)==null?void 0:r.defaultRenderer)==="dagre-wrapper"||((n=t==null?void 0:t.flowchart)==null?void 0:n.defaultRenderer)==="elk"?!1:/^\s*graph/.test(e)},"detector"),Mje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./flowDiagram-NV44I4VS-C5HQUzU9-BNXI-d2R.js");return{diagram:t}},__vite__mapDeps([10,11,12,13,14]));return{id:wie,diagram:e}},"loader"),Fje={id:wie,detector:Qje,loader:Mje},Yje=Fje,fie="flowchart-v2",bje=k((e,t)=>{var r,n,i;return((r=t==null?void 0:t.flowchart)==null?void 0:r.defaultRenderer)==="dagre-d3"?!1:(((n=t==null?void 0:t.flowchart)==null?void 0:n.defaultRenderer)==="elk"&&(t.layout="elk"),/^\s*graph/.test(e)&&((i=t==null?void 0:t.flowchart)==null?void 0:i.defaultRenderer)==="dagre-wrapper"?!0:/^\s*flowchart/.test(e))},"detector"),xje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./flowDiagram-NV44I4VS-C5HQUzU9-BNXI-d2R.js");return{diagram:t}},__vite__mapDeps([10,11,12,13,14]));return{id:fie,diagram:e}},"loader"),Nje={id:fie,detector:bje,loader:xje},Dje=Nje,yie="er",kje=k(e=>/^\s*erDiagram/.test(e),"detector"),Sje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./erDiagram-Q2GNP2WA-DgUeO5_h-BNJGcHpr.js");return{diagram:t}},__vite__mapDeps([15,12,13,14]));return{id:yie,diagram:e}},"loader"),Uje={id:yie,detector:kje,loader:Sje},vje=Uje,Eie="gitGraph",Gje=k(e=>/^\s*gitGraph/.test(e),"detector"),Rje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./gitGraphDiagram-NY62KEGX-DY5loT9K-LIsl5uZ3.js");return{diagram:t}},__vite__mapDeps([16,17,18,19,2,4,5]));return{id:Eie,diagram:e}},"loader"),zje={id:Eie,detector:Gje,loader:Rje},Tje=zje,Iie="gantt",jje=k(e=>/^\s*gantt/.test(e),"detector"),Lje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./ganttDiagram-JELNMOA3-DgSZ1ixF-CqqwgL-1.js");return{diagram:t}},[]);return{id:Iie,diagram:e}},"loader"),Hje={id:Iie,detector:jje,loader:Lje},Jje=Hje,Cie="info",Oje=k(e=>/^\s*info/.test(e),"detector"),Wje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./infoDiagram-WHAUD3N6-DIqQ6vCk-CgIZNz5k.js");return{diagram:t}},__vite__mapDeps([20,19,2,4,5]));return{id:Cie,diagram:e}},"loader"),Pje={id:Cie,detector:Oje,loader:Wje},Qie="pie",Kje=k(e=>/^\s*pie/.test(e),"detector"),Vje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./pieDiagram-ADFJNKIX-Cj0EHHtj-DoZkugbn.js");return{diagram:t}},__vite__mapDeps([21,17,19,2,4,5,22]));return{id:Qie,diagram:e}},"loader"),Xje={id:Qie,detector:Kje,loader:Vje},Mie="quadrantChart",Zje=k(e=>/^\s*quadrantChart/.test(e),"detector"),qje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./quadrantDiagram-AYHSOK5B-CnLDz007-B5oIgb5_.js");return{diagram:t}},[]);return{id:Mie,diagram:e}},"loader"),_je={id:Mie,detector:Zje,loader:qje},$je=_je,Fie="xychart",eLe=k(e=>/^\s*xychart(-beta)?/.test(e),"detector"),tLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./xychartDiagram-PRI3JC2R-CSr0GxaP-CvHeGt3A.js");return{diagram:t}},[]);return{id:Fie,diagram:e}},"loader"),rLe={id:Fie,detector:eLe,loader:tLe},nLe=rLe,Yie="requirement",iLe=k(e=>/^\s*requirement(Diagram)?/.test(e),"detector"),ALe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./requirementDiagram-UZGBJVZJ-rDaI-8Be-CxOGR1Zn.js");return{diagram:t}},__vite__mapDeps([23,12,13]));return{id:Yie,diagram:e}},"loader"),aLe={id:Yie,detector:iLe,loader:ALe},sLe=aLe,bie="sequence",oLe=k(e=>/^\s*sequenceDiagram/.test(e),"detector"),lLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./sequenceDiagram-WL72ISMW-BFF7TtP7-hG33hfBF.js");return{diagram:t}},__vite__mapDeps([24,9,18]));return{id:bie,diagram:e}},"loader"),cLe={id:bie,detector:oLe,loader:lLe},uLe=cLe,xie="class",gLe=k((e,t)=>{var r;return((r=t==null?void 0:t.class)==null?void 0:r.defaultRenderer)==="dagre-wrapper"?!1:/^\s*classDiagram/.test(e)},"detector"),hLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./classDiagram-2ON5EDUG-Crd6O69V-CTb_giLj.js");return{diagram:t}},__vite__mapDeps([25,26,11,12,13]));return{id:xie,diagram:e}},"loader"),dLe={id:xie,detector:gLe,loader:hLe},BLe=dLe,Nie="classDiagram",pLe=k((e,t)=>{var r;return/^\s*classDiagram/.test(e)&&((r=t==null?void 0:t.class)==null?void 0:r.defaultRenderer)==="dagre-wrapper"?!0:/^\s*classDiagram-v2/.test(e)},"detector"),mLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./classDiagram-v2-WZHVMYZB-Crd6O69V-CTb_giLj.js");return{diagram:t}},__vite__mapDeps([27,26,11,12,13]));return{id:Nie,diagram:e}},"loader"),wLe={id:Nie,detector:pLe,loader:mLe},fLe=wLe,Die="state",yLe=k((e,t)=>{var r;return((r=t==null?void 0:t.state)==null?void 0:r.defaultRenderer)==="dagre-wrapper"?!1:/^\s*stateDiagram/.test(e)},"detector"),ELe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./stateDiagram-FKZM4ZOC-ofFsB7HJ-DTDtfvGY.js");return{diagram:t}},__vite__mapDeps([28,29,12,13,1,2,3,4]));return{id:Die,diagram:e}},"loader"),ILe={id:Die,detector:yLe,loader:ELe},CLe=ILe,kie="stateDiagram",QLe=k((e,t)=>{var r;return!!(/^\s*stateDiagram-v2/.test(e)||/^\s*stateDiagram/.test(e)&&((r=t==null?void 0:t.state)==null?void 0:r.defaultRenderer)==="dagre-wrapper")},"detector"),MLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./stateDiagram-v2-4FDKWEC3-CEZFbksU-N2nGVIZ8.js");return{diagram:t}},__vite__mapDeps([30,29,12,13]));return{id:kie,diagram:e}},"loader"),FLe={id:kie,detector:QLe,loader:MLe},YLe=FLe,Sie="journey",bLe=k(e=>/^\s*journey/.test(e),"detector"),xLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./journeyDiagram-XKPGCS4Q-DXjg3S3r-BFSr5Y_O.js");return{diagram:t}},__vite__mapDeps([31,9,11,22]));return{id:Sie,diagram:e}},"loader"),NLe={id:Sie,detector:bLe,loader:xLe},DLe=NLe,kLe=k((e,t,r)=>{ve.debug(`rendering svg for syntax error
|
|
1082
|
-
`);const n=gUe(t),i=n.append("g");n.attr("viewBox","0 0 2412 512"),Y_(n,100,512,!0),i.append("path").attr("class","error-icon").attr("d","m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z"),i.append("path").attr("class","error-icon").attr("d","m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z"),i.append("path").attr("class","error-icon").attr("d","m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z"),i.append("path").attr("class","error-icon").attr("d","m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z"),i.append("path").attr("class","error-icon").attr("d","m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z"),i.append("path").attr("class","error-icon").attr("d","m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z"),i.append("text").attr("class","error-text").attr("x",1440).attr("y",250).attr("font-size","150px").style("text-anchor","middle").text("Syntax error in text"),i.append("text").attr("class","error-text").attr("x",1250).attr("y",400).attr("font-size","100px").style("text-anchor","middle").text(`mermaid version ${r}`)},"draw"),Uie={draw:kLe},SLe=Uie,ULe={db:{},renderer:Uie,parser:{parse:k(()=>{},"parse")}},vLe=ULe,vie="flowchart-elk",GLe=k((e,t={})=>{var r;return/^\s*flowchart-elk/.test(e)||/^\s*(flowchart|graph)/.test(e)&&((r=t==null?void 0:t.flowchart)==null?void 0:r.defaultRenderer)==="elk"?(t.layout="elk",!0):!1},"detector"),RLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./flowDiagram-NV44I4VS-C5HQUzU9-
|
|
1081
|
+
L0,20`)},"requirement_arrow"),zTe=k((e,t,r)=>{const n=e.append("defs").append("marker").attr("id",r+"_"+t+"-requirement_containsStart").attr("refX",0).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").append("g");n.append("circle").attr("cx",10).attr("cy",10).attr("r",9).attr("fill","none"),n.append("line").attr("x1",1).attr("x2",19).attr("y1",10).attr("y2",10),n.append("line").attr("y1",1).attr("y2",19).attr("x1",10).attr("x2",10)},"requirement_contains"),TTe={extension:QTe,composition:MTe,aggregation:FTe,dependency:YTe,lollipop:bTe,point:xTe,circle:NTe,cross:DTe,barb:kTe,only_one:STe,zero_or_one:UTe,one_or_more:vTe,zero_or_more:GTe,requirement_arrow:RTe,requirement_contains:zTe},jTe=CTe,LTe={common:Pg,getConfig:Ri,insertCluster:Xze,insertEdge:ITe,insertEdgeLabel:pTe,insertMarkers:jTe,insertNode:aie,interpolateToCurve:LS,labelHelper:Ft,log:ve,positionEdgeLabel:mTe},Id={},cie=k(e=>{for(const t of e)Id[t.name]=t},"registerLayoutLoaders"),HTe=k(()=>{cie([{name:"dagre",loader:k(async()=>await rr(()=>import("./dagre-6UL2VRFP-BPf604Df-C0WwjL5r.js"),__vite__mapDeps([0,1,2,3,4,5])),"loader")},{name:"cose-bilkent",loader:k(async()=>await rr(()=>import("./cose-bilkent-S5V4N54A-DKeVcPDK-DzjcbsIY.js"),__vite__mapDeps([6,7])),"loader")}])},"registerDefaultLayoutLoaders");HTe();var pnt=k(async(e,t)=>{if(!(e.layoutAlgorithm in Id))throw new Error(`Unknown layout algorithm: ${e.layoutAlgorithm}`);const r=Id[e.layoutAlgorithm];return(await r.loader()).render(e,t,LTe,{algorithm:r.algorithm})},"render"),mnt=k((e="",{fallback:t="dagre"}={})=>{if(e in Id)return e;if(t in Id)return ve.warn(`Layout algorithm ${e} is not registered. Using ${t} as fallback.`),t;throw new Error(`Both layout algorithms ${e} and ${t} are not registered.`)},"getRegisteredLayoutAlgorithm"),uie="comm",gie="rule",hie="decl",JTe="@import",OTe="@namespace",WTe="@keyframes",PTe="@layer",die=Math.abs,sU=String.fromCharCode;function Bie(e){return e.trim()}function km(e,t,r){return e.replace(t,r)}function KTe(e,t,r){return e.indexOf(t,r)}function lg(e,t){return e.charCodeAt(t)|0}function Dg(e,t,r){return e.slice(t,r)}function gs(e){return e.length}function VTe(e){return e.length}function Lp(e,t){return t.push(e),e}var aE=1,kg=1,pie=0,ya=0,Gn=0,_g="";function oU(e,t,r,n,i,A,a,s){return{value:e,root:t,parent:r,type:n,props:i,children:A,line:aE,column:kg,length:a,return:"",siblings:s}}function XTe(){return Gn}function ZTe(){return Gn=ya>0?lg(_g,--ya):0,kg--,Gn===10&&(kg=1,aE--),Gn}function Pa(){return Gn=ya<pie?lg(_g,ya++):0,kg++,Gn===10&&(kg=1,aE++),Gn}function cl(){return lg(_g,ya)}function Sm(){return ya}function sE(e,t){return Dg(_g,e,t)}function Cd(e){switch(e){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function qTe(e){return aE=kg=1,pie=gs(_g=e),ya=0,[]}function _Te(e){return _g="",e}function Zx(e){return Bie(sE(ya-1,R2(e===91?e+2:e===40?e+1:e)))}function $Te(e){for(;(Gn=cl())&&Gn<33;)Pa();return Cd(e)>2||Cd(Gn)>3?"":" "}function eje(e,t){for(;--t&&Pa()&&!(Gn<48||Gn>102||Gn>57&&Gn<65||Gn>70&&Gn<97););return sE(e,Sm()+(t<6&&cl()==32&&Pa()==32))}function R2(e){for(;Pa();)switch(Gn){case e:return ya;case 34:case 39:e!==34&&e!==39&&R2(Gn);break;case 40:e===41&&R2(e);break;case 92:Pa();break}return ya}function tje(e,t){for(;Pa()&&e+Gn!==57&&!(e+Gn===84&&cl()===47););return"/*"+sE(t,ya-1)+"*"+sU(e===47?e:Pa())}function rje(e){for(;!Cd(cl());)Pa();return sE(e,ya)}function nje(e){return _Te(Um("",null,null,null,[""],e=qTe(e),0,[0],e))}function Um(e,t,r,n,i,A,a,s,o){for(var l=0,c=0,u=a,g=0,h=0,d=0,B=1,y=1,w=1,f=0,I="",Y=i,Q=A,M=n,D=I;y;)switch(d=f,f=Pa()){case 40:if(d!=108&&lg(D,u-1)==58){KTe(D+=km(Zx(f),"&","&\f"),"&\f",die(l?s[l-1]:0))!=-1&&(w=-1);break}case 34:case 39:case 91:D+=Zx(f);break;case 9:case 10:case 13:case 32:D+=$Te(d);break;case 92:D+=eje(Sm()-1,7);continue;case 47:switch(cl()){case 42:case 47:Lp(ije(tje(Pa(),Sm()),t,r,o),o),(Cd(d||1)==5||Cd(cl()||1)==5)&&gs(D)&&Dg(D,-1,void 0)!==" "&&(D+=" ");break;default:D+="/"}break;case 123*B:s[l++]=gs(D)*w;case 125*B:case 59:case 0:switch(f){case 0:case 125:y=0;case 59+c:w==-1&&(D=km(D,/\f/g,"")),h>0&&(gs(D)-u||B===0&&d===47)&&Lp(h>32?kJ(D+";",n,r,u-1,o):kJ(km(D," ","")+";",n,r,u-2,o),o);break;case 59:D+=";";default:if(Lp(M=DJ(D,t,r,l,c,i,s,I,Y=[],Q=[],u,A),A),f===123)if(c===0)Um(D,t,M,M,Y,A,u,s,Q);else{switch(g){case 99:if(lg(D,3)===110)break;case 108:if(lg(D,2)===97)break;default:c=0;case 100:case 109:case 115:}c?Um(e,M,M,n&&Lp(DJ(e,M,M,0,0,i,s,I,i,Y=[],u,Q),Q),i,Q,u,s,n?Y:Q):Um(D,M,M,M,[""],Q,0,s,Q)}}l=c=h=0,B=w=1,I=D="",u=a;break;case 58:u=1+gs(D),h=d;default:if(B<1){if(f==123)--B;else if(f==125&&B++==0&&ZTe()==125)continue}switch(D+=sU(f),f*B){case 38:w=c>0?1:(D+="\f",-1);break;case 44:s[l++]=(gs(D)-1)*w,w=1;break;case 64:cl()===45&&(D+=Zx(Pa())),g=cl(),c=u=gs(I=D+=rje(Sm())),f++;break;case 45:d===45&&gs(D)==2&&(B=0)}}return A}function DJ(e,t,r,n,i,A,a,s,o,l,c,u){for(var g=i-1,h=i===0?A:[""],d=VTe(h),B=0,y=0,w=0;B<n;++B)for(var f=0,I=Dg(e,g+1,g=die(y=a[B])),Y=e;f<d;++f)(Y=Bie(y>0?h[f]+" "+I:km(I,/&\f/g,h[f])))&&(o[w++]=Y);return oU(e,t,r,i===0?gie:s,o,l,c,u)}function ije(e,t,r,n){return oU(e,t,r,uie,sU(XTe()),Dg(e,2,-2),0,n)}function kJ(e,t,r,n,i){return oU(e,t,r,hie,Dg(e,0,n),Dg(e,n+1,-1),n,i)}function z2(e,t){for(var r="",n=0;n<e.length;n++)r+=t(e[n],n,e,t)||"";return r}function Aje(e,t,r,n){switch(e.type){case PTe:if(e.children.length)break;case JTe:case OTe:case hie:return e.return=e.return||e.value;case uie:return"";case WTe:return e.return=e.value+"{"+z2(e.children,n)+"}";case gie:if(!gs(e.value=e.props.join(",")))return""}return gs(r=z2(e.children,n))?e.return=e.value+"{"+r+"}":""}var aje=Hte(Object.keys,Object),sje=Object.prototype,oje=sje.hasOwnProperty;function lje(e){if(!Zy(e))return aje(e);var t=[];for(var r in Object(e))oje.call(e,r)&&r!="constructor"&&t.push(r);return t}var T2=ou(ks,"DataView"),j2=ou(ks,"Promise"),L2=ou(ks,"Set"),H2=ou(ks,"WeakMap"),SJ="[object Map]",cje="[object Object]",UJ="[object Promise]",vJ="[object Set]",GJ="[object WeakMap]",RJ="[object DataView]",uje=su(T2),gje=su(yd),hje=su(j2),dje=su(L2),Bje=su(H2),nc=Xg;(T2&&nc(new T2(new ArrayBuffer(1)))!=RJ||yd&&nc(new yd)!=SJ||j2&&nc(j2.resolve())!=UJ||L2&&nc(new L2)!=vJ||H2&&nc(new H2)!=GJ)&&(nc=function(e){var t=Xg(e),r=t==cje?e.constructor:void 0,n=r?su(r):"";if(n)switch(n){case uje:return RJ;case gje:return SJ;case hje:return UJ;case dje:return vJ;case Bje:return GJ}return t});var pje="[object Map]",mje="[object Set]",wje=Object.prototype,fje=wje.hasOwnProperty;function zJ(e){if(e==null)return!0;if(qy(e)&&($w(e)||typeof e=="string"||typeof e.splice=="function"||TS(e)||jS(e)||_w(e)))return!e.length;var t=nc(e);if(t==pje||t==mje)return!e.size;if(Zy(e))return!lje(e).length;for(var r in e)if(fje.call(e,r))return!1;return!0}var mie="c4",yje=k(e=>/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(e),"detector"),Eje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./c4Diagram-YG6GDRKO-DBs8r9gh-DC_egmCX.js");return{diagram:t}},__vite__mapDeps([8,9]));return{id:mie,diagram:e}},"loader"),Ije={id:mie,detector:yje,loader:Eje},Cje=Ije,wie="flowchart",Qje=k((e,t)=>{var r,n;return((r=t==null?void 0:t.flowchart)==null?void 0:r.defaultRenderer)==="dagre-wrapper"||((n=t==null?void 0:t.flowchart)==null?void 0:n.defaultRenderer)==="elk"?!1:/^\s*graph/.test(e)},"detector"),Mje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./flowDiagram-NV44I4VS-C5HQUzU9-66FPNpP3.js");return{diagram:t}},__vite__mapDeps([10,11,12,13,14]));return{id:wie,diagram:e}},"loader"),Fje={id:wie,detector:Qje,loader:Mje},Yje=Fje,fie="flowchart-v2",bje=k((e,t)=>{var r,n,i;return((r=t==null?void 0:t.flowchart)==null?void 0:r.defaultRenderer)==="dagre-d3"?!1:(((n=t==null?void 0:t.flowchart)==null?void 0:n.defaultRenderer)==="elk"&&(t.layout="elk"),/^\s*graph/.test(e)&&((i=t==null?void 0:t.flowchart)==null?void 0:i.defaultRenderer)==="dagre-wrapper"?!0:/^\s*flowchart/.test(e))},"detector"),xje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./flowDiagram-NV44I4VS-C5HQUzU9-66FPNpP3.js");return{diagram:t}},__vite__mapDeps([10,11,12,13,14]));return{id:fie,diagram:e}},"loader"),Nje={id:fie,detector:bje,loader:xje},Dje=Nje,yie="er",kje=k(e=>/^\s*erDiagram/.test(e),"detector"),Sje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./erDiagram-Q2GNP2WA-DgUeO5_h-D8uM7AsV.js");return{diagram:t}},__vite__mapDeps([15,12,13,14]));return{id:yie,diagram:e}},"loader"),Uje={id:yie,detector:kje,loader:Sje},vje=Uje,Eie="gitGraph",Gje=k(e=>/^\s*gitGraph/.test(e),"detector"),Rje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./gitGraphDiagram-NY62KEGX-DY5loT9K-B22n5mHi.js");return{diagram:t}},__vite__mapDeps([16,17,18,19,2,4,5]));return{id:Eie,diagram:e}},"loader"),zje={id:Eie,detector:Gje,loader:Rje},Tje=zje,Iie="gantt",jje=k(e=>/^\s*gantt/.test(e),"detector"),Lje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./ganttDiagram-JELNMOA3-DgSZ1ixF-B9F9GbD_.js");return{diagram:t}},[]);return{id:Iie,diagram:e}},"loader"),Hje={id:Iie,detector:jje,loader:Lje},Jje=Hje,Cie="info",Oje=k(e=>/^\s*info/.test(e),"detector"),Wje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./infoDiagram-WHAUD3N6-DIqQ6vCk-xD2zIyk6.js");return{diagram:t}},__vite__mapDeps([20,19,2,4,5]));return{id:Cie,diagram:e}},"loader"),Pje={id:Cie,detector:Oje,loader:Wje},Qie="pie",Kje=k(e=>/^\s*pie/.test(e),"detector"),Vje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./pieDiagram-ADFJNKIX-Cj0EHHtj-dX98b0XZ.js");return{diagram:t}},__vite__mapDeps([21,17,19,2,4,5,22]));return{id:Qie,diagram:e}},"loader"),Xje={id:Qie,detector:Kje,loader:Vje},Mie="quadrantChart",Zje=k(e=>/^\s*quadrantChart/.test(e),"detector"),qje=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./quadrantDiagram-AYHSOK5B-CnLDz007-CdAKZqPT.js");return{diagram:t}},[]);return{id:Mie,diagram:e}},"loader"),_je={id:Mie,detector:Zje,loader:qje},$je=_je,Fie="xychart",eLe=k(e=>/^\s*xychart(-beta)?/.test(e),"detector"),tLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./xychartDiagram-PRI3JC2R-CSr0GxaP-xg5Sy4er.js");return{diagram:t}},[]);return{id:Fie,diagram:e}},"loader"),rLe={id:Fie,detector:eLe,loader:tLe},nLe=rLe,Yie="requirement",iLe=k(e=>/^\s*requirement(Diagram)?/.test(e),"detector"),ALe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./requirementDiagram-UZGBJVZJ-rDaI-8Be-BJPCvjkD.js");return{diagram:t}},__vite__mapDeps([23,12,13]));return{id:Yie,diagram:e}},"loader"),aLe={id:Yie,detector:iLe,loader:ALe},sLe=aLe,bie="sequence",oLe=k(e=>/^\s*sequenceDiagram/.test(e),"detector"),lLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./sequenceDiagram-WL72ISMW-BFF7TtP7-BSpeW2is.js");return{diagram:t}},__vite__mapDeps([24,9,18]));return{id:bie,diagram:e}},"loader"),cLe={id:bie,detector:oLe,loader:lLe},uLe=cLe,xie="class",gLe=k((e,t)=>{var r;return((r=t==null?void 0:t.class)==null?void 0:r.defaultRenderer)==="dagre-wrapper"?!1:/^\s*classDiagram/.test(e)},"detector"),hLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./classDiagram-2ON5EDUG-Crd6O69V-Chm9m1T4.js");return{diagram:t}},__vite__mapDeps([25,26,11,12,13]));return{id:xie,diagram:e}},"loader"),dLe={id:xie,detector:gLe,loader:hLe},BLe=dLe,Nie="classDiagram",pLe=k((e,t)=>{var r;return/^\s*classDiagram/.test(e)&&((r=t==null?void 0:t.class)==null?void 0:r.defaultRenderer)==="dagre-wrapper"?!0:/^\s*classDiagram-v2/.test(e)},"detector"),mLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./classDiagram-v2-WZHVMYZB-Crd6O69V-Chm9m1T4.js");return{diagram:t}},__vite__mapDeps([27,26,11,12,13]));return{id:Nie,diagram:e}},"loader"),wLe={id:Nie,detector:pLe,loader:mLe},fLe=wLe,Die="state",yLe=k((e,t)=>{var r;return((r=t==null?void 0:t.state)==null?void 0:r.defaultRenderer)==="dagre-wrapper"?!1:/^\s*stateDiagram/.test(e)},"detector"),ELe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./stateDiagram-FKZM4ZOC-ofFsB7HJ-CebwML_S.js");return{diagram:t}},__vite__mapDeps([28,29,12,13,1,2,3,4]));return{id:Die,diagram:e}},"loader"),ILe={id:Die,detector:yLe,loader:ELe},CLe=ILe,kie="stateDiagram",QLe=k((e,t)=>{var r;return!!(/^\s*stateDiagram-v2/.test(e)||/^\s*stateDiagram/.test(e)&&((r=t==null?void 0:t.state)==null?void 0:r.defaultRenderer)==="dagre-wrapper")},"detector"),MLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./stateDiagram-v2-4FDKWEC3-CEZFbksU-DblRbnEz.js");return{diagram:t}},__vite__mapDeps([30,29,12,13]));return{id:kie,diagram:e}},"loader"),FLe={id:kie,detector:QLe,loader:MLe},YLe=FLe,Sie="journey",bLe=k(e=>/^\s*journey/.test(e),"detector"),xLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./journeyDiagram-XKPGCS4Q-DXjg3S3r-BUFxCU2Q.js");return{diagram:t}},__vite__mapDeps([31,9,11,22]));return{id:Sie,diagram:e}},"loader"),NLe={id:Sie,detector:bLe,loader:xLe},DLe=NLe,kLe=k((e,t,r)=>{ve.debug(`rendering svg for syntax error
|
|
1082
|
+
`);const n=gUe(t),i=n.append("g");n.attr("viewBox","0 0 2412 512"),Y_(n,100,512,!0),i.append("path").attr("class","error-icon").attr("d","m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z"),i.append("path").attr("class","error-icon").attr("d","m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z"),i.append("path").attr("class","error-icon").attr("d","m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z"),i.append("path").attr("class","error-icon").attr("d","m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z"),i.append("path").attr("class","error-icon").attr("d","m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z"),i.append("path").attr("class","error-icon").attr("d","m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z"),i.append("text").attr("class","error-text").attr("x",1440).attr("y",250).attr("font-size","150px").style("text-anchor","middle").text("Syntax error in text"),i.append("text").attr("class","error-text").attr("x",1250).attr("y",400).attr("font-size","100px").style("text-anchor","middle").text(`mermaid version ${r}`)},"draw"),Uie={draw:kLe},SLe=Uie,ULe={db:{},renderer:Uie,parser:{parse:k(()=>{},"parse")}},vLe=ULe,vie="flowchart-elk",GLe=k((e,t={})=>{var r;return/^\s*flowchart-elk/.test(e)||/^\s*(flowchart|graph)/.test(e)&&((r=t==null?void 0:t.flowchart)==null?void 0:r.defaultRenderer)==="elk"?(t.layout="elk",!0):!1},"detector"),RLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./flowDiagram-NV44I4VS-C5HQUzU9-66FPNpP3.js");return{diagram:t}},__vite__mapDeps([10,11,12,13,14]));return{id:vie,diagram:e}},"loader"),zLe={id:vie,detector:GLe,loader:RLe},TLe=zLe,Gie="timeline",jLe=k(e=>/^\s*timeline/.test(e),"detector"),LLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./timeline-definition-IT6M3QCI-5W361ZNm-DWTb5GU0.js");return{diagram:t}},__vite__mapDeps([32,22]));return{id:Gie,diagram:e}},"loader"),HLe={id:Gie,detector:jLe,loader:LLe},JLe=HLe,Rie="mindmap",OLe=k(e=>/^\s*mindmap/.test(e),"detector"),WLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./mindmap-definition-VGOIOE7T-DXwVuAPE-8H0GPPLn.js");return{diagram:t}},__vite__mapDeps([33,12,13]));return{id:Rie,diagram:e}},"loader"),PLe={id:Rie,detector:OLe,loader:WLe},KLe=PLe,zie="kanban",VLe=k(e=>/^\s*kanban/.test(e),"detector"),XLe=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./kanban-definition-3W4ZIXB7-Uxt7Am6n-Csei5eOU.js");return{diagram:t}},__vite__mapDeps([34,11]));return{id:zie,diagram:e}},"loader"),ZLe={id:zie,detector:VLe,loader:XLe},qLe=ZLe,Tie="sankey",_Le=k(e=>/^\s*sankey(-beta)?/.test(e),"detector"),$Le=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./sankeyDiagram-TZEHDZUN-A0YO8ixs-DvqHljpO.js");return{diagram:t}},[]);return{id:Tie,diagram:e}},"loader"),e8e={id:Tie,detector:_Le,loader:$Le},t8e=e8e,jie="packet",r8e=k(e=>/^\s*packet(-beta)?/.test(e),"detector"),n8e=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./diagram-S2PKOQOG-DVx43aon-Du-jFDIt.js");return{diagram:t}},__vite__mapDeps([35,17,19,2,4,5]));return{id:jie,diagram:e}},"loader"),i8e={id:jie,detector:r8e,loader:n8e},Lie="radar",A8e=k(e=>/^\s*radar-beta/.test(e),"detector"),a8e=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./diagram-QEK2KX5R-C_5RR1NJ-CTdkvrxF.js");return{diagram:t}},__vite__mapDeps([36,17,19,2,4,5]));return{id:Lie,diagram:e}},"loader"),s8e={id:Lie,detector:A8e,loader:a8e},Hie="block",o8e=k(e=>/^\s*block(-beta)?/.test(e),"detector"),l8e=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./blockDiagram-VD42YOAC-D-In4h7h-QH2TogI4.js");return{diagram:t}},__vite__mapDeps([37,11,5,2,1,14]));return{id:Hie,diagram:e}},"loader"),c8e={id:Hie,detector:o8e,loader:l8e},u8e=c8e,Jie="architecture",g8e=k(e=>/^\s*architecture/.test(e),"detector"),h8e=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./architectureDiagram-VXUJARFQ-zzJsgPC6-DHQldRFY.js");return{diagram:t}},__vite__mapDeps([38,17,19,2,4,5,7]));return{id:Jie,diagram:e}},"loader"),d8e={id:Jie,detector:g8e,loader:h8e},B8e=d8e,Oie="treemap",p8e=k(e=>/^\s*treemap/.test(e),"detector"),m8e=k(async()=>{const{diagram:e}=await rr(async()=>{const{diagram:t}=await import("./diagram-PSM6KHXK-DeLcpEV3-Bj0ToVQD.js");return{diagram:t}},__vite__mapDeps([39,13,17,19,2,4,5]));return{id:Oie,diagram:e}},"loader"),w8e={id:Oie,detector:p8e,loader:m8e},TJ=!1,oE=k(()=>{TJ||(TJ=!0,Fw("error",vLe,e=>e.toLowerCase().trim()==="error"),Fw("---",{db:{clear:k(()=>{},"clear")},styles:{},renderer:{draw:k(()=>{},"draw")},parser:{parse:k(()=>{throw new Error("Diagrams beginning with --- are not valid. If you were trying to use a YAML front-matter, please ensure that you've correctly opened and closed the YAML front-matter with un-indented `---` blocks")},"parse")},init:k(()=>null,"init")},e=>e.toLowerCase().trimStart().startsWith("---")),J1(TLe,KLe,B8e),J1(Cje,qLe,fLe,BLe,vje,Jje,Pje,Xje,sLe,uLe,Dje,Yje,JLe,Tje,YLe,CLe,DLe,$je,t8e,i8e,nLe,u8e,s8e,w8e))},"addDiagrams"),f8e=k(async()=>{ve.debug("Loading registered diagrams");const e=(await Promise.allSettled(Object.entries(Uc).map(async([t,{detector:r,loader:n}])=>{if(n)try{K1(t)}catch{try{const{diagram:i,id:A}=await n();Fw(A,i,r)}catch(i){throw ve.error(`Failed to load external diagram with key ${t}. Removing from detectors.`),delete Uc[t],i}}}))).filter(t=>t.status==="rejected");if(e.length>0){ve.error(`Failed to load ${e.length} external diagrams`);for(const t of e)ve.error(t);throw new Error(`Failed to load ${e.length} external diagrams`)}},"loadRegisteredDiagrams"),y8e="graphics-document document";function Wie(e,t){e.attr("role",y8e),t!==""&&e.attr("aria-roledescription",t)}k(Wie,"setA11yDiagramInfo");function Pie(e,t,r,n){if(e.insert!==void 0){if(r){const i=`chart-desc-${n}`;e.attr("aria-describedby",i),e.insert("desc",":first-child").attr("id",i).text(r)}if(t){const i=`chart-title-${n}`;e.attr("aria-labelledby",i),e.insert("title",":first-child").attr("id",i).text(t)}}}k(Pie,"addSVGa11yTitleDescription");var Hp,J2=(Hp=class{constructor(e,t,r,n,i){this.type=e,this.text=t,this.db=r,this.parser=n,this.renderer=i}static async fromText(e,t={}){var r,n;const i=Ri(),A=Sk(e,i);e=wRe(e)+`
|
|
1083
1083
|
`;try{K1(A)}catch{const c=CNe(A);if(!c)throw new B_(`Diagram ${A} not found.`);const{id:u,diagram:g}=await c();Fw(u,g)}const{db:a,parser:s,renderer:o,init:l}=K1(A);return s.parser&&(s.parser.yy=a),(r=a.clear)==null||r.call(a),l==null||l(i),t.title&&((n=a.setDiagramTitle)==null||n.call(a,t.title)),await s.parse(e),new Hp(A,e,a,s,o)}async render(e,t){await this.renderer.draw(this.text,e,t,this)}getParser(){return this.parser}getType(){return this.type}},k(Hp,"Diagram"),Hp),jJ=[],E8e=k(()=>{jJ.forEach(e=>{e()}),jJ=[]},"attachFunctions"),I8e=k(e=>e.replace(/^\s*%%(?!{)[^\n]+\n?/gm,"").trimStart(),"cleanupComments");function Kie(e){const t=e.match(d_);if(!t)return{text:e,metadata:{}};let r=f3e(t[1],{schema:w3e})??{};r=typeof r=="object"&&!Array.isArray(r)?r:{};const n={};return r.displayMode&&(n.displayMode=r.displayMode.toString()),r.title&&(n.title=r.title.toString()),r.config&&(n.config=r.config),{text:e.slice(t[0].length),metadata:n}}k(Kie,"extractFrontMatter");var C8e=k(e=>e.replace(/\r\n?/g,`
|
|
1084
1084
|
`).replace(/<(\w+)([^>]*)>/g,(t,r,n)=>"<"+r+n.replace(/="([^"]*)"/g,"='$1'")+">"),"cleanupText"),Q8e=k(e=>{const{text:t,metadata:r}=Kie(e),{displayMode:n,title:i,config:A={}}=r;return n&&(A.gantt||(A.gantt={}),A.gantt.displayMode=n),{title:i,config:A,text:t}},"processFrontmatter"),M8e=k(e=>{const t=Ta.detectInit(e)??{},r=Ta.detectDirective(e,"wrap");return Array.isArray(r)?t.wrap=r.some(({type:n})=>n==="wrap"):(r==null?void 0:r.type)==="wrap"&&(t.wrap=!0),{text:ARe(e),directive:t}},"processDirectives");function lU(e){const t=C8e(e),r=Q8e(t),n=M8e(r.text),i=PS(r.config,n.directive);return e=I8e(n.text),{code:e,title:r.title,config:i}}k(lU,"preprocessDiagram");function Vie(e){const t=new TextEncoder().encode(e),r=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(r)}k(Vie,"toBase64");var F8e=5e4,Y8e="graph TB;a[Maximum text size in diagram exceeded];style a fill:#faa",b8e="sandbox",x8e="loose",N8e="http://www.w3.org/2000/svg",D8e="http://www.w3.org/1999/xlink",k8e="http://www.w3.org/1999/xhtml",S8e="100%",U8e="100%",v8e="border:0;margin:0;",G8e="margin:0",R8e="allow-top-navigation-by-user-activation allow-popups",z8e='The "iframe" tag is not supported by your browser.',T8e=["foreignobject"],j8e=["dominant-baseline"];function cU(e){const t=lU(e);return Qw(),TNe(t.config??{}),t}k(cU,"processAndSetConfigs");async function Xie(e,t){oE();try{const{code:r,config:n}=cU(e);return{diagramType:(await qie(r)).type,config:n}}catch(r){if(t!=null&&t.suppressErrors)return!1;throw r}}k(Xie,"parse");var LJ=k((e,t,r=[])=>`
|
|
1085
1085
|
.${e} ${t} { ${r.join(" !important; ")} !important; }`,"cssImportantStyles"),L8e=k((e,t=new Map)=>{var r;let n="";if(e.themeCSS!==void 0&&(n+=`
|
|
@@ -1178,7 +1178,7 @@ ${e.themeCSS}`),e.fontFamily!==void 0&&(n+=`
|
|
|
1178
1178
|
from { transform: rotate(0deg); }
|
|
1179
1179
|
to { transform: rotate(360deg); }
|
|
1180
1180
|
}
|
|
1181
|
-
`})]}),s.title&&fe.jsx("h4",{style:{textAlign:"center",marginBottom:s.description?"4px":"12px",marginTop:0,color:X,fontWeight:600,background:"transparent"},children:s.title}),s.description&&fe.jsx("p",{style:{textAlign:"center",marginTop:0,marginBottom:"12px",color:K,fontSize:"0.9rem"},children:s.description}),fe.jsxs(vJe,{width:"100%",height:f,children:[s.type==="bar"&&fe.jsxs(ptt,{data:s.data,margin:Ve,barCategoryGap:"20%",children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"name",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{yAxisId:"left",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),Y&&fe.jsx(ls,{yAxisId:"right",orientation:"right",width:80,tickFormatter:et,...$,children:Ws(j,"right")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,I.map(Ne=>fe.jsx(ND,{name:Ne.name,dataKey:Ne.key,fill:Ne.color,stackId:Ne.stackId,yAxisId:Ne.yAxisId,radius:[4,4,0,0]},Ne.key))]}),s.type==="line"&&fe.jsxs(dtt,{data:s.data,margin:Ve,children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"name",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{yAxisId:"left",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),Y&&fe.jsx(ls,{yAxisId:"right",orientation:"right",width:80,tickFormatter:et,...$,children:Ws(j,"right")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,I.map(Ne=>fe.jsx(DD,{name:Ne.name,type:"monotone",dataKey:Ne.key,stroke:Ne.color,yAxisId:Ne.yAxisId,strokeWidth:Ne.strokeWidth,dot:Ne.dot},Ne.key))]}),s.type==="area"&&fe.jsxs(ktt,{data:s.data,margin:Ve,children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"name",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{yAxisId:"left",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),Y&&fe.jsx(ls,{yAxisId:"right",orientation:"right",width:80,tickFormatter:et,...$,children:Ws(j,"right")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,I.map(Ne=>fe.jsx(kD,{name:Ne.name,type:"monotone",dataKey:Ne.key,stroke:Ne.color,yAxisId:Ne.yAxisId,fill:Ne.color,fillOpacity:Ne.opacity,stackId:Ne.stackId},Ne.key))]}),s.type==="composed"&&fe.jsxs(Utt,{data:s.data,margin:Ve,children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"name",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{yAxisId:"left",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),Y&&fe.jsx(ls,{yAxisId:"right",orientation:"right",width:80,tickFormatter:et,...$,children:Ws(j,"right")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,I.map(Ne=>{switch(Ne.type){case"line":return fe.jsx(DD,{name:Ne.name,type:"monotone",dataKey:Ne.key,stroke:Ne.color,yAxisId:Ne.yAxisId,strokeWidth:Ne.strokeWidth,dot:Ne.dot},Ne.key);case"area":return fe.jsx(kD,{name:Ne.name,type:"monotone",dataKey:Ne.key,stroke:Ne.color,yAxisId:Ne.yAxisId,fill:Ne.color,fillOpacity:Ne.opacity,stackId:Ne.stackId},Ne.key);case"scatter":return fe.jsx(UD,{name:Ne.name,dataKey:Ne.key,fill:Ne.color,yAxisId:Ne.yAxisId},Ne.key);default:return fe.jsx(ND,{name:Ne.name,dataKey:Ne.key,fill:Ne.color,stackId:Ne.stackId,yAxisId:Ne.yAxisId,radius:[4,4,0,0]},Ne.key)}})]}),s.type==="pie"&&fe.jsxs(btt,{children:[fe.jsx(Yoe,{data:s.data,dataKey:((n=s.dataKeys)==null?void 0:n[0])||"value",nameKey:s.xKey||"name",cx:"50%",cy:"50%",outerRadius:f/3,label:{fill:X},children:s.data.map((Ne,Yt)=>fe.jsx(g0,{fill:w[Yt%w.length]},`cell-${Yt}`))}),fe.jsx(Fu,{contentStyle:xe,itemStyle:Se,formatter:Ke}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"})]}),s.type==="scatter"&&fe.jsxs(Ntt,{margin:Ve,children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"x",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{dataKey:((i=s.dataKeys)==null?void 0:i[0])||"y",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,fe.jsx(UD,{name:"Data",data:s.data,fill:w[0]})]})]})]})};let Yu=null;const Htt=async()=>{if(typeof window>"u")throw new Error("abcjs requires a browser environment");if(Yu)return Yu;try{const e=await rr(()=>import("./index-BAOVR-xx-
|
|
1181
|
+
`})]}),s.title&&fe.jsx("h4",{style:{textAlign:"center",marginBottom:s.description?"4px":"12px",marginTop:0,color:X,fontWeight:600,background:"transparent"},children:s.title}),s.description&&fe.jsx("p",{style:{textAlign:"center",marginTop:0,marginBottom:"12px",color:K,fontSize:"0.9rem"},children:s.description}),fe.jsxs(vJe,{width:"100%",height:f,children:[s.type==="bar"&&fe.jsxs(ptt,{data:s.data,margin:Ve,barCategoryGap:"20%",children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"name",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{yAxisId:"left",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),Y&&fe.jsx(ls,{yAxisId:"right",orientation:"right",width:80,tickFormatter:et,...$,children:Ws(j,"right")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,I.map(Ne=>fe.jsx(ND,{name:Ne.name,dataKey:Ne.key,fill:Ne.color,stackId:Ne.stackId,yAxisId:Ne.yAxisId,radius:[4,4,0,0]},Ne.key))]}),s.type==="line"&&fe.jsxs(dtt,{data:s.data,margin:Ve,children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"name",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{yAxisId:"left",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),Y&&fe.jsx(ls,{yAxisId:"right",orientation:"right",width:80,tickFormatter:et,...$,children:Ws(j,"right")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,I.map(Ne=>fe.jsx(DD,{name:Ne.name,type:"monotone",dataKey:Ne.key,stroke:Ne.color,yAxisId:Ne.yAxisId,strokeWidth:Ne.strokeWidth,dot:Ne.dot},Ne.key))]}),s.type==="area"&&fe.jsxs(ktt,{data:s.data,margin:Ve,children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"name",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{yAxisId:"left",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),Y&&fe.jsx(ls,{yAxisId:"right",orientation:"right",width:80,tickFormatter:et,...$,children:Ws(j,"right")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,I.map(Ne=>fe.jsx(kD,{name:Ne.name,type:"monotone",dataKey:Ne.key,stroke:Ne.color,yAxisId:Ne.yAxisId,fill:Ne.color,fillOpacity:Ne.opacity,stackId:Ne.stackId},Ne.key))]}),s.type==="composed"&&fe.jsxs(Utt,{data:s.data,margin:Ve,children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"name",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{yAxisId:"left",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),Y&&fe.jsx(ls,{yAxisId:"right",orientation:"right",width:80,tickFormatter:et,...$,children:Ws(j,"right")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,I.map(Ne=>{switch(Ne.type){case"line":return fe.jsx(DD,{name:Ne.name,type:"monotone",dataKey:Ne.key,stroke:Ne.color,yAxisId:Ne.yAxisId,strokeWidth:Ne.strokeWidth,dot:Ne.dot},Ne.key);case"area":return fe.jsx(kD,{name:Ne.name,type:"monotone",dataKey:Ne.key,stroke:Ne.color,yAxisId:Ne.yAxisId,fill:Ne.color,fillOpacity:Ne.opacity,stackId:Ne.stackId},Ne.key);case"scatter":return fe.jsx(UD,{name:Ne.name,dataKey:Ne.key,fill:Ne.color,yAxisId:Ne.yAxisId},Ne.key);default:return fe.jsx(ND,{name:Ne.name,dataKey:Ne.key,fill:Ne.color,stackId:Ne.stackId,yAxisId:Ne.yAxisId,radius:[4,4,0,0]},Ne.key)}})]}),s.type==="pie"&&fe.jsxs(btt,{children:[fe.jsx(Yoe,{data:s.data,dataKey:((n=s.dataKeys)==null?void 0:n[0])||"value",nameKey:s.xKey||"name",cx:"50%",cy:"50%",outerRadius:f/3,label:{fill:X},children:s.data.map((Ne,Yt)=>fe.jsx(g0,{fill:w[Yt%w.length]},`cell-${Yt}`))}),fe.jsx(Fu,{contentStyle:xe,itemStyle:Se,formatter:Ke}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"})]}),s.type==="scatter"&&fe.jsxs(Ntt,{margin:Ve,children:[M&&fe.jsx(ku,{strokeDasharray:"3 3",stroke:te}),fe.jsx(Su,{dataKey:s.xKey||"x",label:vt,...$,...je,tickFormatter:gr}),fe.jsx(ls,{dataKey:((i=s.dataKeys)==null?void 0:i[0])||"y",width:80,tickFormatter:et,...$,children:Ws(R,"left")}),fe.jsx(Fu,{contentStyle:xe,labelStyle:Ie,itemStyle:Se,formatter:Ke,labelFormatter:yr,cursor:Te}),Q&&fe.jsx(Ac,{wrapperStyle:Ge,iconSize:10,iconType:"square"}),D,fe.jsx(UD,{name:"Data",data:s.data,fill:w[0]})]})]})]})};let Yu=null;const Htt=async()=>{if(typeof window>"u")throw new Error("abcjs requires a browser environment");if(Yu)return Yu;try{const e=await rr(()=>import("./index-BAOVR-xx-CgGkM_kf.js"),[]).then(r=>r.i),t=e.default||e;if(!t)throw new Error("abcjs module is empty");if(typeof t.renderAbc!="function")throw new Error(`renderAbc is not a function. Available methods: ${Object.keys(t).join(", ")}`);return Yu=t,Yu}catch(e){if(typeof window<"u"&&window.ABCJS)return Yu=window.ABCJS,Yu;const t=e instanceof Error?e.message:"Failed to load abcjs";throw new Error(`Failed to load abcjs: ${t}`)}},Jtt=e=>{const t=e.trim();return/^[XMTLK]:/m.test(t)||/^X:\d+/m.test(t)},Ott=e=>{const t=e.trim();if(!t.includes("X:")||!/^K:/m.test(t))return!0;const r=t.split(`
|
|
1182
1182
|
`),n=r[r.length-1].trim();return!!(n.match(/^[A-Z]:?\s*$/)&&n.length<3||n.endsWith("|")&&!n.endsWith("|]")&&!n.endsWith("||")&&n.replace(/\|/g,"").trim().length<2)},Wtt=({code:e})=>{const t=F.useRef(null),[r,n]=F.useState(null),[i,A]=F.useState(!0),[a,s]=F.useState(!1),[o,l]=F.useState(!1),[c,u]=F.useState(!1),g=F.useRef(""),h=F.useRef(0),d=F.useRef(null);return F.useEffect(()=>{const B=e.trim();if(!B){A(!1),l(!1),s(!1);return}const y=Date.now(),w=y-h.current,f=e!==g.current;g.current=e,h.current=y;const I=Ott(B),Y=f&&w<500&&w>0,Q=I||Y;if(I){s(!0),A(!0),n(null);return}Jtt(e)?(l(!0),n(null),Q&&s(!0)):(l(!1),Q?(s(!0),n(null)):(n("Unable to detect ABC notation. Expected ABC notation starting with headers like X:, T:, M:, L:, or K:"),A(!1),s(!1)))},[e]),F.useEffect(()=>!o||!e.trim()?void 0:(a&&(d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{s(!1)},400)),(async()=>{try{A(!0);let B=0;const y=10;for(;!t.current&&B<y;)await new Promise(f=>setTimeout(f,50)),B++;if(!t.current)throw new Error("Container element not found after waiting");const w=await Htt();t.current.innerHTML="",w.renderAbc(t.current,e,{responsive:"resize",staffwidth:740,paddingleft:0,paddingright:0,paddingtop:15,paddingbottom:15,scale:1}),n(null),A(!1)}catch(B){const y=B instanceof Error?B.message:"Failed to render ABC notation";n(y),A(!1)}})(),()=>{d.current&&clearTimeout(d.current)}),[e,o,a]),r?fe.jsxs("div",{className:"graph-error",children:[fe.jsxs("div",{className:"graph-error-header",children:[fe.jsx("div",{className:"graph-error-icon",children:"⚠️"}),fe.jsxs("div",{className:"graph-error-content",children:[fe.jsx("div",{className:"graph-error-title",children:"ABC Notation Rendering Error"}),fe.jsx("div",{className:"graph-error-message",children:r})]})]}),fe.jsxs("button",{className:"graph-error-toggle",onClick:()=>u(!c),type:"button",children:[c?"Hide":"Show"," Details"]}),c&&fe.jsxs("details",{className:"graph-error-details",open:!0,children:[fe.jsx("summary",{style:{cursor:"pointer",marginBottom:"8px",fontWeight:500},children:"ABC Notation Code"}),fe.jsx("pre",{style:{marginTop:"8px",fontSize:"0.8em",opacity:.8,padding:"8px",background:"rgba(0, 0, 0, 0.05)",borderRadius:"4px",overflow:"auto",maxHeight:"200px"},children:fe.jsx("code",{children:e})})]})]}):(i||a)&&!o?fe.jsx("div",{className:"graph-container music-container abc-container",children:fe.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"30px 20px",color:"var(--md-text-secondary, #6b7280)",minHeight:"120px"},children:[fe.jsx("svg",{style:{animation:"spin 1s linear infinite",marginBottom:"10px",width:"28px",height:"28px"},viewBox:"0 0 24 24",fill:"none",children:fe.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2",strokeDasharray:"32",strokeLinecap:"round"})}),fe.jsx("span",{style:{fontWeight:500,fontSize:"14px"},children:a?"Receiving music notation...":"Loading music notation..."}),fe.jsx("style",{children:`
|
|
1183
1183
|
@keyframes spin {
|
|
1184
1184
|
from { transform: rotate(0deg); }
|
|
@@ -1196,20 +1196,20 @@ ${e.themeCSS}`),e.fontFamily!==void 0&&(n+=`
|
|
|
1196
1196
|
}
|
|
1197
1197
|
`})]}),fe.jsx("div",{ref:t,style:{display:"flex",justifyContent:"center",overflow:"auto"}})]}):null},Ptt=e=>{var t,r;if(!e)return typeof window<"u"&&(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light";const n=e.closest(".markdown-content");if(n){if(n.classList.contains("dark"))return"dark";if(n.classList.contains("light"))return"light"}if(e.closest(".dark"))return"dark";if(e.closest(".light"))return"light";const i=e.closest("[data-theme]");if(i){const A=i.getAttribute("data-theme");if(A==="dark")return"dark";if(A==="light")return"light"}return typeof window<"u"&&(r=window.matchMedia)!=null&&r.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"},Ktt=(e,t)=>{const[r,n]=F.useState("light");return F.useEffect(()=>{var i,A,a;if(t||typeof window>"u"||typeof document>"u")return;const s=()=>{n(Ptt(e.current))};s();const o=((i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)"))??null,l=()=>s();o&&(o.addEventListener?o.addEventListener("change",l):o.addListener&&o.addListener(l));const c=typeof MutationObserver<"u"?new MutationObserver(()=>s()):null;if(c){const u=((a=(A=e.current)==null?void 0:A.closest)==null?void 0:a.call(A,".markdown-content"))??null;u&&c.observe(u,{attributes:!0,attributeFilter:["class","data-theme"]}),document.body&&c.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]})}return()=>{o&&(o.removeEventListener?o.removeEventListener("change",l):o.removeListener&&o.removeListener(l)),c==null||c.disconnect()}},[t,e]),t??r},Vtt={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"tsx",sh:"bash",shell:"bash",shellsession:"bash",yml:"yaml",yaml:"yaml",py:"python",rb:"ruby",kt:"kotlin",md:"markdown",csharp:"csharp","c#":"csharp","c++":"cpp",tf:"hcl",terraform:"hcl",docker:"dockerfile",dotenv:"env",env:"env",plaintext:"text",text:"text"},Xtt=e=>{if(!e)return"";const t=e.match(/(?:^|\s)language-([^\s]+)/);if(!t)return"";const r=t[1].toLowerCase().split("{")[0].split("[")[0].split("<")[0].split(":")[0].trim().replace(/[^a-z0-9+#-]+$/g,"");return r?Vtt[r]??r:""},Ztt=e=>Kn.Children.toArray(e).map(t=>typeof t=="string"||typeof t=="number"?String(t):"").join("").replace(/\n$/,""),PK=({code:e})=>{const[t,r]=F.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)}catch{const i=document.createElement("textarea");i.value=e,i.style.position="fixed",i.style.opacity="0",document.body.appendChild(i),i.select();try{document.execCommand("copy"),r(!0),setTimeout(()=>r(!1),2e3)}catch(A){console.error("Failed to copy code:",A)}document.body.removeChild(i)}};return fe.jsxs("button",{className:"code-copy-button",onClick:n,title:t?"Copied!":"Copy code","aria-label":t?"Copied!":"Copy code to clipboard",children:[t?fe.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:fe.jsx("path",{d:"M13.5 4.5L6 12L2.5 8.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):fe.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[fe.jsx("path",{d:"M5.5 4.5H3.5C2.94772 4.5 2.5 4.94772 2.5 5.5V12.5C2.5 13.0523 2.94772 13.5 3.5 13.5H10.5C11.0523 13.5 11.5 13.0523 11.5 12.5V10.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),fe.jsx("path",{d:"M6.5 2.5H12.5C13.0523 2.5 13.5 2.94772 13.5 3.5V9.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),fe.jsx("path",{d:"M9.5 6.5L13.5 2.5L9.5 2.5V6.5Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),fe.jsx("span",{className:"code-copy-button-text",children:t?"Copied!":"Copy"})]})},qtt=({inline:e,className:t="",children:r,enableGraphs:n=!0,enableMermaid:i=!0,enableSVG:A=!0,enableCharts:a=!0,enableMusic:s=!0,enableSyntaxHighlighting:o=!0,syntaxTheme:l})=>{const c=F.useRef(null),u=Ktt(c,l);if(e)return fe.jsx("code",{className:t,children:r});const g=Xtt(t),h=Ztt(r);if(a&&(g==="chart"||g==="chart-json"||g==="chart-table"))return fe.jsx("div",{ref:c,children:fe.jsx(Ltt,{code:h,language:g})});if(s&&(g==="abc"||g==="music"))return fe.jsx("div",{ref:c,children:fe.jsx(Wtt,{code:h})});if(n){if(g==="mermaid"&&i)return fe.jsx("div",{ref:c,children:fe.jsx(nHe,{code:h})});if(g==="svg"&&A)return fe.jsx("div",{ref:c,children:fe.jsx(oHe,{code:h})})}if(o&&g){const d=u==="light"?Lxe:Hxe;try{return fe.jsxs("div",{ref:c,className:"syntax-highlighted-wrapper code-block-container",children:[fe.jsx(PK,{code:h}),fe.jsx(a_,{language:g,style:d,customStyle:{margin:"12px 0",borderRadius:"6px",fontSize:"0.9em"},showLineNumbers:!1,children:h})]})}catch(B){console.warn(`Syntax highlighting failed for "${g}". Falling back to plain code block.`,B)}}return fe.jsxs("div",{ref:c,className:`markdown-code-block code-block-container ${t}`.trim(),children:[fe.jsx(PK,{code:h}),fe.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:fe.jsx("code",{children:h})})]})},KK=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),_tt=({children:e,href:t,...r})=>fe.jsx("a",{...r,href:t,target:"_blank",rel:"noopener noreferrer",children:e}),VK=({content:e,className:t="",disableMath:r=!1,enableGraphs:n=!0,enableMermaid:i=!0,enableSVG:A=!0,enableCharts:a=!0,enableMusic:s=!0,enableSyntaxHighlighting:o=!0,syntaxTheme:l="dark"})=>{const c=nIe(e);if(!c)return null;const u=r?[Lz]:[Lz,[sfe,{singleDollarTextMath:!0}]],g=[];r||g.push([Tfe,{throwOnError:!1,errorColor:"#cc0000",strict:!1,trust:!0,macros:{"\\RR":"\\mathbb{R}","\\NN":"\\mathbb{N}","\\ZZ":"\\mathbb{Z}","\\QQ":"\\mathbb{Q}","\\CC":"\\mathbb{C}","\\dx":"\\,dx","\\dy":"\\,dy","\\dt":"\\,dt","\\dz":"\\,dz"}}]);const h={a:_tt,code:d=>{const{className:B,children:y,...w}=d,f=B&&/language-/.test(B),I="inline"in d&&typeof d.inline=="boolean"&&d.inline||!f,Y=f;return fe.jsx(qtt,{inline:I,className:B,enableGraphs:n,enableMermaid:i,enableSVG:A,enableCharts:a,enableMusic:s,enableSyntaxHighlighting:o,syntaxTheme:l,"data-block-code":Y?"true":void 0,...w,children:y})},p:({node:d,...B})=>{var y;const w=Kn.Children.toArray(B.children).filter(I=>!(typeof I=="string"&&I.trim()==="")).some(I=>{var Y;return Kn.isValidElement(I)?((Y=I.props)==null?void 0:Y["data-block-code"])==="true"?!0:typeof I.type=="string"?KK.has(I.type):!1:!1}),f=(y=d==null?void 0:d.children)==null?void 0:y.some(I=>{var Y;if(I.type==="code")return!0;if(I.type==="element"){if(I.tagName&&KK.has(I.tagName))return!0;if(I.tagName==="code"){const Q=(Y=I.properties)==null?void 0:Y.className;return Array.isArray(Q)?Q.some(M=>typeof M=="string"&&M.startsWith("language-")):!0}}return!1});return w||f?fe.jsx(fe.Fragment,{children:B.children}):fe.jsx("p",{...B})}};return fe.jsx("div",{className:`markdown-content ${t}`,children:fe.jsx(_pe,{remarkPlugins:u,rehypePlugins:g,components:h,children:c})})},XK="schmitech-markdown-renderer-styles",$tt=`${H0e}
|
|
1198
1198
|
${L0e}`,ert=()=>{if(typeof document>"u"||document.getElementById(XK))return;const e=document.createElement("style");e.id=XK,e.textContent=$tt,document.head.appendChild(e)};ert();const Xe=(...e)=>{},jr=(...e)=>{},zg=(...e)=>{},oi=(...e)=>{console.error(...e)},trt={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_ADAPTERS:`[
|
|
1199
|
-
{ "name": "Simple Chat", "apiKey": "default-key", "apiUrl": "http://
|
|
1200
|
-
{ "name": "Chat With Files", "apiKey": "multimodal", "apiUrl": "http://
|
|
1201
|
-
{ "name": "e-commerce", "apiKey": "postgres", "apiUrl": "http://
|
|
1202
|
-
{ "name": "Human Resources", "apiKey": "contact", "apiUrl": "http://
|
|
1203
|
-
{ "name": "Movies", "apiKey": "mflix", "apiUrl": "http://
|
|
1204
|
-
{ "name": "Application Logs", "apiKey": "elasticsearch", "apiUrl": "http://
|
|
1205
|
-
{ "name": "Classified CMS", "apiKey": "classified", "apiUrl": "http://
|
|
1206
|
-
{ "name": "Business Analytics", "apiKey": "analytical", "apiUrl": "http://
|
|
1207
|
-
{ "name": "Travel Expenses", "apiKey": "travel-expenses", "apiUrl": "http://
|
|
1208
|
-
]`,VITE_API_URL:"http://
|
|
1199
|
+
{ "name": "Simple Chat", "apiKey": "default-key", "apiUrl": "http://16.52.153.174:3000" },
|
|
1200
|
+
{ "name": "Chat With Files", "apiKey": "multimodal", "apiUrl": "http://16.52.153.174:3000" },
|
|
1201
|
+
{ "name": "e-commerce", "apiKey": "postgres", "apiUrl": "http://16.52.153.174:3000" },
|
|
1202
|
+
{ "name": "Human Resources", "apiKey": "contact", "apiUrl": "http://16.52.153.174:3000" },
|
|
1203
|
+
{ "name": "Movies", "apiKey": "mflix", "apiUrl": "http://16.52.153.174:3000" },
|
|
1204
|
+
{ "name": "Application Logs", "apiKey": "elasticsearch", "apiUrl": "http://16.52.153.174:3000" },
|
|
1205
|
+
{ "name": "Classified CMS", "apiKey": "classified", "apiUrl": "http://16.52.153.174:3000" },
|
|
1206
|
+
{ "name": "Business Analytics", "apiKey": "analytical", "apiUrl": "http://16.52.153.174:3000" },
|
|
1207
|
+
{ "name": "Travel Expenses", "apiKey": "travel-expenses", "apiUrl": "http://16.52.153.174:3000" }
|
|
1208
|
+
]`,VITE_API_URL:"http://16.52.153.174:3000",VITE_CONSOLE_DEBUG:"false",VITE_DEFAULT_KEY:"default-key",VITE_ENABLE_API_MIDDLEWARE:"false",VITE_ENABLE_AUDIO_OUTPUT:"true",VITE_ENABLE_CONVERSATION_THREADS:"true",VITE_ENABLE_FEEDBACK:"false",VITE_ENABLE_UPLOAD:"true",VITE_GITHUB_OWNER:"schmitech",VITE_GITHUB_REPO:"orbit",VITE_LOCALE:"en-US",VITE_MAX_CONVERSATIONS:"10",VITE_MAX_FILES_PER_CONVERSATION:"5",VITE_MAX_FILE_SIZE_MB:"50",VITE_MAX_MESSAGES_PER_CONVERSATION:"1000",VITE_MAX_MESSAGE_LENGTH:"500",VITE_MAX_TOTAL_FILES:"100",VITE_MAX_TOTAL_MESSAGES:"10000",VITE_SHOW_GITHUB_STATS:"true",VITE_USE_LOCAL_API:"false"},qc="http://localhost:3000";function rrt(e){return typeof e=="object"&&e!==null}const nrt={apiUrl:"VITE_API_URL",defaultKey:"VITE_DEFAULT_KEY",useLocalApi:"VITE_USE_LOCAL_API",localApiPath:"VITE_LOCAL_API_PATH",consoleDebug:"VITE_CONSOLE_DEBUG",enableUploadButton:"VITE_ENABLE_UPLOAD",enableAudioOutput:"VITE_ENABLE_AUDIO_OUTPUT",enableFeedbackButtons:"VITE_ENABLE_FEEDBACK",enableConversationThreads:"VITE_ENABLE_CONVERSATION_THREADS",enableApiMiddleware:"VITE_ENABLE_API_MIDDLEWARE",showGitHubStats:"VITE_SHOW_GITHUB_STATS",githubOwner:"VITE_GITHUB_OWNER",githubRepo:"VITE_GITHUB_REPO",adapters:"VITE_ADAPTERS",maxFilesPerConversation:"VITE_MAX_FILES_PER_CONVERSATION",maxFileSizeMB:"VITE_MAX_FILE_SIZE_MB",maxTotalFiles:"VITE_MAX_TOTAL_FILES",maxConversations:"VITE_MAX_CONVERSATIONS",maxMessagesPerConversation:"VITE_MAX_MESSAGES_PER_CONVERSATION",maxTotalMessages:"VITE_MAX_TOTAL_MESSAGES",maxMessageLength:"VITE_MAX_MESSAGE_LENGTH"};function irt(){return typeof window<"u"&&rrt(window.ORBIT_CHAT_CONFIG)}function br(e,t,r="string"){var o;const n=e==="showGitHubStats"||e==="githubOwner"||e==="githubRepo",i=irt();if(!n){if(i){const l=(o=window.ORBIT_CHAT_CONFIG)==null?void 0:o[e];return l??t}if(typeof window<"u")switch(e){case"apiUrl":if(window.CHATBOT_API_URL)return window.CHATBOT_API_URL;break;case"defaultKey":if(window.CHATBOT_API_KEY)return window.CHATBOT_API_KEY;break}}const A=nrt[e],s=A?trt[A]:void 0;if(s!=null&&s!==""){if(r==="boolean")return s==="true";if(r==="number"||r==="numberOrNull"){const l=parseInt(s,10);if(!isNaN(l))return r==="numberOrNull"&&l===0?null:l}else return s}return t}function nm(e,t){if(e===void 0||e==="")return t===0?null:t;const r=parseInt(e,10);return isNaN(r)||r<0?t===0?null:t:r===0?null:r}function wN(e,t){if(e===void 0||e==="")return t;const r=parseInt(e,10);return isNaN(r)||r<0?t:r}const hs={apiUrl:br("apiUrl",qc,"string"),defaultKey:br("defaultKey","default-key","string"),useLocalApi:br("useLocalApi",!1,"boolean"),localApiPath:br("localApiPath",void 0,"string"),consoleDebug:br("consoleDebug",!1,"boolean"),enableUploadButton:br("enableUploadButton",!1,"boolean"),enableAudioOutput:br("enableAudioOutput",!1,"boolean"),enableFeedbackButtons:br("enableFeedbackButtons",!1,"boolean"),enableConversationThreads:br("enableConversationThreads",!0,"boolean"),enableApiMiddleware:br("enableApiMiddleware",!1,"boolean"),showGitHubStats:br("showGitHubStats",!0,"boolean"),githubOwner:br("githubOwner","schmitech","string"),githubRepo:br("githubRepo","orbit","string"),maxFilesPerConversation:(()=>{const e=br("maxFilesPerConversation","5","string");return wN(e,5)})(),maxFileSizeMB:(()=>{const e=br("maxFileSizeMB","50","string");return wN(e,50)})(),maxTotalFiles:(()=>{const e=br("maxTotalFiles","100","string");return nm(e,100)})(),maxConversations:(()=>{const e=br("maxConversations","10","string");return nm(e,10)})(),maxMessagesPerConversation:(()=>{const e=br("maxMessagesPerConversation","1000","string");return nm(e,1e3)})(),maxTotalMessages:(()=>{const e=br("maxTotalMessages","10000","string");return nm(e,1e4)})(),maxMessageLength:(()=>{const e=br("maxMessageLength","1000","string");return wN(e,1e3)})()};function Pn(){return br("apiUrl",qc,"string")}function to(e){const t=e==null?void 0:e.trim();return t&&t.length>0?t:Pn()}function Fc(){return br("defaultKey","default-key","string")}function Art(){return br("useLocalApi",!1,"boolean")}function art(){return br("localApiPath",void 0,"string")}function srt(){return br("enableUploadButton",!1,"boolean")}function ort(){return br("enableAudioOutput",!1,"boolean")}function lrt(){return br("enableFeedbackButtons",!1,"boolean")}function crt(){return br("enableConversationThreads",!0,"boolean")}function Ii(){return br("enableApiMiddleware",!1,"boolean")}function urt(){return hs.showGitHubStats}function ZK(){return hs.githubOwner}function qK(){return hs.githubRepo}function grt({audio:e,audioFormat:t="mp3",autoPlay:r=!1,maxSizeMB:n=10}){const i=F.useRef(null),[A,a]=F.useState(!1),[s,o]=F.useState(0),[l,c]=F.useState(0),[u,g]=F.useState(!0),[h,d]=F.useState(null),[B,y]=F.useState(null);F.useEffect(()=>{if(!e)return;let z=null,R=!0;return(async()=>{try{g(!0),d(null),y(null);const te=e.length*3/4/(1024*1024);if(te>n)throw new Error(`Audio file too large (${te.toFixed(1)}MB > ${n}MB limit)`);if(te>2&&(y(`Large audio file (${te.toFixed(1)}MB) - may take time to load`),Xe("[AudioPlayer] Large audio file detected",{sizeMB:te.toFixed(2)})),!/^[A-Za-z0-9+/=]+$/.test(e.replace(/\s/g,"")))throw new Error("Invalid base64 audio data");const X=atob(e),Z=new Uint8Array(X.length);for(let K=0;K<X.length;K++)Z[K]=X.charCodeAt(K);const ee=t==="mp3"?"audio/mpeg":t==="wav"?"audio/wav":t==="ogg"?"audio/ogg":t==="opus"?"audio/opus":t==="webm"?"audio/webm":`audio/${t}`,Ae=new Blob([Z],{type:ee});if(z=URL.createObjectURL(Ae),!R||!i.current){z&&URL.revokeObjectURL(z);return}i.current.src=z,g(!1),Xe("[AudioPlayer] Audio loaded successfully",{format:t,mimeType:ee,size:Ae.size}),r&&i.current&&i.current.play().catch(K=>{zg("[AudioPlayer] Auto-play failed:",K)})}catch{R&&(d("Failed to load audio"),g(!1))}})(),()=>{R=!1,z&&URL.revokeObjectURL(z)}},[e,t,r,n]);const w=()=>{i.current&&o(i.current.duration)},f=()=>{i.current&&c(i.current.currentTime)},I=()=>a(!0),Y=()=>a(!1),Q=()=>{a(!1),c(0)},M=()=>{i.current&&(A?i.current.pause():i.current.play().catch(z=>{d("Playback failed")}))},D=z=>{if(!i.current)return;const R=parseFloat(z.target.value);i.current.currentTime=R,c(R)},G=z=>{if(!isFinite(z))return"0:00";const R=Math.floor(z/60),j=Math.floor(z%60);return`${R}:${j.toString().padStart(2,"0")}`};return h?T.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-700 dark:bg-red-900/20 dark:text-red-400",children:[T.jsx(uw,{className:"h-4 w-4"}),T.jsx("span",{children:h})]}):T.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[B&&T.jsxs("div",{className:"text-xs text-amber-600 dark:text-amber-400 px-1",children:["⚠️ ",B]}),T.jsxs("div",{className:"flex items-center gap-3 rounded-md border border-gray-300 bg-white px-3 py-2 dark:border-[#4a4b54] dark:bg-[#343541]",children:[T.jsx("audio",{ref:i,onLoadedMetadata:w,onTimeUpdate:f,onPlay:I,onPause:Y,onEnded:Q}),T.jsx("button",{onClick:M,disabled:u,className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 disabled:opacity-50 dark:bg-[#4a4b54] dark:hover:bg-[#565869]",title:A?"Pause":"Play",children:u?T.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-gray-400 border-t-transparent"}):A?T.jsx(C0e,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):T.jsx(M0e,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})}),T.jsxs("div",{className:"flex flex-1 items-center gap-2",children:[T.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:G(l)}),T.jsx("input",{type:"range",min:"0",max:s||0,value:l,onChange:D,disabled:u||!s,className:"flex-1 cursor-pointer accent-gray-600 dark:accent-[#bfc2cd]",style:{background:s?`linear-gradient(to right, rgb(75 85 99) 0%, rgb(75 85 99) ${l/s*100}%, rgb(229 231 235) ${l/s*100}%, rgb(229 231 235) 100%)`:"rgb(229 231 235)"}}),T.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:G(s)})]}),T.jsx(uw,{className:"h-4 w-4 text-gray-500 dark:text-[#bfc2cd]"})]})]})}const hrt=["#","*","`","[","]","(",")","{","}","|","<",">"],wle=e=>hrt.some(t=>e.includes(t));function fle(e){if(!e||e.length<1e3)return!1;const t=/^[A-Za-z0-9+/=]+$/,r=e.replace(/\s+/g,"");if(r.length>1e4&&t.test(r)){const n=/\b(the|and|for|are|but|not|you|all|can|function|const|let|var|class|return|import|export|async|await|if|else|while|true|false|null|undefined|http|https|www|error|data|response|request|api|json|xml|html|css|js|py|java|cpp|def|print|console|log)\b/i.test(e),i=wle(e),A=/[.,;:!?'"()-]/.test(e);if(!n&&!i&&!A)return!0}return!!(r.length>5e4&&t.test(r)&&e.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}function Lh(e){if(!e)return e;if(fle(e))return"";const t=/([A-Za-z0-9+/=]{10000,})/g;return e.replace(t,n=>{const i=n.replace(/\s+/g,"");if(i.length>1e4&&/^[A-Za-z0-9+/=]+$/.test(i)){const A=/\b(function|const|let|var|class|return|import|export|if|else|while|for|true|false|null|def|print)\b/i.test(n),a=wle(n),s=/[.,;:!?'"()-]/.test(n);if(!A&&!a&&!s)return""}return n}).trim()}function LD(e,t=5e4){return!e||e.length<=t?e:fle(e)?"":e.substring(0,t)+`
|
|
1209
1209
|
|
|
1210
|
-
... (content truncated due to length)`}const xr={maxFilesPerConversation:hs.maxFilesPerConversation,maxFileSizeMB:hs.maxFileSizeMB,maxTotalFiles:hs.maxTotalFiles,maxConversations:hs.maxConversations,maxMessagesPerConversation:hs.maxMessagesPerConversation,maxTotalMessages:hs.maxTotalMessages,maxMessageLength:hs.maxMessageLength},drt=[];function Brt({message:e,onRegenerate:t,onStartThread:r,onSendThreadMessage:n,threadMessages:i,sessionId:A,isThreadSendDisabled:a}){var xe,Ie;const[s,o]=F.useState(!1),[l,c]=F.useState(null),[u,g]=F.useState(""),[h,d]=F.useState(!1),[B,y]=F.useState(!1),w=F.useRef(((xe=e.threadInfo)==null?void 0:xe.thread_id)||null),f=F.useRef(null),I=e.role==="assistant",Y=i??drt,Q=Y.filter(Se=>Se.role==="assistant").length,M=Y.some(Se=>Se.isStreaming),D="en-US",G=crt(),z=xr.maxMessageLength,{theme:R,isDark:j}=EX(),W=R.mode==="dark"?"dark":R.mode==="light"?"light":"",te=j?"dark":"light",X=F.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",W].filter(Boolean).join(" "),[W]),Z=F.useMemo(()=>["message-markdown w-full min-w-0","prose prose-invert max-w-none",W].filter(Boolean).join(" "),[W]),ee=I?X:Z,Ae=`${X} text-sm leading-6`,K=`${Z} text-sm leading-6`;F.useEffect(()=>{var Se,Te;!w.current&&((Se=e.threadInfo)!=null&&Se.thread_id)&&d(!0),w.current=((Te=e.threadInfo)==null?void 0:Te.thread_id)||null},[(Ie=e.threadInfo)==null?void 0:Ie.thread_id]),F.useEffect(()=>{e.threadInfo||(g(""),d(!1),y(!1))},[e.threadInfo]),F.useEffect(()=>{Q>0&&d(!0)},[Q]);const $=F.useMemo(()=>{const Se=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp),Te=Se.toLocaleDateString(D,{weekday:"short"}),Ke=Se.toLocaleDateString(D,{month:"short"}),et=Se.getDate().toString().padStart(2,"0"),rt=Se.getFullYear(),It=Se.toLocaleTimeString(D,{hour:"2-digit",minute:"2-digit",hour12:!0});return`${Te}, ${Ke} ${et}, ${rt} ${It}`},[e.timestamp,D]),L=I?"bg-gradient-to-br from-blue-100 to-blue-200 text-blue-900 dark:from-[#1f2a36] dark:to-[#1a2230] dark:text-[#c5d7ff]":"bg-gradient-to-br from-emerald-100 to-emerald-200 text-emerald-900 dark:from-[#0f1f17] dark:to-[#0b1712] dark:text-[#c7f5df]",ne=`message-bubble min-w-0 break-words leading-relaxed ${I?"border border-blue-100/80 bg-transparent text-[#0f172a] shadow-[0_15px_35px_-20px_rgba(15,23,42,0.25)] dark:border-[#1f2a36] dark:bg-transparent dark:text-[#e5edff]":"border border-emerald-100 bg-transparent text-[#1c3226] shadow-[0_12px_30px_-18px_rgba(15,52,33,0.25)] dark:border-[#1a2b21] dark:bg-transparent dark:text-[#dffbea]"} rounded-2xl px-4 py-3`,ge=I?"border-blue-100 bg-white/80 dark:border-[#1f2a36] dark:bg-white/5":"border-emerald-100 bg-white/80 dark:border-[#1a2b21] dark:bg-white/5",P=async()=>{try{await navigator.clipboard.writeText(e.content),o(!0),setTimeout(()=>o(!1),2e3)}catch{}},Be=Se=>{c(l===Se?null:Se)},Fe=F.useCallback(Se=>(Se instanceof Date?Se:new Date(Se)).toLocaleTimeString(D,{hour:"2-digit",minute:"2-digit"}),[D]),Me=async()=>{if(!n||!e.threadInfo)return;const Se=u.trim();if(Se){y(!0);try{await n(e.threadInfo.thread_id,e.id,Se),g(""),setTimeout(()=>{f.current&&f.current.focus()},100)}catch{setTimeout(()=>{f.current&&f.current.focus()},100)}finally{y(!1)}}},pe=Se=>{Se.key==="Enter"&&!Se.shiftKey&&(Se.preventDefault(),Me())},ke=!e.threadInfo||!n||a||M||B;F.useEffect(()=>{if(!h||ke)return;const Se=f.current;if(!Se)return;const Te=requestAnimationFrame(()=>{Se.focus();const Ke=Se.value.length;Se.setSelectionRange(Ke,Ke)});return()=>cancelAnimationFrame(Te)},[h,ke,B]),F.useEffect(()=>{if(f.current){const Te=f.current;Te.style.height="auto";const Ke=Te.scrollHeight;Te.style.height=`${Math.min(Ke,120)}px`,Te.style.overflowY=Ke>120?"auto":"hidden"}},[u]);const Ee=F.useMemo(()=>e.isStreaming&&(!e.content||e.content==="…")?T.jsx("div",{className:ee,children:T.jsxs("div",{className:"flex items-center gap-1.5 py-1",children:[T.jsx("span",{className:"inline-block h-2.5 w-2.5 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"0ms"}}),T.jsx("span",{className:"inline-block h-2.5 w-2.5 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"150ms"}}),T.jsx("span",{className:"inline-block h-2.5 w-2.5 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"300ms"}})]})}):T.jsx(VK,{content:LD(Lh(e.content||"")),className:ee,syntaxTheme:te}),[ee,e.content,e.isStreaming,te]),je=F.useMemo(()=>[...Y].sort((Te,Ke)=>{const et=Te.timestamp instanceof Date?Te.timestamp.getTime():new Date(Te.timestamp).getTime(),rt=Ke.timestamp instanceof Date?Ke.timestamp.getTime():new Date(Ke.timestamp).getTime();return et-rt}).map(Te=>{const Ke=Te.role==="assistant",et=Ke?Ae:K,rt=Te.isStreaming&&(!Te.content||Te.content==="…")?T.jsx("div",{className:et,children:T.jsxs("div",{className:"flex items-center gap-1.5 py-1",children:[T.jsx("span",{className:"inline-block h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"0ms"}}),T.jsx("span",{className:"inline-block h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"150ms"}}),T.jsx("span",{className:"inline-block h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"300ms"}})]})}):T.jsx(VK,{content:LD(Lh(Te.content||"")),className:et,syntaxTheme:te});return T.jsxs("div",{className:"flex items-start gap-3",children:[T.jsx("div",{className:`mt-0.5 flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-full ${Ke?"bg-blue-100 text-blue-700 dark:bg-[#1f2a36] dark:text-[#c5d7ff]":"bg-emerald-100 text-emerald-700 dark:bg-[#1f2a36] dark:text-[#9ef0d5]"}`,children:Ke?T.jsx(eR,{className:"h-3.5 w-3.5"}):T.jsx(rR,{className:"h-3.5 w-3.5"})}),T.jsxs("div",{className:"flex-1 min-w-0 rounded-2xl border border-white/70 bg-white/90 px-4 py-3 text-sm shadow-sm dark:border-white/5 dark:bg-white/5 backdrop-blur overflow-hidden",children:[T.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] font-semibold uppercase tracking-wide text-blue-900/70 dark:text-[#c5d7ff]",children:[T.jsx("span",{children:Ke?"Assistant":"You"}),T.jsx("span",{children:Fe(Te.timestamp)})]}),T.jsx("div",{className:"thread-markdown-wrapper overflow-x-auto",children:rt})]})]},Te.id)}),[Fe,te,Ae,Y,K]);return T.jsxs("div",{className:"group flex items-start gap-3 px-1 animate-fadeIn min-w-0 sm:px-0",children:[T.jsx("div",{className:`flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full self-start -mt-2 ml-1 shadow-sm ring-2 ring-white/50 dark:ring-white/10 sm:-mt-3 sm:ml-2 ${L}`,children:I?T.jsx(eR,{className:"h-5 w-5"}):T.jsx(rR,{className:"h-5 w-5"})}),T.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[T.jsxs("div",{className:"flex flex-col gap-1.5 mb-1",children:[T.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-700 dark:text-[#ececf1]",children:I?"Assistant":"You"}),T.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:$})]}),T.jsxs("div",{className:ne,children:[Ee,e.attachments&&e.attachments.length>0&&T.jsx("div",{className:"mt-3 space-y-2",children:e.attachments.map(Se=>T.jsxs("div",{className:`flex items-center gap-3 rounded-xl border p-3 ${ge}`,children:[T.jsx(B0e,{className:"h-4 w-4 text-gray-500 dark:text-[#bfc2cd]"}),T.jsxs("div",{className:"min-w-0 flex-1",children:[T.jsx("p",{className:"truncate text-sm font-medium text-[#353740] dark:text-[#ececf1]",children:Se.filename}),T.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[(Se.file_size/1024).toFixed(1)," KB"]})]})]},Se.file_id))}),e.audio&&I&&!e.isStreaming&&T.jsx(grt,{audio:e.audio,audioFormat:e.audioFormat,autoPlay:!1})]}),I&&!e.isStreaming&&T.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-gray-500 transition-opacity dark:text-[#bfc2cd] sm:opacity-0 sm:group-hover:opacity-100",children:[T.jsxs("button",{onClick:P,className:"inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a]",title:"Copy message",children:[T.jsx(g0e,{className:"h-4 w-4"}),"Copy"]}),t&&T.jsxs("button",{onClick:()=>t(e.id),className:"inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a]",title:"Regenerate response",children:[T.jsx(b0e,{className:"h-4 w-4"}),"Retry"]}),G&&r&&e.supportsThreading&&!e.threadInfo&&A&&T.jsxs("button",{onClick:()=>r(e.id,A),className:"inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a]",title:"Start thread for follow-up questions",children:[T.jsx(Mh,{className:"h-4 w-4"}),"Start Thread"]}),lrt()&&T.jsxs("div",{className:"flex items-center gap-1",children:[T.jsx("button",{onClick:()=>Be("up"),className:`rounded p-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a] ${l==="up"?"text-[#353740] dark:text-[#ececf1]":""}`,title:"Good response",children:T.jsx(k0e,{className:"h-4 w-4"})}),T.jsx("button",{onClick:()=>Be("down"),className:`rounded p-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a] ${l==="down"?"text-[#353740] dark:text-[#ececf1]":""}`,title:"Poor response",children:T.jsx(D0e,{className:"h-4 w-4"})})]}),s&&T.jsx("span",{children:"Copied"})]}),G&&e.threadInfo&&T.jsxs("div",{className:"ml-12 mt-4 rounded-xl border border-blue-100/80 bg-blue-50/70 p-4 text-sm shadow-sm ring-1 ring-blue-100/60 dark:border-[#1f2a36] dark:bg-[#0f1821] dark:ring-[#1f2a36]",children:[T.jsxs("div",{className:"flex items-center justify-between text-sm font-semibold text-blue-900 dark:text-[#c5d7ff]",children:[T.jsxs("div",{className:"inline-flex items-center gap-2 uppercase tracking-wide",children:[T.jsx(Mh,{className:"h-3.5 w-3.5"}),T.jsxs("span",{children:["Thread replies",Q>0?` (${Q})`:""]})]}),T.jsx("button",{onClick:()=>d(Se=>!Se),className:"inline-flex items-center gap-2 rounded-full border border-blue-200/80 px-3 py-1.5 text-xs uppercase tracking-wide text-blue-900 transition hover:bg-white/70 dark:border-[#233449] dark:text-[#c5d7ff] dark:hover:bg-white/10",children:h?T.jsxs(T.Fragment,{children:["Hide ",T.jsx(u0e,{className:"h-3 w-3"})]}):T.jsxs(T.Fragment,{children:["Show ",T.jsx(MX,{className:"h-3 w-3"})]})})]}),h&&T.jsxs(T.Fragment,{children:[T.jsx("div",{className:"mt-3 space-y-3",children:je}),T.jsx("div",{className:"mt-3 rounded-xl border border-white/80 bg-white/95 p-3 shadow-sm dark:border-white/10 dark:bg-white/10",children:T.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[T.jsx("textarea",{ref:f,className:"flex-1 min-w-0 resize-none rounded-md border border-transparent bg-transparent px-3 py-1.5 text-sm text-[#353740] placeholder-gray-600 outline-none transition focus:border-gray-400 focus:ring-1 focus:ring-gray-300 disabled:opacity-60 dark:text-[#ececf1] dark:placeholder-[#bfc2cd] dark:focus:border-[#8e8ea0] dark:focus:ring-[#8e8ea0]",placeholder:Q>0?"Reply in thread...":"Ask a follow-up...",value:u,onChange:Se=>g(Se.target.value),onKeyDown:pe,disabled:ke,rows:1,maxLength:z,style:{minHeight:"38px",maxHeight:"120px",border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none"}}),T.jsxs("div",{className:"flex items-center gap-2",children:[u.length>0&&T.jsx("div",{className:"text-xs text-gray-500 dark:text-[#bfc2cd] whitespace-nowrap",children:T.jsxs("span",{className:u.length>=z?"text-red-600 font-semibold":"",children:[u.length,"/",z]})}),T.jsx("button",{type:"button",onClick:Me,disabled:ke||u.trim().length===0,className:`flex h-9 w-9 items-center justify-center rounded-full transition ${u.trim().length>0&&!ke?"bg-[#10a37f] text-white hover:bg-[#0f8f6f]":"bg-gray-200 text-gray-400 dark:bg-[#2f313a] dark:text-[#6b6f7a]"} disabled:cursor-not-allowed`,title:"Send thread message",children:B?T.jsx(ng,{className:"h-4 w-4 animate-spin"}):T.jsx(QX,{className:"h-4 w-4"})})]})]})})]})]})]})]})}function prt(e=800,t=100,r="sine"){try{if(typeof window>"u"){Xe("[SoundEffects] Window is not available for audio playback");return}const n=window.AudioContext??window.webkitAudioContext;if(!n){Xe("[SoundEffects] AudioContext not supported in this browser");return}const i=new n,A=i.createOscillator(),a=i.createGain();A.connect(a),a.connect(i.destination),A.frequency.value=e,A.type=r,a.gain.setValueAtTime(.3,i.currentTime),a.gain.exponentialRampToValueAtTime(.01,i.currentTime+t/1e3),A.start(i.currentTime),A.stop(i.currentTime+t/1e3)}catch{}}const mrt={messageSent:{frequency:600,duration:80,type:"sine"},messageReceived:{frequency:800,duration:100,type:"sine"},success:{frequency:1e3,duration:150,type:"sine"},error:{frequency:400,duration:200,type:"square"},notification:{frequency:700,duration:120,type:"sine"}};function Bh(e,t){if(!t)return;const r=mrt[e];if(r)try{prt(r.frequency,r.duration,r.type),Xe(`[SoundEffects] Playing ${e} sound effect`)}catch{}}function wrt({messages:e,onRegenerate:t,onStartThread:r,onSendThreadMessage:n,sessionId:i,isLoading:A}){const a=F.useRef(null),s=F.useRef(null),o=F.useRef(e.length),l=F.useRef(""),c=F.useRef(A),u=F.useRef(!0),{settings:g}=cy(),{topLevelMessages:h,threadLookup:d}=F.useMemo(()=>{const w=new Map,f=[];return e.forEach(I=>{if(I.isThreadMessage&&I.parentMessageId){const Y=w.get(I.parentMessageId)||[];w.set(I.parentMessageId,[...Y,I]);return}f.push(I)}),{topLevelMessages:f,threadLookup:w}},[e]),B=()=>{if(!s.current)return;const{scrollTop:w,scrollHeight:f,clientHeight:I}=s.current,Q=f-w-I<200;u.current=Q},y=(w="smooth")=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{a.current?a.current.scrollIntoView({behavior:w}):s.current&&(s.current.scrollTop=s.current.scrollHeight)})})};return F.useEffect(()=>{const w=e.length,f=o.current,I=w>f,Y=e[e.length-1],Q=(Y==null?void 0:Y.content)||"",M=Q!==l.current;I||Y!=null&&Y.isStreaming||M&&(Y==null?void 0:Y.role)==="assistant"?(y(I?"auto":"smooth"),u.current=!0):u.current&&M&&y("smooth"),o.current=w,l.current=Q},[e]),F.useEffect(()=>{A&&(y("auto"),u.current=!0)},[A]),F.useEffect(()=>{if(c.current&&!A){const w=e[e.length-1];(w==null?void 0:w.role)==="assistant"&&w.content&&Bh("messageReceived",g.soundEnabled)}c.current=A},[A,e,g.soundEnabled]),h.length===0?T.jsx("div",{className:"flex-1 flex items-center justify-center px-4 sm:px-6",children:T.jsxs("div",{className:"text-center text-lg text-gray-500 dark:text-[#bfc2cd]",children:[T.jsx("p",{className:"text-xl",children:"Your messages will appear here."}),T.jsx("p",{className:"mt-1 text-lg",children:"Start the conversation by sending a prompt below."})]})}):T.jsx("div",{ref:s,className:"message-list flex-1 overflow-y-auto py-6",onScroll:B,children:T.jsxs("div",{className:"space-y-6 px-3 sm:px-4",children:[h.map(w=>T.jsx(Brt,{message:w,onRegenerate:t,onStartThread:r,onSendThreadMessage:n,threadMessages:d.get(w.id),sessionId:i,isThreadSendDisabled:A},w.id)),T.jsx("div",{ref:a,className:"h-8"})]})})}const frt=2e3;function yrt(e,t){const[r,n]=F.useState(!1),[i,A]=F.useState(null),a=F.useRef(null),s=F.useRef(""),o=F.useRef(!1),l=F.useRef(null),c=F.useCallback(()=>{if(!s.current)return;const w=s.current;s.current="",e(" "+w)},[e]),u=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),g=F.useCallback(()=>{!t||o.current||(o.current=!0,t())},[t]),h=F.useCallback(()=>{l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),d=F.useCallback(()=>{h(),l.current=setTimeout(()=>{a.current?a.current.stop():g()},frt)},[h,g]),B=F.useCallback(()=>{if(!u){A("Speech recognition is not supported in this browser. Please try Chrome, Edge, or Safari.");return}if(!r)try{o.current=!1;const w=window.SpeechRecognition||window.webkitSpeechRecognition,f=new w;f.continuous=!0,f.interimResults=!0,f.lang=navigator.language||"en-US",f.maxAlternatives=1,f.onstart=()=>{n(!0),A(null),Xe("Speech recognition started"),d()},f.onresult=I=>{let Y="",Q="";for(let M=I.resultIndex;M<I.results.length;M++){const D=I.results[M][0].transcript;I.results[M].isFinal?Y+=D:Q+=D}Q&&(s.current=Q),Y&&(s.current="",e(" "+Y)),d()},f.onend=()=>{h(),c(),n(!1),a.current=null,Xe("Speech recognition ended"),g()},f.onerror=I=>{switch(h(),zg("Speech recognition error:",I.error),n(!1),a.current=null,s.current="",g(),I.error){case"no-speech":A("No speech detected. Please try again.");break;case"audio-capture":A("Microphone access denied. Please allow microphone access and try again.");break;case"not-allowed":A("Microphone access not allowed. Please enable microphone permissions.");break;case"network":A("Network error occurred. Please check your connection.");break;default:A(`Speech recognition error: ${I.error}`)}},f.start(),a.current=f}catch{A("Failed to start speech recognition. Please try again."),n(!1)}},[u,e,r,c,g,d,h]),y=F.useCallback(()=>{if(a.current){const w=a.current;w.onend=null,w.onerror=null,w.onresult=null,w.onstart=null;try{w.stop()}catch{}a.current=null}h(),c(),n(!1),A(null),g()},[h,c,g]);return{isListening:r,isSupported:u,startListening:B,stopListening:y,error:i}}const Ert="2.3.2",Irt={"@schmitech/chatbot-api":"^2.1.1"},yle={version:Ert,dependencies:Irt},Ele=yle.version,_K=yle.dependencies["@schmitech/chatbot-api"];async function HD(){try{return(await rr(()=>import("./api-LelnGrLi.js"),[])).version||_K}catch{return _K}}async function Ile(){const e=await HD();return{appVersion:Ele,apiVersion:e,isLocalApi:!1}}let Ps=null;function q0(){let e=null,t=null;const r=(i,A,a,s)=>{e=a||null,t=s||null},n=()=>{if(!t)throw new Error("Adapter name is required when middleware is enabled");return{async*streamChat(i,A,a,s,o,l,c,u,g,h,d){var w,f;const B={messages:[{role:"user",content:i}],stream:A!==!1};a&&a.length>0&&(B.file_ids=a),s&&(B.thread_id=s),o&&(B.audio_input=o),l&&(B.audio_format=l),c&&(B.language=c),u!==void 0&&(B.return_audio=u),g&&(B.tts_voice=g),h&&(B.source_language=h),d&&(B.target_language=d);const y=await fetch("/api/proxy/v1/chat",{method:"POST",headers:{"Content-Type":"application/json","X-Adapter-Name":t,...e?{"X-Session-ID":e}:{}},body:JSON.stringify(B)});if(!y.ok)throw new Error(`API request failed: ${y.status} ${y.statusText}`);if((w=y.headers.get("content-type"))!=null&&w.includes("text/event-stream")){const I=(f=y.body)==null?void 0:f.getReader(),Y=new TextDecoder;let Q="";if(!I)throw new Error("Response body is not readable");for(;;){const{done:M,value:D}=await I.read();if(M)break;Q+=Y.decode(D,{stream:!0});const G=Q.split(`
|
|
1210
|
+
... (content truncated due to length)`}const xr={maxFilesPerConversation:hs.maxFilesPerConversation,maxFileSizeMB:hs.maxFileSizeMB,maxTotalFiles:hs.maxTotalFiles,maxConversations:hs.maxConversations,maxMessagesPerConversation:hs.maxMessagesPerConversation,maxTotalMessages:hs.maxTotalMessages,maxMessageLength:hs.maxMessageLength},drt=[];function Brt({message:e,onRegenerate:t,onStartThread:r,onSendThreadMessage:n,threadMessages:i,sessionId:A,isThreadSendDisabled:a}){var xe,Ie;const[s,o]=F.useState(!1),[l,c]=F.useState(null),[u,g]=F.useState(""),[h,d]=F.useState(!1),[B,y]=F.useState(!1),w=F.useRef(((xe=e.threadInfo)==null?void 0:xe.thread_id)||null),f=F.useRef(null),I=e.role==="assistant",Y=i??drt,Q=Y.filter(Se=>Se.role==="assistant").length,M=Y.some(Se=>Se.isStreaming),D="en-US",G=crt(),z=xr.maxMessageLength,{theme:R,isDark:j}=EX(),W=R.mode==="dark"?"dark":R.mode==="light"?"light":"",te=j?"dark":"light",X=F.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",W].filter(Boolean).join(" "),[W]),Z=F.useMemo(()=>["message-markdown w-full min-w-0","prose prose-invert max-w-none",W].filter(Boolean).join(" "),[W]),ee=I?X:Z,Ae=`${X} text-sm leading-6`,K=`${Z} text-sm leading-6`;F.useEffect(()=>{var Se,Te;!w.current&&((Se=e.threadInfo)!=null&&Se.thread_id)&&d(!0),w.current=((Te=e.threadInfo)==null?void 0:Te.thread_id)||null},[(Ie=e.threadInfo)==null?void 0:Ie.thread_id]),F.useEffect(()=>{e.threadInfo||(g(""),d(!1),y(!1))},[e.threadInfo]),F.useEffect(()=>{Q>0&&d(!0)},[Q]);const $=F.useMemo(()=>{const Se=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp),Te=Se.toLocaleDateString(D,{weekday:"short"}),Ke=Se.toLocaleDateString(D,{month:"short"}),et=Se.getDate().toString().padStart(2,"0"),rt=Se.getFullYear(),It=Se.toLocaleTimeString(D,{hour:"2-digit",minute:"2-digit",hour12:!0});return`${Te}, ${Ke} ${et}, ${rt} ${It}`},[e.timestamp,D]),L=I?"bg-gradient-to-br from-blue-100 to-blue-200 text-blue-900 dark:from-[#1f2a36] dark:to-[#1a2230] dark:text-[#c5d7ff]":"bg-gradient-to-br from-emerald-100 to-emerald-200 text-emerald-900 dark:from-[#0f1f17] dark:to-[#0b1712] dark:text-[#c7f5df]",ne=`message-bubble min-w-0 break-words leading-relaxed ${I?"border border-blue-100/80 bg-transparent text-[#0f172a] shadow-[0_15px_35px_-20px_rgba(15,23,42,0.25)] dark:border-[#1f2a36] dark:bg-transparent dark:text-[#e5edff]":"border border-emerald-100 bg-transparent text-[#1c3226] shadow-[0_12px_30px_-18px_rgba(15,52,33,0.25)] dark:border-[#1a2b21] dark:bg-transparent dark:text-[#dffbea]"} rounded-2xl px-4 py-3`,ge=I?"border-blue-100 bg-white/80 dark:border-[#1f2a36] dark:bg-white/5":"border-emerald-100 bg-white/80 dark:border-[#1a2b21] dark:bg-white/5",P=async()=>{try{await navigator.clipboard.writeText(e.content),o(!0),setTimeout(()=>o(!1),2e3)}catch{}},Be=Se=>{c(l===Se?null:Se)},Fe=F.useCallback(Se=>(Se instanceof Date?Se:new Date(Se)).toLocaleTimeString(D,{hour:"2-digit",minute:"2-digit"}),[D]),Me=async()=>{if(!n||!e.threadInfo)return;const Se=u.trim();if(Se){y(!0);try{await n(e.threadInfo.thread_id,e.id,Se),g(""),setTimeout(()=>{f.current&&f.current.focus()},100)}catch{setTimeout(()=>{f.current&&f.current.focus()},100)}finally{y(!1)}}},pe=Se=>{Se.key==="Enter"&&!Se.shiftKey&&(Se.preventDefault(),Me())},ke=!e.threadInfo||!n||a||M||B;F.useEffect(()=>{if(!h||ke)return;const Se=f.current;if(!Se)return;const Te=requestAnimationFrame(()=>{Se.focus();const Ke=Se.value.length;Se.setSelectionRange(Ke,Ke)});return()=>cancelAnimationFrame(Te)},[h,ke,B]),F.useEffect(()=>{if(f.current){const Te=f.current;Te.style.height="auto";const Ke=Te.scrollHeight;Te.style.height=`${Math.min(Ke,120)}px`,Te.style.overflowY=Ke>120?"auto":"hidden"}},[u]);const Ee=F.useMemo(()=>e.isStreaming&&(!e.content||e.content==="…")?T.jsx("div",{className:ee,children:T.jsxs("div",{className:"flex items-center gap-1.5 py-1",children:[T.jsx("span",{className:"inline-block h-2.5 w-2.5 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"0ms"}}),T.jsx("span",{className:"inline-block h-2.5 w-2.5 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"150ms"}}),T.jsx("span",{className:"inline-block h-2.5 w-2.5 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"300ms"}})]})}):T.jsx(VK,{content:LD(Lh(e.content||"")),className:ee,syntaxTheme:te}),[ee,e.content,e.isStreaming,te]),je=F.useMemo(()=>[...Y].sort((Te,Ke)=>{const et=Te.timestamp instanceof Date?Te.timestamp.getTime():new Date(Te.timestamp).getTime(),rt=Ke.timestamp instanceof Date?Ke.timestamp.getTime():new Date(Ke.timestamp).getTime();return et-rt}).map(Te=>{const Ke=Te.role==="assistant",et=Ke?Ae:K,rt=Te.isStreaming&&(!Te.content||Te.content==="…")?T.jsx("div",{className:et,children:T.jsxs("div",{className:"flex items-center gap-1.5 py-1",children:[T.jsx("span",{className:"inline-block h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"0ms"}}),T.jsx("span",{className:"inline-block h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"150ms"}}),T.jsx("span",{className:"inline-block h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]",style:{animationDelay:"300ms"}})]})}):T.jsx(VK,{content:LD(Lh(Te.content||"")),className:et,syntaxTheme:te});return T.jsxs("div",{className:"flex items-start gap-3",children:[T.jsx("div",{className:`mt-0.5 flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-full ${Ke?"bg-blue-100 text-blue-700 dark:bg-[#1f2a36] dark:text-[#c5d7ff]":"bg-emerald-100 text-emerald-700 dark:bg-[#1f2a36] dark:text-[#9ef0d5]"}`,children:Ke?T.jsx(eR,{className:"h-3.5 w-3.5"}):T.jsx(rR,{className:"h-3.5 w-3.5"})}),T.jsxs("div",{className:"flex-1 min-w-0 rounded-2xl border border-white/70 bg-white/90 px-4 py-3 text-sm shadow-sm dark:border-white/5 dark:bg-white/5 backdrop-blur overflow-hidden",children:[T.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] font-semibold uppercase tracking-wide text-blue-900/70 dark:text-[#c5d7ff]",children:[T.jsx("span",{children:Ke?"Assistant":"You"}),T.jsx("span",{children:Fe(Te.timestamp)})]}),T.jsx("div",{className:"thread-markdown-wrapper overflow-x-auto",children:rt})]})]},Te.id)}),[Fe,te,Ae,Y,K]);return T.jsxs("div",{className:"group flex items-start gap-3 px-1 animate-fadeIn min-w-0 sm:px-0",children:[T.jsx("div",{className:`flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full self-start -mt-2 ml-1 shadow-sm ring-2 ring-white/50 dark:ring-white/10 sm:-mt-3 sm:ml-2 ${L}`,children:I?T.jsx(eR,{className:"h-5 w-5"}):T.jsx(rR,{className:"h-5 w-5"})}),T.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[T.jsxs("div",{className:"flex flex-col gap-1.5 mb-1",children:[T.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-700 dark:text-[#ececf1]",children:I?"Assistant":"You"}),T.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:$})]}),T.jsxs("div",{className:ne,children:[Ee,e.attachments&&e.attachments.length>0&&T.jsx("div",{className:"mt-3 space-y-2",children:e.attachments.map(Se=>T.jsxs("div",{className:`flex items-center gap-3 rounded-xl border p-3 ${ge}`,children:[T.jsx(B0e,{className:"h-4 w-4 text-gray-500 dark:text-[#bfc2cd]"}),T.jsxs("div",{className:"min-w-0 flex-1",children:[T.jsx("p",{className:"truncate text-sm font-medium text-[#353740] dark:text-[#ececf1]",children:Se.filename}),T.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[(Se.file_size/1024).toFixed(1)," KB"]})]})]},Se.file_id))}),e.audio&&I&&!e.isStreaming&&T.jsx(grt,{audio:e.audio,audioFormat:e.audioFormat,autoPlay:!1})]}),I&&!e.isStreaming&&T.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-gray-500 transition-opacity dark:text-[#bfc2cd] sm:opacity-0 sm:group-hover:opacity-100",children:[T.jsxs("button",{onClick:P,className:"inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a]",title:"Copy message",children:[T.jsx(g0e,{className:"h-4 w-4"}),"Copy"]}),t&&T.jsxs("button",{onClick:()=>t(e.id),className:"inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a]",title:"Regenerate response",children:[T.jsx(b0e,{className:"h-4 w-4"}),"Retry"]}),G&&r&&e.supportsThreading&&!e.threadInfo&&A&&T.jsxs("button",{onClick:()=>r(e.id,A),className:"inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a]",title:"Start thread for follow-up questions",children:[T.jsx(Mh,{className:"h-4 w-4"}),"Start Thread"]}),lrt()&&T.jsxs("div",{className:"flex items-center gap-1",children:[T.jsx("button",{onClick:()=>Be("up"),className:`rounded p-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a] ${l==="up"?"text-[#353740] dark:text-[#ececf1]":""}`,title:"Good response",children:T.jsx(k0e,{className:"h-4 w-4"})}),T.jsx("button",{onClick:()=>Be("down"),className:`rounded p-1 hover:bg-gray-200 dark:hover:bg-[#3c3f4a] ${l==="down"?"text-[#353740] dark:text-[#ececf1]":""}`,title:"Poor response",children:T.jsx(D0e,{className:"h-4 w-4"})})]}),s&&T.jsx("span",{children:"Copied"})]}),G&&e.threadInfo&&T.jsxs("div",{className:"ml-12 mt-4 rounded-xl border border-blue-100/80 bg-blue-50/70 p-4 text-sm shadow-sm ring-1 ring-blue-100/60 dark:border-[#1f2a36] dark:bg-[#0f1821] dark:ring-[#1f2a36]",children:[T.jsxs("div",{className:"flex items-center justify-between text-sm font-semibold text-blue-900 dark:text-[#c5d7ff]",children:[T.jsxs("div",{className:"inline-flex items-center gap-2 uppercase tracking-wide",children:[T.jsx(Mh,{className:"h-3.5 w-3.5"}),T.jsxs("span",{children:["Thread replies",Q>0?` (${Q})`:""]})]}),T.jsx("button",{onClick:()=>d(Se=>!Se),className:"inline-flex items-center gap-2 rounded-full border border-blue-200/80 px-3 py-1.5 text-xs uppercase tracking-wide text-blue-900 transition hover:bg-white/70 dark:border-[#233449] dark:text-[#c5d7ff] dark:hover:bg-white/10",children:h?T.jsxs(T.Fragment,{children:["Hide ",T.jsx(u0e,{className:"h-3 w-3"})]}):T.jsxs(T.Fragment,{children:["Show ",T.jsx(MX,{className:"h-3 w-3"})]})})]}),h&&T.jsxs(T.Fragment,{children:[T.jsx("div",{className:"mt-3 space-y-3",children:je}),T.jsx("div",{className:"mt-3 rounded-xl border border-white/80 bg-white/95 p-3 shadow-sm dark:border-white/10 dark:bg-white/10",children:T.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[T.jsx("textarea",{ref:f,className:"flex-1 min-w-0 resize-none rounded-md border border-transparent bg-transparent px-3 py-1.5 text-sm text-[#353740] placeholder-gray-600 outline-none transition focus:border-gray-400 focus:ring-1 focus:ring-gray-300 disabled:opacity-60 dark:text-[#ececf1] dark:placeholder-[#bfc2cd] dark:focus:border-[#8e8ea0] dark:focus:ring-[#8e8ea0]",placeholder:Q>0?"Reply in thread...":"Ask a follow-up...",value:u,onChange:Se=>g(Se.target.value),onKeyDown:pe,disabled:ke,rows:1,maxLength:z,style:{minHeight:"38px",maxHeight:"120px",border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none"}}),T.jsxs("div",{className:"flex items-center gap-2",children:[u.length>0&&T.jsx("div",{className:"text-xs text-gray-500 dark:text-[#bfc2cd] whitespace-nowrap",children:T.jsxs("span",{className:u.length>=z?"text-red-600 font-semibold":"",children:[u.length,"/",z]})}),T.jsx("button",{type:"button",onClick:Me,disabled:ke||u.trim().length===0,className:`flex h-9 w-9 items-center justify-center rounded-full transition ${u.trim().length>0&&!ke?"bg-[#10a37f] text-white hover:bg-[#0f8f6f]":"bg-gray-200 text-gray-400 dark:bg-[#2f313a] dark:text-[#6b6f7a]"} disabled:cursor-not-allowed`,title:"Send thread message",children:B?T.jsx(ng,{className:"h-4 w-4 animate-spin"}):T.jsx(QX,{className:"h-4 w-4"})})]})]})})]})]})]})]})}function prt(e=800,t=100,r="sine"){try{if(typeof window>"u"){Xe("[SoundEffects] Window is not available for audio playback");return}const n=window.AudioContext??window.webkitAudioContext;if(!n){Xe("[SoundEffects] AudioContext not supported in this browser");return}const i=new n,A=i.createOscillator(),a=i.createGain();A.connect(a),a.connect(i.destination),A.frequency.value=e,A.type=r,a.gain.setValueAtTime(.3,i.currentTime),a.gain.exponentialRampToValueAtTime(.01,i.currentTime+t/1e3),A.start(i.currentTime),A.stop(i.currentTime+t/1e3)}catch{}}const mrt={messageSent:{frequency:600,duration:80,type:"sine"},messageReceived:{frequency:800,duration:100,type:"sine"},success:{frequency:1e3,duration:150,type:"sine"},error:{frequency:400,duration:200,type:"square"},notification:{frequency:700,duration:120,type:"sine"}};function Bh(e,t){if(!t)return;const r=mrt[e];if(r)try{prt(r.frequency,r.duration,r.type),Xe(`[SoundEffects] Playing ${e} sound effect`)}catch{}}function wrt({messages:e,onRegenerate:t,onStartThread:r,onSendThreadMessage:n,sessionId:i,isLoading:A}){const a=F.useRef(null),s=F.useRef(null),o=F.useRef(e.length),l=F.useRef(""),c=F.useRef(A),u=F.useRef(!0),{settings:g}=cy(),{topLevelMessages:h,threadLookup:d}=F.useMemo(()=>{const w=new Map,f=[];return e.forEach(I=>{if(I.isThreadMessage&&I.parentMessageId){const Y=w.get(I.parentMessageId)||[];w.set(I.parentMessageId,[...Y,I]);return}f.push(I)}),{topLevelMessages:f,threadLookup:w}},[e]),B=()=>{if(!s.current)return;const{scrollTop:w,scrollHeight:f,clientHeight:I}=s.current,Q=f-w-I<200;u.current=Q},y=(w="smooth")=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{a.current?a.current.scrollIntoView({behavior:w}):s.current&&(s.current.scrollTop=s.current.scrollHeight)})})};return F.useEffect(()=>{const w=e.length,f=o.current,I=w>f,Y=e[e.length-1],Q=(Y==null?void 0:Y.content)||"",M=Q!==l.current;I||Y!=null&&Y.isStreaming||M&&(Y==null?void 0:Y.role)==="assistant"?(y(I?"auto":"smooth"),u.current=!0):u.current&&M&&y("smooth"),o.current=w,l.current=Q},[e]),F.useEffect(()=>{A&&(y("auto"),u.current=!0)},[A]),F.useEffect(()=>{if(c.current&&!A){const w=e[e.length-1];(w==null?void 0:w.role)==="assistant"&&w.content&&Bh("messageReceived",g.soundEnabled)}c.current=A},[A,e,g.soundEnabled]),h.length===0?T.jsx("div",{className:"flex-1 flex items-center justify-center px-4 sm:px-6",children:T.jsxs("div",{className:"text-center text-lg text-gray-500 dark:text-[#bfc2cd]",children:[T.jsx("p",{className:"text-xl",children:"Your messages will appear here."}),T.jsx("p",{className:"mt-1 text-lg",children:"Start the conversation by sending a prompt below."})]})}):T.jsx("div",{ref:s,className:"message-list flex-1 overflow-y-auto py-6",onScroll:B,children:T.jsxs("div",{className:"space-y-6 px-3 sm:px-4",children:[h.map(w=>T.jsx(Brt,{message:w,onRegenerate:t,onStartThread:r,onSendThreadMessage:n,threadMessages:d.get(w.id),sessionId:i,isThreadSendDisabled:A},w.id)),T.jsx("div",{ref:a,className:"h-8"})]})})}const frt=2e3;function yrt(e,t){const[r,n]=F.useState(!1),[i,A]=F.useState(null),a=F.useRef(null),s=F.useRef(""),o=F.useRef(!1),l=F.useRef(null),c=F.useCallback(()=>{if(!s.current)return;const w=s.current;s.current="",e(" "+w)},[e]),u=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),g=F.useCallback(()=>{!t||o.current||(o.current=!0,t())},[t]),h=F.useCallback(()=>{l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),d=F.useCallback(()=>{h(),l.current=setTimeout(()=>{a.current?a.current.stop():g()},frt)},[h,g]),B=F.useCallback(()=>{if(!u){A("Speech recognition is not supported in this browser. Please try Chrome, Edge, or Safari.");return}if(!r)try{o.current=!1;const w=window.SpeechRecognition||window.webkitSpeechRecognition,f=new w;f.continuous=!0,f.interimResults=!0,f.lang=navigator.language||"en-US",f.maxAlternatives=1,f.onstart=()=>{n(!0),A(null),Xe("Speech recognition started"),d()},f.onresult=I=>{let Y="",Q="";for(let M=I.resultIndex;M<I.results.length;M++){const D=I.results[M][0].transcript;I.results[M].isFinal?Y+=D:Q+=D}Q&&(s.current=Q),Y&&(s.current="",e(" "+Y)),d()},f.onend=()=>{h(),c(),n(!1),a.current=null,Xe("Speech recognition ended"),g()},f.onerror=I=>{switch(h(),zg("Speech recognition error:",I.error),n(!1),a.current=null,s.current="",g(),I.error){case"no-speech":A("No speech detected. Please try again.");break;case"audio-capture":A("Microphone access denied. Please allow microphone access and try again.");break;case"not-allowed":A("Microphone access not allowed. Please enable microphone permissions.");break;case"network":A("Network error occurred. Please check your connection.");break;default:A(`Speech recognition error: ${I.error}`)}},f.start(),a.current=f}catch{A("Failed to start speech recognition. Please try again."),n(!1)}},[u,e,r,c,g,d,h]),y=F.useCallback(()=>{if(a.current){const w=a.current;w.onend=null,w.onerror=null,w.onresult=null,w.onstart=null;try{w.stop()}catch{}a.current=null}h(),c(),n(!1),A(null),g()},[h,c,g]);return{isListening:r,isSupported:u,startListening:B,stopListening:y,error:i}}const Ert="2.3.3",Irt={"@schmitech/chatbot-api":"^2.1.1"},yle={version:Ert,dependencies:Irt},Ele=yle.version,_K=yle.dependencies["@schmitech/chatbot-api"];async function HD(){try{return(await rr(()=>import("./api-CvFCgVm7.js"),[])).version||_K}catch{return _K}}async function Ile(){const e=await HD();return{appVersion:Ele,apiVersion:e,isLocalApi:!1}}let Ps=null;function q0(){let e=null,t=null;const r=(i,A,a,s)=>{e=a||null,t=s||null},n=()=>{if(!t)throw new Error("Adapter name is required when middleware is enabled");return{async*streamChat(i,A,a,s,o,l,c,u,g,h,d){var w,f;const B={messages:[{role:"user",content:i}],stream:A!==!1};a&&a.length>0&&(B.file_ids=a),s&&(B.thread_id=s),o&&(B.audio_input=o),l&&(B.audio_format=l),c&&(B.language=c),u!==void 0&&(B.return_audio=u),g&&(B.tts_voice=g),h&&(B.source_language=h),d&&(B.target_language=d);const y=await fetch("/api/proxy/v1/chat",{method:"POST",headers:{"Content-Type":"application/json","X-Adapter-Name":t,...e?{"X-Session-ID":e}:{}},body:JSON.stringify(B)});if(!y.ok)throw new Error(`API request failed: ${y.status} ${y.statusText}`);if((w=y.headers.get("content-type"))!=null&&w.includes("text/event-stream")){const I=(f=y.body)==null?void 0:f.getReader(),Y=new TextDecoder;let Q="";if(!I)throw new Error("Response body is not readable");for(;;){const{done:M,value:D}=await I.read();if(M)break;Q+=Y.decode(D,{stream:!0});const G=Q.split(`
|
|
1211
1211
|
`);Q=G.pop()||"";for(const z of G)if(z.startsWith("data: "))try{const R=JSON.parse(z.substring(6));yield{text:R.text||R.content||R.message||R.response||"",done:R.done||!1,audio:R.audio,audioFormat:R.audio_format||R.audioFormat,audio_chunk:R.audio_chunk,chunk_index:R.chunk_index,threading:R.threading}}catch{}}if(Q.trim()){const M=Q.split(`
|
|
1212
|
-
`);for(const D of M)if(D.startsWith("data: "))try{const G=JSON.parse(D.substring(6));yield{text:G.text||G.content||G.message||G.response||"",done:G.done||!1,audio:G.audio,audioFormat:G.audio_format||G.audioFormat,audio_chunk:G.audio_chunk,chunk_index:G.chunk_index,threading:G.threading}}catch{}}}else{const I=await y.json();yield{text:I.message||I.response||"",done:!0}}},async createThread(i,A){const a=await fetch("/api/proxy/api/threads",{method:"POST",headers:{"Content-Type":"application/json","X-Adapter-Name":t,"X-Session-ID":A},body:JSON.stringify({message_id:i,session_id:A})});if(!a.ok)throw new Error(`Failed to create thread: ${a.statusText}`);return a.json()},async getThreadInfo(i){const A=await fetch(`/api/proxy/api/threads/${i}`,{headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to get thread info: ${A.statusText}`);return A.json()},async deleteThread(i){const A=await fetch(`/api/proxy/api/threads/${i}`,{method:"DELETE",headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to delete thread: ${A.statusText}`);return A.json()},async clearConversationHistory(i){const A=await fetch(`/api/proxy/admin/chat-history/${i||e}`,{method:"DELETE",headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to clear history: ${A.statusText}`);return A.json()},async deleteConversationWithFiles(i,A){const a=i||e,s=A&&A.length>0?`?file_ids=${A.join(",")}`:"",o=await fetch(`/api/proxy/admin/conversations/${a}${s}`,{method:"DELETE",headers:{"X-Adapter-Name":t}});if(!o.ok)throw new Error(`Failed to delete conversation: ${o.statusText}`);return o.json()},getSessionId:()=>e,async uploadFile(i){const A=new FormData;A.append("file",i);const a=await fetch("/api/proxy/api/files/upload",{method:"POST",headers:{"X-Adapter-Name":t},body:A});if(!a.ok)throw new Error(`Failed to upload file: ${a.statusText}`);return a.json()},async listFiles(){const i=await fetch("/api/proxy/api/files",{headers:{"X-Adapter-Name":t}});if(!i.ok)throw new Error(`Failed to list files: ${i.statusText}`);const A=await i.json();return Array.isArray(A)?A:A.files||[]},async getFileInfo(i){const A=await fetch(`/api/proxy/api/files/${i}`,{headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to get file info: ${A.statusText}`);return A.json()},async queryFile(i,A,a){const s=await fetch(`/api/proxy/api/files/${i}/query`,{method:"POST",headers:{"Content-Type":"application/json","X-Adapter-Name":t},body:JSON.stringify({query:A,max_results:a})});if(!s.ok)throw new Error(`Failed to query file: ${s.statusText}`);return s.json()},async deleteFile(i){const A=await fetch(`/api/proxy/api/files/${i}`,{method:"DELETE",headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to delete file: ${A.statusText}`);return A.json()},async validateApiKey(){const i=await fetch(`/api/proxy/admin/api-keys/${t}/status`,{headers:{"X-Adapter-Name":t}});if(!i.ok)throw new Error(`Failed to validate API key: ${i.statusText}`);return i.json()},async getAdapterInfo(){const i=await fetch("/api/proxy/admin/api-keys/info",{headers:{"X-Adapter-Name":t}});if(!i.ok){const A=await i.text();throw new Error(`Failed to get adapter info: ${i.status} ${i.statusText} - ${A}`)}return i.json()}}};return{configureApi:r,streamChat:async function*(i,A,a,s,o,l,c,u,g,h,d){yield*n().streamChat(i,A,a,s,o,l,c,u,g,h,d)},ApiClient:class{constructor(A){gA(this,"client");t=A.adapterName||null,e=A.sessionId||null,this.client=n()}async*streamChat(...A){yield*this.client.streamChat(...A)}get createThread(){var A;return(A=this.client.createThread)==null?void 0:A.bind(this.client)}get getThreadInfo(){var A;return(A=this.client.getThreadInfo)==null?void 0:A.bind(this.client)}get deleteThread(){var A;return(A=this.client.deleteThread)==null?void 0:A.bind(this.client)}get clearConversationHistory(){var A;return(A=this.client.clearConversationHistory)==null?void 0:A.bind(this.client)}get deleteConversationWithFiles(){var A;return(A=this.client.deleteConversationWithFiles)==null?void 0:A.bind(this.client)}get getSessionId(){var A;return(A=this.client.getSessionId)==null?void 0:A.bind(this.client)}get uploadFile(){var A;return(A=this.client.uploadFile)==null?void 0:A.bind(this.client)}get listFiles(){var A;return(A=this.client.listFiles)==null?void 0:A.bind(this.client)}get getFileInfo(){var A;return(A=this.client.getFileInfo)==null?void 0:A.bind(this.client)}get queryFile(){var A;return(A=this.client.queryFile)==null?void 0:A.bind(this.client)}get deleteFile(){var A;return(A=this.client.deleteFile)==null?void 0:A.bind(this.client)}get validateApiKey(){var A;return(A=this.client.validateApiKey)==null?void 0:A.bind(this.client)}get getAdapterInfo(){var A;return(A=this.client.getAdapterInfo)==null?void 0:A.bind(this.client)}}}}async function Crt(e){return e==="@local-node-api/api.mjs"?rr(()=>import("./api-BHF9IxKN.js"),[]):import(e)}async function Qrt(){if(Ps)return Ps;const e=Art(),t=art(),r=Ii();try{if(e){let n;t?t.startsWith("/")?n=t.startsWith("/src/")?`.${t.substring(4)}${t.endsWith(".mjs")?"":"/api.mjs"}`:"../../../node-api/dist/api.mjs":t.startsWith("../")||t.startsWith("./")?n=t.endsWith(".mjs")?t:`${t}/api.mjs`:n=`./${t}${t.endsWith(".mjs")?"":"/api.mjs"}`:n="../../../node-api/dist/api.mjs",Xe(`🔧 Loading local API from: ${n}`);const i=await Crt(n);r?(Xe("🔐 API Middleware enabled - routing through proxy"),Ps=q0()):Ps={configureApi:i.configureApi,streamChat:i.streamChat,ApiClient:i.ApiClient},Xe("✅ Local API loaded successfully")}else{Xe("📦 Loading npm package API");const n=await rr(()=>import("./api-LelnGrLi.js"),[]),i=async function*(s,o,l,c,u,g,h,d,B,y,w){yield*n.streamChat(s,o,l,c,u,g,h,d,B,y,w)};class A{constructor(o){gA(this,"client");if(r&&o.adapterName){const l=q0();this.client=new l.ApiClient(o)}else this.client=new n.ApiClient(o)}async*streamChat(o,l,c,u,g,h,d,B,y,w,f){yield*this.client.streamChat(o,l,c,u,g,h,d,B,y,w,f)}get createThread(){var o;return(o=this.client.createThread)==null?void 0:o.bind(this.client)}get getThreadInfo(){var o;return(o=this.client.getThreadInfo)==null?void 0:o.bind(this.client)}get deleteThread(){var o;return(o=this.client.deleteThread)==null?void 0:o.bind(this.client)}get clearConversationHistory(){var o;return(o=this.client.clearConversationHistory)==null?void 0:o.bind(this.client)}get deleteConversationWithFiles(){var o;return(o=this.client.deleteConversationWithFiles)==null?void 0:o.bind(this.client)}get getSessionId(){var o;return(o=this.client.getSessionId)==null?void 0:o.bind(this.client)}get uploadFile(){var o;return(o=this.client.uploadFile)==null?void 0:o.bind(this.client)}get listFiles(){var o;return(o=this.client.listFiles)==null?void 0:o.bind(this.client)}get getFileInfo(){var o;return(o=this.client.getFileInfo)==null?void 0:o.bind(this.client)}get queryFile(){var o;return(o=this.client.queryFile)==null?void 0:o.bind(this.client)}get deleteFile(){var o;return(o=this.client.deleteFile)==null?void 0:o.bind(this.client)}get validateApiKey(){var o;return(o=this.client.validateApiKey)==null?void 0:o.bind(this.client)}get getAdapterInfo(){var o;return(o=this.client.getAdapterInfo)==null?void 0:o.bind(this.client)}}r?(Xe("🔐 API Middleware enabled - routing through proxy"),Ps=q0()):Ps={configureApi:n.configureApi,streamChat:i,ApiClient:A};const a=await HD();Xe(`✅ NPM package API loaded successfully (v${a})`)}}catch(n){if(e)try{const i=await rr(()=>import("./api-LelnGrLi.js"),[]),A=async function*(o,l,c,u,g,h,d,B,y,w,f){yield*i.streamChat(o,l,c,u,g,h,d,B,y,w,f)};class a{constructor(l){gA(this,"client");if(r&&l.adapterName){const c=q0();this.client=new c.ApiClient(l)}else this.client=new i.ApiClient(l)}async*streamChat(l,c,u,g,h,d,B,y,w,f,I){yield*this.client.streamChat(l,c,u,g,h,d,B,y,w,f,I)}get createThread(){var l;return(l=this.client.createThread)==null?void 0:l.bind(this.client)}get getThreadInfo(){var l;return(l=this.client.getThreadInfo)==null?void 0:l.bind(this.client)}get deleteThread(){var l;return(l=this.client.deleteThread)==null?void 0:l.bind(this.client)}get clearConversationHistory(){var l;return(l=this.client.clearConversationHistory)==null?void 0:l.bind(this.client)}get deleteConversationWithFiles(){var l;return(l=this.client.deleteConversationWithFiles)==null?void 0:l.bind(this.client)}get getSessionId(){var l;return(l=this.client.getSessionId)==null?void 0:l.bind(this.client)}get uploadFile(){var l;return(l=this.client.uploadFile)==null?void 0:l.bind(this.client)}get listFiles(){var l;return(l=this.client.listFiles)==null?void 0:l.bind(this.client)}get getFileInfo(){var l;return(l=this.client.getFileInfo)==null?void 0:l.bind(this.client)}get queryFile(){var l;return(l=this.client.queryFile)==null?void 0:l.bind(this.client)}get deleteFile(){var l;return(l=this.client.deleteFile)==null?void 0:l.bind(this.client)}get validateApiKey(){var l;return(l=this.client.validateApiKey)==null?void 0:l.bind(this.client)}get getAdapterInfo(){var l;return(l=this.client.getAdapterInfo)==null?void 0:l.bind(this.client)}}r?(Xe("🔐 API Middleware enabled - routing through proxy"),Ps=q0()):Ps={configureApi:i.configureApi,streamChat:A,ApiClient:a};const s=await HD();Xe(`✅ Fallback to NPM package successful (v${s})`)}catch{throw new Error("Failed to load both local and npm API packages")}else throw n}return Ps}async function li(){return await Qrt()}const im=Fc(),Mrt=()=>{try{if(typeof window>"u"||!window.localStorage)return null;const e=window.localStorage.getItem("chat-api-url");return e&&e===qc?(window.localStorage.removeItem("chat-api-url"),null):e}catch{return null}},_0=e=>{const t=e==null?void 0:e.trim();if(t)return t;const r=Mrt();return r&&r!==qc?r:Pn()},Am=()=>typeof window>"u"?null:window.CHATBOT_API_KEY||null;class Rd{static async uploadFile(t,r,n,i,A){try{const a=xr.maxFileSizeMB*1024*1024;if(t.size>a)throw new Error(`File size exceeds maximum limit of ${xr.maxFileSizeMB}MB`);if(!(["application/pdf","text/plain","text/markdown","text/csv","application/json","text/html","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","application/vnd.ms-excel.sheet.macroEnabled.12","text/x-python","text/x-python-script","text/x-java-source","text/x-java","text/x-sql","text/javascript","application/javascript","text/typescript","application/typescript","text/x-c++src","text/x-csrc","text/x-c","text/x-go","text/x-rust","text/x-ruby","text/x-php","text/x-shellscript","text/x-sh","text/yaml","text/x-yaml","text/xml","application/xml","text/css","text/x-scss","text/x-sass","text/x-less","image/png","image/jpeg","image/tiff","audio/wav","audio/mpeg","audio/mp3","audio/mp4","audio/ogg","audio/flac","audio/webm","audio/x-m4a","audio/aac","text/vtt"].includes(t.type)||/\.(pdf|txt|md|csv|json|html|docx|pptx|xlsx|py|java|sql|js|mjs|ts|tsx|cpp|cxx|cc|c|h|hpp|go|rs|rb|php|sh|bash|zsh|yaml|yml|xml|css|scss|sass|less|png|jpe?g|tiff?|wav|mp3|mp4|ogg|flac|webm|m4a|aac|vtt)$/i.test(t.name)||(t.type==="application/x-zip-compressed"||t.type==="application/zip")&&/\.xlsx$/i.test(t.name)))throw new Error(`File type not supported: ${t.type||"unknown"}`);r&&r({filename:t.name,progress:0,status:"uploading"});const l=await li(),c=_0(i),u=Ii();let g=null,h=null;if(u){if(h=A||(typeof window<"u"?localStorage.getItem("chat-adapter-name"):null),!h)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");Xe(`🔑 Using adapter: ${h}`)}else{if(g=n||localStorage.getItem("chat-api-key")||Am()||im,!g||g==="your-api-key-here")throw new Error(`API key not configured or invalid. Please:
|
|
1212
|
+
`);for(const D of M)if(D.startsWith("data: "))try{const G=JSON.parse(D.substring(6));yield{text:G.text||G.content||G.message||G.response||"",done:G.done||!1,audio:G.audio,audioFormat:G.audio_format||G.audioFormat,audio_chunk:G.audio_chunk,chunk_index:G.chunk_index,threading:G.threading}}catch{}}}else{const I=await y.json();yield{text:I.message||I.response||"",done:!0}}},async createThread(i,A){const a=await fetch("/api/proxy/api/threads",{method:"POST",headers:{"Content-Type":"application/json","X-Adapter-Name":t,"X-Session-ID":A},body:JSON.stringify({message_id:i,session_id:A})});if(!a.ok)throw new Error(`Failed to create thread: ${a.statusText}`);return a.json()},async getThreadInfo(i){const A=await fetch(`/api/proxy/api/threads/${i}`,{headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to get thread info: ${A.statusText}`);return A.json()},async deleteThread(i){const A=await fetch(`/api/proxy/api/threads/${i}`,{method:"DELETE",headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to delete thread: ${A.statusText}`);return A.json()},async clearConversationHistory(i){const A=await fetch(`/api/proxy/admin/chat-history/${i||e}`,{method:"DELETE",headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to clear history: ${A.statusText}`);return A.json()},async deleteConversationWithFiles(i,A){const a=i||e,s=A&&A.length>0?`?file_ids=${A.join(",")}`:"",o=await fetch(`/api/proxy/admin/conversations/${a}${s}`,{method:"DELETE",headers:{"X-Adapter-Name":t}});if(!o.ok)throw new Error(`Failed to delete conversation: ${o.statusText}`);return o.json()},getSessionId:()=>e,async uploadFile(i){const A=new FormData;A.append("file",i);const a=await fetch("/api/proxy/api/files/upload",{method:"POST",headers:{"X-Adapter-Name":t},body:A});if(!a.ok)throw new Error(`Failed to upload file: ${a.statusText}`);return a.json()},async listFiles(){const i=await fetch("/api/proxy/api/files",{headers:{"X-Adapter-Name":t}});if(!i.ok)throw new Error(`Failed to list files: ${i.statusText}`);const A=await i.json();return Array.isArray(A)?A:A.files||[]},async getFileInfo(i){const A=await fetch(`/api/proxy/api/files/${i}`,{headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to get file info: ${A.statusText}`);return A.json()},async queryFile(i,A,a){const s=await fetch(`/api/proxy/api/files/${i}/query`,{method:"POST",headers:{"Content-Type":"application/json","X-Adapter-Name":t},body:JSON.stringify({query:A,max_results:a})});if(!s.ok)throw new Error(`Failed to query file: ${s.statusText}`);return s.json()},async deleteFile(i){const A=await fetch(`/api/proxy/api/files/${i}`,{method:"DELETE",headers:{"X-Adapter-Name":t}});if(!A.ok)throw new Error(`Failed to delete file: ${A.statusText}`);return A.json()},async validateApiKey(){const i=await fetch(`/api/proxy/admin/api-keys/${t}/status`,{headers:{"X-Adapter-Name":t}});if(!i.ok)throw new Error(`Failed to validate API key: ${i.statusText}`);return i.json()},async getAdapterInfo(){const i=await fetch("/api/proxy/admin/api-keys/info",{headers:{"X-Adapter-Name":t}});if(!i.ok){const A=await i.text();throw new Error(`Failed to get adapter info: ${i.status} ${i.statusText} - ${A}`)}return i.json()}}};return{configureApi:r,streamChat:async function*(i,A,a,s,o,l,c,u,g,h,d){yield*n().streamChat(i,A,a,s,o,l,c,u,g,h,d)},ApiClient:class{constructor(A){gA(this,"client");t=A.adapterName||null,e=A.sessionId||null,this.client=n()}async*streamChat(...A){yield*this.client.streamChat(...A)}get createThread(){var A;return(A=this.client.createThread)==null?void 0:A.bind(this.client)}get getThreadInfo(){var A;return(A=this.client.getThreadInfo)==null?void 0:A.bind(this.client)}get deleteThread(){var A;return(A=this.client.deleteThread)==null?void 0:A.bind(this.client)}get clearConversationHistory(){var A;return(A=this.client.clearConversationHistory)==null?void 0:A.bind(this.client)}get deleteConversationWithFiles(){var A;return(A=this.client.deleteConversationWithFiles)==null?void 0:A.bind(this.client)}get getSessionId(){var A;return(A=this.client.getSessionId)==null?void 0:A.bind(this.client)}get uploadFile(){var A;return(A=this.client.uploadFile)==null?void 0:A.bind(this.client)}get listFiles(){var A;return(A=this.client.listFiles)==null?void 0:A.bind(this.client)}get getFileInfo(){var A;return(A=this.client.getFileInfo)==null?void 0:A.bind(this.client)}get queryFile(){var A;return(A=this.client.queryFile)==null?void 0:A.bind(this.client)}get deleteFile(){var A;return(A=this.client.deleteFile)==null?void 0:A.bind(this.client)}get validateApiKey(){var A;return(A=this.client.validateApiKey)==null?void 0:A.bind(this.client)}get getAdapterInfo(){var A;return(A=this.client.getAdapterInfo)==null?void 0:A.bind(this.client)}}}}async function Crt(e){return e==="@local-node-api/api.mjs"?rr(()=>import("./api-BHF9IxKN.js"),[]):import(e)}async function Qrt(){if(Ps)return Ps;const e=Art(),t=art(),r=Ii();try{if(e){let n;t?t.startsWith("/")?n=t.startsWith("/src/")?`.${t.substring(4)}${t.endsWith(".mjs")?"":"/api.mjs"}`:"../../../node-api/dist/api.mjs":t.startsWith("../")||t.startsWith("./")?n=t.endsWith(".mjs")?t:`${t}/api.mjs`:n=`./${t}${t.endsWith(".mjs")?"":"/api.mjs"}`:n="../../../node-api/dist/api.mjs",Xe(`🔧 Loading local API from: ${n}`);const i=await Crt(n);r?(Xe("🔐 API Middleware enabled - routing through proxy"),Ps=q0()):Ps={configureApi:i.configureApi,streamChat:i.streamChat,ApiClient:i.ApiClient},Xe("✅ Local API loaded successfully")}else{Xe("📦 Loading npm package API");const n=await rr(()=>import("./api-CvFCgVm7.js"),[]),i=async function*(s,o,l,c,u,g,h,d,B,y,w){yield*n.streamChat(s,o,l,c,u,g,h,d,B,y,w)};class A{constructor(o){gA(this,"client");if(r&&o.adapterName){const l=q0();this.client=new l.ApiClient(o)}else this.client=new n.ApiClient(o)}async*streamChat(o,l,c,u,g,h,d,B,y,w,f){yield*this.client.streamChat(o,l,c,u,g,h,d,B,y,w,f)}get createThread(){var o;return(o=this.client.createThread)==null?void 0:o.bind(this.client)}get getThreadInfo(){var o;return(o=this.client.getThreadInfo)==null?void 0:o.bind(this.client)}get deleteThread(){var o;return(o=this.client.deleteThread)==null?void 0:o.bind(this.client)}get clearConversationHistory(){var o;return(o=this.client.clearConversationHistory)==null?void 0:o.bind(this.client)}get deleteConversationWithFiles(){var o;return(o=this.client.deleteConversationWithFiles)==null?void 0:o.bind(this.client)}get getSessionId(){var o;return(o=this.client.getSessionId)==null?void 0:o.bind(this.client)}get uploadFile(){var o;return(o=this.client.uploadFile)==null?void 0:o.bind(this.client)}get listFiles(){var o;return(o=this.client.listFiles)==null?void 0:o.bind(this.client)}get getFileInfo(){var o;return(o=this.client.getFileInfo)==null?void 0:o.bind(this.client)}get queryFile(){var o;return(o=this.client.queryFile)==null?void 0:o.bind(this.client)}get deleteFile(){var o;return(o=this.client.deleteFile)==null?void 0:o.bind(this.client)}get validateApiKey(){var o;return(o=this.client.validateApiKey)==null?void 0:o.bind(this.client)}get getAdapterInfo(){var o;return(o=this.client.getAdapterInfo)==null?void 0:o.bind(this.client)}}r?(Xe("🔐 API Middleware enabled - routing through proxy"),Ps=q0()):Ps={configureApi:n.configureApi,streamChat:i,ApiClient:A};const a=await HD();Xe(`✅ NPM package API loaded successfully (v${a})`)}}catch(n){if(e)try{const i=await rr(()=>import("./api-CvFCgVm7.js"),[]),A=async function*(o,l,c,u,g,h,d,B,y,w,f){yield*i.streamChat(o,l,c,u,g,h,d,B,y,w,f)};class a{constructor(l){gA(this,"client");if(r&&l.adapterName){const c=q0();this.client=new c.ApiClient(l)}else this.client=new i.ApiClient(l)}async*streamChat(l,c,u,g,h,d,B,y,w,f,I){yield*this.client.streamChat(l,c,u,g,h,d,B,y,w,f,I)}get createThread(){var l;return(l=this.client.createThread)==null?void 0:l.bind(this.client)}get getThreadInfo(){var l;return(l=this.client.getThreadInfo)==null?void 0:l.bind(this.client)}get deleteThread(){var l;return(l=this.client.deleteThread)==null?void 0:l.bind(this.client)}get clearConversationHistory(){var l;return(l=this.client.clearConversationHistory)==null?void 0:l.bind(this.client)}get deleteConversationWithFiles(){var l;return(l=this.client.deleteConversationWithFiles)==null?void 0:l.bind(this.client)}get getSessionId(){var l;return(l=this.client.getSessionId)==null?void 0:l.bind(this.client)}get uploadFile(){var l;return(l=this.client.uploadFile)==null?void 0:l.bind(this.client)}get listFiles(){var l;return(l=this.client.listFiles)==null?void 0:l.bind(this.client)}get getFileInfo(){var l;return(l=this.client.getFileInfo)==null?void 0:l.bind(this.client)}get queryFile(){var l;return(l=this.client.queryFile)==null?void 0:l.bind(this.client)}get deleteFile(){var l;return(l=this.client.deleteFile)==null?void 0:l.bind(this.client)}get validateApiKey(){var l;return(l=this.client.validateApiKey)==null?void 0:l.bind(this.client)}get getAdapterInfo(){var l;return(l=this.client.getAdapterInfo)==null?void 0:l.bind(this.client)}}r?(Xe("🔐 API Middleware enabled - routing through proxy"),Ps=q0()):Ps={configureApi:i.configureApi,streamChat:A,ApiClient:a};const s=await HD();Xe(`✅ Fallback to NPM package successful (v${s})`)}catch{throw new Error("Failed to load both local and npm API packages")}else throw n}return Ps}async function li(){return await Qrt()}const im=Fc(),Mrt=()=>{try{if(typeof window>"u"||!window.localStorage)return null;const e=window.localStorage.getItem("chat-api-url");return e&&e===qc?(window.localStorage.removeItem("chat-api-url"),null):e}catch{return null}},_0=e=>{const t=e==null?void 0:e.trim();if(t)return t;const r=Mrt();return r&&r!==qc?r:Pn()},Am=()=>typeof window>"u"?null:window.CHATBOT_API_KEY||null;class Rd{static async uploadFile(t,r,n,i,A){try{const a=xr.maxFileSizeMB*1024*1024;if(t.size>a)throw new Error(`File size exceeds maximum limit of ${xr.maxFileSizeMB}MB`);if(!(["application/pdf","text/plain","text/markdown","text/csv","application/json","text/html","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","application/vnd.ms-excel.sheet.macroEnabled.12","text/x-python","text/x-python-script","text/x-java-source","text/x-java","text/x-sql","text/javascript","application/javascript","text/typescript","application/typescript","text/x-c++src","text/x-csrc","text/x-c","text/x-go","text/x-rust","text/x-ruby","text/x-php","text/x-shellscript","text/x-sh","text/yaml","text/x-yaml","text/xml","application/xml","text/css","text/x-scss","text/x-sass","text/x-less","image/png","image/jpeg","image/tiff","audio/wav","audio/mpeg","audio/mp3","audio/mp4","audio/ogg","audio/flac","audio/webm","audio/x-m4a","audio/aac","text/vtt"].includes(t.type)||/\.(pdf|txt|md|csv|json|html|docx|pptx|xlsx|py|java|sql|js|mjs|ts|tsx|cpp|cxx|cc|c|h|hpp|go|rs|rb|php|sh|bash|zsh|yaml|yml|xml|css|scss|sass|less|png|jpe?g|tiff?|wav|mp3|mp4|ogg|flac|webm|m4a|aac|vtt)$/i.test(t.name)||(t.type==="application/x-zip-compressed"||t.type==="application/zip")&&/\.xlsx$/i.test(t.name)))throw new Error(`File type not supported: ${t.type||"unknown"}`);r&&r({filename:t.name,progress:0,status:"uploading"});const l=await li(),c=_0(i),u=Ii();let g=null,h=null;if(u){if(h=A||(typeof window<"u"?localStorage.getItem("chat-adapter-name"):null),!h)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");Xe(`🔑 Using adapter: ${h}`)}else{if(g=n||localStorage.getItem("chat-api-key")||Am()||im,!g||g==="your-api-key-here")throw new Error(`API key not configured or invalid. Please:
|
|
1213
1213
|
1. Open Settings (⚙️ icon) in the top-right corner
|
|
1214
1214
|
2. Enter a valid API key
|
|
1215
1215
|
3. To create an API key: POST to /admin/api-keys with admin credentials
|
|
@@ -1220,17 +1220,17 @@ ${L0e}`,ert=()=>{if(typeof document>"u"||document.getElementById(XK))return;cons
|
|
|
1220
1220
|
Example: curl -X POST ${c}/admin/api-keys \\
|
|
1221
1221
|
-H "Authorization: Bearer <admin-token>" \\
|
|
1222
1222
|
-H "Content-Type: application/json" \\
|
|
1223
|
-
-d '{"client_name": "chat-app", "adapter_name": "file-document-qa"}'`}else s.includes("API key not configured")&&(s=a instanceof Error?a.message:s);throw r&&r({filename:t.name,progress:0,status:"error",error:s}),new Error(s)}}static async uploadFiles(t,r){const n=t.map(async(i,A)=>{try{return await this.uploadFile(i,a=>{r&&r(A,a)})}catch(a){throw oi(`Failed to upload file ${i.name}:`,a),a}});return Promise.all(n)}static async listFiles(t,r,n){try{const i=await li(),A=_0(r),a=Ii();let s=null,o=null;if(a){if(o=n||(typeof window<"u"?localStorage.getItem("chat-adapter-name"):null),!o)throw new Error("Adapter not configured")}else if(s=t||localStorage.getItem("chat-api-key")||Am()||im,!s||s==="your-api-key-here"||s==="orbit-123456789")throw new Error("API key not configured");const l=new i.ApiClient({apiUrl:A,apiKey:s,sessionId:null,adapterName:o});if(!l.listFiles)throw new Error("File listing is not available. Please use the local API build or update the npm package.");const c=await l.listFiles();return(Array.isArray(c)?c:Array.isArray(c.files)?c.files:[]).map(g=>({file_id:g.file_id,filename:g.filename,mime_type:g.mime_type,file_size:g.file_size,upload_timestamp:g.upload_timestamp,processing_status:g.processing_status,chunk_count:g.chunk_count}))}catch(i){oi("Failed to list files:",i);const A=i instanceof Error?i.message:"Failed to list files";throw new Error(A)}}static async getFileInfo(t,r,n,i){try{const A=await li(),a=_0(n),s=Ii();let o=null,l=null;if(s){if(l=i||(typeof window<"u"?localStorage.getItem("chat-adapter-name"):null),!l)throw new Error("Adapter not configured")}else if(o=r||localStorage.getItem("chat-api-key")||Am()||im,!o||o==="your-api-key-here"||o==="orbit-123456789")throw new Error("API key not configured");const c=new A.ApiClient({apiUrl:a,apiKey:o,sessionId:null,adapterName:l});if(!c.getFileInfo)throw new Error("File info retrieval is not available. Please use the local API build or update the npm package.");const u=await c.getFileInfo(t);return{file_id:u.file_id,filename:u.filename,mime_type:u.mime_type,file_size:u.file_size,upload_timestamp:u.upload_timestamp,processing_status:u.processing_status,chunk_count:u.chunk_count}}catch(A){if(A instanceof Error&&(A.message.includes("404")||A.message.includes("File not found")))throw new Error(`File ${t} was deleted`);oi(`Failed to get file info for ${t}:`,A);const a=A instanceof Error?A.message:`Failed to get file info: ${t}`;throw new Error(a)}}static async pollFileStatus(t,r=30,n=2e3,i,A,a,s){for(let o=0;o<r;o++)try{if(i&&!i())throw new Error("Polling cancelled - component unmounted");const l=await this.getFileInfo(t,A,a,s);if(l.processing_status==="completed")return l;if(l.processing_status==="error"||l.processing_status==="failed")throw new Error(`File processing failed for ${t}`);o<r-1&&await new Promise(c=>setTimeout(c,n))}catch(l){const c=l instanceof Error?l.message:String(l);if(c.includes("404")||c.includes("File not found")||c.includes("was deleted"))throw new Error(`File ${t} was deleted during upload`);if(c.includes("component unmounted"))throw l;if(o<r-1){await new Promise(u=>setTimeout(u,n));continue}throw l}throw new Error(`File processing timeout: ${t} did not complete within ${r*n/1e3} seconds`)}static async deleteFile(t,r,n,i){try{const A=await li(),a=_0(n),s=Ii();let o=null,l=null;if(s){if(l=i||(typeof window<"u"?localStorage.getItem("chat-adapter-name"):null),!l)throw new Error("Adapter not configured")}else if(o=r||localStorage.getItem("chat-api-key")||Am()||im,!o||o==="your-api-key-here"||o==="orbit-123456789")throw new Error("API key not configured");const c=new A.ApiClient({apiUrl:a,apiKey:o,sessionId:null,adapterName:l});if(!c.deleteFile)throw new Error("File deletion is not available. Please use the local API build or update the npm package.");return await c.deleteFile(t)}catch(A){if(A instanceof Error&&(A.message.includes("404")||A.message.includes("File not found")||A.message.includes("Not Found")))return{message:"File already deleted",file_id:t};oi(`Failed to delete file ${t}:`,A);const a=A instanceof Error?A.message:`Failed to delete file: ${t}`;throw new Error(a)}}}const $K=e=>{let t;const r=new Set,n=(l,c)=>{const u=typeof l=="function"?l(t):l;if(!Object.is(u,t)){const g=t;t=c??(typeof u!="object"||u===null)?u:Object.assign({},t,u),r.forEach(h=>h(t,g))}},i=()=>t,s={setState:n,getState:i,getInitialState:()=>o,subscribe:l=>(r.add(l),()=>r.delete(l))},o=t=e(n,i,s);return s},Frt=e=>e?$K(e):$K,Yrt=e=>e;function brt(e,t=Yrt){const r=Kn.useSyncExternalStore(e.subscribe,Kn.useCallback(()=>t(e.getState()),[e,t]),Kn.useCallback(()=>t(e.getInitialState()),[e,t]));return Kn.useDebugValue(r),r}const eV=e=>{const t=Frt(e),r=n=>brt(t,n);return Object.assign(r,t),r},xrt=e=>e?eV(e):eV;class Nrt{constructor(){gA(this,"audioQueue",[]);gA(this,"isPlaying",!1);gA(this,"currentAudio",null);gA(this,"audioContext",null);gA(this,"isEnabled",!1);gA(this,"onPlaybackStart",null);gA(this,"onPlaybackEnd",null);gA(this,"onChunkPlayed",null);gA(this,"blobUrls",[]);gA(this,"suppressPlaybackErrors",!1)}async enableAudio(){try{try{const t=new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=");t.volume=0,await t.play(),t.pause()}catch{Xe("[AudioStreamManager] Silent audio unlock deferred (will work on next interaction)")}return this.isEnabled=!0,Xe("[AudioStreamManager] Audio playback enabled"),!0}catch{return!1}}disableAudio(){!this.isEnabled&&!this.isPlaying||(this.isEnabled=!1,this.stop())}async ensureAudioContext(){if(!this.audioContext&&typeof AudioContext<"u")try{return this.audioContext=new AudioContext,this.audioContext.state==="suspended"&&await this.audioContext.resume(),!0}catch{return!1}if(this.audioContext&&this.audioContext.state==="suspended")try{await this.audioContext.resume()}catch{return!1}return!0}isAudioEnabled(){return this.isEnabled}setOnPlaybackStart(t){this.onPlaybackStart=t}setOnPlaybackEnd(t){this.onPlaybackEnd=t}setOnChunkPlayed(t){this.onChunkPlayed=t}async addChunk(t){if(!this.isEnabled){Xe(`[AudioStreamManager] Audio disabled, dropping chunk ${t.chunkIndex}`);return}Xe(`[AudioStreamManager] Adding chunk ${t.chunkIndex} to queue`),this.audioQueue.push(t),this.audioQueue.sort((r,n)=>r.chunkIndex-n.chunkIndex),this.isPlaying||this.playNextChunk()}async playNextChunk(){var r,n;if(this.audioQueue.length===0){this.isPlaying=!1,this.onPlaybackEnd&&this.onPlaybackEnd();return}if(!this.isEnabled){this.audioQueue=[],this.isPlaying=!1;return}this.suppressPlaybackErrors=!1,await this.ensureAudioContext(),this.isPlaying=!0;const t=this.audioQueue.shift();try{if(!this.isPlaying)return;if(this.onPlaybackStart&&t.chunkIndex===0&&this.onPlaybackStart(),Xe(`[AudioStreamManager] Playing chunk ${t.chunkIndex}`),!t.audio||t.audio.length===0)throw new Error(`Empty audio data for chunk ${t.chunkIndex}`);let i;try{i=atob(t.audio)}catch(u){throw new Error(`Failed to decode base64 audio for chunk ${t.chunkIndex}: ${u instanceof Error?u.message:String(u)}`)}if(i.length===0)throw new Error(`Decoded audio data is empty for chunk ${t.chunkIndex}`);const A=new Uint8Array(i.length);for(let u=0;u<i.length;u++)A[u]=i.charCodeAt(u);const a=t.audioFormat==="mp3"?"audio/mpeg":t.audioFormat==="wav"?"audio/wav":t.audioFormat==="ogg"?"audio/ogg":t.audioFormat==="opus"?"audio/ogg; codecs=opus":t.audioFormat==="webm"?"audio/webm":`audio/${t.audioFormat}`,s=new Blob([A],{type:a}),o=URL.createObjectURL(s);this.blobUrls.push(o);const l=new Audio;l.src=o,this.currentAudio=l;const c=()=>{l.src&&(l.src=""),URL.revokeObjectURL(o),this.blobUrls=this.blobUrls.filter(u=>u!==o)};await new Promise((u,g)=>{let h=!1;const d=()=>{var f;if(h)return;const y=l.error,w=y?{code:y.code,message:y.message||`MediaError code ${y.code}`,MEDIA_ERR_ABORTED:y.code===MediaError.MEDIA_ERR_ABORTED,MEDIA_ERR_NETWORK:y.code===MediaError.MEDIA_ERR_NETWORK,MEDIA_ERR_DECODE:y.code===MediaError.MEDIA_ERR_DECODE,MEDIA_ERR_SRC_NOT_SUPPORTED:y.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"Unknown error";if(this.suppressPlaybackErrors){h=!0,c(),u();return}h=!0,console.error(`[AudioStreamManager] Error playing chunk ${t.chunkIndex}:`,w,{audioFormat:t.audioFormat,chunkIndex:t.chunkIndex,audioLength:t.audio.length,mimeType:a,audioContextState:(f=this.audioContext)==null?void 0:f.state,audioSrc:l.src,audioReadyState:l.readyState}),zg(`[AudioStreamManager] Error playing chunk ${t.chunkIndex}:`,w),c(),g(new Error(`Audio playback error: ${JSON.stringify(w)}`))};l.addEventListener("error",d,{once:!0});const B=async()=>{var y;if(!h)try{l.addEventListener("ended",()=>{h||(h=!0,Xe(`[AudioStreamManager] Chunk ${t.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(t.chunkIndex),c(),u())},{once:!0});const w=l.play();w&&await w}catch(w){if(h)return;if(this.suppressPlaybackErrors){h=!0,c(),u();return}h=!0,console.error(`[AudioStreamManager] Audio.play() rejected for chunk ${t.chunkIndex}:`,w,{audioFormat:t.audioFormat,chunkIndex:t.chunkIndex,audioContextState:(y=this.audioContext)==null?void 0:y.state,isEnabled:this.isEnabled,audioSrc:l.src,audioReadyState:l.readyState}),c(),g(w)}};l.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?B():l.addEventListener("canplay",B,{once:!0})}),this.currentAudio=null,this.playNextChunk()}catch(i){if(this.suppressPlaybackErrors)return;const A=i instanceof Error?i.message:String(i);console.error(`[AudioStreamManager] Failed to play chunk ${t.chunkIndex}:`,A,i,{audioFormat:t.audioFormat,chunkIndex:t.chunkIndex,audioLength:(r=t.audio)==null?void 0:r.length,audioContextState:(n=this.audioContext)==null?void 0:n.state,isEnabled:this.isEnabled}),zg(`[AudioStreamManager] Failed to play chunk ${t.chunkIndex}:`,i),this.playNextChunk()}}stop(){this.suppressPlaybackErrors=!0,this.isPlaying=!1,this.audioQueue=[],this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.blobUrls.forEach(t=>URL.revokeObjectURL(t)),this.blobUrls=[]}reset(){this.stop()}getQueueSize(){return this.audioQueue.length}isCurrentlyPlaying(){return this.isPlaying}}const mc=new Nrt,Jn=Fc(),Pf=()=>{const e=localStorage.getItem("chatbot-session-id");if(e)return e;const t=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return localStorage.setItem("chatbot-session-id",t),t},Drt=e=>{localStorage.setItem("chatbot-session-id",e)};let krt=0;const fN=e=>{const t=Date.now(),r=++krt,n=Math.random().toString(36).substr(2,9);return`msg_${t}_${r}_${n}_${e}`},io=()=>{const e=Date.now(),t=Math.random().toString(36).substr(2,9);return`session_${e}_${t}`};let zd=!1,Td="";async function qo(){if(zd&&Td)return!0;try{const e=await li(),t=localStorage.getItem("chat-api-url");t&&t===qc&&localStorage.removeItem("chat-api-url");const r=t&&t!==qc?t:Pn(),n=localStorage.getItem("chat-api-key")||Jn,i=Pf();return e.configureApi(r,n,i),Td=r,zd=!0,!0}catch(e){return oi("Failed to configure API:",e),!1}}const fr=xrt((e,t)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,sessionId:Pf(),getSessionId:()=>t().sessionId,configureApiSettings:async(r,n,i,A)=>{const a=t(),s=a.conversations.find(c=>c.id===a.currentConversationId),o=Ii(),l=(s==null?void 0:s.sessionId)||i||Pf();i&&Drt(i),e({sessionId:l});try{const c=await li();if(o){if(!A||!A.trim())throw new Error("Adapter name is required when API middleware is enabled");c.configureApi(r,null,l,A),Td=r,zd=!0;let u;try{const g=new c.ApiClient({apiUrl:r,apiKey:null,sessionId:null,adapterName:A});typeof g.getAdapterInfo=="function"&&(u=await g.getAdapterInfo(),Xe("Adapter info loaded:",u))}catch(g){jr("Failed to load adapter info:",g)}if(s)e(g=>({conversations:g.conversations.map(h=>h.id===s.id?{...h,adapterName:A,apiUrl:r,adapterInfo:u,apiKey:void 0,updatedAt:new Date}:h)}));else if(A&&A.trim()){const g=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=io();e(d=>({conversations:[...d.conversations,{id:g,sessionId:h,title:"New Conversation",messages:[],createdAt:new Date,updatedAt:new Date,adapterName:A,apiUrl:r,adapterInfo:u}],currentConversationId:g}))}}else{let u;if(n&&n.trim())try{const g=new c.ApiClient({apiUrl:r,apiKey:n,sessionId:null});if(typeof g.validateApiKey=="function"){Xe("Validating API key before configuration...");const h=await g.validateApiKey();Xe("API key validation successful:",{exists:h.exists,active:h.active,adapter_name:h.adapter_name,client_name:h.client_name})}else jr("API key validation not available (validateApiKey method not found)");if(typeof g.getAdapterInfo=="function")try{u=await g.getAdapterInfo(),Xe("Adapter info loaded:",u)}catch(h){jr("Failed to load adapter info:",h)}}catch(g){throw g instanceof Error?g:new Error(`API key validation failed: ${String(g)}`)}if(c.configureApi(r,n||"",l),Td=r,zd=!0,s&&n&&n.trim())e(g=>({conversations:g.conversations.map(h=>h.id===s.id?{...h,apiKey:n,apiUrl:r,adapterInfo:u,adapterName:void 0,updatedAt:new Date}:h)})),setTimeout(()=>{const g=t();localStorage.setItem("chat-state",JSON.stringify({conversations:g.conversations,currentConversationId:g.currentConversationId}))},0);else if(n&&n.trim()){const g=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=io(),d={id:g,sessionId:h,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:n,apiUrl:r,adapterInfo:u};e(B=>{let y=[d,...B.conversations];const w=xr.maxConversations;return w!==null&&y.length>w&&(y=y.slice(0,w)),{conversations:y,currentConversationId:g,sessionId:h}}),setTimeout(()=>{const B=t();localStorage.setItem("chat-state",JSON.stringify({conversations:B.conversations,currentConversationId:B.currentConversationId}))},0)}}}catch(c){throw e({isLoading:!1}),c instanceof Error?c:new Error("Failed to configure API settings")}o?A?localStorage.setItem("chat-adapter-name",A):localStorage.removeItem("chat-adapter-name"):(r&&r!==qc?localStorage.setItem("chat-api-url",r):localStorage.removeItem("chat-api-url"),n&&localStorage.setItem("chat-api-key",n)),e({isLoading:!1})},createConversation:()=>{const r=t(),n=xr.maxConversations,i=r.conversations.length,A=r.currentConversationId?r.conversations.find(h=>h.id===r.currentConversationId):null;if(n!==null&&i>=n){const h=`Maximum of ${n} conversations reached. Please delete an existing conversation before starting a new one.`;throw e({error:h}),new Error(h)}if(A&&A.messages.length===0){const h="Finish or delete the current conversation before starting a new one.";throw e({error:h}),new Error(h)}const a=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=io(),o=Pn(),l=Jn,c=Ii(),u=c&&typeof window<"u"?localStorage.getItem("chat-adapter-name"):null,g={id:a,sessionId:s,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:c?void 0:l,apiUrl:o,adapterName:u||void 0};return e(h=>{let d=[g,...h.conversations];const B=xr.maxConversations;return B!==null&&d.length>B&&(d=d.slice(0,B)),{conversations:d,currentConversationId:a,sessionId:s}}),qo().then(h=>{h&&li().then(d=>{c&&u?d.configureApi(o,null,s,u):d.configureApi(o,l,s);try{const B=new d.ApiClient({apiUrl:o,apiKey:c?null:l,sessionId:null,adapterName:c?u:null});typeof B.getAdapterInfo=="function"&&B.getAdapterInfo().then(y=>{Xe("✅ Adapter info loaded for new conversation:",y);const w=fr.getState();fr.setState({conversations:w.conversations.map(f=>f.id===a?{...f,adapterInfo:y,updatedAt:new Date}:f)})}).catch(y=>{jr("Failed to load adapter info for new conversation:",y)})}catch{}})}),setTimeout(()=>{const h=t();localStorage.setItem("chat-state",JSON.stringify({conversations:h.conversations,currentConversationId:h.currentConversationId}))},0),a},selectConversation:async r=>{const n=t().conversations.find(i=>i.id===r);if(n){const i=n.messages.some(o=>o.role==="assistant"&&o.isStreaming);e({currentConversationId:r,sessionId:n.sessionId,isLoading:i});const A=n.apiUrl||Pn(),a=n.apiKey||Jn;if(await qo()){const o=await li();if(o.configureApi(A,a,n.sessionId),!n.adapterInfo)try{const l=new o.ApiClient({apiUrl:A,apiKey:a,sessionId:null});if(typeof l.getAdapterInfo=="function"){const c=await l.getAdapterInfo();Xe("Adapter info loaded for conversation:",c),e(u=>({conversations:u.conversations.map(g=>g.id===r?{...g,adapterInfo:c,updatedAt:new Date}:g)})),setTimeout(()=>{const u=t();localStorage.setItem("chat-state",JSON.stringify({conversations:u.conversations,currentConversationId:u.currentConversationId}))},0)}}catch{}}}setTimeout(()=>{const i=t();localStorage.setItem("chat-state",JSON.stringify({conversations:i.conversations,currentConversationId:i.currentConversationId}))},0)},deleteConversation:async r=>{var A,a;const n=t(),i=n.conversations.find(s=>s.id===r);if(Xe(`🗑️ Deleting conversation ${r}:`,{conversationId:r,sessionId:i==null?void 0:i.sessionId,title:i==null?void 0:i.title,messageCount:i==null?void 0:i.messages.length,fileCount:((A=i==null?void 0:i.attachedFiles)==null?void 0:A.length)||0}),n.currentConversationId===r&&mc.stop(),i!=null&&i.sessionId)try{if(!await qo())oi("Failed to configure API for conversation deletion");else{const o=Ii(),l=i.apiUrl||Pn(),c=i.apiKey||Jn,u=i.adapterName;o?u?Xe(`🔑 Using conversation's adapter for deletion: ${u} (conversation: ${r})`):jr(`Skipping server deletion for conversation ${r}: adapter not configured`):Xe(`🔑 Using conversation's API key for deletion: ${c.substring(0,8)}... (conversation: ${r})`);const g=await li(),h=new g.ApiClient({apiUrl:l,apiKey:o?null:c,sessionId:i.sessionId,adapterName:o?u:null}),d=((a=i==null?void 0:i.attachedFiles)==null?void 0:a.map(B=>B.file_id))||[];if(Xe(`🔧 Calling deleteConversationWithFiles for session: ${i.sessionId}`),Xe(`🔧 File IDs to delete: ${d.join(", ")||"none"}`),h.deleteConversationWithFiles){const B=await h.deleteConversationWithFiles(i.sessionId,d);Xe(`✅ Deleted conversation and files for session: ${i.sessionId}`,B),Xe(` - Deleted ${B.deleted_messages} messages`),Xe(` - Deleted ${B.deleted_files} files`),B.file_deletion_errors&&B.file_deletion_errors.length>0&&jr(` - Errors deleting files: ${B.file_deletion_errors.join(", ")}`)}else jr("⚠️ deleteConversationWithFiles method not available on API client")}}catch(s){oi("Failed to clear conversation history from server:",s)}e(s=>{var c;const o=s.conversations.filter(u=>u.id!==r),l=s.currentConversationId===r?((c=o[0])==null?void 0:c.id)||null:s.currentConversationId;if(o.length===0){const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=io(),h=Pn(),d={id:u,sessionId:g,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:h};return qo().then(B=>{B&&li().then(y=>{y.configureApi(h,Jn,g);try{const w=new y.ApiClient({apiUrl:h,apiKey:Jn,sessionId:null});typeof w.validateApiKey=="function"&&w.validateApiKey().then(()=>{Xe("✅ Default API key validated after creating new conversation")}).catch(()=>{jr("Failed to validate default API key")}),typeof w.getAdapterInfo=="function"&&w.getAdapterInfo().then(f=>{Xe("✅ Adapter info loaded for default key:",f);const I=fr.getState();fr.setState({conversations:I.conversations.map(Y=>Y.id===u?{...Y,adapterInfo:f,updatedAt:new Date}:Y)})}).catch(()=>{jr("Failed to load adapter info for default key")})}catch{}})}),setTimeout(()=>{localStorage.setItem("chat-state",JSON.stringify({conversations:[d],currentConversationId:u}))},0),{conversations:[d],currentConversationId:u,sessionId:g}}return setTimeout(()=>{localStorage.setItem("chat-state",JSON.stringify({conversations:o,currentConversationId:l}))},0),{conversations:o,currentConversationId:l}})},deleteAllConversations:async()=>{const n=[...t().conversations];mc.stop();const i=n.map(async l=>{var c;if(l!=null&&l.sessionId)try{if(!await qo()){oi("Failed to configure API for conversation deletion");return}const g=Ii(),h=to(l.apiUrl),d=l.apiKey||Jn,B=l.adapterName,y=await li(),w=new y.ApiClient({apiUrl:h,apiKey:g?null:d,sessionId:l.sessionId,adapterName:g?B:null}),f=((c=l==null?void 0:l.attachedFiles)==null?void 0:c.map(I=>I.file_id))||[];w.deleteConversationWithFiles?(await w.deleteConversationWithFiles(l.sessionId,f),Xe(`✅ Deleted conversation ${l.id} and files`)):jr(`deleteConversationWithFiles not available for conversation ${l.id}`)}catch(u){oi(`Failed to delete conversation ${l.id} from server:`,u)}});Promise.allSettled(i).then(l=>{const c=l.filter(u=>u.status==="rejected");c.length>0&&oi(`Some conversations failed to delete from server: ${c.length}`,c)});const A=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a=io(),s=Pn(),o={id:A,sessionId:a,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:s};qo().then(l=>{l&&li().then(c=>{c.configureApi(s,Jn,a);try{const u=new c.ApiClient({apiUrl:s,apiKey:Jn,sessionId:null});typeof u.validateApiKey=="function"&&u.validateApiKey().then(()=>{Xe("✅ Default API key validated after clearing all conversations")}).catch(()=>{jr("Failed to validate default API key")}),typeof u.getAdapterInfo=="function"&&u.getAdapterInfo().then(g=>{Xe("✅ Adapter info loaded for default key:",g);const h=fr.getState();fr.setState({conversations:h.conversations.map(d=>d.id===A?{...d,adapterInfo:g,updatedAt:new Date}:d)})}).catch(()=>{jr("Failed to load adapter info for default key")})}catch{}})}),e({conversations:[o],currentConversationId:A,sessionId:a}),setTimeout(()=>{localStorage.setItem("chat-state",JSON.stringify({conversations:[o],currentConversationId:A}))},0)},sendMessage:async(r,n,i)=>{var A,a,s,o,l,c,u,g,h,d,B;try{if(t().isLoading){jr("Another request is already in progress");return}if(!await qo())throw new Error("API not properly configured. Please configure API settings first.");let w=t().currentConversationId;w||(w=t().createConversation());const f=t().conversations.find(X=>X.id===w);if(!f)throw new Error("Conversation not found");const I=n?n.map(X=>{var ee;const Z=(ee=f==null?void 0:f.attachedFiles)==null?void 0:ee.find(Ae=>Ae.file_id===X);return Z||{file_id:X,filename:"",mime_type:"",file_size:0}}).filter(X=>X!==void 0):[];I.length>0&&I.forEach(X=>{t().addFileToConversation(w,X)});const Y=i||null;let Q,M=null;if(Y){if(Q=f.messages.find(X=>{var Z;return((Z=X.threadInfo)==null?void 0:Z.thread_id)===Y}),!Q)throw new Error("Thread metadata not found. Please recreate the thread from this message.");if(M=((A=Q.threadInfo)==null?void 0:A.thread_session_id)||null,!M)throw new Error("Thread session is missing. Please recreate the thread from this message.")}const D={id:fN("user"),content:r,role:"user",timestamp:new Date,attachments:I.length>0?I:void 0},G=fN("assistant"),z={id:G,content:"",role:"assistant",timestamp:new Date,isStreaming:!0};Y&&Q&&(D.isThreadMessage=!0,D.threadId=Y,D.parentMessageId=Q.id,z.isThreadMessage=!0,z.threadId=Y,z.parentMessageId=Q.id);let R=!1,j=!1;if(e(X=>{const Z=X.conversations.find($=>$.id===w),ee=(Z==null?void 0:Z.messages.filter($=>$.role==="assistant"&&$.isStreaming))||[];ee.length>0&&jr(`Cleaning up ${ee.length} existing streaming messages`);const Ae=X.conversations.map($=>{if($.id!==w){const P=xr.maxMessagesPerConversation;if(P!==null){const Be=$.messages.filter(Fe=>!(Fe.role==="assistant"&&Fe.isStreaming));if(Be.length>=P){R=!0;const Fe=Math.max(1,P-1),Me=Be.slice(-Fe),pe=$.messages.filter(ke=>ke.role==="assistant"&&ke.isStreaming);return{...$,messages:[...Me,...pe]}}}return $}const L=$.messages.filter(P=>!(P.role==="assistant"&&P.isStreaming)),ne=xr.maxMessagesPerConversation;let ge=L;if(ne!==null&&L.length>=ne){R=!0;const P=Math.max(1,ne-1);ge=L.slice(-P)}return{...$,messages:[...ge,D,z],updatedAt:new Date,title:$.messages.length===0?r.slice(0,50)+(r.length>50?"...":""):$.title}}),K=xr.maxTotalMessages;if(K!==null){const $=Ae.reduce((L,ne)=>L+ne.messages.filter(ge=>!(ge.role==="assistant"&&ge.isStreaming)).length,0);if($>K){j=!0;let L=$-K;const ne=[...Ae].sort((ge,P)=>ge.updatedAt.getTime()-P.updatedAt.getTime());for(const ge of ne){if(L<=0)break;const P=ge.messages.filter(Be=>!(Be.role==="assistant"&&Be.isStreaming));if(P.length>0){const Be=Math.min(L,P.length),Fe=ge.messages.filter(ke=>ke.role==="assistant"&&ke.isStreaming),Me=[...P.slice(Be),...Fe],pe=Ae.findIndex(ke=>ke.id===ge.id);pe!==-1&&(Ae[pe]={...ge,messages:Me}),L-=Be}}}}return{conversations:Ae,isLoading:!0,error:null}}),R||j){const X=[];R&&xr.maxMessagesPerConversation!==null&&X.push(`Only the most recent ${xr.maxMessagesPerConversation} messages are kept per conversation. Older messages in this chat were removed automatically.`),j&&xr.maxTotalMessages!==null&&X.push(`There is a workspace limit of ${xr.maxTotalMessages} total messages. Older conversations were trimmed to stay within that limit.`),X.length>0&&e({error:X.join(" ")})}const W=w;let te=!1;mc.reset();try{const X=t().conversations.find(xe=>xe.id===W);if(!X)throw new Error("Conversation not found");const Z=Ii();if(Z){if(!X.adapterName)throw jr(`[sendMessage] Conversation ${W} has no adapter name`),new Error("Adapter not configured for this conversation. Please select an adapter first.");Xe(`[sendMessage] Using adapter for conversation ${W}: ${X.adapterName}`)}else{if(!X.apiKey)throw jr(`[sendMessage] Conversation ${W} has no API key`),new Error("API key not configured for this conversation. Please configure API settings first.");Xe(`[sendMessage] Using API key for conversation ${W}: ${X.apiKey.substring(0,8)}...`)}const ee=to(X.apiUrl),Ae=X.apiKey,K=X.adapterName,$=i||null,L=M||X.sessionId,ne=await li();Z?ne.configureApi(ee,null,L,K):ne.configureApi(ee,Ae,L),$&&L!==X.sessionId&&Xe(`[chatStore] Thread mode: using thread session ${L} (original: ${X.sessionId})`),Xe("[chatStore] Starting streamChat with fileIds:",n);const ge=t().conversations.find(xe=>xe.id===W),P=((s=(a=ge==null?void 0:ge.adapterInfo)==null?void 0:a.adapter_name)==null?void 0:s.includes("voice"))||((l=(o=ge==null?void 0:ge.adapterInfo)==null?void 0:o.adapter_name)==null?void 0:l.includes("audio"))||((u=(c=ge==null?void 0:ge.adapterInfo)==null?void 0:c.adapter_name)==null?void 0:u.includes("multilingual")),Be=()=>{try{const xe=localStorage.getItem("chat-settings");if(xe)return JSON.parse(xe).voiceEnabled===!0}catch(xe){jr("Failed to read global voice setting:",xe)}return!1},Fe=ge==null?void 0:ge.audioSettings,Me=Be(),pe=(Fe==null?void 0:Fe.enabled)??Me??P,ke=(Fe==null?void 0:Fe.ttsVoice)||void 0,Ee=(Fe==null?void 0:Fe.language)||"en-US",je=Fe==null?void 0:Fe.audioFormat;Xe("[chatStore] Audio settings:",{returnAudio:pe,ttsVoice:ke,language:Ee,audioFormat:je,isVoiceAdapter:P,adapterName:(g=ge==null?void 0:ge.adapterInfo)==null?void 0:g.adapter_name});for await(const xe of ne.streamChat(r,!0,n,$||void 0,void 0,void 0,Ee,pe,ke)){if(Xe("[chatStore] Received stream chunk:",{text:(h=xe.text)==null?void 0:h.substring(0,50),done:xe.done,hasAudio:!!xe.audio,hasAudioChunk:!!xe.audio_chunk,audioFormat:xe.audioFormat,audioLength:(d=xe.audio)==null?void 0:d.length,chunkIndex:xe.chunk_index}),xe.audio_chunk){Xe("[chatStore] Received audio chunk:",{chunk_index:xe.chunk_index,audioFormat:xe.audioFormat,audioLength:(B=xe.audio_chunk)==null?void 0:B.length});const Ie=xe.chunk_index??0;mc.addChunk({audio:xe.audio_chunk,audioFormat:xe.audioFormat||"opus",chunkIndex:Ie})}if(xe.text){const Ie=Lh(xe.text);Ie?(t().appendToLastMessage(Ie,W),te=!0,await new Promise(Se=>setTimeout(Se,30))):xe.text.length>100&&jr("[chatStore] Filtered out potential base64 audio data from message content")}if(xe.audio&&xe.done&&e(Ie=>({conversations:Ie.conversations.map(Se=>{if(Se.id!==W)return Se;const Te=[...Se.messages],Ke=Te[Te.length-1];return Ke&&Ke.role==="assistant"&&(Te[Te.length-1]={...Ke,audio:xe.audio,audioFormat:xe.audioFormat||"mp3"}),{...Se,messages:Te,updatedAt:new Date}})})),xe.done){Xe("[chatStore] Stream completed, receivedAnyText:",te),Xe("[chatStore] Done chunk received:",{hasThreading:!!xe.threading,threading:xe.threading,assistantMessageId:G});const Ie=xe.threading;Ie&&Ie.supports_threading&&(e(Se=>({conversations:Se.conversations.map(Te=>Te.id!==W?Te:{...Te,messages:Te.messages.map(Ke=>Ke.id===G?{...Ke,supportsThreading:!0,databaseMessageId:Ie.message_id}:Ke),updatedAt:new Date})})),Xe(`[chatStore] Message ${G} marked as supporting threading`,{message_id:Ie.message_id,session_id:Ie.session_id,databaseMessageId:Ie.message_id}));break}}te||(jr("[chatStore] No text received from stream, showing error message"),t().appendToLastMessage("No response received from the server. Please try again later.",W))}catch(X){oi("Chat API error:",X),t().appendToLastMessage("Sorry, there was an error processing your request.",W)}e(X=>{const Z=X.conversations.map(K=>K.id===W?{...K,messages:K.messages.map($=>$.id===G?{...$,isStreaming:!1}:$),updatedAt:new Date}:K),ee=Z.find(K=>K.id===X.currentConversationId),Ae=ee?ee.messages.some(K=>K.role==="assistant"&&K.isStreaming):!1;return{conversations:Z,isLoading:Ae}}),setTimeout(()=>{const X=t();localStorage.setItem("chat-state",JSON.stringify({conversations:X.conversations,currentConversationId:X.currentConversationId}))},0)}catch(y){oi("Chat store error:",y),e(()=>({isLoading:!1,error:`Failed to send message: ${y instanceof Error?y.message:"Unknown error"}`}))}},createThread:async(r,n)=>{try{const i=t().conversations.find(B=>B.sessionId===n);if(!i)throw new Error("Conversation not found for session");const A=Ii();if(A&&!i.adapterName)throw new Error("Adapter not configured for this conversation");if(!A&&!i.apiKey)throw new Error("API key not configured for this conversation");const a=i.messages.find(B=>B.id===r);if(!a)throw new Error("Message not found");const s=a.databaseMessageId||r,o=to(i.apiUrl||Pn()),l=i.apiKey||Jn,c=i.adapterName,u=await li(),g=new u.ApiClient({apiUrl:o,apiKey:A?null:l,sessionId:n,adapterName:A?c:null}),d=await new(await rr(async()=>{const{ThreadService:B}=await import("./threadService-B9Db3n0J.js");return{ThreadService:B}},[])).ThreadService(g).createThread(s,n);e(B=>({conversations:B.conversations.map(y=>y.sessionId!==n?y:{...y,messages:y.messages.map(w=>w.id===r?{...w,threadInfo:d,supportsThreading:!0}:w),currentThreadId:void 0,currentThreadSessionId:void 0})})),Xe(`[chatStore] Created thread ${d.thread_id} for message ${r}`)}catch(i){throw oi("Failed to create thread:",i),i}},appendToLastMessage:(r,n)=>{const i=Lh(r);if(!i&&r)return;const A=LD(i);e(a=>{const s=n||a.currentConversationId;return{conversations:a.conversations.map(o=>{if(o.id!==s)return o;const l=[...o.messages],c=l[l.length-1];return c&&c.role==="assistant"&&c.isStreaming&&(l[l.length-1]={...c,content:c.content+A}),{...o,messages:l,updatedAt:new Date}})}})},regenerateResponse:async r=>{var n,i,A,a,s,o;try{if(t().isLoading){jr("Another request is already in progress");return}if(!await qo())throw new Error("API not properly configured");const c=t(),u=c.conversations.find(f=>f.id===c.currentConversationId);if(!u)return;const g=u.messages.findIndex(f=>f.id===r);if(g===-1)return;const h=u.messages[g-1];if(!h||h.role!=="user")return;const d=(h.attachments||[]).map(f=>f.file_id).filter(f=>typeof f=="string"&&f.length>0),B=fN("assistant");e(f=>({conversations:f.conversations.map(I=>I.id===f.currentConversationId?{...I,messages:[...I.messages.slice(0,g),{id:B,content:"",role:"assistant",timestamp:new Date,isStreaming:!0}],updatedAt:new Date}:I),isLoading:!0,error:null}));const y=c.currentConversationId;if(!y)throw new Error("No conversation selected");let w=!1;try{const f=t().conversations.find(te=>te.id===y);if(!f)throw new Error("Conversation not found");const I=Ii();if(I){if(!f.adapterName)throw new Error("Adapter not configured for this conversation. Please select an adapter first.")}else if(!f.apiKey)throw new Error("API key not configured for this conversation. Please configure API settings first.");if(f.sessionId){const te=to(f.apiUrl),X=f.apiKey,Z=f.adapterName,ee=await li();I?ee.configureApi(te,null,f.sessionId,Z):ee.configureApi(te,X,f.sessionId)}const Y=await li(),Q=t().conversations.find(te=>te.id===y),M=((i=(n=Q==null?void 0:Q.adapterInfo)==null?void 0:n.adapter_name)==null?void 0:i.includes("voice"))||((a=(A=Q==null?void 0:Q.adapterInfo)==null?void 0:A.adapter_name)==null?void 0:a.includes("audio"))||((o=(s=Q==null?void 0:Q.adapterInfo)==null?void 0:s.adapter_name)==null?void 0:o.includes("multilingual")),D=()=>{try{const te=localStorage.getItem("chat-settings");if(te)return JSON.parse(te).voiceEnabled===!0}catch(te){jr("Failed to read global voice setting:",te)}return!1},G=Q==null?void 0:Q.audioSettings,z=D(),R=(G==null?void 0:G.enabled)??z??M,j=(G==null?void 0:G.ttsVoice)||void 0,W=(G==null?void 0:G.language)||"en-US";for await(const te of Y.streamChat(h.content,!0,d.length>0?d:void 0,void 0,void 0,void 0,W,R,j)){if(te.text){const X=Lh(te.text);X?(t().appendToLastMessage(X,y),w=!0,await new Promise(Z=>setTimeout(Z,30))):te.text.length>100&&jr("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(te.audio&&te.done&&e(X=>({conversations:X.conversations.map(Z=>{if(Z.id!==y)return Z;const ee=[...Z.messages],Ae=ee[ee.length-1];return Ae&&Ae.role==="assistant"&&(ee[ee.length-1]={...Ae,audio:te.audio,audioFormat:te.audioFormat||"mp3"}),{...Z,messages:ee,updatedAt:new Date}})})),te.done)break}w||t().appendToLastMessage("No response received from the server. Please try again later.",y)}catch(f){oi("Regenerate API error:",f),t().appendToLastMessage("Sorry, there was an error regenerating the response.",y)}e(f=>{const I=f.conversations.map(M=>M.id===y?{...M,messages:M.messages.map(D=>D.id===B?{...D,isStreaming:!1}:D),updatedAt:new Date}:M),Y=I.find(M=>M.id===f.currentConversationId),Q=Y?Y.messages.some(M=>M.role==="assistant"&&M.isStreaming):!1;return{conversations:I,isLoading:Q}})}catch(l){oi("Regenerate error:",l),e({isLoading:!1,error:`Failed to regenerate response: ${l instanceof Error?l.message:"Unknown error"}`})}},updateConversationTitle:(r,n)=>{e(i=>({conversations:i.conversations.map(A=>A.id===r?{...A,title:n,updatedAt:new Date}:A)})),setTimeout(()=>{const i=t();localStorage.setItem("chat-state",JSON.stringify({conversations:i.conversations,currentConversationId:i.currentConversationId}))},0)},clearError:()=>{e({error:null})},cleanupStreamingMessages:()=>{e(r=>({conversations:r.conversations.map(n=>(n.id===r.currentConversationId,n)),isLoading:!1}))},canCreateNewConversation:()=>{const r=t(),n=xr.maxConversations;if(!r.currentConversationId)return n===null||r.conversations.length<n;const i=r.conversations.find(A=>A.id===r.currentConversationId);return i&&i.messages.length>0?n===null||r.conversations.length<n:!1},getConversationCount:()=>t().conversations.length,addFileToConversation:(r,n)=>{Xe("[chatStore] addFileToConversation called",{conversationId:r,fileId:n.file_id,filename:n.filename}),e(i=>{var s,o;const A={conversations:i.conversations.map(l=>l.id===r?{...l,attachedFiles:[...(l.attachedFiles||[]).filter(c=>c.file_id!==n.file_id),n],updatedAt:new Date}:l)},a=A.conversations.find(l=>l.id===r);return Xe(`[chatStore] Updated conversation ${r}`,{hasConversation:!!a,attachedFilesCount:((s=a==null?void 0:a.attachedFiles)==null?void 0:s.length)||0,attachedFiles:(o=a==null?void 0:a.attachedFiles)==null?void 0:o.map(l=>({file_id:l.file_id,filename:l.filename}))}),A}),setTimeout(()=>{const i=t();localStorage.setItem("chat-state",JSON.stringify({conversations:i.conversations,currentConversationId:i.currentConversationId}))},0)},removeFileFromConversation:async(r,n)=>{try{const i=t().conversations.find(l=>l.id===r);if(!i)throw new Error("Conversation not found");if(Ii()){if(!i.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.")}else if(!i.apiKey)throw new Error("API key not configured for this conversation. Cannot delete file.");const a=i.apiKey,s=i.adapterName,o=to(i.apiUrl);Xe(`[chatStore] Calling FileUploadService.deleteFile for ${n}`),await Rd.deleteFile(n,a,o,s),Xe(`[chatStore] Successfully deleted file ${n} from server`)}catch(i){i instanceof Error&&(i.message.includes("404")||i.message.includes("File not found"))}e(i=>({conversations:i.conversations.map(A=>A.id===r?{...A,attachedFiles:(A.attachedFiles||[]).filter(a=>a.file_id!==n),updatedAt:new Date}:A)})),setTimeout(()=>{const i=t();localStorage.setItem("chat-state",JSON.stringify({conversations:i.conversations,currentConversationId:i.currentConversationId}))},0)},loadConversationFiles:async r=>{try{const n=t().conversations.find(g=>g.id===r);if(!n)return;if(Ii()){if(!n.adapterName){Xe(`Skipping file load for conversation ${r}: adapter not configured`);return}}else if(!n.apiKey){Xe(`Skipping file load for conversation ${r}: API key not configured`);return}const A=n.apiKey,a=n.adapterName,s=to(n.apiUrl);if(new Set((n.attachedFiles||[]).map(g=>g.file_id)).size===0){Xe(`No files to sync for conversation ${r}`);return}const c=(await Rd.listFiles(A,s,a)).map(g=>({file_id:g.file_id,filename:g.filename,mime_type:g.mime_type,file_size:g.file_size,upload_timestamp:g.upload_timestamp,processing_status:g.processing_status,chunk_count:g.chunk_count})),u=new Map(c.map(g=>[g.file_id,g]));e(g=>{const h=g.conversations.find(B=>B.id===r);if(!h)return g;const d=(h.attachedFiles||[]).map(B=>u.get(B.file_id)||B).filter(B=>u.has(B.file_id)||!B.processing_status||B.processing_status==="processing");return{conversations:g.conversations.map(B=>B.id===r?{...B,attachedFiles:d,updatedAt:new Date}:B)}}),setTimeout(()=>{const g=t();localStorage.setItem("chat-state",JSON.stringify({conversations:g.conversations,currentConversationId:g.currentConversationId}))},0)}catch(n){oi(`Failed to load files for conversation ${r}:`,n)}},syncConversationFiles:async r=>{await t().loadConversationFiles(r)}})),Srt=async()=>{var l;const e=localStorage.getItem("chat-state"),t=Pn(),r=typeof window<"u"?!!localStorage.getItem("chat-api-url"):!1;let n=Pf(),i=!1;if(e)try{const c=JSON.parse(e),u=d=>{if(d instanceof Date)return d;const B=d?new Date(d):new Date;return Number.isNaN(B.getTime())?new Date:B},g=Array.isArray(c.conversations)?c.conversations:[];if(c.conversations=g.map(d=>{const y=(Array.isArray(d.messages)?d.messages:[]).filter(Y=>!(Y.role==="assistant"&&Y.isStreaming)).map(Y=>({...Y,timestamp:u(Y.timestamp),isStreaming:!1})),w={id:d.id,sessionId:d.sessionId||io(),title:d.title||"New Chat",messages:y,createdAt:u(d.createdAt),updatedAt:u(d.updatedAt),attachedFiles:d.attachedFiles||[],apiKey:d.apiKey||Jn,adapterName:d.adapterName,apiUrl:d.apiUrl,adapterInfo:d.adapterInfo,audioSettings:d.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},I=w.messages.length===0&&(!w.apiKey||w.apiKey===Jn)&&!r?t:to(d.apiUrl);return{...w,apiUrl:I}}),i=c.conversations&&c.conversations.length>0,c.currentConversationId&&c.conversations){const d=c.conversations.find(B=>B.id===c.currentConversationId);d&&d.sessionId&&(n=d.sessionId)}if(!c.conversations||c.conversations.length===0){const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,B=io(),y={id:d,sessionId:B,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:Pn()};fr.setState({conversations:[y],currentConversationId:d,sessionId:B}),n=B}else fr.setState({conversations:c.conversations||[],currentConversationId:c.currentConversationId||((l=c.conversations[0])==null?void 0:l.id)||null,sessionId:n}),!c.currentConversationId&&c.conversations.length>0&&(fr.setState({currentConversationId:c.conversations[0].id,sessionId:c.conversations[0].sessionId||n}),n=c.conversations[0].sessionId||n);const h=fr.getState().conversations;Xe("📋 Loaded conversations:",h.map(d=>{var B;return{id:d.id,title:d.title,sessionId:d.sessionId,messageCount:((B=d.messages)==null?void 0:B.length)||0}})),setTimeout(()=>{fr.getState().cleanupStreamingMessages()},100)}catch(c){oi("Failed to load chat state:",c);const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=io(),h=Pn(),d={id:u,sessionId:g,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:h};fr.setState({conversations:[d],currentConversationId:u,sessionId:g}),n=g}else{const c=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=io(),g=Pn(),h={id:c,sessionId:u,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:g};fr.setState({conversations:[h],currentConversationId:c,sessionId:u}),n=u}const A=fr.getState(),a=A.currentConversationId?A.conversations.find(c=>c.id===A.currentConversationId):null,s=i&&(a!=null&&a.apiKey)?a.apiKey:Jn,o=i&&(a!=null&&a.apiUrl)?a.apiUrl:Pn();try{const c=await li();if(c.configureApi(o,s,n),Td=o,zd=!0,s===Jn)try{const u=new c.ApiClient({apiUrl:o,apiKey:s,sessionId:null});if(typeof u.validateApiKey=="function"&&(await u.validateApiKey(),Xe("✅ Default API key validated on startup")),typeof u.getAdapterInfo=="function"){const g=await u.getAdapterInfo();Xe("✅ Adapter info loaded for default key:",g);const h=fr.getState();h.currentConversationId&&fr.setState({conversations:h.conversations.map(d=>d.id===h.currentConversationId?{...d,adapterInfo:g,updatedAt:new Date}:d)})}}catch(u){jr("Failed to validate default API key on startup:",u)}}catch(c){oi("Failed to initialize API:",c)}};typeof window<"u"&&Srt();const Urt=Fc(),vrt=new Map,Grt=new Map,Rrt=new Map,zrt=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},Cle=e=>typeof e=="object"&&e!==null&&"message"in e,Trt=e=>e instanceof Error?e.message:typeof e=="string"?e:Cle(e)?e.message??"Unknown error":"Unknown error";function jrt({conversationId:e,onFilesSelected:t,onUploadError:r,onClose:n,onUploadingChange:i,onUploadSuccess:A,maxFiles:a=xr.maxFilesPerConversation,disabled:s=!1}){const[o,l]=F.useState(!1),[c,u]=F.useState(0),g=F.useRef(null),h=F.useRef(Rrt),d=F.useRef(new Map),B=F.useRef(!0),y=F.useRef(vrt),w=F.useRef(Grt),f=F.useRef(e),I=fr(ne=>ne.conversations),Y=F.useMemo(()=>{if(!e)return new Map;const ne=y.current.get(e);return ne?new Map(ne):new Map},[e,c]),Q=F.useCallback(ne=>{if(!ne){i==null||i(null,!1),u(Be=>Be+1);return}const ge=y.current.get(ne)||new Map,P=I.find(Be=>Be.id===ne);if(P&&P.attachedFiles){const Be=P.attachedFiles.filter(pe=>!pe.processing_status||pe.processing_status==="processing"||pe.processing_status==="uploading"),Fe=new Map(ge);let Me=!1;Be.forEach(pe=>{if(!Array.from(ge.values()).find(Ee=>Ee.fileId===pe.file_id)){const Ee=`${ne}-${pe.filename}-${pe.file_id}`;Fe.set(Ee,{filename:pe.filename,progress:pe.processing_status==="uploading"?50:90,status:pe.processing_status||"processing",fileId:pe.file_id}),Me=!0}}),Me||Fe.size>0?(y.current.set(ne,Fe),i==null||i(ne,!0)):(y.current.delete(ne),i==null||i(ne,!1))}else ge.size>0?y.current.set(ne,ge):y.current.delete(ne),i==null||i(ne,ge.size>0);u(Be=>Be+1)},[I,i]);F.useEffect(()=>{f.current=e,Q(e)},[e,Q]),F.useEffect(()=>{e&&Q(e)},[I,e,Q]);const M=F.useCallback((ne,ge)=>{if(!ne)return;const P=y.current.get(ne)||new Map,Be=ge(new Map(P));Be.size>0?y.current.set(ne,Be):y.current.delete(ne),i==null||i(ne,Be.size>0),u(Fe=>Fe+1)},[i]),D=F.useCallback((ne,ge)=>{if(!ne)return;const P=w.current.get(ne)||[],Be=ge([...P||[]]),Fe=new Set(P.map(Me=>Me.file_id));if(w.current.set(ne,Be),t(ne,Be),A){const Me=Be.filter(pe=>!Fe.has(pe.file_id));Me.length>0&&A(ne,Me)}u(Me=>Me+1)},[t,A]),G=fr(ne=>ne.removeFileFromConversation),z=fr(ne=>ne.addFileToConversation);F.useEffect(()=>(B.current=!0,()=>{B.current=!1}),[]);const R=F.useCallback(()=>{B.current=!1,new Map(d.current).forEach(ge=>ge.abort()),setTimeout(()=>{const ge=fr.getState(),P=new Map(ge.conversations.map(Fe=>[Fe.id,Fe])),Be=[];h.current.forEach((Fe,Me)=>{var pe;if(Fe){const ke=P.get(Fe);if(new Set(((pe=ke==null?void 0:ke.attachedFiles)==null?void 0:pe.map(je=>je.file_id))||[]).has(Me)){h.current.delete(Me);return}}Be.push({fileId:Me,conversationId:Fe||null})}),Be.length>0&&(n==null||n(),Be.forEach(async({fileId:Fe,conversationId:Me})=>{try{if(Me)await G(Me,Fe);else{const ke=Ii()?zrt():null;await Rd.deleteFile(Fe,void 0,void 0,ke??void 0)}}catch(pe){if(Cle(pe)){const ke=pe.message??"";!ke.includes("404")&&ke.includes("File not found")}}}))},300)},[n,G]);F.useEffect(()=>R,[R]);const j=F.useCallback(async ne=>{if(!ne||ne.length===0)return;const ge=Array.from(ne),P=fr.getState(),Be=e||P.currentConversationId;if(!Be){r==null||r("Please select or create a conversation before uploading files.");return}const Fe=P.conversations.find(xe=>xe.id===Be);if(!Fe){r==null||r("Conversation not found. Please try again.");return}if((w.current.get(Be)||[]).length+ge.length>a){const xe=`Maximum ${a} files allowed per conversation. Please remove some files first.`;r==null||r(xe);return}if(xr.maxTotalFiles!==null&&P.conversations.reduce((Se,Te)=>{var Ke;return Se+(((Ke=Te.attachedFiles)==null?void 0:Ke.length)||0)},0)+ge.length>xr.maxTotalFiles){const Se=`Maximum ${xr.maxTotalFiles} total files allowed across all conversations. Please remove some files from other conversations first.`;r==null||r(Se);return}const pe=Ii();if(pe){if(!Fe.adapterName){r==null||r("Adapter not configured for this conversation. Please select an adapter first.");return}}else if(!Fe.apiKey||Fe.apiKey===Urt){r==null||r("API key not configured for this conversation. Please configure API settings first.");return}const ke=Fe.apiKey,Ee=Fe.adapterName,je=to(Fe.apiUrl);for(let xe=0;xe<ge.length;xe++){const Ie=ge[xe],Se=new AbortController;d.current.set(Ie.name,Se);const Te=`${Be}-${Ie.name}-${Date.now()}-${xe}`;let Ke=null;try{const et=await Rd.uploadFile(Ie,rt=>{if(M(Be,It=>(It.set(Te,rt),It)),rt.fileId&&!Ke){Ke=rt.fileId,h.current.set(rt.fileId,Be);const It={file_id:rt.fileId,filename:Ie.name,mime_type:Ie.type||"application/octet-stream",file_size:Ie.size,processing_status:rt.status==="uploading"?"uploading":rt.status==="processing"?"processing":rt.status==="completed"?"completed":void 0};Xe(`[FileUpload] Adding file ${rt.fileId} to conversation ${Be} immediately (status: ${It.processing_status})`),z(Be,It)}},ke,je,pe?Ee:void 0).catch(rt=>{if(rt.message&&rt.message.includes("was deleted")){Ke&&h.current.delete(Ke);const It=rt.message.match(/File\s+([\w-]+)\s+was deleted/);return It&&It[1]&&h.current.delete(It[1]),Xe(`File ${Ie.name} was deleted during upload`),null}throw rt});et?(h.current.set(et.file_id,Be),Xe(`[FileUpload] Updating file ${et.file_id} in conversation ${Be} with final status`),z(Be,et),et.processing_status==="completed"?M(Be,rt=>(rt.delete(Te),rt)):M(Be,rt=>{const It=rt.get(Te);return It&&rt.set(Te,{...It,progress:90,status:"processing",fileId:et.file_id}),rt}),D(Be,rt=>{if(new Set(rt.map(yr=>yr.file_id)).has(et.file_id))return rt;const gr=[...rt,et];return Xe(`[FileUpload] Updated uploadedFiles for ${Be}: ${gr.length} files`,gr),gr})):(jr(`Upload completed for ${Ie.name} but uploadedAttachment is null`),M(Be,rt=>(rt.delete(Te),rt)))}catch(et){const rt=Trt(et);if(et instanceof DOMException&&et.name==="AbortError"||Se.signal.aborted){Xe(`Upload cancelled for ${Ie.name}`),Ke&&h.current.delete(Ke);continue}if(rt.includes("was deleted")){Xe(`File ${Ie.name} was deleted during upload`),Ke&&h.current.delete(Ke);const It=rt.match(/File\s+([\w-]+)\s+was deleted/);It&&It[1]&&h.current.delete(It[1]);continue}B.current?(zg(`Failed to upload file ${Ie.name}:`,et),zg(`File type: ${Ie.type}, File name: ${Ie.name}`),r==null||r(rt||`Failed to upload ${Ie.name}`)):jr(`Upload error for ${Ie.name} (component unmounted):`,rt),Ke&&h.current.delete(Ke)}finally{d.current.delete(Ie.name)}}},[z,e,a,r,D,M]),W=F.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),s||l(!0)},[s]),te=F.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),l(!1)},[]),X=F.useCallback(ne=>{if(ne.preventDefault(),ne.stopPropagation(),l(!1),s)return;const ge=ne.dataTransfer.files;j(ge)},[s,j]),Z=F.useCallback(ne=>{const ge=ne.target.files;j(ge),g.current&&(g.current.value="")},[j]),ee=F.useCallback(()=>{!s&&g.current&&g.current.click()},[s]),Ae=Y.size>0,K=F.useMemo(()=>{const ne=new Map;return I.forEach(ge=>{ne.set(ge.id,ge.title||"Conversation")}),ne},[I]),$=F.useMemo(()=>{const ne=[];return y.current.forEach((ge,P)=>{P!==e&&ge.size>0&&ne.push({conversationId:P,uploads:Array.from(ge.entries()).map(([Be,Fe])=>({key:Be,progress:Fe}))})}),ne},[e,c]),L=T.jsx("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:Array.from(Y.values()).map(ne=>T.jsxs("div",{className:"w-full max-w-full flex items-center gap-3 p-3 bg-slate-50 dark:bg-slate-800/50 rounded-lg overflow-hidden",children:[T.jsx(ng,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400 animate-spin flex-shrink-0"}),T.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[T.jsx("p",{className:"text-sm font-medium text-slate-700 dark:text-slate-300 truncate",children:ne.filename}),T.jsx("div",{className:"mt-1 bg-slate-200 dark:bg-slate-700 rounded-full h-1.5",children:T.jsx("div",{className:"bg-emerald-600 dark:bg-emerald-400 h-1.5 rounded-full transition-all duration-300",style:{width:`${ne.progress}%`}})})]}),T.jsx("span",{className:"text-xs text-slate-500 dark:text-slate-400",children:ne.status==="uploading"?"Uploading...":ne.status==="processing"?"Processing...":ne.status==="completed"?"Done":"Error"})]},ne.filename))});return Ae?T.jsx("div",{className:"w-full max-w-full overflow-hidden space-y-3",children:L}):T.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-3",children:[T.jsxs("div",{onClick:ee,onDragOver:W,onDragLeave:te,onDrop:X,className:`
|
|
1223
|
+
-d '{"client_name": "chat-app", "adapter_name": "file-document-qa"}'`}else s.includes("API key not configured")&&(s=a instanceof Error?a.message:s);throw r&&r({filename:t.name,progress:0,status:"error",error:s}),new Error(s)}}static async uploadFiles(t,r){const n=t.map(async(i,A)=>{try{return await this.uploadFile(i,a=>{r&&r(A,a)})}catch(a){throw oi(`Failed to upload file ${i.name}:`,a),a}});return Promise.all(n)}static async listFiles(t,r,n){try{const i=await li(),A=_0(r),a=Ii();let s=null,o=null;if(a){if(o=n||(typeof window<"u"?localStorage.getItem("chat-adapter-name"):null),!o)throw new Error("Adapter not configured")}else if(s=t||localStorage.getItem("chat-api-key")||Am()||im,!s||s==="your-api-key-here"||s==="orbit-123456789")throw new Error("API key not configured");const l=new i.ApiClient({apiUrl:A,apiKey:s,sessionId:null,adapterName:o});if(!l.listFiles)throw new Error("File listing is not available. Please use the local API build or update the npm package.");const c=await l.listFiles();return(Array.isArray(c)?c:Array.isArray(c.files)?c.files:[]).map(g=>({file_id:g.file_id,filename:g.filename,mime_type:g.mime_type,file_size:g.file_size,upload_timestamp:g.upload_timestamp,processing_status:g.processing_status,chunk_count:g.chunk_count}))}catch(i){oi("Failed to list files:",i);const A=i instanceof Error?i.message:"Failed to list files";throw new Error(A)}}static async getFileInfo(t,r,n,i){try{const A=await li(),a=_0(n),s=Ii();let o=null,l=null;if(s){if(l=i||(typeof window<"u"?localStorage.getItem("chat-adapter-name"):null),!l)throw new Error("Adapter not configured")}else if(o=r||localStorage.getItem("chat-api-key")||Am()||im,!o||o==="your-api-key-here"||o==="orbit-123456789")throw new Error("API key not configured");const c=new A.ApiClient({apiUrl:a,apiKey:o,sessionId:null,adapterName:l});if(!c.getFileInfo)throw new Error("File info retrieval is not available. Please use the local API build or update the npm package.");const u=await c.getFileInfo(t);return{file_id:u.file_id,filename:u.filename,mime_type:u.mime_type,file_size:u.file_size,upload_timestamp:u.upload_timestamp,processing_status:u.processing_status,chunk_count:u.chunk_count}}catch(A){if(A instanceof Error&&(A.message.includes("404")||A.message.includes("File not found")))throw new Error(`File ${t} was deleted`);oi(`Failed to get file info for ${t}:`,A);const a=A instanceof Error?A.message:`Failed to get file info: ${t}`;throw new Error(a)}}static async pollFileStatus(t,r=30,n=2e3,i,A,a,s){for(let o=0;o<r;o++)try{if(i&&!i())throw new Error("Polling cancelled - component unmounted");const l=await this.getFileInfo(t,A,a,s);if(l.processing_status==="completed")return l;if(l.processing_status==="error"||l.processing_status==="failed")throw new Error(`File processing failed for ${t}`);o<r-1&&await new Promise(c=>setTimeout(c,n))}catch(l){const c=l instanceof Error?l.message:String(l);if(c.includes("404")||c.includes("File not found")||c.includes("was deleted"))throw new Error(`File ${t} was deleted during upload`);if(c.includes("component unmounted"))throw l;if(o<r-1){await new Promise(u=>setTimeout(u,n));continue}throw l}throw new Error(`File processing timeout: ${t} did not complete within ${r*n/1e3} seconds`)}static async deleteFile(t,r,n,i){try{const A=await li(),a=_0(n),s=Ii();let o=null,l=null;if(s){if(l=i||(typeof window<"u"?localStorage.getItem("chat-adapter-name"):null),!l)throw new Error("Adapter not configured")}else if(o=r||localStorage.getItem("chat-api-key")||Am()||im,!o||o==="your-api-key-here"||o==="orbit-123456789")throw new Error("API key not configured");const c=new A.ApiClient({apiUrl:a,apiKey:o,sessionId:null,adapterName:l});if(!c.deleteFile)throw new Error("File deletion is not available. Please use the local API build or update the npm package.");return await c.deleteFile(t)}catch(A){if(A instanceof Error&&(A.message.includes("404")||A.message.includes("File not found")||A.message.includes("Not Found")))return{message:"File already deleted",file_id:t};oi(`Failed to delete file ${t}:`,A);const a=A instanceof Error?A.message:`Failed to delete file: ${t}`;throw new Error(a)}}}const $K=e=>{let t;const r=new Set,n=(l,c)=>{const u=typeof l=="function"?l(t):l;if(!Object.is(u,t)){const g=t;t=c??(typeof u!="object"||u===null)?u:Object.assign({},t,u),r.forEach(h=>h(t,g))}},i=()=>t,s={setState:n,getState:i,getInitialState:()=>o,subscribe:l=>(r.add(l),()=>r.delete(l))},o=t=e(n,i,s);return s},Frt=e=>e?$K(e):$K,Yrt=e=>e;function brt(e,t=Yrt){const r=Kn.useSyncExternalStore(e.subscribe,Kn.useCallback(()=>t(e.getState()),[e,t]),Kn.useCallback(()=>t(e.getInitialState()),[e,t]));return Kn.useDebugValue(r),r}const eV=e=>{const t=Frt(e),r=n=>brt(t,n);return Object.assign(r,t),r},xrt=e=>e?eV(e):eV;class Nrt{constructor(){gA(this,"audioQueue",[]);gA(this,"isPlaying",!1);gA(this,"currentAudio",null);gA(this,"audioContext",null);gA(this,"isEnabled",!1);gA(this,"onPlaybackStart",null);gA(this,"onPlaybackEnd",null);gA(this,"onChunkPlayed",null);gA(this,"blobUrls",[]);gA(this,"suppressPlaybackErrors",!1)}async enableAudio(){try{try{const t=new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=");t.volume=0,await t.play(),t.pause()}catch{Xe("[AudioStreamManager] Silent audio unlock deferred (will work on next interaction)")}return this.isEnabled=!0,Xe("[AudioStreamManager] Audio playback enabled"),!0}catch{return!1}}disableAudio(){!this.isEnabled&&!this.isPlaying||(this.isEnabled=!1,this.stop())}async ensureAudioContext(){if(!this.audioContext&&typeof AudioContext<"u")try{return this.audioContext=new AudioContext,this.audioContext.state==="suspended"&&await this.audioContext.resume(),!0}catch{return!1}if(this.audioContext&&this.audioContext.state==="suspended")try{await this.audioContext.resume()}catch{return!1}return!0}isAudioEnabled(){return this.isEnabled}setOnPlaybackStart(t){this.onPlaybackStart=t}setOnPlaybackEnd(t){this.onPlaybackEnd=t}setOnChunkPlayed(t){this.onChunkPlayed=t}async addChunk(t){if(!this.isEnabled){Xe(`[AudioStreamManager] Audio disabled, dropping chunk ${t.chunkIndex}`);return}Xe(`[AudioStreamManager] Adding chunk ${t.chunkIndex} to queue`),this.audioQueue.push(t),this.audioQueue.sort((r,n)=>r.chunkIndex-n.chunkIndex),this.isPlaying||this.playNextChunk()}async playNextChunk(){var r,n;if(this.audioQueue.length===0){this.isPlaying=!1,this.onPlaybackEnd&&this.onPlaybackEnd();return}if(!this.isEnabled){this.audioQueue=[],this.isPlaying=!1;return}this.suppressPlaybackErrors=!1,await this.ensureAudioContext(),this.isPlaying=!0;const t=this.audioQueue.shift();try{if(!this.isPlaying)return;if(this.onPlaybackStart&&t.chunkIndex===0&&this.onPlaybackStart(),Xe(`[AudioStreamManager] Playing chunk ${t.chunkIndex}`),!t.audio||t.audio.length===0)throw new Error(`Empty audio data for chunk ${t.chunkIndex}`);let i;try{i=atob(t.audio)}catch(u){throw new Error(`Failed to decode base64 audio for chunk ${t.chunkIndex}: ${u instanceof Error?u.message:String(u)}`)}if(i.length===0)throw new Error(`Decoded audio data is empty for chunk ${t.chunkIndex}`);const A=new Uint8Array(i.length);for(let u=0;u<i.length;u++)A[u]=i.charCodeAt(u);const a=t.audioFormat==="mp3"?"audio/mpeg":t.audioFormat==="wav"?"audio/wav":t.audioFormat==="ogg"?"audio/ogg":t.audioFormat==="opus"?"audio/ogg; codecs=opus":t.audioFormat==="webm"?"audio/webm":`audio/${t.audioFormat}`,s=new Blob([A],{type:a}),o=URL.createObjectURL(s);this.blobUrls.push(o);const l=new Audio;l.src=o,this.currentAudio=l;const c=()=>{l.src&&(l.src=""),URL.revokeObjectURL(o),this.blobUrls=this.blobUrls.filter(u=>u!==o)};await new Promise((u,g)=>{let h=!1;const d=()=>{var f;if(h)return;const y=l.error,w=y?{code:y.code,message:y.message||`MediaError code ${y.code}`,MEDIA_ERR_ABORTED:y.code===MediaError.MEDIA_ERR_ABORTED,MEDIA_ERR_NETWORK:y.code===MediaError.MEDIA_ERR_NETWORK,MEDIA_ERR_DECODE:y.code===MediaError.MEDIA_ERR_DECODE,MEDIA_ERR_SRC_NOT_SUPPORTED:y.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"Unknown error";if(this.suppressPlaybackErrors){h=!0,c(),u();return}h=!0,console.error(`[AudioStreamManager] Error playing chunk ${t.chunkIndex}:`,w,{audioFormat:t.audioFormat,chunkIndex:t.chunkIndex,audioLength:t.audio.length,mimeType:a,audioContextState:(f=this.audioContext)==null?void 0:f.state,audioSrc:l.src,audioReadyState:l.readyState}),zg(`[AudioStreamManager] Error playing chunk ${t.chunkIndex}:`,w),c(),g(new Error(`Audio playback error: ${JSON.stringify(w)}`))};l.addEventListener("error",d,{once:!0});const B=async()=>{var y;if(!h)try{l.addEventListener("ended",()=>{h||(h=!0,Xe(`[AudioStreamManager] Chunk ${t.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(t.chunkIndex),c(),u())},{once:!0});const w=l.play();w&&await w}catch(w){if(h)return;if(this.suppressPlaybackErrors){h=!0,c(),u();return}h=!0,console.error(`[AudioStreamManager] Audio.play() rejected for chunk ${t.chunkIndex}:`,w,{audioFormat:t.audioFormat,chunkIndex:t.chunkIndex,audioContextState:(y=this.audioContext)==null?void 0:y.state,isEnabled:this.isEnabled,audioSrc:l.src,audioReadyState:l.readyState}),c(),g(w)}};l.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?B():l.addEventListener("canplay",B,{once:!0})}),this.currentAudio=null,this.playNextChunk()}catch(i){if(this.suppressPlaybackErrors)return;const A=i instanceof Error?i.message:String(i);console.error(`[AudioStreamManager] Failed to play chunk ${t.chunkIndex}:`,A,i,{audioFormat:t.audioFormat,chunkIndex:t.chunkIndex,audioLength:(r=t.audio)==null?void 0:r.length,audioContextState:(n=this.audioContext)==null?void 0:n.state,isEnabled:this.isEnabled}),zg(`[AudioStreamManager] Failed to play chunk ${t.chunkIndex}:`,i),this.playNextChunk()}}stop(){this.suppressPlaybackErrors=!0,this.isPlaying=!1,this.audioQueue=[],this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.blobUrls.forEach(t=>URL.revokeObjectURL(t)),this.blobUrls=[]}reset(){this.stop()}getQueueSize(){return this.audioQueue.length}isCurrentlyPlaying(){return this.isPlaying}}const mc=new Nrt,Jn=Fc(),Pf=()=>{const e=localStorage.getItem("chatbot-session-id");if(e)return e;const t=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return localStorage.setItem("chatbot-session-id",t),t},Drt=e=>{localStorage.setItem("chatbot-session-id",e)};let krt=0;const fN=e=>{const t=Date.now(),r=++krt,n=Math.random().toString(36).substr(2,9);return`msg_${t}_${r}_${n}_${e}`},io=()=>{const e=Date.now(),t=Math.random().toString(36).substr(2,9);return`session_${e}_${t}`};let zd=!1,Td="";async function qo(){if(zd&&Td)return!0;try{const e=await li(),t=localStorage.getItem("chat-api-url");t&&t===qc&&localStorage.removeItem("chat-api-url");const r=t&&t!==qc?t:Pn(),n=localStorage.getItem("chat-api-key")||Jn,i=Pf();return e.configureApi(r,n,i),Td=r,zd=!0,!0}catch(e){return oi("Failed to configure API:",e),!1}}const fr=xrt((e,t)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,sessionId:Pf(),getSessionId:()=>t().sessionId,configureApiSettings:async(r,n,i,A)=>{const a=t(),s=a.conversations.find(c=>c.id===a.currentConversationId),o=Ii(),l=(s==null?void 0:s.sessionId)||i||Pf();i&&Drt(i),e({sessionId:l});try{const c=await li();if(o){if(!A||!A.trim())throw new Error("Adapter name is required when API middleware is enabled");c.configureApi(r,null,l,A),Td=r,zd=!0;let u;try{const g=new c.ApiClient({apiUrl:r,apiKey:null,sessionId:null,adapterName:A});typeof g.getAdapterInfo=="function"&&(u=await g.getAdapterInfo(),Xe("Adapter info loaded:",u))}catch(g){jr("Failed to load adapter info:",g)}if(s)e(g=>({conversations:g.conversations.map(h=>h.id===s.id?{...h,adapterName:A,apiUrl:r,adapterInfo:u,apiKey:void 0,updatedAt:new Date}:h)}));else if(A&&A.trim()){const g=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=io();e(d=>({conversations:[...d.conversations,{id:g,sessionId:h,title:"New Conversation",messages:[],createdAt:new Date,updatedAt:new Date,adapterName:A,apiUrl:r,adapterInfo:u}],currentConversationId:g}))}}else{let u;if(n&&n.trim())try{const g=new c.ApiClient({apiUrl:r,apiKey:n,sessionId:null});if(typeof g.validateApiKey=="function"){Xe("Validating API key before configuration...");const h=await g.validateApiKey();Xe("API key validation successful:",{exists:h.exists,active:h.active,adapter_name:h.adapter_name,client_name:h.client_name})}else jr("API key validation not available (validateApiKey method not found)");if(typeof g.getAdapterInfo=="function")try{u=await g.getAdapterInfo(),Xe("Adapter info loaded:",u)}catch(h){jr("Failed to load adapter info:",h)}}catch(g){throw g instanceof Error?g:new Error(`API key validation failed: ${String(g)}`)}if(c.configureApi(r,n||"",l),Td=r,zd=!0,s&&n&&n.trim())e(g=>({conversations:g.conversations.map(h=>h.id===s.id?{...h,apiKey:n,apiUrl:r,adapterInfo:u,adapterName:void 0,updatedAt:new Date}:h)})),setTimeout(()=>{const g=t();localStorage.setItem("chat-state",JSON.stringify({conversations:g.conversations,currentConversationId:g.currentConversationId}))},0);else if(n&&n.trim()){const g=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=io(),d={id:g,sessionId:h,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:n,apiUrl:r,adapterInfo:u};e(B=>{let y=[d,...B.conversations];const w=xr.maxConversations;return w!==null&&y.length>w&&(y=y.slice(0,w)),{conversations:y,currentConversationId:g,sessionId:h}}),setTimeout(()=>{const B=t();localStorage.setItem("chat-state",JSON.stringify({conversations:B.conversations,currentConversationId:B.currentConversationId}))},0)}}}catch(c){throw e({isLoading:!1}),c instanceof Error?c:new Error("Failed to configure API settings")}o?A?localStorage.setItem("chat-adapter-name",A):localStorage.removeItem("chat-adapter-name"):(r&&r!==qc?localStorage.setItem("chat-api-url",r):localStorage.removeItem("chat-api-url"),n&&localStorage.setItem("chat-api-key",n)),e({isLoading:!1})},createConversation:()=>{const r=t(),n=xr.maxConversations,i=r.conversations.length,A=r.currentConversationId?r.conversations.find(h=>h.id===r.currentConversationId):null;if(n!==null&&i>=n){const h=`Maximum of ${n} conversations reached. Please delete an existing conversation before starting a new one.`;throw e({error:h}),new Error(h)}if(A&&A.messages.length===0){const h="Finish or delete the current conversation before starting a new one.";throw e({error:h}),new Error(h)}const a=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=io(),o=Pn(),l=Jn,c=Ii(),u=c&&typeof window<"u"?localStorage.getItem("chat-adapter-name"):null,g={id:a,sessionId:s,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:c?void 0:l,apiUrl:o,adapterName:u||void 0};return e(h=>{let d=[g,...h.conversations];const B=xr.maxConversations;return B!==null&&d.length>B&&(d=d.slice(0,B)),{conversations:d,currentConversationId:a,sessionId:s}}),qo().then(h=>{h&&li().then(d=>{c&&u?d.configureApi(o,null,s,u):d.configureApi(o,l,s);try{const B=new d.ApiClient({apiUrl:o,apiKey:c?null:l,sessionId:null,adapterName:c?u:null});typeof B.getAdapterInfo=="function"&&B.getAdapterInfo().then(y=>{Xe("✅ Adapter info loaded for new conversation:",y);const w=fr.getState();fr.setState({conversations:w.conversations.map(f=>f.id===a?{...f,adapterInfo:y,updatedAt:new Date}:f)})}).catch(y=>{jr("Failed to load adapter info for new conversation:",y)})}catch{}})}),setTimeout(()=>{const h=t();localStorage.setItem("chat-state",JSON.stringify({conversations:h.conversations,currentConversationId:h.currentConversationId}))},0),a},selectConversation:async r=>{const n=t().conversations.find(i=>i.id===r);if(n){const i=n.messages.some(o=>o.role==="assistant"&&o.isStreaming);e({currentConversationId:r,sessionId:n.sessionId,isLoading:i});const A=n.apiUrl||Pn(),a=n.apiKey||Jn;if(await qo()){const o=await li();if(o.configureApi(A,a,n.sessionId),!n.adapterInfo)try{const l=new o.ApiClient({apiUrl:A,apiKey:a,sessionId:null});if(typeof l.getAdapterInfo=="function"){const c=await l.getAdapterInfo();Xe("Adapter info loaded for conversation:",c),e(u=>({conversations:u.conversations.map(g=>g.id===r?{...g,adapterInfo:c,updatedAt:new Date}:g)})),setTimeout(()=>{const u=t();localStorage.setItem("chat-state",JSON.stringify({conversations:u.conversations,currentConversationId:u.currentConversationId}))},0)}}catch{}}}setTimeout(()=>{const i=t();localStorage.setItem("chat-state",JSON.stringify({conversations:i.conversations,currentConversationId:i.currentConversationId}))},0)},deleteConversation:async r=>{var A,a;const n=t(),i=n.conversations.find(s=>s.id===r);if(Xe(`🗑️ Deleting conversation ${r}:`,{conversationId:r,sessionId:i==null?void 0:i.sessionId,title:i==null?void 0:i.title,messageCount:i==null?void 0:i.messages.length,fileCount:((A=i==null?void 0:i.attachedFiles)==null?void 0:A.length)||0}),n.currentConversationId===r&&mc.stop(),i!=null&&i.sessionId)try{if(!await qo())oi("Failed to configure API for conversation deletion");else{const o=Ii(),l=i.apiUrl||Pn(),c=i.apiKey||Jn,u=i.adapterName;o?u?Xe(`🔑 Using conversation's adapter for deletion: ${u} (conversation: ${r})`):jr(`Skipping server deletion for conversation ${r}: adapter not configured`):Xe(`🔑 Using conversation's API key for deletion: ${c.substring(0,8)}... (conversation: ${r})`);const g=await li(),h=new g.ApiClient({apiUrl:l,apiKey:o?null:c,sessionId:i.sessionId,adapterName:o?u:null}),d=((a=i==null?void 0:i.attachedFiles)==null?void 0:a.map(B=>B.file_id))||[];if(Xe(`🔧 Calling deleteConversationWithFiles for session: ${i.sessionId}`),Xe(`🔧 File IDs to delete: ${d.join(", ")||"none"}`),h.deleteConversationWithFiles){const B=await h.deleteConversationWithFiles(i.sessionId,d);Xe(`✅ Deleted conversation and files for session: ${i.sessionId}`,B),Xe(` - Deleted ${B.deleted_messages} messages`),Xe(` - Deleted ${B.deleted_files} files`),B.file_deletion_errors&&B.file_deletion_errors.length>0&&jr(` - Errors deleting files: ${B.file_deletion_errors.join(", ")}`)}else jr("⚠️ deleteConversationWithFiles method not available on API client")}}catch(s){oi("Failed to clear conversation history from server:",s)}e(s=>{var c;const o=s.conversations.filter(u=>u.id!==r),l=s.currentConversationId===r?((c=o[0])==null?void 0:c.id)||null:s.currentConversationId;if(o.length===0){const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=io(),h=Pn(),d={id:u,sessionId:g,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:h};return qo().then(B=>{B&&li().then(y=>{y.configureApi(h,Jn,g);try{const w=new y.ApiClient({apiUrl:h,apiKey:Jn,sessionId:null});typeof w.validateApiKey=="function"&&w.validateApiKey().then(()=>{Xe("✅ Default API key validated after creating new conversation")}).catch(()=>{jr("Failed to validate default API key")}),typeof w.getAdapterInfo=="function"&&w.getAdapterInfo().then(f=>{Xe("✅ Adapter info loaded for default key:",f);const I=fr.getState();fr.setState({conversations:I.conversations.map(Y=>Y.id===u?{...Y,adapterInfo:f,updatedAt:new Date}:Y)})}).catch(()=>{jr("Failed to load adapter info for default key")})}catch{}})}),setTimeout(()=>{localStorage.setItem("chat-state",JSON.stringify({conversations:[d],currentConversationId:u}))},0),{conversations:[d],currentConversationId:u,sessionId:g}}return setTimeout(()=>{localStorage.setItem("chat-state",JSON.stringify({conversations:o,currentConversationId:l}))},0),{conversations:o,currentConversationId:l}})},deleteAllConversations:async()=>{const n=[...t().conversations];mc.stop();const i=n.map(async l=>{var c;if(l!=null&&l.sessionId)try{if(!await qo()){oi("Failed to configure API for conversation deletion");return}const g=Ii(),h=to(l.apiUrl),d=l.apiKey||Jn,B=l.adapterName;if(g&&!B){Xe(`Skipping server deletion for conversation ${l.id}: adapter not configured`);return}const y=await li(),w=new y.ApiClient({apiUrl:h,apiKey:g?null:d,sessionId:l.sessionId,adapterName:g?B:null}),f=((c=l==null?void 0:l.attachedFiles)==null?void 0:c.map(I=>I.file_id))||[];w.deleteConversationWithFiles?(await w.deleteConversationWithFiles(l.sessionId,f),Xe(`✅ Deleted conversation ${l.id} and files`)):jr(`deleteConversationWithFiles not available for conversation ${l.id}`)}catch(u){oi(`Failed to delete conversation ${l.id} from server:`,u)}});Promise.allSettled(i).then(l=>{const c=l.filter(u=>u.status==="rejected");c.length>0&&oi(`Some conversations failed to delete from server: ${c.length}`,c)});const A=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a=io(),s=Pn(),o={id:A,sessionId:a,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:s};qo().then(l=>{l&&li().then(c=>{c.configureApi(s,Jn,a);try{const u=new c.ApiClient({apiUrl:s,apiKey:Jn,sessionId:null});typeof u.validateApiKey=="function"&&u.validateApiKey().then(()=>{Xe("✅ Default API key validated after clearing all conversations")}).catch(()=>{jr("Failed to validate default API key")}),typeof u.getAdapterInfo=="function"&&u.getAdapterInfo().then(g=>{Xe("✅ Adapter info loaded for default key:",g);const h=fr.getState();fr.setState({conversations:h.conversations.map(d=>d.id===A?{...d,adapterInfo:g,updatedAt:new Date}:d)})}).catch(()=>{jr("Failed to load adapter info for default key")})}catch{}})}),e({conversations:[o],currentConversationId:A,sessionId:a}),setTimeout(()=>{localStorage.setItem("chat-state",JSON.stringify({conversations:[o],currentConversationId:A}))},0)},sendMessage:async(r,n,i)=>{var A,a,s,o,l,c,u,g,h,d,B;try{if(t().isLoading){jr("Another request is already in progress");return}if(!await qo())throw new Error("API not properly configured. Please configure API settings first.");let w=t().currentConversationId;w||(w=t().createConversation());const f=t().conversations.find(X=>X.id===w);if(!f)throw new Error("Conversation not found");const I=n?n.map(X=>{var ee;const Z=(ee=f==null?void 0:f.attachedFiles)==null?void 0:ee.find(Ae=>Ae.file_id===X);return Z||{file_id:X,filename:"",mime_type:"",file_size:0}}).filter(X=>X!==void 0):[];I.length>0&&I.forEach(X=>{t().addFileToConversation(w,X)});const Y=i||null;let Q,M=null;if(Y){if(Q=f.messages.find(X=>{var Z;return((Z=X.threadInfo)==null?void 0:Z.thread_id)===Y}),!Q)throw new Error("Thread metadata not found. Please recreate the thread from this message.");if(M=((A=Q.threadInfo)==null?void 0:A.thread_session_id)||null,!M)throw new Error("Thread session is missing. Please recreate the thread from this message.")}const D={id:fN("user"),content:r,role:"user",timestamp:new Date,attachments:I.length>0?I:void 0},G=fN("assistant"),z={id:G,content:"",role:"assistant",timestamp:new Date,isStreaming:!0};Y&&Q&&(D.isThreadMessage=!0,D.threadId=Y,D.parentMessageId=Q.id,z.isThreadMessage=!0,z.threadId=Y,z.parentMessageId=Q.id);let R=!1,j=!1;if(e(X=>{const Z=X.conversations.find($=>$.id===w),ee=(Z==null?void 0:Z.messages.filter($=>$.role==="assistant"&&$.isStreaming))||[];ee.length>0&&jr(`Cleaning up ${ee.length} existing streaming messages`);const Ae=X.conversations.map($=>{if($.id!==w){const P=xr.maxMessagesPerConversation;if(P!==null){const Be=$.messages.filter(Fe=>!(Fe.role==="assistant"&&Fe.isStreaming));if(Be.length>=P){R=!0;const Fe=Math.max(1,P-1),Me=Be.slice(-Fe),pe=$.messages.filter(ke=>ke.role==="assistant"&&ke.isStreaming);return{...$,messages:[...Me,...pe]}}}return $}const L=$.messages.filter(P=>!(P.role==="assistant"&&P.isStreaming)),ne=xr.maxMessagesPerConversation;let ge=L;if(ne!==null&&L.length>=ne){R=!0;const P=Math.max(1,ne-1);ge=L.slice(-P)}return{...$,messages:[...ge,D,z],updatedAt:new Date,title:$.messages.length===0?r.slice(0,50)+(r.length>50?"...":""):$.title}}),K=xr.maxTotalMessages;if(K!==null){const $=Ae.reduce((L,ne)=>L+ne.messages.filter(ge=>!(ge.role==="assistant"&&ge.isStreaming)).length,0);if($>K){j=!0;let L=$-K;const ne=[...Ae].sort((ge,P)=>ge.updatedAt.getTime()-P.updatedAt.getTime());for(const ge of ne){if(L<=0)break;const P=ge.messages.filter(Be=>!(Be.role==="assistant"&&Be.isStreaming));if(P.length>0){const Be=Math.min(L,P.length),Fe=ge.messages.filter(ke=>ke.role==="assistant"&&ke.isStreaming),Me=[...P.slice(Be),...Fe],pe=Ae.findIndex(ke=>ke.id===ge.id);pe!==-1&&(Ae[pe]={...ge,messages:Me}),L-=Be}}}}return{conversations:Ae,isLoading:!0,error:null}}),R||j){const X=[];R&&xr.maxMessagesPerConversation!==null&&X.push(`Only the most recent ${xr.maxMessagesPerConversation} messages are kept per conversation. Older messages in this chat were removed automatically.`),j&&xr.maxTotalMessages!==null&&X.push(`There is a workspace limit of ${xr.maxTotalMessages} total messages. Older conversations were trimmed to stay within that limit.`),X.length>0&&e({error:X.join(" ")})}const W=w;let te=!1;mc.reset();try{const X=t().conversations.find(xe=>xe.id===W);if(!X)throw new Error("Conversation not found");const Z=Ii();if(Z){if(!X.adapterName)throw jr(`[sendMessage] Conversation ${W} has no adapter name`),new Error("Adapter not configured for this conversation. Please select an adapter first.");Xe(`[sendMessage] Using adapter for conversation ${W}: ${X.adapterName}`)}else{if(!X.apiKey)throw jr(`[sendMessage] Conversation ${W} has no API key`),new Error("API key not configured for this conversation. Please configure API settings first.");Xe(`[sendMessage] Using API key for conversation ${W}: ${X.apiKey.substring(0,8)}...`)}const ee=to(X.apiUrl),Ae=X.apiKey,K=X.adapterName,$=i||null,L=M||X.sessionId,ne=await li();Z?ne.configureApi(ee,null,L,K):ne.configureApi(ee,Ae,L),$&&L!==X.sessionId&&Xe(`[chatStore] Thread mode: using thread session ${L} (original: ${X.sessionId})`),Xe("[chatStore] Starting streamChat with fileIds:",n);const ge=t().conversations.find(xe=>xe.id===W),P=((s=(a=ge==null?void 0:ge.adapterInfo)==null?void 0:a.adapter_name)==null?void 0:s.includes("voice"))||((l=(o=ge==null?void 0:ge.adapterInfo)==null?void 0:o.adapter_name)==null?void 0:l.includes("audio"))||((u=(c=ge==null?void 0:ge.adapterInfo)==null?void 0:c.adapter_name)==null?void 0:u.includes("multilingual")),Be=()=>{try{const xe=localStorage.getItem("chat-settings");if(xe)return JSON.parse(xe).voiceEnabled===!0}catch(xe){jr("Failed to read global voice setting:",xe)}return!1},Fe=ge==null?void 0:ge.audioSettings,Me=Be(),pe=(Fe==null?void 0:Fe.enabled)??Me??P,ke=(Fe==null?void 0:Fe.ttsVoice)||void 0,Ee=(Fe==null?void 0:Fe.language)||"en-US",je=Fe==null?void 0:Fe.audioFormat;Xe("[chatStore] Audio settings:",{returnAudio:pe,ttsVoice:ke,language:Ee,audioFormat:je,isVoiceAdapter:P,adapterName:(g=ge==null?void 0:ge.adapterInfo)==null?void 0:g.adapter_name});for await(const xe of ne.streamChat(r,!0,n,$||void 0,void 0,void 0,Ee,pe,ke)){if(Xe("[chatStore] Received stream chunk:",{text:(h=xe.text)==null?void 0:h.substring(0,50),done:xe.done,hasAudio:!!xe.audio,hasAudioChunk:!!xe.audio_chunk,audioFormat:xe.audioFormat,audioLength:(d=xe.audio)==null?void 0:d.length,chunkIndex:xe.chunk_index}),xe.audio_chunk){Xe("[chatStore] Received audio chunk:",{chunk_index:xe.chunk_index,audioFormat:xe.audioFormat,audioLength:(B=xe.audio_chunk)==null?void 0:B.length});const Ie=xe.chunk_index??0;mc.addChunk({audio:xe.audio_chunk,audioFormat:xe.audioFormat||"opus",chunkIndex:Ie})}if(xe.text){const Ie=Lh(xe.text);Ie?(t().appendToLastMessage(Ie,W),te=!0,await new Promise(Se=>setTimeout(Se,30))):xe.text.length>100&&jr("[chatStore] Filtered out potential base64 audio data from message content")}if(xe.audio&&xe.done&&e(Ie=>({conversations:Ie.conversations.map(Se=>{if(Se.id!==W)return Se;const Te=[...Se.messages],Ke=Te[Te.length-1];return Ke&&Ke.role==="assistant"&&(Te[Te.length-1]={...Ke,audio:xe.audio,audioFormat:xe.audioFormat||"mp3"}),{...Se,messages:Te,updatedAt:new Date}})})),xe.done){Xe("[chatStore] Stream completed, receivedAnyText:",te),Xe("[chatStore] Done chunk received:",{hasThreading:!!xe.threading,threading:xe.threading,assistantMessageId:G});const Ie=xe.threading;Ie&&Ie.supports_threading&&(e(Se=>({conversations:Se.conversations.map(Te=>Te.id!==W?Te:{...Te,messages:Te.messages.map(Ke=>Ke.id===G?{...Ke,supportsThreading:!0,databaseMessageId:Ie.message_id}:Ke),updatedAt:new Date})})),Xe(`[chatStore] Message ${G} marked as supporting threading`,{message_id:Ie.message_id,session_id:Ie.session_id,databaseMessageId:Ie.message_id}));break}}te||(jr("[chatStore] No text received from stream, showing error message"),t().appendToLastMessage("No response received from the server. Please try again later.",W))}catch(X){oi("Chat API error:",X),t().appendToLastMessage("Sorry, there was an error processing your request.",W)}e(X=>{const Z=X.conversations.map(K=>K.id===W?{...K,messages:K.messages.map($=>$.id===G?{...$,isStreaming:!1}:$),updatedAt:new Date}:K),ee=Z.find(K=>K.id===X.currentConversationId),Ae=ee?ee.messages.some(K=>K.role==="assistant"&&K.isStreaming):!1;return{conversations:Z,isLoading:Ae}}),setTimeout(()=>{const X=t();localStorage.setItem("chat-state",JSON.stringify({conversations:X.conversations,currentConversationId:X.currentConversationId}))},0)}catch(y){oi("Chat store error:",y),e(()=>({isLoading:!1,error:`Failed to send message: ${y instanceof Error?y.message:"Unknown error"}`}))}},createThread:async(r,n)=>{try{const i=t().conversations.find(B=>B.sessionId===n);if(!i)throw new Error("Conversation not found for session");const A=Ii();if(A&&!i.adapterName)throw new Error("Adapter not configured for this conversation");if(!A&&!i.apiKey)throw new Error("API key not configured for this conversation");const a=i.messages.find(B=>B.id===r);if(!a)throw new Error("Message not found");const s=a.databaseMessageId||r,o=to(i.apiUrl||Pn()),l=i.apiKey||Jn,c=i.adapterName,u=await li(),g=new u.ApiClient({apiUrl:o,apiKey:A?null:l,sessionId:n,adapterName:A?c:null}),d=await new(await rr(async()=>{const{ThreadService:B}=await import("./threadService-B9Db3n0J.js");return{ThreadService:B}},[])).ThreadService(g).createThread(s,n);e(B=>({conversations:B.conversations.map(y=>y.sessionId!==n?y:{...y,messages:y.messages.map(w=>w.id===r?{...w,threadInfo:d,supportsThreading:!0}:w),currentThreadId:void 0,currentThreadSessionId:void 0})})),Xe(`[chatStore] Created thread ${d.thread_id} for message ${r}`)}catch(i){throw oi("Failed to create thread:",i),i}},appendToLastMessage:(r,n)=>{const i=Lh(r);if(!i&&r)return;const A=LD(i);e(a=>{const s=n||a.currentConversationId;return{conversations:a.conversations.map(o=>{if(o.id!==s)return o;const l=[...o.messages],c=l[l.length-1];return c&&c.role==="assistant"&&c.isStreaming&&(l[l.length-1]={...c,content:c.content+A}),{...o,messages:l,updatedAt:new Date}})}})},regenerateResponse:async r=>{var n,i,A,a,s,o;try{if(t().isLoading){jr("Another request is already in progress");return}if(!await qo())throw new Error("API not properly configured");const c=t(),u=c.conversations.find(f=>f.id===c.currentConversationId);if(!u)return;const g=u.messages.findIndex(f=>f.id===r);if(g===-1)return;const h=u.messages[g-1];if(!h||h.role!=="user")return;const d=(h.attachments||[]).map(f=>f.file_id).filter(f=>typeof f=="string"&&f.length>0),B=fN("assistant");e(f=>({conversations:f.conversations.map(I=>I.id===f.currentConversationId?{...I,messages:[...I.messages.slice(0,g),{id:B,content:"",role:"assistant",timestamp:new Date,isStreaming:!0}],updatedAt:new Date}:I),isLoading:!0,error:null}));const y=c.currentConversationId;if(!y)throw new Error("No conversation selected");let w=!1;try{const f=t().conversations.find(te=>te.id===y);if(!f)throw new Error("Conversation not found");const I=Ii();if(I){if(!f.adapterName)throw new Error("Adapter not configured for this conversation. Please select an adapter first.")}else if(!f.apiKey)throw new Error("API key not configured for this conversation. Please configure API settings first.");if(f.sessionId){const te=to(f.apiUrl),X=f.apiKey,Z=f.adapterName,ee=await li();I?ee.configureApi(te,null,f.sessionId,Z):ee.configureApi(te,X,f.sessionId)}const Y=await li(),Q=t().conversations.find(te=>te.id===y),M=((i=(n=Q==null?void 0:Q.adapterInfo)==null?void 0:n.adapter_name)==null?void 0:i.includes("voice"))||((a=(A=Q==null?void 0:Q.adapterInfo)==null?void 0:A.adapter_name)==null?void 0:a.includes("audio"))||((o=(s=Q==null?void 0:Q.adapterInfo)==null?void 0:s.adapter_name)==null?void 0:o.includes("multilingual")),D=()=>{try{const te=localStorage.getItem("chat-settings");if(te)return JSON.parse(te).voiceEnabled===!0}catch(te){jr("Failed to read global voice setting:",te)}return!1},G=Q==null?void 0:Q.audioSettings,z=D(),R=(G==null?void 0:G.enabled)??z??M,j=(G==null?void 0:G.ttsVoice)||void 0,W=(G==null?void 0:G.language)||"en-US";for await(const te of Y.streamChat(h.content,!0,d.length>0?d:void 0,void 0,void 0,void 0,W,R,j)){if(te.text){const X=Lh(te.text);X?(t().appendToLastMessage(X,y),w=!0,await new Promise(Z=>setTimeout(Z,30))):te.text.length>100&&jr("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(te.audio&&te.done&&e(X=>({conversations:X.conversations.map(Z=>{if(Z.id!==y)return Z;const ee=[...Z.messages],Ae=ee[ee.length-1];return Ae&&Ae.role==="assistant"&&(ee[ee.length-1]={...Ae,audio:te.audio,audioFormat:te.audioFormat||"mp3"}),{...Z,messages:ee,updatedAt:new Date}})})),te.done)break}w||t().appendToLastMessage("No response received from the server. Please try again later.",y)}catch(f){oi("Regenerate API error:",f),t().appendToLastMessage("Sorry, there was an error regenerating the response.",y)}e(f=>{const I=f.conversations.map(M=>M.id===y?{...M,messages:M.messages.map(D=>D.id===B?{...D,isStreaming:!1}:D),updatedAt:new Date}:M),Y=I.find(M=>M.id===f.currentConversationId),Q=Y?Y.messages.some(M=>M.role==="assistant"&&M.isStreaming):!1;return{conversations:I,isLoading:Q}})}catch(l){oi("Regenerate error:",l),e({isLoading:!1,error:`Failed to regenerate response: ${l instanceof Error?l.message:"Unknown error"}`})}},updateConversationTitle:(r,n)=>{e(i=>({conversations:i.conversations.map(A=>A.id===r?{...A,title:n,updatedAt:new Date}:A)})),setTimeout(()=>{const i=t();localStorage.setItem("chat-state",JSON.stringify({conversations:i.conversations,currentConversationId:i.currentConversationId}))},0)},clearError:()=>{e({error:null})},cleanupStreamingMessages:()=>{e(r=>({conversations:r.conversations.map(n=>(n.id===r.currentConversationId,n)),isLoading:!1}))},canCreateNewConversation:()=>{const r=t(),n=xr.maxConversations;if(!r.currentConversationId)return n===null||r.conversations.length<n;const i=r.conversations.find(A=>A.id===r.currentConversationId);return i&&i.messages.length>0?n===null||r.conversations.length<n:!1},getConversationCount:()=>t().conversations.length,addFileToConversation:(r,n)=>{Xe("[chatStore] addFileToConversation called",{conversationId:r,fileId:n.file_id,filename:n.filename}),e(i=>{var s,o;const A={conversations:i.conversations.map(l=>l.id===r?{...l,attachedFiles:[...(l.attachedFiles||[]).filter(c=>c.file_id!==n.file_id),n],updatedAt:new Date}:l)},a=A.conversations.find(l=>l.id===r);return Xe(`[chatStore] Updated conversation ${r}`,{hasConversation:!!a,attachedFilesCount:((s=a==null?void 0:a.attachedFiles)==null?void 0:s.length)||0,attachedFiles:(o=a==null?void 0:a.attachedFiles)==null?void 0:o.map(l=>({file_id:l.file_id,filename:l.filename}))}),A}),setTimeout(()=>{const i=t();localStorage.setItem("chat-state",JSON.stringify({conversations:i.conversations,currentConversationId:i.currentConversationId}))},0)},removeFileFromConversation:async(r,n)=>{try{const i=t().conversations.find(l=>l.id===r);if(!i)throw new Error("Conversation not found");if(Ii()){if(!i.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.")}else if(!i.apiKey)throw new Error("API key not configured for this conversation. Cannot delete file.");const a=i.apiKey,s=i.adapterName,o=to(i.apiUrl);Xe(`[chatStore] Calling FileUploadService.deleteFile for ${n}`),await Rd.deleteFile(n,a,o,s),Xe(`[chatStore] Successfully deleted file ${n} from server`)}catch(i){i instanceof Error&&(i.message.includes("404")||i.message.includes("File not found"))}e(i=>({conversations:i.conversations.map(A=>A.id===r?{...A,attachedFiles:(A.attachedFiles||[]).filter(a=>a.file_id!==n),updatedAt:new Date}:A)})),setTimeout(()=>{const i=t();localStorage.setItem("chat-state",JSON.stringify({conversations:i.conversations,currentConversationId:i.currentConversationId}))},0)},loadConversationFiles:async r=>{try{const n=t().conversations.find(g=>g.id===r);if(!n)return;if(Ii()){if(!n.adapterName){Xe(`Skipping file load for conversation ${r}: adapter not configured`);return}}else if(!n.apiKey){Xe(`Skipping file load for conversation ${r}: API key not configured`);return}const A=n.apiKey,a=n.adapterName,s=to(n.apiUrl);if(new Set((n.attachedFiles||[]).map(g=>g.file_id)).size===0){Xe(`No files to sync for conversation ${r}`);return}const c=(await Rd.listFiles(A,s,a)).map(g=>({file_id:g.file_id,filename:g.filename,mime_type:g.mime_type,file_size:g.file_size,upload_timestamp:g.upload_timestamp,processing_status:g.processing_status,chunk_count:g.chunk_count})),u=new Map(c.map(g=>[g.file_id,g]));e(g=>{const h=g.conversations.find(B=>B.id===r);if(!h)return g;const d=(h.attachedFiles||[]).map(B=>u.get(B.file_id)||B).filter(B=>u.has(B.file_id)||!B.processing_status||B.processing_status==="processing");return{conversations:g.conversations.map(B=>B.id===r?{...B,attachedFiles:d,updatedAt:new Date}:B)}}),setTimeout(()=>{const g=t();localStorage.setItem("chat-state",JSON.stringify({conversations:g.conversations,currentConversationId:g.currentConversationId}))},0)}catch(n){oi(`Failed to load files for conversation ${r}:`,n)}},syncConversationFiles:async r=>{await t().loadConversationFiles(r)}})),Srt=async()=>{var l;const e=localStorage.getItem("chat-state"),t=Pn(),r=typeof window<"u"?!!localStorage.getItem("chat-api-url"):!1;let n=Pf(),i=!1;if(e)try{const c=JSON.parse(e),u=d=>{if(d instanceof Date)return d;const B=d?new Date(d):new Date;return Number.isNaN(B.getTime())?new Date:B},g=Array.isArray(c.conversations)?c.conversations:[];if(c.conversations=g.map(d=>{const y=(Array.isArray(d.messages)?d.messages:[]).filter(Y=>!(Y.role==="assistant"&&Y.isStreaming)).map(Y=>({...Y,timestamp:u(Y.timestamp),isStreaming:!1})),w={id:d.id,sessionId:d.sessionId||io(),title:d.title||"New Chat",messages:y,createdAt:u(d.createdAt),updatedAt:u(d.updatedAt),attachedFiles:d.attachedFiles||[],apiKey:d.apiKey||Jn,adapterName:d.adapterName,apiUrl:d.apiUrl,adapterInfo:d.adapterInfo,audioSettings:d.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},I=w.messages.length===0&&(!w.apiKey||w.apiKey===Jn)&&!r?t:to(d.apiUrl);return{...w,apiUrl:I}}),i=c.conversations&&c.conversations.length>0,c.currentConversationId&&c.conversations){const d=c.conversations.find(B=>B.id===c.currentConversationId);d&&d.sessionId&&(n=d.sessionId)}if(!c.conversations||c.conversations.length===0){const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,B=io(),y={id:d,sessionId:B,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:Pn()};fr.setState({conversations:[y],currentConversationId:d,sessionId:B}),n=B}else fr.setState({conversations:c.conversations||[],currentConversationId:c.currentConversationId||((l=c.conversations[0])==null?void 0:l.id)||null,sessionId:n}),!c.currentConversationId&&c.conversations.length>0&&(fr.setState({currentConversationId:c.conversations[0].id,sessionId:c.conversations[0].sessionId||n}),n=c.conversations[0].sessionId||n);const h=fr.getState().conversations;Xe("📋 Loaded conversations:",h.map(d=>{var B;return{id:d.id,title:d.title,sessionId:d.sessionId,messageCount:((B=d.messages)==null?void 0:B.length)||0}})),setTimeout(()=>{fr.getState().cleanupStreamingMessages()},100)}catch(c){oi("Failed to load chat state:",c);const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=io(),h=Pn(),d={id:u,sessionId:g,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:h};fr.setState({conversations:[d],currentConversationId:u,sessionId:g}),n=g}else{const c=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=io(),g=Pn(),h={id:c,sessionId:u,title:"New Chat",messages:[],createdAt:new Date,updatedAt:new Date,apiKey:Jn,apiUrl:g};fr.setState({conversations:[h],currentConversationId:c,sessionId:u}),n=u}const A=fr.getState(),a=A.currentConversationId?A.conversations.find(c=>c.id===A.currentConversationId):null,s=i&&(a!=null&&a.apiKey)?a.apiKey:Jn,o=i&&(a!=null&&a.apiUrl)?a.apiUrl:Pn();try{const c=await li();if(c.configureApi(o,s,n),Td=o,zd=!0,s===Jn)try{const u=new c.ApiClient({apiUrl:o,apiKey:s,sessionId:null});if(typeof u.validateApiKey=="function"&&(await u.validateApiKey(),Xe("✅ Default API key validated on startup")),typeof u.getAdapterInfo=="function"){const g=await u.getAdapterInfo();Xe("✅ Adapter info loaded for default key:",g);const h=fr.getState();h.currentConversationId&&fr.setState({conversations:h.conversations.map(d=>d.id===h.currentConversationId?{...d,adapterInfo:g,updatedAt:new Date}:d)})}}catch(u){jr("Failed to validate default API key on startup:",u)}}catch(c){oi("Failed to initialize API:",c)}};typeof window<"u"&&Srt();const Urt=Fc(),vrt=new Map,Grt=new Map,Rrt=new Map,zrt=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},Cle=e=>typeof e=="object"&&e!==null&&"message"in e,Trt=e=>e instanceof Error?e.message:typeof e=="string"?e:Cle(e)?e.message??"Unknown error":"Unknown error";function jrt({conversationId:e,onFilesSelected:t,onUploadError:r,onClose:n,onUploadingChange:i,onUploadSuccess:A,maxFiles:a=xr.maxFilesPerConversation,disabled:s=!1}){const[o,l]=F.useState(!1),[c,u]=F.useState(0),g=F.useRef(null),h=F.useRef(Rrt),d=F.useRef(new Map),B=F.useRef(!0),y=F.useRef(vrt),w=F.useRef(Grt),f=F.useRef(e),I=fr(ne=>ne.conversations),Y=F.useMemo(()=>{if(!e)return new Map;const ne=y.current.get(e);return ne?new Map(ne):new Map},[e,c]),Q=F.useCallback(ne=>{if(!ne){i==null||i(null,!1),u(Be=>Be+1);return}const ge=y.current.get(ne)||new Map,P=I.find(Be=>Be.id===ne);if(P&&P.attachedFiles){const Be=P.attachedFiles.filter(pe=>!pe.processing_status||pe.processing_status==="processing"||pe.processing_status==="uploading"),Fe=new Map(ge);let Me=!1;Be.forEach(pe=>{if(!Array.from(ge.values()).find(Ee=>Ee.fileId===pe.file_id)){const Ee=`${ne}-${pe.filename}-${pe.file_id}`;Fe.set(Ee,{filename:pe.filename,progress:pe.processing_status==="uploading"?50:90,status:pe.processing_status||"processing",fileId:pe.file_id}),Me=!0}}),Me||Fe.size>0?(y.current.set(ne,Fe),i==null||i(ne,!0)):(y.current.delete(ne),i==null||i(ne,!1))}else ge.size>0?y.current.set(ne,ge):y.current.delete(ne),i==null||i(ne,ge.size>0);u(Be=>Be+1)},[I,i]);F.useEffect(()=>{f.current=e,Q(e)},[e,Q]),F.useEffect(()=>{e&&Q(e)},[I,e,Q]);const M=F.useCallback((ne,ge)=>{if(!ne)return;const P=y.current.get(ne)||new Map,Be=ge(new Map(P));Be.size>0?y.current.set(ne,Be):y.current.delete(ne),i==null||i(ne,Be.size>0),u(Fe=>Fe+1)},[i]),D=F.useCallback((ne,ge)=>{if(!ne)return;const P=w.current.get(ne)||[],Be=ge([...P||[]]),Fe=new Set(P.map(Me=>Me.file_id));if(w.current.set(ne,Be),t(ne,Be),A){const Me=Be.filter(pe=>!Fe.has(pe.file_id));Me.length>0&&A(ne,Me)}u(Me=>Me+1)},[t,A]),G=fr(ne=>ne.removeFileFromConversation),z=fr(ne=>ne.addFileToConversation);F.useEffect(()=>(B.current=!0,()=>{B.current=!1}),[]);const R=F.useCallback(()=>{B.current=!1,new Map(d.current).forEach(ge=>ge.abort()),setTimeout(()=>{const ge=fr.getState(),P=new Map(ge.conversations.map(Fe=>[Fe.id,Fe])),Be=[];h.current.forEach((Fe,Me)=>{var pe;if(Fe){const ke=P.get(Fe);if(new Set(((pe=ke==null?void 0:ke.attachedFiles)==null?void 0:pe.map(je=>je.file_id))||[]).has(Me)){h.current.delete(Me);return}}Be.push({fileId:Me,conversationId:Fe||null})}),Be.length>0&&(n==null||n(),Be.forEach(async({fileId:Fe,conversationId:Me})=>{try{if(Me)await G(Me,Fe);else{const ke=Ii()?zrt():null;await Rd.deleteFile(Fe,void 0,void 0,ke??void 0)}}catch(pe){if(Cle(pe)){const ke=pe.message??"";!ke.includes("404")&&ke.includes("File not found")}}}))},300)},[n,G]);F.useEffect(()=>R,[R]);const j=F.useCallback(async ne=>{if(!ne||ne.length===0)return;const ge=Array.from(ne),P=fr.getState(),Be=e||P.currentConversationId;if(!Be){r==null||r("Please select or create a conversation before uploading files.");return}const Fe=P.conversations.find(xe=>xe.id===Be);if(!Fe){r==null||r("Conversation not found. Please try again.");return}if((w.current.get(Be)||[]).length+ge.length>a){const xe=`Maximum ${a} files allowed per conversation. Please remove some files first.`;r==null||r(xe);return}if(xr.maxTotalFiles!==null&&P.conversations.reduce((Se,Te)=>{var Ke;return Se+(((Ke=Te.attachedFiles)==null?void 0:Ke.length)||0)},0)+ge.length>xr.maxTotalFiles){const Se=`Maximum ${xr.maxTotalFiles} total files allowed across all conversations. Please remove some files from other conversations first.`;r==null||r(Se);return}const pe=Ii();if(pe){if(!Fe.adapterName){r==null||r("Adapter not configured for this conversation. Please select an adapter first.");return}}else if(!Fe.apiKey||Fe.apiKey===Urt){r==null||r("API key not configured for this conversation. Please configure API settings first.");return}const ke=Fe.apiKey,Ee=Fe.adapterName,je=to(Fe.apiUrl);for(let xe=0;xe<ge.length;xe++){const Ie=ge[xe],Se=new AbortController;d.current.set(Ie.name,Se);const Te=`${Be}-${Ie.name}-${Date.now()}-${xe}`;let Ke=null;try{const et=await Rd.uploadFile(Ie,rt=>{if(M(Be,It=>(It.set(Te,rt),It)),rt.fileId&&!Ke){Ke=rt.fileId,h.current.set(rt.fileId,Be);const It={file_id:rt.fileId,filename:Ie.name,mime_type:Ie.type||"application/octet-stream",file_size:Ie.size,processing_status:rt.status==="uploading"?"uploading":rt.status==="processing"?"processing":rt.status==="completed"?"completed":void 0};Xe(`[FileUpload] Adding file ${rt.fileId} to conversation ${Be} immediately (status: ${It.processing_status})`),z(Be,It)}},ke,je,pe?Ee:void 0).catch(rt=>{if(rt.message&&rt.message.includes("was deleted")){Ke&&h.current.delete(Ke);const It=rt.message.match(/File\s+([\w-]+)\s+was deleted/);return It&&It[1]&&h.current.delete(It[1]),Xe(`File ${Ie.name} was deleted during upload`),null}throw rt});et?(h.current.set(et.file_id,Be),Xe(`[FileUpload] Updating file ${et.file_id} in conversation ${Be} with final status`),z(Be,et),et.processing_status==="completed"?M(Be,rt=>(rt.delete(Te),rt)):M(Be,rt=>{const It=rt.get(Te);return It&&rt.set(Te,{...It,progress:90,status:"processing",fileId:et.file_id}),rt}),D(Be,rt=>{if(new Set(rt.map(yr=>yr.file_id)).has(et.file_id))return rt;const gr=[...rt,et];return Xe(`[FileUpload] Updated uploadedFiles for ${Be}: ${gr.length} files`,gr),gr})):(jr(`Upload completed for ${Ie.name} but uploadedAttachment is null`),M(Be,rt=>(rt.delete(Te),rt)))}catch(et){const rt=Trt(et);if(et instanceof DOMException&&et.name==="AbortError"||Se.signal.aborted){Xe(`Upload cancelled for ${Ie.name}`),Ke&&h.current.delete(Ke);continue}if(rt.includes("was deleted")){Xe(`File ${Ie.name} was deleted during upload`),Ke&&h.current.delete(Ke);const It=rt.match(/File\s+([\w-]+)\s+was deleted/);It&&It[1]&&h.current.delete(It[1]);continue}B.current?(zg(`Failed to upload file ${Ie.name}:`,et),zg(`File type: ${Ie.type}, File name: ${Ie.name}`),r==null||r(rt||`Failed to upload ${Ie.name}`)):jr(`Upload error for ${Ie.name} (component unmounted):`,rt),Ke&&h.current.delete(Ke)}finally{d.current.delete(Ie.name)}}},[z,e,a,r,D,M]),W=F.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),s||l(!0)},[s]),te=F.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),l(!1)},[]),X=F.useCallback(ne=>{if(ne.preventDefault(),ne.stopPropagation(),l(!1),s)return;const ge=ne.dataTransfer.files;j(ge)},[s,j]),Z=F.useCallback(ne=>{const ge=ne.target.files;j(ge),g.current&&(g.current.value="")},[j]),ee=F.useCallback(()=>{!s&&g.current&&g.current.click()},[s]),Ae=Y.size>0,K=F.useMemo(()=>{const ne=new Map;return I.forEach(ge=>{ne.set(ge.id,ge.title||"Conversation")}),ne},[I]),$=F.useMemo(()=>{const ne=[];return y.current.forEach((ge,P)=>{P!==e&&ge.size>0&&ne.push({conversationId:P,uploads:Array.from(ge.entries()).map(([Be,Fe])=>({key:Be,progress:Fe}))})}),ne},[e,c]),L=T.jsx("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:Array.from(Y.values()).map(ne=>T.jsxs("div",{className:"w-full max-w-full flex items-center gap-3 p-3 bg-slate-50 dark:bg-slate-800/50 rounded-lg overflow-hidden",children:[T.jsx(ng,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400 animate-spin flex-shrink-0"}),T.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[T.jsx("p",{className:"text-sm font-medium text-slate-700 dark:text-slate-300 truncate",children:ne.filename}),T.jsx("div",{className:"mt-1 bg-slate-200 dark:bg-slate-700 rounded-full h-1.5",children:T.jsx("div",{className:"bg-emerald-600 dark:bg-emerald-400 h-1.5 rounded-full transition-all duration-300",style:{width:`${ne.progress}%`}})})]}),T.jsx("span",{className:"text-xs text-slate-500 dark:text-slate-400",children:ne.status==="uploading"?"Uploading...":ne.status==="processing"?"Processing...":ne.status==="completed"?"Done":"Error"})]},ne.filename))});return Ae?T.jsx("div",{className:"w-full max-w-full overflow-hidden space-y-3",children:L}):T.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-3",children:[T.jsxs("div",{onClick:ee,onDragOver:W,onDragLeave:te,onDrop:X,className:`
|
|
1224
1224
|
relative w-full max-w-full border-2 border-dashed rounded-xl p-3 sm:p-4 transition-all cursor-pointer
|
|
1225
1225
|
${o?"border-emerald-500 bg-emerald-50 dark:bg-emerald-900/20 dark:border-emerald-400":s?"border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50 cursor-not-allowed opacity-50":"border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900/50 hover:border-emerald-400 hover:bg-emerald-50/30 dark:hover:bg-emerald-900/10"}
|
|
1226
1226
|
`,children:[T.jsx("input",{ref:g,type:"file",multiple:!0,onChange:Z,className:"hidden",disabled:s,accept:".pdf,.doc,.docx,.txt,.md,.csv,.json,.html,.pptx,.xlsx,.py,.java,.sql,.js,.mjs,.ts,.tsx,.cpp,.cxx,.cc,.c,.h,.hpp,.go,.rs,.rb,.php,.sh,.bash,.zsh,.yaml,.yml,.xml,.css,.scss,.sass,.less,.png,.jpg,.jpeg,.tiff,.wav,.mp3,.mp4,.ogg,.flac,.webm,.m4a,.aac,.vtt"}),T.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 text-center",children:[T.jsx(v0e,{className:`w-6 h-6 ${o?"text-emerald-600 dark:text-emerald-400":"text-slate-400 dark:text-slate-500"}`}),T.jsxs("div",{className:"px-2",children:[T.jsx("p",{className:"text-xs sm:text-sm font-medium text-slate-700 dark:text-slate-300",children:s?"File upload disabled":o?"Drop files here":"Click or drag files to upload"}),T.jsxs("p",{className:"text-[10px] sm:text-xs text-slate-500 dark:text-slate-400 mt-0.5 px-1",children:["PDF, DOCX, TXT, CSV, JSON, HTML, code files (.py, .js, .ts, .java, .sql, etc.), images, audio (max ",a," files)"]})]})]})]}),$.length>0&&T.jsxs("div",{className:"w-full max-w-full space-y-3 rounded-lg border border-slate-200 bg-white p-3 dark:border-slate-700 dark:bg-slate-900/40",children:[T.jsx("p",{className:"text-xs font-semibold text-slate-600 dark:text-slate-300",children:"Uploads in other conversations"}),$.map(({conversationId:ne,uploads:ge})=>T.jsxs("div",{className:"space-y-2",children:[T.jsx("div",{className:"text-xs font-medium text-slate-500 dark:text-slate-400",children:K.get(ne)||"Conversation"}),ge.map(({key:P,progress:Be})=>T.jsxs("div",{className:"w-full max-w-full flex items-center gap-3 p-3 bg-slate-50 dark:bg-slate-800/50 rounded-lg overflow-hidden",children:[T.jsx(ng,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400 animate-spin flex-shrink-0"}),T.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[T.jsx("p",{className:"text-sm font-medium text-slate-700 dark:text-slate-300 truncate",children:Be.filename}),T.jsx("div",{className:"mt-1 bg-slate-200 dark:bg-slate-700 rounded-full h-1.5",children:T.jsx("div",{className:"bg-emerald-600 dark:bg-emerald-400 h-1.5 rounded-full transition-all duration-300",style:{width:`${Be.progress}%`}})})]}),T.jsx("span",{className:"text-xs text-slate-500 dark:text-slate-400",children:Be.status==="uploading"?"Uploading...":Be.status==="processing"?"Processing...":Be.status==="completed"?"Done":"Error"})]},P))]},ne))]})]})}const tV={"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/tiff":"tiff","image/tif":"tif","image/gif":"gif","image/webp":"webp","application/pdf":"pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/msword":"doc","text/plain":"txt","text/markdown":"md","application/json":"json"};function Lrt(e){if(!e)return"bin";if(tV[e])return tV[e];const t=e.split("/");return t.length===2&&t[1]?t[1]:"bin"}function Hrt(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function Jrt(e){const t=e.lastIndexOf(".");return t===-1||t===e.length-1?null:e.slice(t+1).toLowerCase()}function Ort(e){const t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Wrt(e,t){const r=Date.now(),n=e.name&&e.name.trim().length>0?e.name.trim():"pasted-file",i=Hrt(Ort(n)),a=Jrt(n)||Lrt(e.type),s=`${i}-${r}-${t}.${a}`;return new File([e],s,{type:e.type||"application/octet-stream"})}function rV({onSend:e,disabled:t=!1,placeholder:r="Ask me anything...",isCentered:n=!1}){var Ot;const[i,A]=F.useState(""),[a,s]=F.useState(!1),[o,l]=F.useState(!1),[c,u]=F.useState(!1),[g,h]=F.useState([]),[d,B]=F.useState({}),[y,w]=F.useState(new Map),[f,I]=F.useState(!1),[Y,Q]=F.useState(!1),[M,D]=F.useState(null),[G,z]=F.useState(null),R=F.useRef(null),j=F.useRef(new Set),W=F.useRef(""),te=F.useRef(!1),X=F.useRef(0),Z=F.useRef(null),{settings:ee,updateSettings:Ae}=cy(),K=F.useCallback((ze,Ze)=>{ze&&B(Jt=>{if(Jt[ze]===Ze)return Jt;const bt={...Jt};return Ze?bt[ze]=!0:delete bt[ze],bt})},[]),[$,L]=F.useState(0),{createConversation:ne,currentConversationId:ge,conversations:P,isLoading:Be,syncConversationFiles:Fe}=fr(),Me=P.find(ze=>ze.id===ge),pe=F.useCallback(()=>{L(ze=>ze+1)},[]),{isListening:ke,isSupported:Ee,startListening:je,stopListening:xe,error:Ie}=yrt(ze=>{A(Ze=>{const Jt=(Ze+ze).slice(0,xr.maxMessageLength);return W.current=Jt,Jt})},pe),Se=ort(),Te=Se&&Ee,Ke=srt(),et=(Me==null?void 0:Me.attachedFiles)||[],rt=((Ot=Me==null?void 0:Me.adapterInfo)==null?void 0:Ot.isFileSupported)??!1,It=g.some(ze=>ze.processing_status?ze.processing_status!=="completed"&&ze.processing_status!=="error"&&ze.processing_status!=="failed":!0)||et.some(ze=>ze.processing_status?ze.processing_status!=="completed"&&ze.processing_status!=="error"&&ze.processing_status!=="failed":!0),gr=ge?!!d[ge]:!1,yr=Object.values(d).some(Boolean),Vt=t||It||gr,ni=Ke&&rt,pi=!ni||Vt;F.useEffect(()=>{if(R.current){R.current.style.height="auto";const Ze=R.current.scrollHeight;R.current.style.height=`${Math.min(Ze,120)}px`,R.current.style.overflowY=Ze>120?"auto":"hidden"}},[i]);const Mn=()=>{const ze=document.activeElement;return ze&&ze.tagName==="TEXTAREA"};F.useEffect(()=>{!Vt&&R.current&&!Mn()&&R.current.focus()},[Vt]);const Mr=F.useRef(Be);F.useEffect(()=>{Mr.current&&!Be&&!Vt&&R.current&&setTimeout(()=>{R.current&&!Mn()&&R.current.focus()},100),Mr.current=Be},[Be,Vt]),F.useEffect(()=>{if(!Te||($>X.current&&(te.current=!0,X.current=$),!te.current||$===0))return;const ze=setTimeout(()=>{const Ze=W.current.trim(),Jt=fr.getState();if(Xe("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!Ze,isInputDisabled:Vt,isComposing:a,isLoading:Jt.isLoading}),!Ze){te.current=!1;return}if(!Vt&&!a&&!Jt.isLoading){const bt=Jt.conversations.find(Er=>Er.id===Jt.currentConversationId),Fr=((bt==null?void 0:bt.attachedFiles)||[]).map(Er=>Er.file_id);e(Ze,Fr.length>0?Fr:void 0),te.current=!1,A(""),W.current="",R.current&&(R.current.style.height="auto",R.current.style.overflowY="hidden")}},400);return()=>clearTimeout(ze)},[Te,$,Vt,a,e]),F.useEffect(()=>{gr&&c&&u(!1)},[gr,c]),F.useEffect(()=>{!gr&&g.length},[gr,g.length,c]);const Ye=F.useCallback((ze,Ze)=>{setTimeout(()=>{let Jt=fr.getState(),bt=Ze||Jt.currentConversationId;if(bt||(bt=ne(),Jt=fr.getState(),bt=Jt.currentConversationId||bt),!bt)return;const Tt=new Set(ze.map(Er=>Er.file_id)),Fr=[];j.current.forEach((Er,Ut)=>{const[,...Vr]=Ut.split("-"),$a=Vr.join("-");Tt.has($a)||Fr.push(Ut)}),Fr.forEach(Er=>j.current.delete(Er)),ze.forEach(Er=>{const Ut=`${bt}-${Er.file_id}`;j.current.has(Ut)||(j.current.add(Ut),Xe(`[MessageInput] Adding file ${Er.file_id} to conversation ${bt}`),Jt.addFileToConversation(bt,Er))})},0)},[ne]);F.useEffect(()=>{if(ge!==Z.current)if(Z.current=ge||null,ge&&Me){const ze=Me.attachedFiles||[];h(ze.map(Ze=>({...Ze})))}else h([])},[ge,Me]),F.useEffect(()=>{if(ge&&Me){const ze=Me.attachedFiles||[];ze.length>0?h(Ze=>{const Jt=new Set(Ze.map(Tt=>Tt.file_id)),bt=ze.filter(Tt=>!Jt.has(Tt.file_id));return bt.length>0?(Xe(`[MessageInput] Syncing ${bt.length} missing files from conversation to UI`),[...Ze,...bt]):Ze}):ze.length===0&&g.length>0&&h([])}},[ge,Me,P,g.length]),F.useEffect(()=>{var Fr;const ze=typeof window<"u"&&((Fr=window.ORBIT_CHAT_CONFIG)==null?void 0:Fr.enableApiMiddleware)===!0;if(!ge||!Me||(ze?!Me.adapterName:!Me.apiKey))return;const Ze=Me.attachedFiles||[],Jt=Ze.length>0,bt=Ze.filter(Er=>!Er.processing_status||Er.processing_status==="processing"||Er.processing_status==="uploading");if(Jt&&(Xe(`[MessageInput] Syncing ${Ze.length} files for conversation ${ge}...`),Fe(ge).catch(Er=>{})),bt.length===0)return;Xe(`[MessageInput] Found ${bt.length} files still processing, starting poll...`);const Tt=setInterval(async()=>{const Ut=fr.getState().conversations.find(_A=>_A.id===ge);if(!Ut){clearInterval(Tt);return}if((Ut.attachedFiles||[]).filter(_A=>!_A.processing_status||_A.processing_status==="processing"||_A.processing_status==="uploading").length===0){clearInterval(Tt);return}try{await Fe(ge)}catch{}},3e3);return()=>{clearInterval(Tt)}},[ge,Me,Fe]),F.useEffect(()=>{B(ze=>{const Ze=new Set(P.map(Tt=>Tt.id));let Jt=!1;const bt={...ze};return Object.keys(bt).forEach(Tt=>{Ze.has(Tt)||(delete bt[Tt],Jt=!0)}),Jt?bt:ze})},[P]);const Ue=ze=>{if(ze.preventDefault(),(i.trim()||g.length>0)&&!Vt&&!a){ke&&xe();const Jt=((Me==null?void 0:Me.attachedFiles)||[]).map(bt=>bt.file_id);e(i.trim(),Jt.length>0?Jt:void 0),Bh("messageSent",ee.soundEnabled),A(""),W.current="",h([]),u(!1),R.current&&(R.current.style.height="auto",R.current.style.overflowY="hidden")}},Ve=F.useCallback(ze=>{if(!ze||ze.length===0)return;const Ze=ze.length===1?`File "${ze[0].filename}" uploaded successfully`:`${ze.length} files uploaded successfully`;Bh("success",ee.soundEnabled),z(Ze),setTimeout(()=>{z(null)},6e3)},[ee.soundEnabled]),Nt=F.useCallback((ze,Ze)=>{Xe(`[MessageInput] handleFilesSelected called with ${Ze.length} files for conversation ${ze}:`,Ze),ze&&(ze===ge&&h(Ze),Ye(Ze,ze))},[ge,Ye]),vt=F.useCallback((ze,Ze)=>{ze===ge&&Ve(Ze)},[ge,Ve]),Dt=ze=>{ze.key==="Enter"&&!ze.shiftKey&&!a&&(ze.preventDefault(),Ue(ze))},Ge=()=>{ke?xe():je()},Ne=()=>{Ae({voiceEnabled:!ee.voiceEnabled})},Yt=F.useCallback(async ze=>{var Er;if(!Ke||!o||!rt||Vt)return;const Ze=ze.clipboardData;if(!Ze||!Ze.items)return;const bt=Array.from(Ze.items).filter(Ut=>Ut.kind==="file");if(bt.length===0)return;const Tt=[];if(bt.forEach((Ut,Vr)=>{const $a=Ut.getAsFile();$a&&Tt.push(Wrt($a,Vr))}),Tt.length===0)return;ze.preventDefault(),D(null),z(null);let Fr=null;try{const Ut=fr.getState(),Vr=Ut.conversations.find(De=>De.id===Ut.currentConversationId);if(((Vr==null?void 0:Vr.attachedFiles)||[]).length+Tt.length>xr.maxFilesPerConversation)throw new Error(`Maximum ${xr.maxFilesPerConversation} files allowed per conversation. Please remove some files first.`);if(xr.maxTotalFiles!==null&&Ut.conversations.reduce((J,ae)=>{var Gt;return J+(((Gt=ae.attachedFiles)==null?void 0:Gt.length)||0)},0)+Tt.length>xr.maxTotalFiles)throw new Error(`Maximum ${xr.maxTotalFiles} total files allowed across all conversations. Please remove some files from other conversations first.`);if(!Vr||!Vr.apiKey||Vr.apiKey===Fc())throw new Error("API key not configured for this conversation. Please configure API settings first.");const es=Vr.apiKey,Ur=to(Vr.apiUrl);Fr=Vr.id,K(Fr,!0);const x=[],U=[];for(let De=0;De<Tt.length;De++){const J=Tt[De],ae=J.name||`Clipboard file ${De+1}`,Gt=`${ae}-${Date.now()}-${De}`;w(vr=>{const Yi=new Map(vr);return Yi.set(Gt,{filename:ae,progress:0,status:"uploading"}),Yi});const nt=vr=>{w(Yi=>{const se=new Map(Yi),le=se.get(Gt);return le&&se.set(Gt,{...le,filename:ae,progress:vr.progress,status:vr.status,fileId:vr.fileId}),se})},kn=()=>new Promise(vr=>{w(Yi=>{const se=new Map(Yi),le=se.get(Gt);return le&&se.set(Gt,{...le,progress:100,status:"completed"}),se}),setTimeout(()=>{w(Yi=>{const se=new Map(Yi);return se.delete(Gt),se}),vr()},2500)});Xe(`[MessageInput] Pasting file: ${J.name}, type: ${J.type||"unknown"}, size: ${J.size}`);const ii=typeof window<"u"&&((Er=window.ORBIT_CHAT_CONFIG)==null?void 0:Er.enableApiMiddleware)===!0,ft=Me==null?void 0:Me.adapterName,Xr=await Rd.uploadFile(J,vr=>{Xe(`[MessageInput] Paste upload progress for ${J.name}: ${vr.progress}% - ${vr.status}`),nt(vr)},es,Ur,ii?ft:void 0);x.push(Xr),U.push(kn())}if(x.length>0){let De=x;if(Fr&&Fr===ge){const J=new Set(g.map(Gt=>Gt.file_id)),ae=x.filter(Gt=>!J.has(Gt.file_id));ae.length>0?(h(Gt=>[...Gt,...ae]),De=ae):De=[]}De.length>0&&Ye(De,Fr),await Promise.all(U),Ve(x)}}catch(Ut){const Vr=Ut instanceof Error?Ut.message:"Failed to paste file";Bh("error",ee.soundEnabled),D(Vr),setTimeout(()=>{D(null)},5e3),w(new Map)}finally{K(Fr,!1)}},[g,Me==null?void 0:Me.adapterName,ge,o,rt,Vt,K,ee.soundEnabled,Ve,Ye,Ke]),zt=It||gr?"Files are uploading/processing, please wait...":ni?"Message ORBIT or drop files here":r;F.useEffect(()=>{!Se||!Ie||Bh("error",ee.soundEnabled)},[Se,ee.soundEnabled,Ie]);const er=n?"max-w-3xl":"max-w-5xl",ar=n?"flex justify-center":"";return T.jsx("div",{className:`bg-white px-3 py-4 dark:bg-[#212121] sm:px-4 ${ar}`,children:T.jsxs("div",{className:`mx-auto w-full ${er}`,children:[Ie&&Se&&T.jsx("div",{className:"mb-3 w-full rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:Ie}),M&&T.jsx("div",{className:"mb-3 w-full rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:M}),G&&T.jsxs("div",{className:"mb-3 w-full flex items-center gap-2 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700 dark:border-green-600/40 dark:bg-green-900/30 dark:text-green-200",children:[T.jsx(c0e,{className:"h-4 w-4 flex-shrink-0"}),T.jsx("span",{children:G})]}),T.jsxs("form",{onSubmit:Ue,className:"flex w-full flex-col gap-3",children:[T.jsxs("div",{className:`flex flex-wrap gap-2 rounded-lg border px-3 py-3 shadow-sm transition-all sm:flex-nowrap sm:px-4 ${o?"border-gray-400 shadow-md dark:border-[#565869] dark:shadow-lg":"border-gray-300 dark:border-[#40414f]"} bg-gray-50 dark:bg-[#2d2f39]`,children:[Ke&&T.jsx("button",{type:"button",onClick:ze=>{ze.preventDefault(),pi||u(!c)},disabled:pi,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors ${c||g.length>0?"bg-gray-100 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":pi?"cursor-not-allowed text-gray-300 dark:text-[#6b6f7a]":"text-gray-500 hover:bg-gray-100 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:rt?Vt?"Files are uploading/processing. Please wait...":g.length>0?`${g.length} file(s) attached`:"Attach files":"File upload not supported by this adapter",children:pi&&f?T.jsx(ig,{className:"h-4 w-4"}):T.jsx(FX,{className:"h-4 w-4"})}),T.jsx("textarea",{ref:R,value:i,onChange:ze=>A(ze.target.value),onKeyDown:Dt,onPaste:Yt,onCompositionStart:()=>s(!0),onCompositionEnd:()=>s(!1),onFocus:()=>l(!0),onBlur:()=>l(!1),placeholder:zt,disabled:Vt,rows:1,maxLength:xr.maxMessageLength,className:"flex-1 min-w-[150px] resize-none bg-transparent py-1 text-sm text-[#353740] placeholder-gray-600 focus:outline-none dark:text-[#ececf1] dark:placeholder-[#bfc2cd]",style:{minHeight:"24px",maxHeight:"120px",border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none",caretColor:i.trim()||o?"inherit":"transparent"}}),T.jsxs("div",{className:"flex flex-shrink-0 flex-wrap items-center justify-end gap-2",children:[i.length>0&&T.jsx("div",{className:"min-w-[72px] text-right text-xs text-gray-500 dark:text-[#bfc2cd]",children:T.jsxs("span",{className:i.length>=xr.maxMessageLength?"text-red-600 font-semibold":"",children:[i.length,"/",xr.maxMessageLength]})}),Se&&T.jsxs(T.Fragment,{children:[T.jsx("button",{type:"button",onClick:Ne,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors ${ee.voiceEnabled?"bg-blue-50 text-blue-600 dark:bg-blue-900/40 dark:text-blue-300":"text-gray-500 hover:bg-gray-100 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:ee.voiceEnabled?"Voice responses enabled - Click to disable":"Enable voice responses (text-to-speech)",children:ee.voiceEnabled?T.jsx(uw,{className:"h-5 w-5"}):T.jsx(G0e,{className:"h-5 w-5"})}),Te&&T.jsx("button",{type:"button",onClick:Ge,disabled:Vt,onMouseEnter:()=>Q(!0),onMouseLeave:()=>Q(!1),className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors ${ke?"bg-red-50 text-red-600 dark:bg-red-900/40 dark:text-red-300":Vt?"cursor-not-allowed text-gray-300 dark:text-[#6b6f7a]":"text-gray-500 hover:bg-gray-100 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:Vt?"Files are uploading/processing. Please wait...":ke?"Stop recording":"Start voice input",children:ke||Vt&&Y?T.jsx(m0e,{className:"h-5 w-5"}):T.jsx(w0e,{className:"h-5 w-5"})})]}),(It||gr)&&T.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:T.jsx(ng,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),T.jsx("button",{type:"submit",disabled:!i.trim()&&g.length===0||Vt||a,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors ${(i.trim()||g.length>0)&&!Vt&&!a?"bg-black text-white hover:bg-gray-800 dark:bg-white dark:text-black dark:hover:bg-gray-200":"bg-gray-200 text-gray-400 dark:bg-[#565869] dark:text-[#6b6f7a]"}`,title:"Send message",children:T.jsx(QX,{className:"h-4 w-4"})})]})]}),g.length>0&&T.jsx("div",{className:"flex flex-wrap gap-2",children:g.map(ze=>{const Ze=!ze.processing_status||ze.processing_status==="processing"||ze.processing_status==="uploading";return T.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-gray-200 bg-white px-2 py-1 text-xs dark:border-[#4a4b54] dark:bg-[#2d2f39]",children:[Ze&&T.jsx(ng,{className:"h-3 w-3 animate-spin text-emerald-600 dark:text-emerald-400 flex-shrink-0"}),T.jsx("span",{className:"truncate max-w-[150px] text-[#353740] dark:text-[#ececf1]",children:ze.filename}),Ze&&T.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:ze.processing_status==="uploading"?"Uploading...":"Processing..."}),T.jsx("button",{disabled:!0,className:"text-gray-300 dark:text-[#4a4b54] cursor-not-allowed",title:"File removal disabled; use Clear All in sidebar",children:T.jsx(ig,{className:"h-3 w-3"})})]},ze.file_id)})}),Ke&&(rt||yr)&&T.jsxs("div",{className:`rounded-md border border-gray-200 bg-white p-3 dark:border-[#4a4b54] dark:bg-[#2d2f39] ${!c&&!gr&&y.size===0&&!yr?"hidden":""}`,children:[c&&T.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm text-[#353740] dark:text-[#ececf1]",children:[T.jsx("span",{children:"Upload files"}),T.jsx("button",{onClick:()=>u(!1),className:"rounded p-1 text-gray-500 hover:bg-gray-100 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a]",title:"Close",children:T.jsx(ig,{className:"h-4 w-4"})})]}),(gr||y.size>0)&&!c&&y.size===0&&T.jsx("div",{className:"mb-2 text-sm text-[#353740] dark:text-[#ececf1]",children:"Uploading files…"}),y.size>0&&T.jsx("div",{className:"mb-2 space-y-2",children:Array.from(y.entries()).map(([ze,Ze])=>T.jsxs("div",{className:"w-full max-w-full flex items-center gap-3 p-3 bg-gray-50 dark:bg-[#1f1f24] rounded-lg overflow-hidden",children:[T.jsx(ng,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400 animate-spin flex-shrink-0"}),T.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[T.jsx("p",{className:"text-sm font-medium text-[#353740] dark:text-[#ececf1] truncate",children:Ze.filename}),T.jsx("div",{className:"mt-1 bg-gray-200 dark:bg-[#3c3f4a] rounded-full h-1.5",children:T.jsx("div",{className:"bg-emerald-600 dark:bg-emerald-400 h-1.5 rounded-full transition-all duration-300",style:{width:`${Ze.progress??0}%`}})})]}),T.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:Ze.status==="uploading"?"Uploading...":Ze.status==="processing"?"Processing...":Ze.status==="completed"?"Done":"Pending"})]},ze))}),T.jsx(jrt,{conversationId:ge,onFilesSelected:Nt,onUploadError:ze=>{},onUploadingChange:K,onUploadSuccess:vt,maxFiles:xr.maxFilesPerConversation,disabled:pi})]}),T.jsx("div",{className:"h-4",children:Te&&ke&&T.jsxs("span",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-[#bfc2cd]",children:[T.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-red-500"}),"Listening..."]})})]})]})})}const nV=e=>{if(!e||typeof e!="object")return null;const t=e;if(typeof t.name!="string"||t.name.trim().length===0)return null;const r=typeof t.apiUrl=="string"&&t.apiUrl.trim().length>0?t.apiUrl:void 0;return{name:t.name.trim(),...r&&{apiUrl:r}}};let _l=null;function Prt(){if(typeof window<"u"){const t=window.ORBIT_CHAT_CONFIG;if(t!=null&&t.adapters&&Array.isArray(t.adapters)){const r=t.adapters.map(nV).filter(n=>n!==null);if(r.length>0)return r}}const e=`[
|
|
1227
|
-
{ "name": "Simple Chat", "apiKey": "default-key", "apiUrl": "http://
|
|
1228
|
-
{ "name": "Chat With Files", "apiKey": "multimodal", "apiUrl": "http://
|
|
1229
|
-
{ "name": "e-commerce", "apiKey": "postgres", "apiUrl": "http://
|
|
1230
|
-
{ "name": "Human Resources", "apiKey": "contact", "apiUrl": "http://
|
|
1231
|
-
{ "name": "Movies", "apiKey": "mflix", "apiUrl": "http://
|
|
1232
|
-
{ "name": "Application Logs", "apiKey": "elasticsearch", "apiUrl": "http://
|
|
1233
|
-
{ "name": "Classified CMS", "apiKey": "classified", "apiUrl": "http://
|
|
1234
|
-
{ "name": "Business Analytics", "apiKey": "analytical", "apiUrl": "http://
|
|
1235
|
-
{ "name": "Travel Expenses", "apiKey": "travel-expenses", "apiUrl": "http://
|
|
1236
|
-
]`;try{const t=JSON.parse(e);if(Array.isArray(t)){Xe("Loading adapters from VITE_ADAPTERS environment variable");const r=t.map(nV).filter(n=>n!==null);if(r.length>0)return r}}catch{}return null}async function Krt(){if(_l)return _l;try{const t=await fetch("/api/adapters");if(t.ok)return _l=(await t.json()).adapters,Xe("Fetched adapters from /api/adapters:",_l),_l;Xe(`/api/adapters returned ${t.status}, trying fallback`)}catch{}const e=Prt();if(e&&e.length>0)return _l=e,_l;throw new Error("No adapters available. Configure VITE_ADAPTERS environment variable.")}function iV({selectedAdapter:e,onAdapterChange:t,disabled:r}){const[n,i]=F.useState([]),[A,a]=F.useState(!0),[s,o]=F.useState(null),[l,c]=F.useState(!1);F.useEffect(()=>{let d=!0;async function B(){try{a(!0),o(null);const y=await Krt();d&&i(y)}catch{d&&o("Failed to load adapters. Please check your connection.")}finally{d&&a(!1)}}return B(),()=>{d=!1}},[]);const u=F.useRef(!1),g=F.useRef(t);F.useEffect(()=>{g.current=t},[t]),F.useEffect(()=>{if(e){u.current=!0;return}!u.current&&n.length>0&&(u.current=!0)},[n,e]);const h=n.find(d=>d.name===e);return T.jsxs("div",{className:"relative w-full sm:w-[220px]",children:[T.jsx("label",{className:"sr-only",children:"Adapter"}),T.jsxs("div",{className:"relative",children:[T.jsx("button",{type:"button",onClick:()=>!r&&c(!l),disabled:r||A||n.length===0,className:"w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-left text-sm text-[#353740] focus:border-gray-400 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1] dark:focus:border-[#6b6f7a]",children:T.jsxs("div",{className:"flex items-center justify-between gap-2",children:[T.jsx("span",{className:`truncate ${h?"":"text-gray-500 dark:text-gray-400"}`,children:A?"Loading adapters…":s?"Error loading adapters":h?h.name:n.length===0?"No adapters available":"Select agent"}),T.jsx(MX,{className:`h-4 w-4 flex-shrink-0 transition-transform ${l?"rotate-180":""}`})]})}),l&&!r&&n.length>0&&T.jsxs(T.Fragment,{children:[T.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>c(!1)}),T.jsx("div",{className:"absolute z-20 mt-1 w-full rounded-md border border-gray-200 bg-white shadow-lg ring-1 ring-black/5 dark:border-[#4a4b54] dark:bg-[#1f2027]",children:T.jsx("div",{className:"max-h-60 overflow-auto py-1",children:n.map(d=>{const B=d.name===e;return T.jsx("button",{type:"button",onClick:()=>{B||t(d.name),c(!1)},className:`w-full px-3 py-2 text-left text-sm transition-colors ${B?"bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-200":"text-[#353740] hover:bg-gray-50 dark:text-[#ececf1] dark:hover:bg-[#2a2d35]"}`,children:T.jsx("span",{className:"font-medium truncate",children:d.name})},d.name)})})})]})]}),s&&T.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:s})]})}function Vrt({onOpenSettings:e,onOpenSidebar:t}){const{conversations:r,currentConversationId:n,sendMessage:i,regenerateResponse:A,isLoading:a,configureApiSettings:s,error:o,clearError:l,createThread:c}=fr(),{settings:u}=cy(),[g,h]=F.useState(!1),[d,B]=F.useState(()=>Pn()),[y,w]=F.useState(()=>Fc()),[f,I]=F.useState(null),[Y,Q]=F.useState(!1),[M,D]=F.useState(!1),[G,z]=F.useState(null),[R,j]=F.useState(!1),W=r.find(L=>L.id===n),te=Ii();F.useEffect(()=>{te&&(W!=null&&W.adapterName)&&I(W.adapterName)},[te,W==null?void 0:W.adapterName]);const X=!W||W.messages.length===0;F.useEffect(()=>{let L=null;const ne=()=>{L&&(L(),L=null)};if(u.voiceEnabled){if(mc.isAudioEnabled())return ne;const ge=()=>{ne();const P=async()=>{ne(),await mc.enableAudio()||ge()};document.addEventListener("pointerdown",P,{once:!0}),document.addEventListener("keydown",P,{once:!0}),L=()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",P)}};return ge(),ne}return ne(),mc.disableAudio(),ne},[u.voiceEnabled]);const Z=(L,ne,ge)=>{i(L,ne,ge)},ee=async(L,ne,ge)=>{await i(ge,void 0,L)},Ae=async()=>{if(!(!W||!W.apiKey&&!W.adapterName)){j(!0);try{const L=await li(),ne=W.apiUrl||Pn(),ge=W.apiKey,P=W.adapterName,Be=new L.ApiClient({apiUrl:ne,apiKey:ge||null,sessionId:null,adapterName:P||null});if(typeof Be.getAdapterInfo=="function"){const Fe=await Be.getAdapterInfo();Xe("Adapter info refreshed:",Fe),fr.setState(Me=>({conversations:Me.conversations.map(pe=>pe.id===n?{...pe,adapterInfo:Fe,updatedAt:new Date}:pe)})),setTimeout(()=>{const Me=fr.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:Me.conversations,currentConversationId:Me.currentConversationId}))},0)}}catch{}finally{j(!1)}}},K=async L=>{if(L&&L.preventDefault(),te){if(d&&f){D(!0),z(null);try{await s(d,void 0,void 0,f),l(),z(null),h(!1)}catch(ne){const ge=ne instanceof Error?ne.message:"Failed to configure adapter";z(ge)}finally{D(!1)}}}else if(d&&y){D(!0),z(null);try{await s(d,y),l(),z(null),Q(!1),h(!1)}catch(ne){const ge=ne instanceof Error?ne.message:"Failed to configure API settings";z(ge)}finally{D(!1)}}},$=L=>{I(L),z(null)};return T.jsx("div",{className:"flex-1 flex flex-col",children:T.jsx("div",{className:"flex h-full w-full flex-col px-3 sm:px-6",children:T.jsxs("div",{className:"mx-auto flex h-full w-full max-w-5xl flex-col",children:[g&&T.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4",children:T.jsxs("form",{onSubmit:K,className:"w-full max-w-md rounded-lg border border-gray-200 bg-white p-6 shadow-lg dark:border-[#444654] dark:bg-[#202123]",children:[T.jsx("h2",{className:"text-lg font-medium text-[#353740] dark:text-[#ececf1] mb-4",children:te?"Select Adapter":"Configure API Settings"}),T.jsxs("div",{className:"space-y-5",children:[!te&&T.jsxs("div",{children:[T.jsx("label",{className:"block text-sm font-medium text-[#353740] dark:text-[#d1d5db] mb-2",children:"API URL"}),T.jsx("input",{type:"text",value:d,onChange:L=>B(L.target.value),className:"w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-[#353740] focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1]",placeholder:"https://api.example.com"})]}),te?T.jsx(iV,{selectedAdapter:f,onAdapterChange:$,disabled:M}):T.jsxs("div",{children:[T.jsx("label",{className:"block text-sm font-medium text-[#353740] dark:text-[#d1d5db] mb-2",children:"API Key"}),T.jsxs("div",{className:"relative",children:[T.jsx("input",{type:Y?"text":"password",value:y,onChange:L=>{w(L.target.value),z(null)},className:"w-full rounded-md border border-gray-300 bg-white px-3 py-2 pr-10 text-sm text-[#353740] focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1]",placeholder:"your-api-key",disabled:M}),T.jsx("button",{type:"button",onClick:()=>Q(!Y),className:"absolute right-2 top-1/2 -translate-y-1/2 rounded p-1 text-gray-500 hover:text-gray-700 dark:text-[#d1d5db] dark:hover:text-white","aria-label":Y?"Hide API key":"Show API key",disabled:M,children:Y?T.jsx(h0e,{className:"h-4 w-4"}):T.jsx(d0e,{className:"h-4 w-4"})})]})]}),G&&T.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:G}),T.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[T.jsx("button",{type:"button",onClick:()=>{const L=(W==null?void 0:W.apiUrl)||Pn(),ne=(W==null?void 0:W.apiKey)||Fc();B(L),w(ne),z(null),Q(!1),h(!1)},className:"rounded-md border border-transparent px-4 py-2 text-sm text-gray-600 hover:border-gray-300 hover:text-gray-900 dark:text-[#d1d5db] dark:hover:text-white disabled:cursor-not-allowed disabled:opacity-50",disabled:M,children:"Cancel"}),T.jsx("button",{type:"submit",disabled:M||(te?!f:!d||!y),className:"rounded-md bg-[#343541] px-4 py-2 text-sm font-medium text-white hover:bg-[#282b32] disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#565869] dark:hover:bg-[#6b6f7a]",children:M?"Validating...":"Update"})]})]})]})}),o&&T.jsx("div",{className:"mt-6 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:T.jsxs("div",{className:"flex items-start justify-between",children:[T.jsx("p",{children:o}),T.jsx("button",{onClick:l,className:"ml-4 rounded p-1 text-red-500 hover:bg-red-100 hover:text-red-700 dark:text-red-200 dark:hover:bg-red-800/40","aria-label":"Dismiss error",children:"×"})]})}),t&&T.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3 md:hidden",children:[T.jsxs("button",{onClick:t,className:"inline-flex items-center gap-2 rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-400 transition-colors dark:border-[#4a4b54] dark:text-[#ececf1] dark:hover:bg-[#343541]","aria-label":"Open conversations menu",children:[T.jsx(p0e,{className:"h-4 w-4"}),"Chats"]}),T.jsx("button",{onClick:e,className:"inline-flex items-center justify-center rounded-md bg-[#343541] p-2 text-white hover:bg-[#282b32] transition-colors dark:bg-[#565869] dark:hover:bg-[#6b6f7a]","aria-label":"Open settings",children:T.jsx(tR,{className:"h-4 w-4"})})]}),T.jsx("div",{className:"border-b border-gray-200 dark:border-[#4a4b54] pb-6 pt-6",children:T.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[T.jsx("div",{className:"min-w-0 flex-1",children:(W==null?void 0:W.adapterInfo)&&T.jsxs("div",{className:"mb-4",children:[T.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3",children:[T.jsxs("div",{className:"inline-flex items-center gap-2 px-2.5 py-1 rounded-md bg-gray-100 dark:bg-[#343541] border border-gray-200 dark:border-[#4a4b54]",children:[T.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-[#bfc2cd] uppercase tracking-wide",children:"Agent"}),T.jsx("span",{className:"text-sm font-semibold text-[#353740] dark:text-[#ececf1]",children:W.adapterInfo.client_name})]}),W.adapterInfo.model&&T.jsxs("div",{className:"inline-flex items-center gap-2 px-2.5 py-1 rounded-md bg-gray-100 dark:bg-[#343541] border border-gray-200 dark:border-[#4a4b54]",children:[T.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-[#bfc2cd] uppercase tracking-wide",children:"Model"}),T.jsx("span",{className:"text-sm font-semibold text-[#353740] dark:text-[#ececf1]",children:W.adapterInfo.model})]}),T.jsx("button",{onClick:Ae,disabled:R||!(W!=null&&W.apiKey)&&!(W!=null&&W.adapterName),className:"inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs text-gray-600 hover:text-gray-900 hover:bg-gray-200 dark:text-[#bfc2cd] dark:hover:text-white dark:hover:bg-[#4a4b54] transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Refresh adapter info",children:T.jsx(Y0e,{className:`h-4 w-4 ${R?"animate-spin":""}`})})]}),T.jsx("h1",{className:"text-2xl font-semibold text-[#353740] dark:text-[#ececf1] mb-2",children:(W==null?void 0:W.title)||"New Chat"}),W&&T.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-[#bfc2cd]",children:[T.jsx("span",{className:"font-medium",children:W.messages.length}),T.jsxs("span",{children:["Updated ",W.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})]})}),T.jsxs("div",{className:"flex w-full flex-wrap items-center gap-3 sm:w-auto sm:flex-nowrap sm:justify-end",children:[T.jsxs("span",{className:"text-sm text-gray-500 dark:text-[#bfc2cd] sm:text-right",children:["v",Ele]}),!te&&T.jsx("button",{onClick:()=>{const L=Pn(),ne=W==null?void 0:W.apiUrl,ge=ne&&ne!==L?ne:L,P=(W==null?void 0:W.apiKey)||Fc();B(ge),w(P),z(null),Q(!1),h(!0)},disabled:!X,className:"w-full rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:border-gray-300 dark:border-[#4a4b54] dark:text-[#ececf1] dark:hover:bg-[#3c3f4a] dark:hover:border-[#6b6f7a] dark:disabled:hover:bg-transparent dark:disabled:hover:border-[#4a4b54] sm:w-auto",title:X?"Configure API settings":"API key cannot be changed once conversation has started. Create a new conversation to use a different API key.",children:"Configure API"}),te&&T.jsx("div",{className:"w-full sm:w-auto",children:T.jsx(iV,{selectedAdapter:f||(W==null?void 0:W.adapterName)||null,onAdapterChange:async L=>{I(L);const ne=(W==null?void 0:W.apiUrl)||Pn();try{await s(ne,void 0,void 0,L),l()}catch{}},disabled:!X})}),T.jsx("button",{onClick:e,className:"hidden rounded-md bg-[#343541] p-2 text-white hover:bg-[#282b32] transition-colors dark:bg-[#565869] dark:hover:bg-[#6b6f7a] md:inline-flex",title:"Settings",children:T.jsx(tR,{className:"h-4 w-4"})})]})]})}),!W||W.messages.length===0?T.jsx("div",{className:"flex-1 flex flex-col items-center justify-center min-h-0 px-4",children:T.jsxs("div",{className:"w-full max-w-3xl mx-auto text-center space-y-3",children:[T.jsx("div",{className:"space-y-1.5",children:T.jsx("h2",{className:"text-2xl font-medium text-[#353740] dark:text-[#ececf1]",children:"How can I assist you today?"})}),T.jsx("div",{className:"w-full",children:T.jsx(rV,{onSend:Z,disabled:a||!W||(te?!W.adapterName:!W.apiKey),placeholder:"Message ORBIT...",isCentered:!0})})]})}):T.jsxs(T.Fragment,{children:[T.jsx(wrt,{messages:W.messages,onRegenerate:A,onStartThread:async(L,ne)=>{try{await c(L,ne)}catch{}},onSendThreadMessage:ee,sessionId:W.sessionId,isLoading:a}),T.jsx(rV,{onSend:Z,disabled:a||!W||(te?!W.adapterName:!W.apiKey),placeholder:"Message ORBIT..."})]})]})})})}function AV({isOpen:e,onClose:t,onConfirm:r,title:n,message:i,confirmText:A="Confirm",cancelText:a="Cancel",type:s="danger",isLoading:o=!1}){if(!e)return null;const l=()=>{o||r()},u=(()=>{switch(s){case"danger":return{icon:"text-red-500",iconBg:"bg-red-100 dark:bg-red-900/20",confirmButton:"bg-red-600 hover:bg-red-700 focus:ring-red-500",border:"border-red-200 dark:border-red-800"};case"warning":return{icon:"text-amber-500",iconBg:"bg-amber-100 dark:bg-amber-900/20",confirmButton:"bg-amber-600 hover:bg-amber-700 focus:ring-amber-500",border:"border-amber-200 dark:border-amber-800"};default:return{icon:"text-blue-500",iconBg:"bg-blue-100 dark:bg-blue-900/20",confirmButton:"bg-blue-600 hover:bg-blue-700 focus:ring-blue-500",border:"border-blue-200 dark:border-blue-800"}}})();return T.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 z-50 animate-fadeIn",children:T.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-md transform animate-fadeIn",children:[T.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700",children:[T.jsxs("div",{className:"flex items-center gap-3",children:[T.jsx("div",{className:`w-10 h-10 rounded-full ${u.iconBg} flex items-center justify-center`,children:T.jsx(CX,{className:`w-5 h-5 ${u.icon}`})}),T.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:n})]}),T.jsx("button",{onClick:t,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:T.jsx(ig,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),T.jsx("div",{className:"p-6",children:T.jsx("p",{className:"text-gray-600 dark:text-gray-300 leading-relaxed",children:i})}),T.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 rounded-b-2xl",children:[T.jsx("button",{onClick:t,disabled:o,className:"px-4 py-2.5 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:a}),T.jsx("button",{onClick:l,disabled:o,className:`px-4 py-2.5 text-white rounded-lg transition-all font-medium shadow-sm hover:shadow-md transform hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-gray-800 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none ${u.confirmButton}`,children:o?T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}),"Clearing..."]}):A})]})]})})}const Xrt=(e,t)=>{const[r,n]=F.useState({stars:0,forks:0,license:"Apache-2.0",description:"An adaptable, open-source context-aware inference engine designed for privacy, control, and independence from proprietary models.",isLoading:!0,error:null});return F.useEffect(()=>{(async()=>{var A;try{const a=await fetch(`https://api.github.com/repos/${e}/${t}`);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);const s=await a.json();n({stars:s.stargazers_count||0,forks:s.forks_count||0,license:((A=s.license)==null?void 0:A.name)||"Apache-2.0",description:s.description||"An adaptable, open-source context-aware inference engine designed for privacy, control, and independence from proprietary models.",isLoading:!1,error:null})}catch(a){console.warn("Failed to fetch GitHub stats:",a),n({stars:104,forks:19,license:"Apache-2.0",description:"An adaptable, open-source context-aware inference engine designed for privacy, control, and independence from proprietary models.",isLoading:!1,error:a instanceof Error?a.message:"Failed to fetch stats"})}})()},[e,t]),r},am=100;function aV({onRequestClose:e}){const{conversations:t,currentConversationId:r,createConversation:n,selectConversation:i,deleteConversation:A,deleteAllConversations:a,updateConversationTitle:s,canCreateNewConversation:o,getConversationCount:l}=fr(),c=t.find(pe=>pe.id===r),[u,g]=F.useState(""),[h,d]=F.useState(null),[B,y]=F.useState(""),[w,f]=F.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[I,Y]=F.useState({isOpen:!1,isDeleting:!1}),Q=t.filter(pe=>pe.title.toLowerCase().includes(u.toLowerCase())||pe.messages.some(ke=>ke.content.toLowerCase().includes(u.toLowerCase()))),M=o(),D=l(),G=xr.maxConversations,z=G!==null&&D>=G,R=c?c.messages.length===0:!1,j=G!==null?`${D}/${G} conversations`:`${D} conversation${D===1?"":"s"}`,W=M?"Start a new conversation":z?`Maximum ${G} conversations reached. Delete a conversation to create a new one.`:R?"Current conversation is empty. Send a message first to create a new conversation.":"Finish your current conversation before starting a new one.",te=urt(),X=Xrt(ZK(),qK()),Z=()=>{try{n(),e==null||e()}catch(pe){jr("Cannot create new conversation:",pe instanceof Error?pe.message:"Unknown error")}},ee=async pe=>{try{await i(pe),e==null||e()}catch{}},Ae=(pe,ke)=>{pe.stopPropagation(),f({isOpen:!0,conversationId:ke.id,conversationTitle:ke.title,isDeleting:!1})},K=async()=>{f(pe=>({...pe,isDeleting:!0}));try{await A(w.conversationId),f({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})}catch{f({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})}},$=()=>{f({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},L=(pe,ke)=>{pe.stopPropagation(),d(ke.id),y(ke.title.slice(0,am))},ne=pe=>{const ke=B.slice(0,am).trim();ke&&s(pe,ke),d(null),y("")},ge=()=>{d(null),y("")},P=()=>{Y({isOpen:!0,isDeleting:!1})},Be=async()=>{Y(pe=>({...pe,isDeleting:!0}));try{await a(),Y({isOpen:!1,isDeleting:!1})}catch{Y({isOpen:!1,isDeleting:!1})}},Fe=()=>{Y({isOpen:!1,isDeleting:!1})},Me=pe=>{const ke=pe.toLocaleDateString([],{year:"numeric",month:"short",day:"numeric"}),Ee=pe.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return`${ke} · ${Ee}`};return T.jsxs(T.Fragment,{children:[T.jsxs("div",{className:"flex h-full w-full md:w-72 flex-col border-r border-b border-gray-200 bg-gray-50 dark:border-[#4a4b54] dark:bg-[#202123]",children:[T.jsxs("div",{className:"border-b border-gray-200 p-4 dark:border-[#4a4b54]",children:[T.jsxs("button",{onClick:Z,disabled:!M,className:`flex w-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium ${M?"bg-[#343541] text-white hover:bg-[#2c2f36] dark:bg-[#565869] dark:hover:bg-[#6b6f7a]":"cursor-not-allowed bg-gray-200 text-gray-500 dark:bg-[#3c3f4a] dark:text-[#6b6f7a]"}`,title:W,children:[T.jsx(F0e,{className:"h-4 w-4"}),"New Conversation"]}),T.jsxs("div",{className:"mt-3 space-y-2",children:[T.jsx("div",{className:"text-center",children:T.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j})}),t.length>0&&T.jsxs("button",{onClick:P,className:"flex w-full items-center justify-center gap-2 rounded-md border border-red-300 px-3 py-2 text-sm font-medium text-red-600 hover:bg-red-50 hover:border-red-400 dark:border-red-600/40 dark:text-red-400 dark:hover:bg-red-900/20 dark:hover:border-red-500/60 transition-colors",title:"Delete all conversations",children:[T.jsx(S0e,{className:"h-4 w-4"}),"Clear All"]})]})]}),T.jsx("div",{className:"border-b border-gray-200 px-4 py-3 dark:border-[#4a4b54]",children:T.jsxs("div",{className:"relative flex items-center",children:[T.jsx(x0e,{className:"pointer-events-none absolute left-3 h-4 w-4 text-gray-400"}),T.jsx("input",{type:"text",placeholder:"Search conversations",value:u,onChange:pe=>g(pe.target.value),className:"w-full rounded-md border border-gray-300 bg-white py-2 pl-9 pr-3 text-sm text-[#353740] placeholder-gray-400 focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1]"})]})}),T.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3",children:Q.length===0?T.jsxs("div",{className:"rounded-md border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500 dark:border-[#4a4b54] dark:text-[#bfc2cd]",children:[T.jsx(Mh,{className:"mx-auto mb-3 h-6 w-6 text-gray-400 dark:text-[#6b6f7a]"}),T.jsx("p",{children:u?"No conversations found":"No conversations yet"})]}):T.jsx("div",{className:"space-y-2",children:Q.map(pe=>T.jsxs("div",{onClick:()=>ee(pe.id),className:`group flex cursor-pointer items-start gap-3 rounded-xl border px-3 py-3 text-left transition ${r===pe.id?"border-[#343541] bg-white shadow-sm dark:border-[#6b6f7a] dark:bg-[#2c2f36]":"border-transparent bg-gray-100/70 hover:border-gray-300 hover:bg-white dark:bg-[#252830] dark:hover:border-[#4a4b54] dark:hover:bg-[#2f323c]"}`,children:[T.jsx("div",{className:`rounded-xl p-2 shadow-sm ${r===pe.id?"bg-[#eceefc] text-[#1d2559] dark:bg-[#3b4055] dark:text-white":"bg-white text-gray-500 dark:bg-[#3a3d46] dark:text-[#bfc2cd]"}`,children:T.jsx(Mh,{className:"h-4 w-4"})}),h===pe.id?T.jsx("input",{type:"text",value:B,onChange:ke=>y(ke.target.value.slice(0,am)),onKeyDown:ke=>{ke.key==="Enter"&&ne(pe.id),ke.key==="Escape"&&ge()},onBlur:()=>ne(pe.id),maxLength:am,className:"flex-1 border-none bg-transparent text-sm text-[#353740] focus:outline-none dark:text-[#ececf1]",autoFocus:!0}):T.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("h3",{className:`flex-1 truncate text-sm font-semibold ${r===pe.id?"text-[#1f2937] dark:text-white":"text-gray-700 dark:text-[#d4d7e2]"}`,children:pe.title}),T.jsxs("div",{className:"flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[T.jsx("button",{onClick:ke=>L(ke,pe),className:"rounded-full p-2 text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a]",title:"Rename conversation",children:T.jsx(Q0e,{className:"h-4 w-4"})}),T.jsx("button",{onClick:ke=>Ae(ke,pe),className:"rounded-full p-2 text-red-500 hover:bg-red-50 dark:text-red-300 dark:hover:bg-red-900/30",title:"Delete conversation",children:T.jsx(YX,{className:"h-4 w-4"})})]})]}),T.jsxs("div",{className:"mt-1 flex items-center gap-1.5 pr-1 text-[11px] text-gray-500 dark:text-[#a6acc5]",children:[T.jsx("span",{className:"whitespace-nowrap leading-none",children:Me(pe.updatedAt)}),T.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-white/80 px-2 py-0.5 font-medium text-gray-600 shadow-sm dark:bg-white/10 dark:text-[#e5e7f4] leading-none",children:[T.jsx(Mh,{className:"h-3 w-3"}),pe.messages.length]}),pe.attachedFiles&&pe.attachedFiles.length>0&&T.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-white/80 px-2 py-0.5 font-medium text-gray-600 shadow-sm dark:bg-white/10 dark:text-[#e5e7f4] leading-none",children:[T.jsx(FX,{className:"h-3 w-3"}),pe.attachedFiles.length]})]})]})]},pe.id))})}),te&&T.jsx("div",{className:"border-t border-gray-200 p-4 dark:border-[#4a4b54]",children:T.jsxs("div",{className:"text-center",children:[T.jsx("div",{className:"flex items-center justify-center mb-3",children:T.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-[#ececf1]",children:"Powered by ORBIT"})}),X.isLoading?T.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-gray-500 dark:text-[#bfc2cd] mb-3",children:[T.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-gray-400"}),T.jsx("span",{children:"Loading stats..."})]}):X.error?T.jsx("div",{className:"flex items-center justify-center gap-2 text-xs text-red-500 dark:text-red-400 mb-3",children:T.jsx("span",{children:"⚠️ Failed to load stats"})}):T.jsxs("div",{className:"flex items-center justify-center gap-4 text-xs text-gray-500 dark:text-[#bfc2cd] mb-3",children:[T.jsxs("div",{className:"flex items-center gap-1",children:[T.jsx("svg",{className:"w-4 h-4 text-yellow-500",fill:"currentColor",viewBox:"0 0 24 24",children:T.jsx("path",{d:"M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"})}),T.jsxs("span",{children:[X.stars.toLocaleString()," stars"]})]}),T.jsxs("div",{className:"flex items-center gap-1",children:[T.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 16 16",children:T.jsx("path",{d:"M5 3.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm0 2.122a2.25 2.25 0 10-1.5 0v.878A2.25 2.25 0 005.75 8.5h1.5v2.128a2.251 2.251 0 101.5 0V8.5h1.5a2.25 2.25 0 002.25-2.25v-.878a2.25 2.25 0 10-1.5 0v.878a.75.75 0 01-.75.75H4.5A.75.75 0 013 6.25v-.878zm3.75 7.378a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm3-8.75a.75.75 0 100-1.5.75.75 0 000 1.5z"})}),T.jsxs("span",{children:[X.forks.toLocaleString()," forks"]})]})]}),T.jsxs("a",{href:`https://github.com/${ZK()}/${qK()}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 transition-colors",children:[T.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 24 24",children:T.jsx("path",{d:"M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"})}),"View on GitHub"]})]})})]}),T.jsx(AV,{isOpen:w.isOpen,onClose:$,onConfirm:K,title:"Delete Conversation",message:`Are you sure you want to delete "${w.conversationTitle}"? This will clear the conversation history from both the server and your local storage. This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",type:"danger",isLoading:w.isDeleting}),T.jsx(AV,{isOpen:I.isOpen,onClose:Fe,onConfirm:Be,title:"Clear All Conversations",message:`Are you sure you want to delete all ${D} conversation${D!==1?"s":""}? This will clear all conversation history from both the server and your local storage. This action cannot be undone.`,confirmText:"Clear All",cancelText:"Cancel",type:"danger",isLoading:I.isDeleting})]})}function Zrt({isOpen:e,onClose:t}){const{theme:r,updateTheme:n}=EX(),{settings:i,updateSettings:A}=cy(),[a,s]=F.useState(null),[o,l]=F.useState(!1),[c,u]=F.useState(""),[g,h]=F.useState(!1);if(F.useEffect(()=>{e&&Ile().then(s)},[e]),!e)return null;const d=M=>{n({mode:M})},B=M=>{n({fontSize:M})},y=()=>{n({highContrast:!r.highContrast})},w=()=>{A({soundEnabled:!i.soundEnabled})},f=()=>{u(""),h(!1),l(!0)},I=()=>{l(!1),u(""),h(!1)},Y=()=>{I(),localStorage.clear(),window.location.reload()},Q=g&&c.trim().toLowerCase()==="reset";return T.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:T.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] flex flex-col overflow-hidden relative",children:[T.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-600",children:[T.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:"Settings"}),T.jsx("button",{onClick:t,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:T.jsx(ig,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),T.jsxs("div",{className:"flex-1 min-h-0 p-6 space-y-6 overflow-y-auto",children:[T.jsxs("div",{className:"space-y-4",children:[T.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[T.jsx(I0e,{className:"w-5 h-5"}),"Appearance"]}),T.jsxs("div",{className:"space-y-2",children:[T.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Theme"}),T.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:"Light",icon:N0e},{value:"dark",label:"Dark",icon:y0e},{value:"system",label:"System",icon:f0e}].map(({value:M,label:D,icon:G})=>T.jsxs("button",{onClick:()=>d(M),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${r.mode===M?"border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300":"border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 text-gray-700 dark:text-gray-300"}`,children:[T.jsx(G,{className:"w-5 h-5"}),T.jsx("span",{className:"text-sm font-medium",children:D})]},M))})]}),T.jsxs("div",{className:"flex items-center justify-between",children:[T.jsxs("div",{children:[T.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"High Contrast"}),T.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Improve readability with enhanced contrast"})]}),T.jsx("button",{onClick:y,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${r.highContrast?"bg-blue-600":"bg-gray-200 dark:bg-gray-600"}`,children:T.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${r.highContrast?"translate-x-6":"translate-x-1"}`})})]}),T.jsxs("div",{className:"space-y-2",children:[T.jsxs("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2",children:[T.jsx(U0e,{className:"w-4 h-4"}),"Font Size"]}),T.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(({value:M,label:D})=>T.jsx("button",{onClick:()=>B(M),className:`p-2 rounded-lg border-2 transition-colors text-center ${r.fontSize===M?"border-blue-500 bg-blue-50 dark:bg-blue-900/20":"border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500"}`,children:T.jsx("span",{className:`font-medium ${M==="small"?"text-sm":M==="large"?"text-lg":"text-base"}`,children:D})},M))})]})]}),T.jsxs("div",{className:"space-y-4",children:[T.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Chat Preferences"}),T.jsxs("div",{className:"flex items-center justify-between",children:[T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx(uw,{className:"w-4 h-4 text-gray-600 dark:text-gray-400"}),T.jsxs("div",{children:[T.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Sound Effects"}),T.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Play sounds for notifications and events"})]})]}),T.jsx("button",{onClick:w,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${i.soundEnabled?"bg-blue-600":"bg-gray-200 dark:bg-gray-600"}`,children:T.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${i.soundEnabled?"translate-x-6":"translate-x-1"}`})})]})]}),T.jsxs("div",{className:"space-y-4 pt-4 border-t border-gray-200 dark:border-gray-600",children:[T.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[T.jsx(YX,{className:"w-5 h-5"}),"Data Management"]}),T.jsxs("div",{className:"space-y-3",children:[T.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Clear all application data including conversations, saved API configurations, and personalized settings."}),T.jsxs("ul",{className:"text-xs text-gray-500 dark:text-gray-400 space-y-1",children:[T.jsxs("li",{className:"flex items-start gap-2",children:[T.jsx("span",{className:"mt-0.5 h-1.5 w-1.5 rounded-full bg-gray-400 dark:bg-gray-500"}),"Conversation history and transcripts"]}),T.jsxs("li",{className:"flex items-start gap-2",children:[T.jsx("span",{className:"mt-0.5 h-1.5 w-1.5 rounded-full bg-gray-400 dark:bg-gray-500"}),"API keys, base URLs, and provider preferences"]}),T.jsxs("li",{className:"flex items-start gap-2",children:[T.jsx("span",{className:"mt-0.5 h-1.5 w-1.5 rounded-full bg-gray-400 dark:bg-gray-500"}),"Theme, accessibility, and notification settings"]})]}),T.jsx("button",{onClick:f,className:"w-full px-4 py-2 text-sm font-medium text-red-600 dark:text-red-400 border border-red-300 dark:border-red-700 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors",children:"Reset Application"}),T.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"You'll be asked to confirm before anything is deleted."})]})]}),T.jsxs("div",{className:"space-y-2 pt-4 border-t border-gray-200 dark:border-gray-600",children:[T.jsxs("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2",children:[T.jsx(E0e,{className:"w-4 h-4"}),"About"]}),T.jsxs("div",{className:"space-y-1",children:[T.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:["AI Chat Application v",(a==null?void 0:a.appVersion)||"1.0.0"]}),T.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:["API Package: @schmitech/chatbot-api v",(a==null?void 0:a.apiVersion)||"^0.5.3",(a==null?void 0:a.isLocalApi)&&T.jsx("span",{className:"ml-1 px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded text-xs font-medium",children:"Local"})]}),T.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Built with React, TypeScript, and Tailwind CSS"})]})]})]}),o&&T.jsx("div",{className:"absolute inset-0 bg-black/70 flex items-center justify-center p-4 z-50",children:T.jsxs("div",{className:"w-full max-w-sm rounded-2xl bg-white dark:bg-gray-900 border border-red-100 dark:border-red-800 shadow-2xl p-6 space-y-4",children:[T.jsxs("div",{className:"flex items-start gap-3",children:[T.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/40",children:T.jsx(CX,{className:"w-5 h-5 text-red-600 dark:text-red-400"})}),T.jsxs("div",{children:[T.jsx("p",{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:"Reset application data?"}),T.jsxs("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:["This removes everything stored on this device. Type ",T.jsx("span",{className:"font-semibold text-gray-900 dark:text-gray-100",children:"RESET"})," to continue."]})]})]}),T.jsxs("div",{className:"space-y-2",children:[T.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:"Confirmation text"}),T.jsx("input",{value:c,onChange:M=>u(M.target.value.toUpperCase()),placeholder:"RESET",className:"w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-transparent px-3 py-2 text-sm uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-red-400 dark:text-gray-100"})]}),T.jsxs("label",{className:"flex items-start gap-2 text-xs text-gray-600 dark:text-gray-400",children:[T.jsx("input",{type:"checkbox",checked:g,onChange:M=>h(M.target.checked),className:"mt-0.5 h-4 w-4 rounded border-gray-300 dark:border-gray-500 text-red-600 focus:ring-red-500"}),T.jsx("span",{children:"I understand this action is permanent and will reload the app."})]}),T.jsxs("div",{className:"flex gap-2 pt-2",children:[T.jsx("button",{onClick:I,className:"flex-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Keep my data"}),T.jsx("button",{onClick:Y,disabled:!Q,className:`flex-1 px-4 py-2 text-sm font-semibold rounded-lg transition-colors ${Q?"bg-red-600 text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600":"bg-red-200 text-red-600/60 dark:bg-red-900/20 dark:text-red-400/60 cursor-not-allowed"}`,children:"Delete everything"})]})]})})]})})}function qrt(){const[e,t]=F.useState(!1),[r,n]=F.useState(!1);return T.jsx(a0e,{children:T.jsx(s0e,{children:T.jsxs("div",{className:"min-h-screen flex flex-col md:flex-row bg-white dark:bg-[#212121] text-slate-900 dark:text-slate-100",children:[T.jsx("div",{className:"hidden md:flex md:min-h-screen",children:T.jsx(aV,{})}),T.jsx("div",{className:"flex-1 flex justify-center w-full",children:T.jsx(Vrt,{onOpenSettings:()=>t(!0),onOpenSidebar:()=>n(!0)})}),T.jsx(Zrt,{isOpen:e,onClose:()=>t(!1)}),r&&T.jsxs("div",{className:"fixed inset-0 z-50 flex md:hidden",children:[T.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:()=>n(!1),"aria-hidden":"true"}),T.jsxs("div",{className:"relative z-10 h-full w-[min(18rem,85vw)]",children:[T.jsx(aV,{onRequestClose:()=>n(!1)}),T.jsx("button",{onClick:()=>n(!1),className:"absolute -right-3 top-3 rounded-full bg-white/90 p-2 text-gray-600 shadow dark:bg-[#2d2f39] dark:text-[#ececf1]","aria-label":"Close menu",children:T.jsx(ig,{className:"h-4 w-4"})})]})]})]})})})}Ile().then(e=>{Xe(`📱 App Version: v${e.appVersion}`),Xe(`📦 API Package: @schmitech/chatbot-api v${e.apiVersion}`),Xe(`🔧 API Mode: ${e.isLocalApi?"Local":"NPM Package"}`)});fX(document.getElementById("root")).render(T.jsx(F.StrictMode,{children:T.jsx(qrt,{})}));export{Xze as $,unt as A,c1e as B,f3e as C,Fa as D,pTe as E,ITe as F,Y_ as G,w3e as H,mTe as I,tnt as J,hTe as K,cnt as L,a1e as M,rnt as N,jTe as O,Kxe as P,d1e as Q,kh as R,PS as S,Ri as T,f_ as U,cRe as V,TSe as W,_7 as X,q7 as Y,u$ as Z,rr as _,ve as a,v$ as a$,Pxe as a0,F$ as a1,oS as a2,zy as a3,Yke as a4,Fke as a5,Mg as a6,Mke as a7,Qke as a8,zw as a9,VNe as aA,Uk as aB,P7 as aC,vh as aD,qGe as aE,_Ge as aF,eRe as aG,ZGe as aH,JGe as aI,$w as aJ,_te as aK,QGe as aL,zS as aM,OGe as aN,bGe as aO,Nve as aP,Zte as aQ,lRe as aR,eB as aS,r1e as aT,$d as aU,gt as aV,Et as aW,b_ as aX,hS as aY,T6 as aZ,z6 as a_,AB as aa,aS as ab,iS as ac,gc as ad,Rw as ae,V_ as af,IA as ag,EDe as ah,Jk as ai,W_ as aj,nB as ak,nnt as al,gUe as am,U7 as an,_y as ao,Zk as ap,en as aq,dS as ar,Hy as as,xNe as at,Qze as au,qk as av,BS as aw,ent as ax,Eg as ay,tRe as az,pt as b,jw as b0,snt as b1,int as b2,Yg as b3,_a as b4,Ant as b5,lnt as b6,ant as b7,ont as b8,$rt as b9,kve as bA,zve as bB,Zg as bC,L2 as bD,Ll as bE,xGe as bF,Uve as bG,Sve as bH,AJ as bI,oB as bJ,Jte as bK,Zw as bL,Xg as bM,Wte as bN,_w as bO,jS as bP,eJ as bQ,sB as bR,$Ge as bS,Zy as bT,y3e as ba,_n as bb,Hl as bc,kre as bd,lu as be,ire as bf,St as bg,Cs as bh,RS as bi,Jve as bj,zJ as bk,cB as bl,Ize as bm,Eze as bn,Xk as bo,Bt as bp,zte as bq,qy as br,Ky as bs,au as bt,Xte as bu,vGe as bv,lje as bw,vve as bx,nc as by,TS as bz,Bnt as c,gnt as d,aie as e,ir as f,o1e as g,l1e as h,Vn as i,GS as j,bo as k,F3e as l,hRe as m,Pg as n,dnt as o,Ir as p,are as q,mnt as r,hnt as s,pnt as t,s1e as u,Ta as v,u1e as w,k as x,fa as y,g1e as z};
|
|
1227
|
+
{ "name": "Simple Chat", "apiKey": "default-key", "apiUrl": "http://16.52.153.174:3000" },
|
|
1228
|
+
{ "name": "Chat With Files", "apiKey": "multimodal", "apiUrl": "http://16.52.153.174:3000" },
|
|
1229
|
+
{ "name": "e-commerce", "apiKey": "postgres", "apiUrl": "http://16.52.153.174:3000" },
|
|
1230
|
+
{ "name": "Human Resources", "apiKey": "contact", "apiUrl": "http://16.52.153.174:3000" },
|
|
1231
|
+
{ "name": "Movies", "apiKey": "mflix", "apiUrl": "http://16.52.153.174:3000" },
|
|
1232
|
+
{ "name": "Application Logs", "apiKey": "elasticsearch", "apiUrl": "http://16.52.153.174:3000" },
|
|
1233
|
+
{ "name": "Classified CMS", "apiKey": "classified", "apiUrl": "http://16.52.153.174:3000" },
|
|
1234
|
+
{ "name": "Business Analytics", "apiKey": "analytical", "apiUrl": "http://16.52.153.174:3000" },
|
|
1235
|
+
{ "name": "Travel Expenses", "apiKey": "travel-expenses", "apiUrl": "http://16.52.153.174:3000" }
|
|
1236
|
+
]`;try{const t=JSON.parse(e);if(Array.isArray(t)){Xe("Loading adapters from VITE_ADAPTERS environment variable");const r=t.map(nV).filter(n=>n!==null);if(r.length>0)return r}}catch{}return null}async function Krt(){if(_l)return _l;try{const t=await fetch("/api/adapters");if(t.ok)return _l=(await t.json()).adapters,Xe("Fetched adapters from /api/adapters:",_l),_l;Xe(`/api/adapters returned ${t.status}, trying fallback`)}catch{}const e=Prt();if(e&&e.length>0)return _l=e,_l;throw new Error("No adapters available. Configure VITE_ADAPTERS environment variable.")}function iV({selectedAdapter:e,onAdapterChange:t,disabled:r}){const[n,i]=F.useState([]),[A,a]=F.useState(!0),[s,o]=F.useState(null),[l,c]=F.useState(!1);F.useEffect(()=>{let d=!0;async function B(){try{a(!0),o(null);const y=await Krt();d&&i(y)}catch{d&&o("Failed to load adapters. Please check your connection.")}finally{d&&a(!1)}}return B(),()=>{d=!1}},[]);const u=F.useRef(!1),g=F.useRef(t);F.useEffect(()=>{g.current=t},[t]),F.useEffect(()=>{if(e){u.current=!0;return}!u.current&&n.length>0&&(u.current=!0)},[n,e]);const h=n.find(d=>d.name===e);return T.jsxs("div",{className:"relative w-full sm:w-[220px]",children:[T.jsx("label",{className:"sr-only",children:"Adapter"}),T.jsxs("div",{className:"relative",children:[T.jsx("button",{type:"button",onClick:()=>!r&&c(!l),disabled:r||A||n.length===0,className:"w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-left text-sm text-[#353740] focus:border-gray-400 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1] dark:focus:border-[#6b6f7a]",children:T.jsxs("div",{className:"flex items-center justify-between gap-2",children:[T.jsx("span",{className:`truncate ${h?"":"text-gray-500 dark:text-gray-400"}`,children:A?"Loading adapters…":s?"Error loading adapters":h?h.name:n.length===0?"No adapters available":"Select agent"}),T.jsx(MX,{className:`h-4 w-4 flex-shrink-0 transition-transform ${l?"rotate-180":""}`})]})}),l&&!r&&n.length>0&&T.jsxs(T.Fragment,{children:[T.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>c(!1)}),T.jsx("div",{className:"absolute z-20 mt-1 w-full rounded-md border border-gray-200 bg-white shadow-lg ring-1 ring-black/5 dark:border-[#4a4b54] dark:bg-[#1f2027]",children:T.jsx("div",{className:"max-h-60 overflow-auto py-1",children:n.map(d=>{const B=d.name===e;return T.jsx("button",{type:"button",onClick:()=>{B||t(d.name),c(!1)},className:`w-full px-3 py-2 text-left text-sm transition-colors ${B?"bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-200":"text-[#353740] hover:bg-gray-50 dark:text-[#ececf1] dark:hover:bg-[#2a2d35]"}`,children:T.jsx("span",{className:"font-medium truncate",children:d.name})},d.name)})})})]})]}),s&&T.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:s})]})}function Vrt({onOpenSettings:e,onOpenSidebar:t}){const{conversations:r,currentConversationId:n,sendMessage:i,regenerateResponse:A,isLoading:a,configureApiSettings:s,error:o,clearError:l,createThread:c}=fr(),{settings:u}=cy(),[g,h]=F.useState(!1),[d,B]=F.useState(()=>Pn()),[y,w]=F.useState(()=>Fc()),[f,I]=F.useState(null),[Y,Q]=F.useState(!1),[M,D]=F.useState(!1),[G,z]=F.useState(null),[R,j]=F.useState(!1),W=r.find(L=>L.id===n),te=Ii();F.useEffect(()=>{te&&(W!=null&&W.adapterName)&&I(W.adapterName)},[te,W==null?void 0:W.adapterName]);const X=!W||W.messages.length===0;F.useEffect(()=>{let L=null;const ne=()=>{L&&(L(),L=null)};if(u.voiceEnabled){if(mc.isAudioEnabled())return ne;const ge=()=>{ne();const P=async()=>{ne(),await mc.enableAudio()||ge()};document.addEventListener("pointerdown",P,{once:!0}),document.addEventListener("keydown",P,{once:!0}),L=()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",P)}};return ge(),ne}return ne(),mc.disableAudio(),ne},[u.voiceEnabled]);const Z=(L,ne,ge)=>{i(L,ne,ge)},ee=async(L,ne,ge)=>{await i(ge,void 0,L)},Ae=async()=>{if(!(!W||!W.apiKey&&!W.adapterName)){j(!0);try{const L=await li(),ne=W.apiUrl||Pn(),ge=W.apiKey,P=W.adapterName,Be=new L.ApiClient({apiUrl:ne,apiKey:ge||null,sessionId:null,adapterName:P||null});if(typeof Be.getAdapterInfo=="function"){const Fe=await Be.getAdapterInfo();Xe("Adapter info refreshed:",Fe),fr.setState(Me=>({conversations:Me.conversations.map(pe=>pe.id===n?{...pe,adapterInfo:Fe,updatedAt:new Date}:pe)})),setTimeout(()=>{const Me=fr.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:Me.conversations,currentConversationId:Me.currentConversationId}))},0)}}catch{}finally{j(!1)}}},K=async L=>{if(L&&L.preventDefault(),te){if(d&&f){D(!0),z(null);try{await s(d,void 0,void 0,f),l(),z(null),h(!1)}catch(ne){const ge=ne instanceof Error?ne.message:"Failed to configure adapter";z(ge)}finally{D(!1)}}}else if(d&&y){D(!0),z(null);try{await s(d,y),l(),z(null),Q(!1),h(!1)}catch(ne){const ge=ne instanceof Error?ne.message:"Failed to configure API settings";z(ge)}finally{D(!1)}}},$=L=>{I(L),z(null)};return T.jsx("div",{className:"flex-1 flex flex-col",children:T.jsx("div",{className:"flex h-full w-full flex-col px-3 sm:px-6",children:T.jsxs("div",{className:"mx-auto flex h-full w-full max-w-5xl flex-col",children:[g&&T.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4",children:T.jsxs("form",{onSubmit:K,className:"w-full max-w-md rounded-lg border border-gray-200 bg-white p-6 shadow-lg dark:border-[#444654] dark:bg-[#202123]",children:[T.jsx("h2",{className:"text-lg font-medium text-[#353740] dark:text-[#ececf1] mb-4",children:te?"Select Adapter":"Configure API Settings"}),T.jsxs("div",{className:"space-y-5",children:[!te&&T.jsxs("div",{children:[T.jsx("label",{className:"block text-sm font-medium text-[#353740] dark:text-[#d1d5db] mb-2",children:"API URL"}),T.jsx("input",{type:"text",value:d,onChange:L=>B(L.target.value),className:"w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-[#353740] focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1]",placeholder:"https://api.example.com"})]}),te?T.jsx(iV,{selectedAdapter:f,onAdapterChange:$,disabled:M}):T.jsxs("div",{children:[T.jsx("label",{className:"block text-sm font-medium text-[#353740] dark:text-[#d1d5db] mb-2",children:"API Key"}),T.jsxs("div",{className:"relative",children:[T.jsx("input",{type:Y?"text":"password",value:y,onChange:L=>{w(L.target.value),z(null)},className:"w-full rounded-md border border-gray-300 bg-white px-3 py-2 pr-10 text-sm text-[#353740] focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1]",placeholder:"your-api-key",disabled:M}),T.jsx("button",{type:"button",onClick:()=>Q(!Y),className:"absolute right-2 top-1/2 -translate-y-1/2 rounded p-1 text-gray-500 hover:text-gray-700 dark:text-[#d1d5db] dark:hover:text-white","aria-label":Y?"Hide API key":"Show API key",disabled:M,children:Y?T.jsx(h0e,{className:"h-4 w-4"}):T.jsx(d0e,{className:"h-4 w-4"})})]})]}),G&&T.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:G}),T.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[T.jsx("button",{type:"button",onClick:()=>{const L=(W==null?void 0:W.apiUrl)||Pn(),ne=(W==null?void 0:W.apiKey)||Fc();B(L),w(ne),z(null),Q(!1),h(!1)},className:"rounded-md border border-transparent px-4 py-2 text-sm text-gray-600 hover:border-gray-300 hover:text-gray-900 dark:text-[#d1d5db] dark:hover:text-white disabled:cursor-not-allowed disabled:opacity-50",disabled:M,children:"Cancel"}),T.jsx("button",{type:"submit",disabled:M||(te?!f:!d||!y),className:"rounded-md bg-[#343541] px-4 py-2 text-sm font-medium text-white hover:bg-[#282b32] disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#565869] dark:hover:bg-[#6b6f7a]",children:M?"Validating...":"Update"})]})]})]})}),o&&T.jsx("div",{className:"mt-6 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:T.jsxs("div",{className:"flex items-start justify-between",children:[T.jsx("p",{children:o}),T.jsx("button",{onClick:l,className:"ml-4 rounded p-1 text-red-500 hover:bg-red-100 hover:text-red-700 dark:text-red-200 dark:hover:bg-red-800/40","aria-label":"Dismiss error",children:"×"})]})}),t&&T.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3 md:hidden",children:[T.jsxs("button",{onClick:t,className:"inline-flex items-center gap-2 rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-400 transition-colors dark:border-[#4a4b54] dark:text-[#ececf1] dark:hover:bg-[#343541]","aria-label":"Open conversations menu",children:[T.jsx(p0e,{className:"h-4 w-4"}),"Chats"]}),T.jsx("button",{onClick:e,className:"inline-flex items-center justify-center rounded-md bg-[#343541] p-2 text-white hover:bg-[#282b32] transition-colors dark:bg-[#565869] dark:hover:bg-[#6b6f7a]","aria-label":"Open settings",children:T.jsx(tR,{className:"h-4 w-4"})})]}),T.jsx("div",{className:"border-b border-gray-200 dark:border-[#4a4b54] pb-6 pt-6",children:T.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[T.jsx("div",{className:"min-w-0 flex-1",children:(W==null?void 0:W.adapterInfo)&&T.jsxs("div",{className:"mb-4",children:[T.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3",children:[T.jsxs("div",{className:"inline-flex items-center gap-2 px-2.5 py-1 rounded-md bg-gray-100 dark:bg-[#343541] border border-gray-200 dark:border-[#4a4b54]",children:[T.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-[#bfc2cd] uppercase tracking-wide",children:"Agent"}),T.jsx("span",{className:"text-sm font-semibold text-[#353740] dark:text-[#ececf1]",children:W.adapterInfo.client_name})]}),W.adapterInfo.model&&T.jsxs("div",{className:"inline-flex items-center gap-2 px-2.5 py-1 rounded-md bg-gray-100 dark:bg-[#343541] border border-gray-200 dark:border-[#4a4b54]",children:[T.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-[#bfc2cd] uppercase tracking-wide",children:"Model"}),T.jsx("span",{className:"text-sm font-semibold text-[#353740] dark:text-[#ececf1]",children:W.adapterInfo.model})]}),T.jsx("button",{onClick:Ae,disabled:R||!(W!=null&&W.apiKey)&&!(W!=null&&W.adapterName),className:"inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs text-gray-600 hover:text-gray-900 hover:bg-gray-200 dark:text-[#bfc2cd] dark:hover:text-white dark:hover:bg-[#4a4b54] transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Refresh adapter info",children:T.jsx(Y0e,{className:`h-4 w-4 ${R?"animate-spin":""}`})})]}),T.jsx("h1",{className:"text-2xl font-semibold text-[#353740] dark:text-[#ececf1] mb-2",children:(W==null?void 0:W.title)||"New Chat"}),W&&T.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-[#bfc2cd]",children:[T.jsx("span",{className:"font-medium",children:W.messages.length}),T.jsxs("span",{children:["Updated ",W.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})]})}),T.jsxs("div",{className:"flex w-full flex-wrap items-center gap-3 sm:w-auto sm:flex-nowrap sm:justify-end",children:[T.jsxs("span",{className:"text-sm text-gray-500 dark:text-[#bfc2cd] sm:text-right",children:["v",Ele]}),!te&&T.jsx("button",{onClick:()=>{const L=Pn(),ne=W==null?void 0:W.apiUrl,ge=ne&&ne!==L?ne:L,P=(W==null?void 0:W.apiKey)||Fc();B(ge),w(P),z(null),Q(!1),h(!0)},disabled:!X,className:"w-full rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:border-gray-300 dark:border-[#4a4b54] dark:text-[#ececf1] dark:hover:bg-[#3c3f4a] dark:hover:border-[#6b6f7a] dark:disabled:hover:bg-transparent dark:disabled:hover:border-[#4a4b54] sm:w-auto",title:X?"Configure API settings":"API key cannot be changed once conversation has started. Create a new conversation to use a different API key.",children:"Configure API"}),te&&T.jsx("div",{className:"w-full sm:w-auto",children:T.jsx(iV,{selectedAdapter:f||(W==null?void 0:W.adapterName)||null,onAdapterChange:async L=>{I(L);const ne=(W==null?void 0:W.apiUrl)||Pn();try{await s(ne,void 0,void 0,L),l()}catch{}},disabled:!X})}),T.jsx("button",{onClick:e,className:"hidden rounded-md bg-[#343541] p-2 text-white hover:bg-[#282b32] transition-colors dark:bg-[#565869] dark:hover:bg-[#6b6f7a] md:inline-flex",title:"Settings",children:T.jsx(tR,{className:"h-4 w-4"})})]})]})}),!W||W.messages.length===0?T.jsx("div",{className:"flex-1 flex flex-col items-center justify-center min-h-0 px-4",children:T.jsxs("div",{className:"w-full max-w-3xl mx-auto text-center space-y-3",children:[T.jsx("div",{className:"space-y-1.5",children:T.jsx("h2",{className:"text-2xl font-medium text-[#353740] dark:text-[#ececf1]",children:"How can I assist you today?"})}),T.jsx("div",{className:"w-full",children:T.jsx(rV,{onSend:Z,disabled:a||!W||(te?!W.adapterName:!W.apiKey),placeholder:"Message ORBIT...",isCentered:!0})})]})}):T.jsxs(T.Fragment,{children:[T.jsx(wrt,{messages:W.messages,onRegenerate:A,onStartThread:async(L,ne)=>{try{await c(L,ne)}catch{}},onSendThreadMessage:ee,sessionId:W.sessionId,isLoading:a}),T.jsx(rV,{onSend:Z,disabled:a||!W||(te?!W.adapterName:!W.apiKey),placeholder:"Message ORBIT..."})]})]})})})}function AV({isOpen:e,onClose:t,onConfirm:r,title:n,message:i,confirmText:A="Confirm",cancelText:a="Cancel",type:s="danger",isLoading:o=!1}){if(!e)return null;const l=()=>{o||r()},u=(()=>{switch(s){case"danger":return{icon:"text-red-500",iconBg:"bg-red-100 dark:bg-red-900/20",confirmButton:"bg-red-600 hover:bg-red-700 focus:ring-red-500",border:"border-red-200 dark:border-red-800"};case"warning":return{icon:"text-amber-500",iconBg:"bg-amber-100 dark:bg-amber-900/20",confirmButton:"bg-amber-600 hover:bg-amber-700 focus:ring-amber-500",border:"border-amber-200 dark:border-amber-800"};default:return{icon:"text-blue-500",iconBg:"bg-blue-100 dark:bg-blue-900/20",confirmButton:"bg-blue-600 hover:bg-blue-700 focus:ring-blue-500",border:"border-blue-200 dark:border-blue-800"}}})();return T.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 z-50 animate-fadeIn",children:T.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-md transform animate-fadeIn",children:[T.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700",children:[T.jsxs("div",{className:"flex items-center gap-3",children:[T.jsx("div",{className:`w-10 h-10 rounded-full ${u.iconBg} flex items-center justify-center`,children:T.jsx(CX,{className:`w-5 h-5 ${u.icon}`})}),T.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:n})]}),T.jsx("button",{onClick:t,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:T.jsx(ig,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),T.jsx("div",{className:"p-6",children:T.jsx("p",{className:"text-gray-600 dark:text-gray-300 leading-relaxed",children:i})}),T.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 rounded-b-2xl",children:[T.jsx("button",{onClick:t,disabled:o,className:"px-4 py-2.5 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:a}),T.jsx("button",{onClick:l,disabled:o,className:`px-4 py-2.5 text-white rounded-lg transition-all font-medium shadow-sm hover:shadow-md transform hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-gray-800 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none ${u.confirmButton}`,children:o?T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}),"Clearing..."]}):A})]})]})})}const Xrt=(e,t)=>{const[r,n]=F.useState({stars:0,forks:0,license:"Apache-2.0",description:"An adaptable, open-source context-aware inference engine designed for privacy, control, and independence from proprietary models.",isLoading:!0,error:null});return F.useEffect(()=>{(async()=>{var A;try{const a=await fetch(`https://api.github.com/repos/${e}/${t}`);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);const s=await a.json();n({stars:s.stargazers_count||0,forks:s.forks_count||0,license:((A=s.license)==null?void 0:A.name)||"Apache-2.0",description:s.description||"An adaptable, open-source context-aware inference engine designed for privacy, control, and independence from proprietary models.",isLoading:!1,error:null})}catch(a){console.warn("Failed to fetch GitHub stats:",a),n({stars:104,forks:19,license:"Apache-2.0",description:"An adaptable, open-source context-aware inference engine designed for privacy, control, and independence from proprietary models.",isLoading:!1,error:a instanceof Error?a.message:"Failed to fetch stats"})}})()},[e,t]),r},am=100;function aV({onRequestClose:e}){const{conversations:t,currentConversationId:r,createConversation:n,selectConversation:i,deleteConversation:A,deleteAllConversations:a,updateConversationTitle:s,canCreateNewConversation:o,getConversationCount:l}=fr(),c=t.find(pe=>pe.id===r),[u,g]=F.useState(""),[h,d]=F.useState(null),[B,y]=F.useState(""),[w,f]=F.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[I,Y]=F.useState({isOpen:!1,isDeleting:!1}),Q=t.filter(pe=>pe.title.toLowerCase().includes(u.toLowerCase())||pe.messages.some(ke=>ke.content.toLowerCase().includes(u.toLowerCase()))),M=o(),D=l(),G=xr.maxConversations,z=G!==null&&D>=G,R=c?c.messages.length===0:!1,j=G!==null?`${D}/${G} conversations`:`${D} conversation${D===1?"":"s"}`,W=M?"Start a new conversation":z?`Maximum ${G} conversations reached. Delete a conversation to create a new one.`:R?"Current conversation is empty. Send a message first to create a new conversation.":"Finish your current conversation before starting a new one.",te=urt(),X=Xrt(ZK(),qK()),Z=()=>{try{n(),e==null||e()}catch(pe){jr("Cannot create new conversation:",pe instanceof Error?pe.message:"Unknown error")}},ee=async pe=>{try{await i(pe),e==null||e()}catch{}},Ae=(pe,ke)=>{pe.stopPropagation(),f({isOpen:!0,conversationId:ke.id,conversationTitle:ke.title,isDeleting:!1})},K=async()=>{f(pe=>({...pe,isDeleting:!0}));try{await A(w.conversationId),f({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})}catch{f({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})}},$=()=>{f({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},L=(pe,ke)=>{pe.stopPropagation(),d(ke.id),y(ke.title.slice(0,am))},ne=pe=>{const ke=B.slice(0,am).trim();ke&&s(pe,ke),d(null),y("")},ge=()=>{d(null),y("")},P=()=>{Y({isOpen:!0,isDeleting:!1})},Be=async()=>{Y(pe=>({...pe,isDeleting:!0}));try{await a(),Y({isOpen:!1,isDeleting:!1})}catch{Y({isOpen:!1,isDeleting:!1})}},Fe=()=>{Y({isOpen:!1,isDeleting:!1})},Me=pe=>{const ke=pe.toLocaleDateString([],{year:"numeric",month:"short",day:"numeric"}),Ee=pe.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return`${ke} · ${Ee}`};return T.jsxs(T.Fragment,{children:[T.jsxs("div",{className:"flex h-full w-full md:w-72 flex-col border-r border-b border-gray-200 bg-gray-50 dark:border-[#4a4b54] dark:bg-[#202123]",children:[T.jsxs("div",{className:"border-b border-gray-200 p-4 dark:border-[#4a4b54]",children:[T.jsxs("button",{onClick:Z,disabled:!M,className:`flex w-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium ${M?"bg-[#343541] text-white hover:bg-[#2c2f36] dark:bg-[#565869] dark:hover:bg-[#6b6f7a]":"cursor-not-allowed bg-gray-200 text-gray-500 dark:bg-[#3c3f4a] dark:text-[#6b6f7a]"}`,title:W,children:[T.jsx(F0e,{className:"h-4 w-4"}),"New Conversation"]}),T.jsxs("div",{className:"mt-3 space-y-2",children:[T.jsx("div",{className:"text-center",children:T.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j})}),t.length>0&&t.some(pe=>pe.messages.length>0)&&T.jsxs("button",{onClick:P,className:"flex w-full items-center justify-center gap-2 rounded-md border border-red-300 px-3 py-2 text-sm font-medium text-red-600 hover:bg-red-50 hover:border-red-400 dark:border-red-600/40 dark:text-red-400 dark:hover:bg-red-900/20 dark:hover:border-red-500/60 transition-colors",title:"Delete all conversations",children:[T.jsx(S0e,{className:"h-4 w-4"}),"Clear All"]})]})]}),T.jsx("div",{className:"border-b border-gray-200 px-4 py-3 dark:border-[#4a4b54]",children:T.jsxs("div",{className:"relative flex items-center",children:[T.jsx(x0e,{className:"pointer-events-none absolute left-3 h-4 w-4 text-gray-400"}),T.jsx("input",{type:"text",placeholder:"Search conversations",value:u,onChange:pe=>g(pe.target.value),className:"w-full rounded-md border border-gray-300 bg-white py-2 pl-9 pr-3 text-sm text-[#353740] placeholder-gray-400 focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1]"})]})}),T.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3",children:Q.length===0?T.jsxs("div",{className:"rounded-md border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500 dark:border-[#4a4b54] dark:text-[#bfc2cd]",children:[T.jsx(Mh,{className:"mx-auto mb-3 h-6 w-6 text-gray-400 dark:text-[#6b6f7a]"}),T.jsx("p",{children:u?"No conversations found":"No conversations yet"})]}):T.jsx("div",{className:"space-y-2",children:Q.map(pe=>T.jsxs("div",{onClick:()=>ee(pe.id),className:`group flex cursor-pointer items-start gap-3 rounded-xl border px-3 py-3 text-left transition ${r===pe.id?"border-[#343541] bg-white shadow-sm dark:border-[#6b6f7a] dark:bg-[#2c2f36]":"border-transparent bg-gray-100/70 hover:border-gray-300 hover:bg-white dark:bg-[#252830] dark:hover:border-[#4a4b54] dark:hover:bg-[#2f323c]"}`,children:[T.jsx("div",{className:`rounded-xl p-2 shadow-sm ${r===pe.id?"bg-[#eceefc] text-[#1d2559] dark:bg-[#3b4055] dark:text-white":"bg-white text-gray-500 dark:bg-[#3a3d46] dark:text-[#bfc2cd]"}`,children:T.jsx(Mh,{className:"h-4 w-4"})}),h===pe.id?T.jsx("input",{type:"text",value:B,onChange:ke=>y(ke.target.value.slice(0,am)),onKeyDown:ke=>{ke.key==="Enter"&&ne(pe.id),ke.key==="Escape"&&ge()},onBlur:()=>ne(pe.id),maxLength:am,className:"flex-1 border-none bg-transparent text-sm text-[#353740] focus:outline-none dark:text-[#ececf1]",autoFocus:!0}):T.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("h3",{className:`flex-1 truncate text-sm font-semibold ${r===pe.id?"text-[#1f2937] dark:text-white":"text-gray-700 dark:text-[#d4d7e2]"}`,children:pe.title}),T.jsxs("div",{className:"flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100",children:[T.jsx("button",{onClick:ke=>L(ke,pe),className:"rounded-full p-2 text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a]",title:"Rename conversation",children:T.jsx(Q0e,{className:"h-4 w-4"})}),T.jsx("button",{onClick:ke=>Ae(ke,pe),className:"rounded-full p-2 text-red-500 hover:bg-red-50 dark:text-red-300 dark:hover:bg-red-900/30",title:"Delete conversation",children:T.jsx(YX,{className:"h-4 w-4"})})]})]}),T.jsxs("div",{className:"mt-1 flex items-center gap-1.5 pr-1 text-[11px] text-gray-500 dark:text-[#a6acc5]",children:[T.jsx("span",{className:"whitespace-nowrap leading-none",children:Me(pe.updatedAt)}),T.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-white/80 px-2 py-0.5 font-medium text-gray-600 shadow-sm dark:bg-white/10 dark:text-[#e5e7f4] leading-none",children:[T.jsx(Mh,{className:"h-3 w-3"}),pe.messages.length]}),pe.attachedFiles&&pe.attachedFiles.length>0&&T.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-white/80 px-2 py-0.5 font-medium text-gray-600 shadow-sm dark:bg-white/10 dark:text-[#e5e7f4] leading-none",children:[T.jsx(FX,{className:"h-3 w-3"}),pe.attachedFiles.length]})]})]})]},pe.id))})}),te&&T.jsx("div",{className:"border-t border-gray-200 p-4 dark:border-[#4a4b54]",children:T.jsxs("div",{className:"text-center",children:[T.jsx("div",{className:"flex items-center justify-center mb-3",children:T.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-[#ececf1]",children:"Powered by ORBIT"})}),X.isLoading?T.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-gray-500 dark:text-[#bfc2cd] mb-3",children:[T.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-gray-400"}),T.jsx("span",{children:"Loading stats..."})]}):X.error?T.jsx("div",{className:"flex items-center justify-center gap-2 text-xs text-red-500 dark:text-red-400 mb-3",children:T.jsx("span",{children:"⚠️ Failed to load stats"})}):T.jsxs("div",{className:"flex items-center justify-center gap-4 text-xs text-gray-500 dark:text-[#bfc2cd] mb-3",children:[T.jsxs("div",{className:"flex items-center gap-1",children:[T.jsx("svg",{className:"w-4 h-4 text-yellow-500",fill:"currentColor",viewBox:"0 0 24 24",children:T.jsx("path",{d:"M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"})}),T.jsxs("span",{children:[X.stars.toLocaleString()," stars"]})]}),T.jsxs("div",{className:"flex items-center gap-1",children:[T.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 16 16",children:T.jsx("path",{d:"M5 3.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm0 2.122a2.25 2.25 0 10-1.5 0v.878A2.25 2.25 0 005.75 8.5h1.5v2.128a2.251 2.251 0 101.5 0V8.5h1.5a2.25 2.25 0 002.25-2.25v-.878a2.25 2.25 0 10-1.5 0v.878a.75.75 0 01-.75.75H4.5A.75.75 0 013 6.25v-.878zm3.75 7.378a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm3-8.75a.75.75 0 100-1.5.75.75 0 000 1.5z"})}),T.jsxs("span",{children:[X.forks.toLocaleString()," forks"]})]})]}),T.jsxs("a",{href:`https://github.com/${ZK()}/${qK()}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 transition-colors",children:[T.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 24 24",children:T.jsx("path",{d:"M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"})}),"View on GitHub"]})]})})]}),T.jsx(AV,{isOpen:w.isOpen,onClose:$,onConfirm:K,title:"Delete Conversation",message:`Are you sure you want to delete "${w.conversationTitle}"? This will clear the conversation history from both the server and your local storage. This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",type:"danger",isLoading:w.isDeleting}),T.jsx(AV,{isOpen:I.isOpen,onClose:Fe,onConfirm:Be,title:"Clear All Conversations",message:`Are you sure you want to delete all ${D} conversation${D!==1?"s":""}? This will clear all conversation history from both the server and your local storage. This action cannot be undone.`,confirmText:"Clear All",cancelText:"Cancel",type:"danger",isLoading:I.isDeleting})]})}function Zrt({isOpen:e,onClose:t}){const{theme:r,updateTheme:n}=EX(),{settings:i,updateSettings:A}=cy(),[a,s]=F.useState(null),[o,l]=F.useState(!1),[c,u]=F.useState(""),[g,h]=F.useState(!1);if(F.useEffect(()=>{e&&Ile().then(s)},[e]),!e)return null;const d=M=>{n({mode:M})},B=M=>{n({fontSize:M})},y=()=>{n({highContrast:!r.highContrast})},w=()=>{A({soundEnabled:!i.soundEnabled})},f=()=>{u(""),h(!1),l(!0)},I=()=>{l(!1),u(""),h(!1)},Y=()=>{I(),localStorage.clear(),window.location.reload()},Q=g&&c.trim().toLowerCase()==="reset";return T.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:T.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] flex flex-col overflow-hidden relative",children:[T.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-600",children:[T.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:"Settings"}),T.jsx("button",{onClick:t,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:T.jsx(ig,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),T.jsxs("div",{className:"flex-1 min-h-0 p-6 space-y-6 overflow-y-auto",children:[T.jsxs("div",{className:"space-y-4",children:[T.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[T.jsx(I0e,{className:"w-5 h-5"}),"Appearance"]}),T.jsxs("div",{className:"space-y-2",children:[T.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Theme"}),T.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:"Light",icon:N0e},{value:"dark",label:"Dark",icon:y0e},{value:"system",label:"System",icon:f0e}].map(({value:M,label:D,icon:G})=>T.jsxs("button",{onClick:()=>d(M),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${r.mode===M?"border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300":"border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 text-gray-700 dark:text-gray-300"}`,children:[T.jsx(G,{className:"w-5 h-5"}),T.jsx("span",{className:"text-sm font-medium",children:D})]},M))})]}),T.jsxs("div",{className:"flex items-center justify-between",children:[T.jsxs("div",{children:[T.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"High Contrast"}),T.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Improve readability with enhanced contrast"})]}),T.jsx("button",{onClick:y,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${r.highContrast?"bg-blue-600":"bg-gray-200 dark:bg-gray-600"}`,children:T.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${r.highContrast?"translate-x-6":"translate-x-1"}`})})]}),T.jsxs("div",{className:"space-y-2",children:[T.jsxs("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2",children:[T.jsx(U0e,{className:"w-4 h-4"}),"Font Size"]}),T.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(({value:M,label:D})=>T.jsx("button",{onClick:()=>B(M),className:`p-2 rounded-lg border-2 transition-colors text-center ${r.fontSize===M?"border-blue-500 bg-blue-50 dark:bg-blue-900/20":"border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500"}`,children:T.jsx("span",{className:`font-medium ${M==="small"?"text-sm":M==="large"?"text-lg":"text-base"}`,children:D})},M))})]})]}),T.jsxs("div",{className:"space-y-4",children:[T.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Chat Preferences"}),T.jsxs("div",{className:"flex items-center justify-between",children:[T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx(uw,{className:"w-4 h-4 text-gray-600 dark:text-gray-400"}),T.jsxs("div",{children:[T.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Sound Effects"}),T.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Play sounds for notifications and events"})]})]}),T.jsx("button",{onClick:w,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${i.soundEnabled?"bg-blue-600":"bg-gray-200 dark:bg-gray-600"}`,children:T.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${i.soundEnabled?"translate-x-6":"translate-x-1"}`})})]})]}),T.jsxs("div",{className:"space-y-4 pt-4 border-t border-gray-200 dark:border-gray-600",children:[T.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[T.jsx(YX,{className:"w-5 h-5"}),"Data Management"]}),T.jsxs("div",{className:"space-y-3",children:[T.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Clear all application data including conversations, saved API configurations, and personalized settings."}),T.jsxs("ul",{className:"text-xs text-gray-500 dark:text-gray-400 space-y-1",children:[T.jsxs("li",{className:"flex items-start gap-2",children:[T.jsx("span",{className:"mt-0.5 h-1.5 w-1.5 rounded-full bg-gray-400 dark:bg-gray-500"}),"Conversation history and transcripts"]}),T.jsxs("li",{className:"flex items-start gap-2",children:[T.jsx("span",{className:"mt-0.5 h-1.5 w-1.5 rounded-full bg-gray-400 dark:bg-gray-500"}),"API keys, base URLs, and provider preferences"]}),T.jsxs("li",{className:"flex items-start gap-2",children:[T.jsx("span",{className:"mt-0.5 h-1.5 w-1.5 rounded-full bg-gray-400 dark:bg-gray-500"}),"Theme, accessibility, and notification settings"]})]}),T.jsx("button",{onClick:f,className:"w-full px-4 py-2 text-sm font-medium text-red-600 dark:text-red-400 border border-red-300 dark:border-red-700 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors",children:"Reset Application"}),T.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"You'll be asked to confirm before anything is deleted."})]})]}),T.jsxs("div",{className:"space-y-2 pt-4 border-t border-gray-200 dark:border-gray-600",children:[T.jsxs("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2",children:[T.jsx(E0e,{className:"w-4 h-4"}),"About"]}),T.jsxs("div",{className:"space-y-1",children:[T.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:["AI Chat Application v",(a==null?void 0:a.appVersion)||"1.0.0"]}),T.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:["API Package: @schmitech/chatbot-api v",(a==null?void 0:a.apiVersion)||"^0.5.3",(a==null?void 0:a.isLocalApi)&&T.jsx("span",{className:"ml-1 px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded text-xs font-medium",children:"Local"})]}),T.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Built with React, TypeScript, and Tailwind CSS"})]})]})]}),o&&T.jsx("div",{className:"absolute inset-0 bg-black/70 flex items-center justify-center p-4 z-50",children:T.jsxs("div",{className:"w-full max-w-sm rounded-2xl bg-white dark:bg-gray-900 border border-red-100 dark:border-red-800 shadow-2xl p-6 space-y-4",children:[T.jsxs("div",{className:"flex items-start gap-3",children:[T.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/40",children:T.jsx(CX,{className:"w-5 h-5 text-red-600 dark:text-red-400"})}),T.jsxs("div",{children:[T.jsx("p",{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:"Reset application data?"}),T.jsxs("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:["This removes everything stored on this device. Type ",T.jsx("span",{className:"font-semibold text-gray-900 dark:text-gray-100",children:"RESET"})," to continue."]})]})]}),T.jsxs("div",{className:"space-y-2",children:[T.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:"Confirmation text"}),T.jsx("input",{value:c,onChange:M=>u(M.target.value.toUpperCase()),placeholder:"RESET",className:"w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-transparent px-3 py-2 text-sm uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-red-400 dark:text-gray-100"})]}),T.jsxs("label",{className:"flex items-start gap-2 text-xs text-gray-600 dark:text-gray-400",children:[T.jsx("input",{type:"checkbox",checked:g,onChange:M=>h(M.target.checked),className:"mt-0.5 h-4 w-4 rounded border-gray-300 dark:border-gray-500 text-red-600 focus:ring-red-500"}),T.jsx("span",{children:"I understand this action is permanent and will reload the app."})]}),T.jsxs("div",{className:"flex gap-2 pt-2",children:[T.jsx("button",{onClick:I,className:"flex-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Keep my data"}),T.jsx("button",{onClick:Y,disabled:!Q,className:`flex-1 px-4 py-2 text-sm font-semibold rounded-lg transition-colors ${Q?"bg-red-600 text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600":"bg-red-200 text-red-600/60 dark:bg-red-900/20 dark:text-red-400/60 cursor-not-allowed"}`,children:"Delete everything"})]})]})})]})})}function qrt(){const[e,t]=F.useState(!1),[r,n]=F.useState(!1);return T.jsx(a0e,{children:T.jsx(s0e,{children:T.jsxs("div",{className:"min-h-screen flex flex-col md:flex-row bg-white dark:bg-[#212121] text-slate-900 dark:text-slate-100",children:[T.jsx("div",{className:"hidden md:flex md:min-h-screen",children:T.jsx(aV,{})}),T.jsx("div",{className:"flex-1 flex justify-center w-full",children:T.jsx(Vrt,{onOpenSettings:()=>t(!0),onOpenSidebar:()=>n(!0)})}),T.jsx(Zrt,{isOpen:e,onClose:()=>t(!1)}),r&&T.jsxs("div",{className:"fixed inset-0 z-50 flex md:hidden",children:[T.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:()=>n(!1),"aria-hidden":"true"}),T.jsxs("div",{className:"relative z-10 h-full w-[min(18rem,85vw)]",children:[T.jsx(aV,{onRequestClose:()=>n(!1)}),T.jsx("button",{onClick:()=>n(!1),className:"absolute -right-3 top-3 rounded-full bg-white/90 p-2 text-gray-600 shadow dark:bg-[#2d2f39] dark:text-[#ececf1]","aria-label":"Close menu",children:T.jsx(ig,{className:"h-4 w-4"})})]})]})]})})})}Ile().then(e=>{Xe(`📱 App Version: v${e.appVersion}`),Xe(`📦 API Package: @schmitech/chatbot-api v${e.apiVersion}`),Xe(`🔧 API Mode: ${e.isLocalApi?"Local":"NPM Package"}`)});fX(document.getElementById("root")).render(T.jsx(F.StrictMode,{children:T.jsx(qrt,{})}));export{Xze as $,unt as A,c1e as B,f3e as C,Fa as D,pTe as E,ITe as F,Y_ as G,w3e as H,mTe as I,tnt as J,hTe as K,cnt as L,a1e as M,rnt as N,jTe as O,Kxe as P,d1e as Q,kh as R,PS as S,Ri as T,f_ as U,cRe as V,TSe as W,_7 as X,q7 as Y,u$ as Z,rr as _,ve as a,v$ as a$,Pxe as a0,F$ as a1,oS as a2,zy as a3,Yke as a4,Fke as a5,Mg as a6,Mke as a7,Qke as a8,zw as a9,VNe as aA,Uk as aB,P7 as aC,vh as aD,qGe as aE,_Ge as aF,eRe as aG,ZGe as aH,JGe as aI,$w as aJ,_te as aK,QGe as aL,zS as aM,OGe as aN,bGe as aO,Nve as aP,Zte as aQ,lRe as aR,eB as aS,r1e as aT,$d as aU,gt as aV,Et as aW,b_ as aX,hS as aY,T6 as aZ,z6 as a_,AB as aa,aS as ab,iS as ac,gc as ad,Rw as ae,V_ as af,IA as ag,EDe as ah,Jk as ai,W_ as aj,nB as ak,nnt as al,gUe as am,U7 as an,_y as ao,Zk as ap,en as aq,dS as ar,Hy as as,xNe as at,Qze as au,qk as av,BS as aw,ent as ax,Eg as ay,tRe as az,pt as b,jw as b0,snt as b1,int as b2,Yg as b3,_a as b4,Ant as b5,lnt as b6,ant as b7,ont as b8,$rt as b9,kve as bA,zve as bB,Zg as bC,L2 as bD,Ll as bE,xGe as bF,Uve as bG,Sve as bH,AJ as bI,oB as bJ,Jte as bK,Zw as bL,Xg as bM,Wte as bN,_w as bO,jS as bP,eJ as bQ,sB as bR,$Ge as bS,Zy as bT,y3e as ba,_n as bb,Hl as bc,kre as bd,lu as be,ire as bf,St as bg,Cs as bh,RS as bi,Jve as bj,zJ as bk,cB as bl,Ize as bm,Eze as bn,Xk as bo,Bt as bp,zte as bq,qy as br,Ky as bs,au as bt,Xte as bu,vGe as bv,lje as bw,vve as bx,nc as by,TS as bz,Bnt as c,gnt as d,aie as e,ir as f,o1e as g,l1e as h,Vn as i,GS as j,bo as k,F3e as l,hRe as m,Pg as n,dnt as o,Ir as p,are as q,mnt as r,hnt as s,pnt as t,s1e as u,Ta as v,u1e as w,k as x,fa as y,g1e as z};
|