@fudrouter/fsrouter 0.6.99 → 0.6.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/lib/db/driver.js +8 -0
  2. package/dist/routes/db/route.js +139 -98
  3. package/package.json +1 -1
  4. package/public/.vite/manifest.json +90 -90
  5. package/public/assets/EndpointPageClient.B1pL25ws.js +6 -0
  6. package/public/assets/Loading.C1s7rolj.js +1 -0
  7. package/public/assets/NoAuthProxyCard.CrFQ6U88.js +89 -0
  8. package/public/assets/index.2a3mqmx-.js +89 -0
  9. package/public/assets/index.Blvwx0HS.css +1 -0
  10. package/public/assets/page.1w2ClxJa.js +64 -0
  11. package/public/assets/page.B1WuiJNL.js +1 -0
  12. package/public/assets/page.B5pzcN8j.js +1 -0
  13. package/public/assets/page.B6HgqxIh.js +1 -0
  14. package/public/assets/page.B9nZj2bM.js +1 -0
  15. package/public/assets/page.BAjMOHLc.js +6 -0
  16. package/public/assets/page.BBAy2gwn.js +1 -0
  17. package/public/assets/page.BFCJJrr_.js +1 -0
  18. package/public/assets/page.BH4eYGdz.js +1 -0
  19. package/public/assets/page.BMlo83oM.js +1 -0
  20. package/public/assets/page.BPMtBhKd.js +1 -0
  21. package/public/assets/page.BWmMDNX0.js +5 -0
  22. package/public/assets/page.B_rBjC41.js +1 -0
  23. package/public/assets/page.Bj0MFcSW.js +1 -0
  24. package/public/assets/page.Bs99xyvS.js +23 -0
  25. package/public/assets/page.BuU3QCO4.js +1 -0
  26. package/public/assets/page.C-4fur3O.js +4 -0
  27. package/public/assets/page.C0iX9Fnf.js +1 -0
  28. package/public/assets/page.C0qR8Y5R.js +1 -0
  29. package/public/assets/page.CAAgcGqN.js +1 -0
  30. package/public/assets/page.CCTU0LkA.js +1 -0
  31. package/public/assets/page.CS8il6ZP.js +2 -0
  32. package/public/assets/page.CTDNnugg.js +1 -0
  33. package/public/assets/page.CaujBCOC.js +1 -0
  34. package/public/assets/page.CcYMJEkz.js +2 -0
  35. package/public/assets/page.CfKwOBap.js +4 -0
  36. package/public/assets/page.Ct47P4hB.js +1 -0
  37. package/public/assets/page.CtZhMjzD.js +31 -0
  38. package/public/assets/page.D6H2uDVR.js +1 -0
  39. package/public/assets/page.D7rC6efy.js +1 -0
  40. package/public/assets/page.DCY06u9A.js +5 -0
  41. package/public/assets/page.DFzXiFFW.js +1 -0
  42. package/public/assets/page.DOgtsHmp.js +1 -0
  43. package/public/assets/page.DiFYTx8K.js +1 -0
  44. package/public/assets/page.Dm8AHdlz.js +1 -0
  45. package/public/assets/page.QIyytaMO.js +1 -0
  46. package/public/assets/page.jbj6FFm0.js +6 -0
  47. package/public/index.html +4 -4
@@ -0,0 +1,64 @@
1
+ import{j as e,B as be,C as $t,g as Ae,M as gt,f as w,u as ve,i as Be,h as pe,N as bt,Q as yt,P as Pt,R as pt,S as Tt,V as _t}from"./index.2a3mqmx-.js";import{b as s,h as Lt,d as It,L as Dt}from"./router.Cjj1--8t.js";import{C as we,T as Ue,E as Ut,B as Oe,S as Ot,N as Bt,A as Kt}from"./NoAuthProxyCard.CrFQ6U88.js";import"./zustand.akaTi5uX.js";const Ft={mode:{label:"Mode",format:t=>t},defaultModel:{label:"Model",format:t=>t,mono:!0},baseUrl:{label:"Endpoint",format:t=>t,isLink:!0,mono:!0},costPerQuery:{label:"Cost / call",format:t=>t===0?"Free":`$${t.toFixed(4)}`},pricingUrl:{label:"Pricing",format:()=>"View pricing",isLink:!0},freeTier:{label:"Free tier",format:t=>t},freeMonthlyQuota:{label:"Free quota",format:t=>t===0?"—":t>=999999?"Unlimited":`${t.toLocaleString()} / mo`},searchTypes:{label:"Types",format:t=>t.join(", ")},formats:{label:"Formats",format:t=>t.join(", ")},maxMaxResults:{label:"Max results",format:t=>t},maxCharacters:{label:"Max chars",format:t=>t.toLocaleString()}};function Vt({config:t,provider:r,title:i="Provider Info"}){var d,p;if(!t)return null;const S=Object.entries(Ft).filter(([h])=>t[h]!==void 0&&t[h]!==null&&t[h]!=="").map(([h,y])=>({key:h,label:y.label,value:y.format(t[h]),isLink:y.isLink,mono:y.mono,raw:t[h]})),c=((d=r==null?void 0:r.notice)==null?void 0:d.apiKeyUrl)||(r==null?void 0:r.website),M=(p=r==null?void 0:r.notice)==null?void 0:p.text;return e.jsxs(we,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:i}),c&&e.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"open_in_new"}),"Get API Key"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-2",children:[S.map(h=>e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:"text-xs text-text-muted w-28 shrink-0",children:h.label}),h.isLink?e.jsx("a",{href:h.raw,target:"_blank",rel:"noopener noreferrer",className:`text-sm text-primary hover:underline truncate ${h.mono?"font-mono":""}`,children:h.value}):e.jsx("span",{className:`text-sm text-text-main truncate ${h.mono?"font-mono":""}`,children:h.value})]},h.key)),M&&e.jsxs("div",{className:"flex items-start gap-3 min-w-0 sm:col-span-2",children:[e.jsx("span",{className:"text-xs text-text-muted w-28 shrink-0 mt-0.5",children:"Notice"}),e.jsx("span",{className:"text-sm text-text-main leading-relaxed",children:M})]})]})]})}function jt({until:t}){const[r,i]=s.useState("");return s.useEffect(()=>{const S=()=>{const M=new Date(t).getTime()-Date.now();if(M<=0){i("");return}const d=Math.floor(M/1e3);d<60?i(`${d}s`):d<3600?i(`${Math.floor(d/60)}m ${d%60}s`):i(`${Math.floor(d/3600)}h ${Math.floor(d%3600/60)}m`)};S();const c=setInterval(S,1e3);return()=>clearInterval(c)},[t]),r?e.jsxs("span",{className:"text-xs text-orange-500 font-mono",children:["⏱ ",r]}):null}jt.propTypes={until:w.string.isRequired};function vt({connection:t,proxyPools:r,isOAuth:i,isFirst:S,isLast:c,onMoveUp:M,onMoveDown:d,onToggleActive:p,onUpdateProxy:h,onEdit:y,onDelete:$}){var a,g,P,K,f,D;const[R,A]=s.useState(!1),[u,v]=s.useState(!1),[U,O]=s.useState(!1),L=s.useRef(null),I=new Map((r||[]).map(b=>[b.id,b])),j=((a=t.providerSpecificData)==null?void 0:a.proxyPoolId)||null,x=j?I.get(j):null,N=((g=t.providerSpecificData)==null?void 0:g.connectionProxyEnabled)===!0&&!!((P=t.providerSpecificData)!=null&&P.connectionProxyUrl),B=!!j||N,X=x?`Pool: ${x.name}`:j?`Pool: ${j} (inactive/missing)`:N?`Legacy: ${(K=t.providerSpecificData)==null?void 0:K.connectionProxyUrl}`:"";let Q="";const V=(x==null?void 0:x.proxyUrl)||((f=t.providerSpecificData)==null?void 0:f.connectionProxyUrl);if(V)try{const b=new URL(V);Q=`${b.protocol}//${b.hostname}${b.port?`:${b.port}`:""}`}catch{Q=V}const re=(x==null?void 0:x.noProxy)||((D=t.providerSpecificData)==null?void 0:D.connectionNoProxy)||"",ae=(x==null?void 0:x.isActive)===!0?"success":j||N?"error":"default",H=Object.entries(t).filter(([b])=>b.startsWith("modelLock_")).map(([,b])=>b).filter(Boolean).sort()[0]||null;s.useEffect(()=>{const b=()=>{const ne=Object.entries(t).filter(([G])=>G.startsWith("modelLock_")).map(([,G])=>G).filter(G=>G&&new Date(G).getTime()>Date.now()).sort()[0]||null;O(!!ne)};b();const Z=H?setInterval(b,1e3):null;return()=>{Z&&clearInterval(Z)}},[H]),s.useEffect(()=>{if(!R)return;const b=Z=>{L.current&&!L.current.contains(Z.target)&&A(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[R]);const W=t.testStatus==="unavailable"&&!U?"active":t.testStatus,le=()=>t.isActive===!1?"default":W==="active"||W==="success"?"success":W==="error"||W==="expired"||W==="unavailable"?"error":"default",m=i?t.name||t.email||t.displayName||"OAuth Account":t.name,o=async b=>{v(!0);try{await h(b==="__none__"?null:b)}finally{v(!1),A(!1)}};return e.jsxs("div",{className:`group flex flex-col gap-3 p-2 rounded-lg sm:flex-row sm:items-center sm:justify-between hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors ${t.isActive===!1?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex w-full min-w-0 flex-1 items-start gap-3 sm:items-center",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("button",{onClick:M,disabled:S,className:`p-0.5 rounded ${S?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_up"})}),e.jsx("button",{onClick:d,disabled:c,className:`p-0.5 rounded ${c?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_down"})})]}),e.jsx("span",{className:"material-symbols-outlined text-base text-text-muted",children:i?"lock":"key"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:m}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-1",children:[e.jsx(Oe,{variant:le(),size:"sm",dot:!0,children:t.isActive===!1?"disabled":W||"Unknown"}),B&&e.jsx(Oe,{variant:ae,size:"sm",children:"Proxy"}),U&&t.isActive!==!1&&e.jsx(jt,{until:H}),t.lastError&&t.isActive!==!1&&e.jsx("span",{className:"text-xs text-red-500 truncate max-w-[300px]",title:t.lastError,children:t.lastError}),e.jsxs("span",{className:"text-xs text-text-muted",children:["#",t.priority]})]}),B&&e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-text-muted truncate max-w-[420px]",title:X,children:X}),Q&&e.jsx("code",{className:"text-[10px] font-mono bg-black/5 dark:bg-white/5 px-1 py-0.5 rounded text-text-muted",children:Q}),re&&e.jsxs("span",{className:"text-[11px] text-text-muted truncate max-w-[320px]",title:re,children:["no_proxy: ",re]})]})]})]}),e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-2 sm:w-auto sm:justify-end",children:[e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(r||[]).length>0&&e.jsxs("div",{className:"relative",ref:L,children:[e.jsxs("button",{onClick:()=>A(b=>!b),className:`flex flex-col items-center px-2 py-1 rounded hover:bg-black/5 dark:hover:bg-white/5 transition-colors ${B?"text-primary":"text-text-muted hover:text-primary"}`,disabled:u,children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:u?"progress_activity":"lan"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Proxy"})]}),R&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-50 bg-bg border border-border rounded-lg shadow-lg py-1 min-w-[160px]",children:[e.jsx("button",{onClick:()=>o("__none__"),className:`w-full text-left px-3 py-1.5 text-sm hover:bg-black/5 dark:hover:bg-white/5 ${j?"text-text-main":"text-primary font-medium"}`,children:"None"}),(r||[]).map(b=>e.jsx("button",{onClick:()=>o(b.id),className:`w-full text-left px-3 py-1.5 text-sm hover:bg-black/5 dark:hover:bg-white/5 ${j===b.id?"text-primary font-medium":"text-text-main"}`,children:b.name},b.id))]})]}),e.jsxs("button",{onClick:y,className:"flex flex-col items-center px-2 py-1 rounded hover:bg-black/5 dark:hover:bg-white/5 text-text-muted hover:text-primary",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"edit"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Edit"})]}),e.jsxs("button",{onClick:$,className:"flex flex-col items-center px-2 py-1 rounded hover:bg-red-500/10 text-red-500",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"delete"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Delete"})]})]}),e.jsx(Ue,{size:"sm",checked:t.isActive??!0,onChange:p,title:t.isActive??!0?"Disable":"Enable"})]})]})}vt.propTypes={connection:w.shape({id:w.string,name:w.string,email:w.string,displayName:w.string,testStatus:w.string,isActive:w.bool,lastError:w.string,priority:w.number}).isRequired,proxyPools:w.array,isOAuth:w.bool.isRequired,isFirst:w.bool.isRequired,isLast:w.bool.isRequired,onMoveUp:w.func.isRequired,onMoveDown:w.func.isRequired,onToggleActive:w.func.isRequired,onUpdateProxy:w.func,onEdit:w.func.isRequired,onDelete:w.func.isRequired};function wt({isOpen:t,provider:r,providerName:i,proxyPools:S,onSave:c,onClose:M}){var j;const d="__none__",[p,h]=s.useState({name:"",apiKey:"",priority:1,proxyPoolId:d,supportsImageRef:!0,supportsVideoRef:!0,supportsStartEndFrame:!0}),[y,$]=s.useState(!1),[R,A]=s.useState(null),[u,v]=s.useState(!1),U=Ae[r],O=((j=U==null?void 0:U.serviceKinds)==null?void 0:j.includes("video"))||r==="leonardo"||r==="runwayml",L=async()=>{$(!0);try{const N=await(await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,apiKey:p.apiKey})})).json();A(N.valid?"success":"failed")}catch{A("failed")}finally{$(!1)}},I=async()=>{if(!(!r||!p.apiKey)){v(!0);try{let x=!1;try{$(!0),A(null),x=!!(await(await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,apiKey:p.apiKey})})).json()).valid,A(x?"success":"failed")}catch{A("failed")}finally{$(!1)}await c({name:p.name,apiKey:p.apiKey,priority:p.priority,proxyPoolId:p.proxyPoolId===d?null:p.proxyPoolId,testStatus:x?"active":"unknown",providerSpecificData:{supportsImageRef:p.supportsImageRef,supportsVideoRef:p.supportsVideoRef,supportsStartEndFrame:p.supportsStartEndFrame}})}finally{v(!1)}}};return r?e.jsx(gt,{isOpen:t,title:`Add ${i||r} API Key`,onClose:M,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-text-muted mb-1 block",children:"Name"}),e.jsx("input",{className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",value:p.name,onChange:x=>h({...p,name:x.target.value}),placeholder:"Production Key"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-xs text-text-muted mb-1 block",children:"API Key"}),e.jsx("input",{type:"password",className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",value:p.apiKey,onChange:x=>h({...p,apiKey:x.target.value})})]}),e.jsx("div",{className:"pt-6",children:e.jsx(be,{onClick:L,disabled:!p.apiKey||y||u,variant:"secondary",children:y?"Checking...":"Check"})})]}),R&&e.jsx(Oe,{variant:R==="success"?"success":"error",children:R==="success"?"Valid":"Invalid"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-text-muted mb-1 block",children:"Priority"}),e.jsx("input",{type:"number",className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",value:p.priority,onChange:x=>h({...p,priority:Number.parseInt(x.target.value)||1})})]}),e.jsx(Ot,{label:"Proxy Pool",value:p.proxyPoolId,onChange:x=>h({...p,proxyPoolId:x.target.value}),options:[{value:d,label:"None"},...(S||[]).map(x=>({value:x.id,label:x.name}))]}),O&&e.jsxs("div",{className:"bg-sidebar/30 p-4 rounded-lg border border-accent/10 flex flex-col gap-3 my-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wider text-text-muted",children:"Capabilities"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Image Reference"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Supports image URL inputs as prompts"})]}),e.jsx(Ue,{checked:p.supportsImageRef??!0,onChange:x=>h({...p,supportsImageRef:x})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-accent/5 pt-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Video Reference"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Supports video URL inputs as prompts"})]}),e.jsx(Ue,{checked:p.supportsVideoRef??!0,onChange:x=>h({...p,supportsVideoRef:x})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-accent/5 pt-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Start/End Frame"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Supports specifying start/end frames"})]}),e.jsx(Ue,{checked:p.supportsStartEndFrame??!0,onChange:x=>h({...p,supportsStartEndFrame:x})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{onClick:I,fullWidth:!0,disabled:!p.name||!p.apiKey||u,children:u?"Saving...":"Save"}),e.jsx(be,{onClick:M,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}):null}wt.propTypes={isOpen:w.bool.isRequired,provider:w.string,providerName:w.string,proxyPools:w.array,onSave:w.func.isRequired,onClose:w.func.isRequired};function Nt({providerId:t,isOAuth:r}){const[i,S]=s.useState([]),[c,M]=s.useState([]),[d,p]=s.useState(!0),[h,y]=s.useState(!1),[$,R]=s.useState(!1),[A,u]=s.useState(null),[v,U]=s.useState(null),[O,L]=s.useState("1"),[I,j]=s.useState(null),[x,N]=s.useState(!1),B=s.useCallback(async()=>{try{const[o,a,g]=await Promise.all([fetch("/api/providers",{cache:"no-store"}),fetch("/api/proxy-pools?isActive=true",{cache:"no-store"}),fetch("/api/settings",{cache:"no-store"})]),P=await o.json(),K=await a.json(),f=g.ok?await g.json():{};o.ok&&S((P.connections||[]).filter(b=>b.provider===t)),a.ok&&M(K.proxyPools||[]);const D=(f.providerStrategies||{})[t]||{};U(D.fallbackStrategy||null),L(D.stickyRoundRobinLimit!=null?String(D.stickyRoundRobinLimit):"1")}catch(o){console.log("ConnectionsCard fetch error:",o)}finally{p(!1)}},[t]);s.useEffect(()=>{B()},[B]);const X=async(o,a)=>{try{const g=await fetch("/api/settings",{cache:"no-store"}),K=(g.ok?await g.json():{}).providerStrategies||{},f={};o&&(f.fallbackStrategy=o),o==="round-robin"&&a!==""&&(f.stickyRoundRobinLimit=Number(a)||3);const D={...K};Object.keys(f).length===0?delete D[t]:D[t]=f,await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerStrategies:D})})}catch(g){console.log("saveStrategy error:",g)}},Q=async(o,a)=>{const g=[...i];[g[o],g[a]]=[g[a],g[o]],S(g);try{await Promise.all([fetch(`/api/providers/${g[o].id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:o})}),fetch(`/api/providers/${g[a].id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:a})})])}catch{await B()}},V=async o=>{j({title:"Delete Connection",message:"Delete this connection?",onConfirm:async()=>{j(null);try{(await fetch(`/api/providers/${o}`,{method:"DELETE"})).ok&&S(g=>g.filter(P=>P.id!==o))}catch(a){console.log("delete error:",a)}}})},re=async(o,a)=>{try{(await fetch(`/api/providers/${o}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:a})})).ok&&S(P=>P.map(K=>K.id===o?{...K,isActive:a}:K))}catch(g){console.log("toggle error:",g)}},ae=async(o,a)=>{try{(await fetch(`/api/providers/${o}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({proxyPoolId:a||null})})).ok&&S(P=>P.map(K=>K.id===o?{...K,providerSpecificData:{...K.providerSpecificData,proxyPoolId:a||null}}:K))}catch(g){console.log("proxy error:",g)}},H=async()=>{if(i.length!==0){N(!0);try{await Promise.all(i.map(o=>fetch(`/api/providers/${o.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({testStatus:"active",lastError:"",lastErrorAt:null})}))),S(o=>o.map(a=>({...a,testStatus:"active",lastError:"",lastErrorAt:null})))}catch(o){console.log("reset all status error:",o)}finally{N(!1)}}},W=async o=>{try{(await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:t,...o})})).ok&&(await B(),y(!1))}catch(a){console.log("save apikey error:",a)}},le=async o=>{try{(await fetch(`/api/providers/${A.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).ok&&(await B(),R(!1))}catch(a){console.log("update connection error:",a)}};if(d)return e.jsx(we,{children:e.jsx("div",{className:"h-20 animate-pulse bg-black/5 rounded-lg"})});const m=i.some(o=>o.lastError||o.testStatus==="error");return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Connections"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.length>0&&e.jsxs("button",{onClick:H,disabled:x,title:"Reset testStatus and lastError for all connections",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-border text-xs text-text-muted hover:text-amber-500 hover:border-amber-500/40 hover:bg-amber-500/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:x?"progress_activity":"restart_alt"}),x?"Resetting...":"Reset All Status",m&&!x&&e.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 rounded-full bg-red-500/15 text-red-500 text-[10px] font-bold",children:"!"})]}),e.jsx("span",{className:"text-xs text-text-muted font-medium",children:"Round Robin"}),e.jsx(Ue,{checked:v==="round-robin",onChange:o=>{const a=o?"round-robin":null;U(a),o&&!O&&L("1"),X(a,o?O||"1":O)}}),v==="round-robin"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-text-muted",children:"Sticky:"}),e.jsx("input",{type:"number",min:1,value:O,onChange:o=>{L(o.target.value),X("round-robin",o.target.value)},className:"w-16 px-2 py-1 text-xs border border-border rounded-md bg-background focus:outline-none focus:border-primary"})]})]})]}),i.length===0?e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"No connections yet"}),e.jsx(be,{size:"sm",icon:"add",onClick:()=>y(!0),children:"Add Connection"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]",children:i.map((o,a)=>e.jsx(vt,{connection:o,proxyPools:c,isOAuth:r,isFirst:a===0,isLast:a===i.length-1,onMoveUp:()=>Q(a,a-1),onMoveDown:()=>Q(a,a+1),onToggleActive:g=>re(o.id,g),onUpdateProxy:g=>ae(o.id,g),onEdit:()=>{u(o),R(!0)},onDelete:()=>V(o.id)},o.id))}),e.jsx("div",{className:"mt-4 flex justify-stretch sm:justify-start",children:e.jsx(be,{size:"sm",icon:"add",onClick:()=>y(!0),children:"Add"})})]})]}),e.jsx(wt,{isOpen:h,provider:t,proxyPools:c,onSave:W,onClose:()=>y(!1)}),e.jsx(Ut,{isOpen:$,connection:A,proxyPools:c,onSave:le,onClose:()=>R(!1)}),e.jsx($t,{isOpen:!!I,onClose:()=>j(null),onConfirm:I==null?void 0:I.onConfirm,title:(I==null?void 0:I.title)||"Confirm",message:I==null?void 0:I.message,variant:"danger"})]})}Nt.propTypes={providerId:w.string.isRequired,isOAuth:w.bool};function Xe({model:t,fullModel:r,copied:i,onCopy:S,testStatus:c,isCustom:M,isFree:d,onDeleteAlias:p,onTest:h,isTesting:y}){const $=c==="ok"?"border-green-500/40":c==="error"?"border-red-500/40":"border-border",R=c==="ok"?"#22c55e":c==="error"?"#ef4444":void 0;return e.jsx("div",{className:`group px-3 py-2 rounded-lg border ${$} hover:bg-sidebar/50`,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-base",style:R?{color:R}:void 0,children:c==="ok"?"check_circle":c==="error"?"cancel":"smart_toy"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("code",{className:"text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded",children:r}),t.name&&e.jsx("span",{className:"text-[9px] text-text-muted/70 italic pl-1",children:t.name})]}),h&&e.jsxs("div",{className:"relative group/btn",children:[e.jsx("button",{onClick:h,disabled:y,className:`p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary transition-opacity ${y?"opacity-100":"opacity-0 group-hover:opacity-100"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",style:y?{animation:"spin 1s linear infinite"}:void 0,children:y?"progress_activity":"science"})}),e.jsx("span",{className:"pointer-events-none absolute mt-1 top-5 left-1/2 -translate-x-1/2 text-[10px] text-text-muted whitespace-nowrap opacity-0 group-hover/btn:opacity-100 transition-opacity",children:y?"Testing...":"Test"})]}),e.jsxs("div",{className:"relative group/btn",children:[e.jsx("button",{onClick:()=>S(r,`model-${t.id}`),className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:i===`model-${t.id}`?"check":"content_copy"})}),e.jsx("span",{className:"pointer-events-none absolute mt-1 top-5 left-1/2 -translate-x-1/2 text-[10px] text-text-muted whitespace-nowrap opacity-0 group-hover/btn:opacity-100 transition-opacity",children:i===`model-${t.id}`?"Copied!":"Copy"})]}),d&&e.jsx("span",{className:"text-[10px] font-bold text-green-500 bg-green-500/10 px-1.5 py-0.5 rounded",children:"FREE"}),M&&e.jsx("button",{onClick:p,className:"p-0.5 hover:bg-red-500/10 rounded text-text-muted hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity ml-auto",title:"Remove custom model",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"close"})})]})})}Xe.propTypes={model:w.shape({id:w.string.isRequired}).isRequired,fullModel:w.string.isRequired,copied:w.string,onCopy:w.func.isRequired,testStatus:w.oneOf(["ok","error"]),isCustom:w.bool,isFree:w.bool,onDeleteAlias:w.func,onTest:w.func,isTesting:w.bool};function kt({isOpen:t,onSave:r,onClose:i}){const[S,c]=s.useState(""),M=()=>{S.trim()&&(r(S.trim()),c(""))};return e.jsx(gt,{isOpen:t,title:"Add Custom Model",onClose:i,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-text-muted mb-1 block",children:"Model ID"}),e.jsx("input",{className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",value:S,onChange:d=>c(d.target.value),onKeyDown:d=>d.key==="Enter"&&M(),placeholder:"e.g. tts-1-hd",autoFocus:!0})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{onClick:M,fullWidth:!0,disabled:!S.trim(),children:"Add"}),e.jsx(be,{onClick:i,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})})}kt.propTypes={isOpen:w.bool.isRequired,onSave:w.func.isRequired,onClose:w.func.isRequired};function St({providerId:t,kindFilter:r,providerAliasOverride:i}){const{copied:S,copy:c}=ve(),[M,d]=s.useState({}),[p,h]=s.useState([]),[y,$]=s.useState({}),[R,A]=s.useState(null),[u,v]=s.useState(""),[U,O]=s.useState(!1),[L,I]=s.useState([]),j=i||Be(t),x=r||"llm",N=s.useCallback(async()=>{try{const[m,o,a]=await Promise.all([fetch("/api/models/alias"),fetch("/api/providers",{cache:"no-store"}),fetch("/api/models/custom",{cache:"no-store"})]),g=await m.json(),P=await o.json(),K=await a.json();m.ok&&d(g.aliases||{}),o.ok&&I((P.connections||[]).filter(f=>f.provider===t)),a.ok&&h(K.models||[])}catch(m){console.log("ModelsCard fetch error:",m)}},[t]);s.useEffect(()=>{N()},[N]);const B=async(m,o)=>{const a=`${j}/${m}`;try{(await fetch("/api/models/alias",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:a,alias:o})})).ok&&await N()}catch(g){console.log("set alias error:",g)}},X=async m=>{try{(await fetch(`/api/models/alias?alias=${encodeURIComponent(m)}`,{method:"DELETE"})).ok&&await N()}catch(o){console.log("delete alias error:",o)}},Q=async m=>{try{(await fetch("/api/models/custom",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerAlias:j,id:m,type:x})})).ok&&(await N(),window.dispatchEvent(new CustomEvent("customModelChanged")))}catch(o){console.log("add custom model error:",o)}},V=async m=>{try{const o=new URLSearchParams({providerAlias:j,id:m,type:x});(await fetch(`/api/models/custom?${o}`,{method:"DELETE"})).ok&&(await N(),window.dispatchEvent(new CustomEvent("customModelChanged")))}catch(o){console.log("delete custom model error:",o)}},re=async m=>{if(!R){A(m);try{const a=await(await fetch("/api/models/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:`${j}/${m}`,kind:r})})).json();$(g=>({...g,[m]:a.ok?"ok":"error"})),v(a.ok?"":a.error||"Model not reachable")}catch{$(o=>({...o,[m]:"error"})),v("Network error")}finally{A(null)}}},ae=pe(t),H=r?ae.filter(m=>m.kinds?m.kinds.includes(r):(m.type||"llm")===r):ae,W=p.filter(m=>m.providerAlias===j&&(m.type||"llm")===x&&!H.some(o=>o.id===m.id)),le=H;return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("h2",{className:"text-lg font-semibold",children:["Models",r?` — ${r.toUpperCase()}`:""]})}),u&&e.jsx("p",{className:"text-xs text-red-500 mb-3 break-words",children:u}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[le.map(m=>{var g;const o=`${j}/${m.id}`,a=(g=Object.entries(M).find(([,P])=>P===o))==null?void 0:g[0];return e.jsx(Xe,{model:m,fullModel:`${j}/${m.id}`,alias:a,copied:S,onCopy:c,onSetAlias:P=>B(m.id,P),onDeleteAlias:()=>X(a),testStatus:y[m.id],onTest:L.length>0?()=>re(m.id):void 0,isTesting:R===m.id,isFree:m.isFree},m.id)}),W.map(m=>e.jsx(Xe,{model:{id:m.id,name:m.name},fullModel:`${j}/${m.id}`,copied:S,onCopy:c,onSetAlias:()=>{},onDeleteAlias:()=>V(m.id),testStatus:y[m.id],onTest:L.length>0?()=>re(m.id):void 0,isTesting:R===m.id,isCustom:!0},`${m.id}-${m.type}`)),e.jsxs("button",{onClick:()=>O(!0),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg border border-dashed border-black/15 dark:border-white/15 text-xs text-text-muted hover:text-primary hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"add"}),"Add Model"]})]})]}),e.jsx(kt,{isOpen:U,onSave:async m=>{await Q(m),O(!1)},onClose:()=>O(!1)})]})}St.propTypes={providerId:w.string.isRequired,kindFilter:w.string,providerAliasOverride:w.string};const xt={"google-tts":{hasLanguageDropdown:!1,hasModelSelector:!1,hasBrowseButton:!0,voiceSource:"hardcoded"},openai:{hasLanguageDropdown:!1,hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"hardcoded",modelKey:"openai-tts-models",voiceKey:"openai-tts-voices",voicesPerModel:!0},openrouter:{hasLanguageDropdown:!1,hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"hardcoded",modelKey:"openrouter-tts-models",voiceKey:"openrouter-tts-voices",voicesPerModel:!0},elevenlabs:{hasLanguageDropdown:!1,hasModelSelector:!0,hasBrowseButton:!0,hasVoiceIdInput:!0,voiceSource:"api-language",modelKey:"elevenlabs-tts-models",apiEndpoint:"/api/media-providers/tts/elevenlabs/voices"},"edge-tts":{hasLanguageDropdown:!1,hasModelSelector:!1,hasBrowseButton:!0,voiceSource:"api-language"},"local-device":{hasLanguageDropdown:!1,hasModelSelector:!1,hasBrowseButton:!0,voiceSource:"api-language"},nvidia:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},hyperbolic:{hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"config"},deepgram:{hasModelSelector:!1,hasBrowseButton:!0,voiceSource:"api-language",apiEndpoint:"/api/media-providers/tts/deepgram/voices"},huggingface:{hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"config"},cartesia:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},playht:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},coqui:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},tortoise:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},inworld:{hasModelSelector:!0,hasBrowseButton:!0,hasVoiceIdInput:!0,voiceSource:"api-language",modelKey:"inworld-tts-models",apiEndpoint:"/api/media-providers/tts/inworld/voices"},qwen:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},minimax:{hasModelSelector:!0,hasBrowseButton:!0,hasVoiceIdInput:!0,voiceSource:"api-language",apiEndpoint:"/api/media-providers/tts/minimax/voices",defaultVoiceId:"English_expressive_narrator"},"minimax-cn":{hasModelSelector:!0,hasBrowseButton:!0,hasVoiceIdInput:!0,voiceSource:"api-language",apiEndpoint:"/api/media-providers/tts/minimax/voices?provider=minimax-cn",defaultVoiceId:"English_expressive_narrator"},gemini:{hasLanguageDropdown:!1,hasLanguageHint:!0,hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"hardcoded",modelKey:"gemini-tts-models",voiceKey:"gemini-tts-voices",voicesPerModel:!0}};function _({label:t,children:r}){return e.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-3",children:[e.jsx("span",{className:"w-full text-xs font-medium text-text-muted sm:w-20 sm:shrink-0",children:t}),e.jsx("div",{className:"w-full min-w-0 flex-1",children:r})]})}const qt=`// Audio will appear here after running.
2
+ // Example JSON response (response_format=json):
3
+ {
4
+ "format": "mp3",
5
+ "audio": "//NExAANaAIIAUAAANNNNNNNN..." // base64 encoded MP3
6
+ }`,Jt=`{
7
+ "object": "list",
8
+ "data": [{
9
+ "object": "embedding",
10
+ "index": 0,
11
+ "embedding": [0.002301, -0.019212, 0.004815, -0.031249, ...]
12
+ }],
13
+ "model": "...",
14
+ "usage": { "prompt_tokens": 9, "total_tokens": 9 }
15
+ }`,ft="https://pub-1fb693cb11cc46b2b2f656f51e015a2c.r2.dev/dog.png",zt="https://pub-1fb693cb11cc46b2b2f656f51e015a2c.r2.dev/dog-mask.png";function Ht(t,r){return t!=="cloudflare-ai"?{}:r==="@cf/runwayml/stable-diffusion-v1-5-img2img"?{image:ft}:r==="@cf/runwayml/stable-diffusion-v1-5-inpainting"?{image:ft,mask_image:zt}:{}}function ht(t){const r=typeof t=="string"?t.trim():"";return r?/^(data:image\/|https?:\/\/)/i.test(r)?r:`data:image/png;base64,${r}`:""}const Ct={webSearch:{inputLabel:"Query",inputPlaceholder:"What is the latest news about AI?",defaultInput:"What is the latest news about AI?",bodyKey:"query",defaultResponse:`{
16
+ "results": [
17
+ { "title": "...", "url": "...", "snippet": "..." }
18
+ ]
19
+ }`,extraFields:[{key:"search_type",label:"Type",type:"select",default:"web",options:["web","news"]},{key:"max_results",label:"Max results",type:"number",default:5,min:1,max:100},{key:"country",label:"Country",type:"text",default:""},{key:"language",label:"Language",type:"text",default:""}]},webFetch:{inputLabel:"URL",inputPlaceholder:"https://example.com",defaultInput:"https://example.com",bodyKey:"url",defaultResponse:`{
20
+ "content": "...",
21
+ "title": "...",
22
+ "url": "..."
23
+ }`,extraFields:[{key:"format",label:"Format",type:"select",default:"markdown",options:["markdown","text","html"]},{key:"max_characters",label:"Max chars",type:"number",default:0,min:0}]},image:{inputLabel:"Prompt",inputPlaceholder:"A cute cat wearing a hat",defaultInput:"A cute cat wearing a hat",bodyKey:"prompt",defaultResponse:`{
24
+ "data": [
25
+ { "url": "...", "b64_json": "..." }
26
+ ]
27
+ }`,extraFields:[{key:"n",label:"n",type:"number",default:1,min:1,max:4},{key:"size",label:"Size",type:"select",default:"auto",options:["auto","1024x1024","1024x1536","1536x1024","1024x1792","1792x1024"]},{key:"quality",label:"Quality",type:"select",default:"auto",options:["auto","low","medium","high","standard","hd"]},{key:"background",label:"Background",type:"select",default:"auto",options:["auto","transparent","opaque"]},{key:"style",label:"Style",type:"select",default:"",options:["","vivid","natural"]},{key:"response_format",label:"Format",type:"select",default:"",options:["","url","b64_json"]},{key:"image_detail",label:"Image Detail",type:"select",default:"high",options:["auto","low","high","original"]},{key:"output_format",label:"Codec",type:"select",default:"png",options:["png","jpeg","webp"]}]},imageToText:{inputLabel:"Image URL",inputPlaceholder:"https://example.com/image.png",defaultInput:"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg",bodyKey:"url",extraBody:{prompt:"Describe this image in detail"},defaultResponse:`{
28
+ "text": "A cat sitting on a windowsill...",
29
+ "model": "..."
30
+ }`},video:{inputLabel:"Prompt",inputPlaceholder:"A serene lake at sunset",defaultInput:"A serene lake at sunset",bodyKey:"prompt",defaultResponse:`{
31
+ "data": [
32
+ { "url": "..." }
33
+ ]
34
+ }`,extraFields:[{key:"duration",label:"Duration (seconds)",type:"number",default:5,min:1,max:10},{key:"resolution",label:"Resolution",type:"select",default:"720",options:["480","720","1080"]},{key:"aspect_ratio",label:"Aspect Ratio",type:"select",default:"16:9",options:["16:9","9:16","1:1"]},{key:"image_url",label:"Image Reference (URL)",type:"text",default:"",placeholder:"https://example.com/image.png"},{key:"video_url",label:"Video Reference (URL)",type:"text",default:"",placeholder:"https://example.com/video.mp4"},{key:"motion_strength",label:"Motion Strength",type:"number",default:5,min:1,max:10}]},music:{inputLabel:"Prompt",inputPlaceholder:"A calm piano melody",defaultInput:"A calm piano melody",bodyKey:"prompt",defaultResponse:`{
35
+ "data": [
36
+ { "url": "...", "format": "mp3" }
37
+ ]
38
+ }`}};function Wt({providerId:t,customAlias:r}){var K;const i=yt(t),S=i?r||t:Be(t),c=i?[]:pe(t).filter(f=>f.type==="embedding"),[M,d]=s.useState(((K=c[0])==null?void 0:K.id)??""),[p,h]=s.useState("The quick brown fox jumps over the lazy dog"),[y,$]=s.useState(""),[R,A]=s.useState(""),[u,v]=s.useState(!1),[U,O]=s.useState(""),[L,I]=s.useState(""),[j,x]=s.useState(null),[N,B]=s.useState(!1),[X,Q]=s.useState(""),{copied:V,copy:re}=ve(),{copied:ae,copy:H}=ve();s.useEffect(()=>{O(window.location.origin),fetch("/api/keys").then(f=>f.json()).then(f=>{var D;A(((D=(f.keys||[]).find(b=>b.isActive!==!1))==null?void 0:D.key)||"")}).catch(()=>{}),fetch("/api/tunnel/status").then(f=>f.json()).then(f=>{f.publicUrl&&I(f.publicUrl)}).catch(()=>{})},[]);const W=u?L:U,le=M?`${S}/${M}`:"",m=()=>{const f={model:le,input:p.trim()},D=Number(y);return y&&Number.isFinite(D)&&D>0&&(f.dimensions=D),f},o=`curl -X POST ${W}/v1/embeddings \\
39
+ -H "Content-Type: application/json" \\
40
+ -H "Authorization: Bearer ${R||"YOUR_KEY"}" \\
41
+ -d '${JSON.stringify(m())}'`,a=async()=>{var D;if(!p.trim()||!le)return;B(!0),Q(""),x(null);const f=Date.now();try{const b={"Content-Type":"application/json"};R&&(b.Authorization=`Bearer ${R}`);const Z=await fetch("/api/v1/embeddings",{method:"POST",headers:b,body:JSON.stringify(m())}),ne=Date.now()-f,G=await Z.json();if(!Z.ok){Q(((D=G==null?void 0:G.error)==null?void 0:D.message)||(G==null?void 0:G.error)||`HTTP ${Z.status}`);return}x({data:G,latencyMs:ne})}catch(b){Q(b.message||"Network error")}finally{B(!1)}},g=f=>{if(!f)return Jt;const D=JSON.parse(JSON.stringify(f));return(D.data||[]).forEach(b=>{Array.isArray(b.embedding)&&b.embedding.length>4&&(b.embedding=[...b.embedding.slice(0,4).map(Z=>parseFloat(Z.toFixed(6))),`... (${b.embedding.length} dims)`])}),JSON.stringify(D,null,2)},P=j?JSON.stringify(j.data,null,2):"";return e.jsxs(we,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Example"}),e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx(_,{label:"Model",children:i?e.jsx("input",{value:M,onChange:f=>d(f.target.value),placeholder:"e.g. voyage-3, embed-english-v3.0, text-embedding-3-small",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"}):e.jsx("select",{value:M,onChange:f=>d(f.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:c.map(f=>e.jsx("option",{value:f.id,children:f.name||f.id},f.id))})}),e.jsx(_,{label:"Endpoint",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsx("input",{value:W,onChange:f=>u?I(f.target.value):O(f.target.value),className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono",placeholder:"http://localhost:3000"}),L&&e.jsxs("button",{onClick:()=>v(f=>!f),title:u?"Using tunnel":"Using local",className:`flex items-center gap-1 text-xs px-2 py-1.5 rounded-lg border shrink-0 transition-colors ${u?"border-primary/40 bg-primary/10 text-primary":"border-border text-text-muted hover:text-primary"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"wifi_tethering"}),"Tunnel"]})]})}),e.jsx(_,{label:"API Key",children:e.jsx("input",{type:"password",value:R,onChange:f=>A(f.target.value),placeholder:"sk-...",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"})}),e.jsx(_,{label:"Input",children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:p,onChange:f=>h(f.target.value),className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),p&&e.jsx("button",{type:"button",onClick:()=>h(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]})}),e.jsx(_,{label:"Dimensions",children:e.jsx("input",{type:"number",min:"1",value:y,onChange:f=>$(f.target.value),placeholder:"optional, e.g. 512, 1024 (leave empty for default)",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})}),e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Request"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("button",{onClick:()=>re(o),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:V?"check":"content_copy"}),V?"Copied":"Copy"]}),e.jsxs("button",{onClick:a,disabled:N||!p.trim()||!le,className:"flex w-full sm:w-auto items-center justify-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",style:N?{animation:"spin 1s linear infinite"}:void 0,children:"play_arrow"}),N?"Running...":"Run"]})]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:o})]}),X&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:X}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:["Response ",j&&e.jsxs("span",{className:"font-normal normal-case",children:["⚡ ",j.latencyMs,"ms"]})]}),j&&e.jsxs("button",{onClick:()=>H(P),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:ae?"check":"content_copy"}),ae?"Copied":"Copy"]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all opacity-70",children:g(j==null?void 0:j.data)})]})]})]})}function Gt({providerId:t}){var Te,Fe,_e,Ce,Ee,Le,Ve;const r=Be(t),i=xt[t]||xt["edge-tts"],[S,c]=s.useState(i.defaultVoiceId||""),[M,d]=s.useState(""),[p,h]=s.useState(i.defaultVoiceId||""),[y,$]=s.useState([]),[R,A]=s.useState(""),[u,v]=s.useState(()=>{var Y,E,F;const n=(E=(Y=Ae[t])==null?void 0:Y.ttsConfig)==null?void 0:E.models;if(n!=null&&n.length)return n[0].id;if(i.hasModelSelector&&i.modelKey){const z=pe(i.modelKey);return((F=z==null?void 0:z[0])==null?void 0:F.id)||""}return""}),[U,O]=s.useState("Hello, this is a text to speech test."),[L,I]=s.useState(""),[j,x]=s.useState(!1),[N,B]=s.useState(""),[X,Q]=s.useState(""),[V,re]=s.useState("mp3"),[ae,H]=s.useState(""),[W,le]=s.useState(null),[m,o]=s.useState(!1),[a,g]=s.useState(""),[P,K]=s.useState(null),{copied:f,copy:D}=ve(),[b,Z]=s.useState(!1),[ne,G]=s.useState([]),[ue,ye]=s.useState(!1),[xe,C]=s.useState(""),[J,ee]=s.useState(""),[ce,fe]=s.useState({}),[Ne,de]=s.useState("");s.useEffect(()=>{var n,Y;if(B(window.location.origin),fetch("/api/keys").then(E=>E.json()).then(E=>{var F;I(((F=(E.keys||[]).find(z=>z.isActive!==!1))==null?void 0:F.key)||"")}).catch(()=>{}),fetch("/api/tunnel/status").then(E=>E.json()).then(E=>{E.publicUrl&&Q(E.publicUrl)}).catch(()=>{}),i.voiceSource==="hardcoded"){const E=i.hasModelSelector&&i.modelKey&&((Y=(n=pe(i.modelKey))==null?void 0:n[0])==null?void 0:Y.id)||"",F=i.voicesPerModel&&E?pt(t,E)||[]:pe(i.voiceKey||t).filter(z=>z.type==="tts");if(F.length)if(i.hasBrowseButton){const z=F.find(ie=>ie.id==="en")||F[0];A(z.id),c(z.id),d(z.name),$([{id:z.id,name:z.name}])}else $(F),c(F[0].id),d(F[0].name||F[0].id)}},[t]),s.useEffect(()=>{if(!i.voicesPerModel||!u)return;const n=pt(t,u)||[];$(n),n.length&&(c(n[0].id),d(n[0].name||n[0].id))},[u]);const Me=async()=>{if(Z(!0),C(""),ee(""),!ne.length){ye(!0);try{if(i.voiceSource==="hardcoded"){const n=i.voiceKey||t,Y=pe(n).filter(F=>F.type==="tts"),E={};for(const F of Y)E[F.id]||(E[F.id]={code:F.id,name:F.name,voices:[{id:F.id,name:F.name}]});fe(E),G(Object.values(E).sort((F,z)=>F.name.localeCompare(z.name)))}else{const n=i.apiEndpoint?i.apiEndpoint:`/api/media-providers/tts/voices?provider=${t==="local-device"?"local-device":"edge-tts"}`,E=await(await fetch(n)).json();if(E.error){ee(E.error);return}G(E.languages||[]),fe(E.byLang||{})}}catch(n){ee(n.message)}finally{ye(!1)}}},ze=n=>{var E;Z(!1),A(n.code);const Y=((E=ce[n.code])==null?void 0:E.voices)||[];$(Y),Y.length&&(c(Y[0].id),d(Y[0].name),i.hasVoiceIdInput&&h(Y[0].id))},$e=xe?ne.filter(n=>n.name.toLowerCase().includes(xe.toLowerCase())||n.code.toLowerCase().includes(xe.toLowerCase())):ne,Pe=j?X:N,ge=i.hasVoiceIdInput&&p||S,je=i.hasModelSelector&&u&&ge?`${r}/${u}/${ge}`:i.hasModelSelector&&u?`${r}/${u}`:ge?`${r}/${ge}`:"",ke=(()=>{const n={model:je,input:U};return i.hasLanguageHint&&Ne&&(n.language=Ne),n})(),Se=`curl -X POST ${Pe}/v1/audio/speech${V==="json"?"?response_format=json":""} \\
42
+ -H "Content-Type: application/json" \\
43
+ -H "Authorization: Bearer ${L||"YOUR_KEY"}" \\
44
+ -d '${JSON.stringify(ke)}' \\
45
+ ${V==="json"?"":"--output speech.mp3"}`,Ke=async()=>{var Y;if(!U.trim()||!je)return;o(!0),g(""),H(""),le(null);const n=Date.now();try{const E={"Content-Type":"application/json"};L&&(E.Authorization=`Bearer ${L}`);const z=await fetch(`/api/v1/audio/speech${V==="json"?"?response_format=json":""}`,{method:"POST",headers:E,body:JSON.stringify({...ke,input:U.trim()})});if(K(Date.now()-n),!z.ok){const ie=await z.json().catch(()=>({}));g(((Y=ie==null?void 0:ie.error)==null?void 0:Y.message)||(ie==null?void 0:ie.error)||`HTTP ${z.status}`);return}if(V==="json"){const ie=await z.json();le(ie);const qe=await fetch(`data:audio/mp3;base64,${ie.audio}`).then(Je=>Je.blob());H(URL.createObjectURL(qe))}else{const ie=await z.blob();H(URL.createObjectURL(ie))}}catch(E){g(E.message||"Network error")}finally{o(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Example"}),e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx(_,{label:"Endpoint",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("span",{className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate",children:[Pe,"/v1/audio/speech"]}),X&&e.jsxs("button",{onClick:()=>x(n=>!n),title:j?"Using tunnel":"Using local",className:`flex items-center gap-1 text-xs px-2 py-1.5 rounded-lg border shrink-0 transition-colors ${j?"border-primary/40 bg-primary/10 text-primary":"border-border text-text-muted hover:text-primary"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"wifi_tethering"}),"Tunnel"]})]})}),e.jsx(_,{label:"API Key",children:e.jsx("span",{className:"px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate block",children:L?`${L.slice(0,8)}${"•".repeat(Math.min(20,L.length-8))}`:e.jsx("span",{className:"text-text-muted italic",children:"No key configured"})})}),i.hasModelSelector&&(i.modelKey||((_e=(Fe=(Te=Ae[t])==null?void 0:Te.ttsConfig)==null?void 0:Fe.models)==null?void 0:_e.length))&&e.jsx(_,{label:"Model",children:e.jsx("select",{value:u,onChange:n=>v(n.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:(((Le=(Ee=(Ce=Ae[t])==null?void 0:Ce.ttsConfig)==null?void 0:Ee.models)!=null&&Le.length?Ae[t].ttsConfig.models:pe(i.modelKey))||[]).map(n=>e.jsx("option",{value:n.id,children:n.name||n.id},n.id))})}),i.hasLanguageHint&&e.jsx(_,{label:"Language",children:e.jsxs("select",{value:Ne,onChange:n=>de(n.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"",children:"Auto-detect"}),Tt.map(n=>e.jsx("option",{value:n.name,children:n.name},n.id))]})}),i.hasBrowseButton&&e.jsx(_,{label:"Language",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsx("button",{onClick:Me,className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-background font-mono truncate text-left hover:border-primary/40 transition-colors",children:R?e.jsx("span",{className:"text-text-main",children:((Ve=ne.find(n=>n.code===R))==null?void 0:Ve.name)||R}):e.jsx("span",{className:"text-text-muted",children:"No language selected"})}),e.jsxs("button",{onClick:Me,className:"flex w-full items-center justify-center gap-1 text-xs px-2.5 py-1.5 rounded-lg border border-border text-text-muted hover:text-primary hover:border-primary/40 transition-colors sm:w-auto sm:shrink-0",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"language"}),"Select language"]})]})}),y.length>0&&e.jsx(_,{label:"Voice",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:y.map(n=>e.jsxs("button",{onClick:()=>{c(n.id),d(n.name),i.hasVoiceIdInput&&h(n.id)},className:`px-2.5 py-1 rounded-full text-xs border transition-colors ${S===n.id?"bg-primary/15 border-primary/40 text-primary font-medium":"border-border text-text-muted hover:text-primary hover:border-primary/40"}`,children:[n.name,n.gender?` · ${n.gender[0].toUpperCase()}`:"",n.free_users_allowed===!0&&e.jsx("span",{className:"ml-1.5 px-1 py-0.5 text-[9px] font-semibold rounded bg-green-500/15 text-green-600 border border-green-500/20",children:"Free"}),n.free_users_allowed===!1&&e.jsx("span",{className:"ml-1.5 px-1 py-0.5 text-[9px] font-semibold rounded bg-amber-500/15 text-amber-600 border border-amber-500/20",children:"Paid"})]},n.id))})}),i.hasVoiceIdInput&&e.jsx(_,{label:"Voice ID",children:e.jsx("div",{className:"flex flex-col gap-1",children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:p,onChange:n=>{h(n.target.value),c(n.target.value)},placeholder:"e.g. CwhRBWXzGAHq8TQ4Fs17",className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"}),p&&e.jsx("button",{type:"button",onClick:()=>{h(""),c("")},className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]})})}),i.hasLanguageDropdown&&e.jsx(_,{label:"Language",children:e.jsx("select",{value:S,onChange:n=>{const Y=pe(t).filter(E=>E.type==="tts").find(E=>E.id===n.target.value);c(n.target.value),d((Y==null?void 0:Y.name)||n.target.value)},className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:pe(t).filter(n=>n.type==="tts").map(n=>e.jsx("option",{value:n.id,children:n.name||n.id},n.id))})}),e.jsx(_,{label:"Input",children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:U,onChange:n=>O(n.target.value),className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),U&&e.jsx("button",{type:"button",onClick:()=>O(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]})}),e.jsx(_,{label:"Output Format",children:e.jsxs("select",{value:V,onChange:n=>re(n.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"mp3",children:"MP3 (Binary)"}),e.jsx("option",{value:"json",children:"JSON (Base64)"})]})}),e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Request"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("button",{onClick:()=>D(Se),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:f?"check":"content_copy"}),f?"Copied":"Copy"]}),e.jsxs("button",{onClick:Ke,disabled:m||!U.trim()||!je,className:"flex w-full sm:w-auto items-center justify-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",style:m?{animation:"spin 1s linear infinite"}:void 0,children:"play_arrow"}),m?"Generating...":"Run"]})]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:Se})]}),a&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:a}),ae?e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:["Response ",P&&e.jsxs("span",{className:"font-normal normal-case",children:["⚡ ",P,"ms"]})]}),e.jsxs("a",{href:ae,download:"speech.mp3",className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"download"}),"Download"]})]}),e.jsx("audio",{controls:!0,src:ae,className:"w-full"}),W&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"JSON Response"})}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:JSON.stringify({format:W.format,audio:W.audio?`${W.audio.substring(0,100)}...`:""},null,2)})]})]}):e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Response"}),e.jsx("pre",{className:"mt-1.5 bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all opacity-50",children:qt})]})]})]}),b&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center sm:items-center",style:{backgroundColor:"rgba(0,0,0,0.6)",backdropFilter:"blur(2px)"},onClick:()=>Z(!1),children:e.jsxs("div",{className:"border border-border rounded-xl shadow-2xl w-full max-w-md mx-4 flex flex-col max-h-[80vh]",style:{backgroundColor:"var(--color-bg)",isolation:"isolate"},onClick:n=>n.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border shrink-0 rounded-t-xl",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Select Language"}),e.jsx("button",{onClick:()=>Z(!1),className:"text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"close"})})]}),e.jsx("div",{className:"px-4 py-2.5 border-b border-border shrink-0",children:e.jsx("input",{autoFocus:!0,value:xe,onChange:n=>C(n.target.value),placeholder:"Search language...",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})}),e.jsxs("div",{className:"overflow-y-auto flex-1 p-2",children:[J&&e.jsx("p",{className:"text-xs text-red-500 px-2 py-1",children:J}),ue?e.jsx("p",{className:"text-xs text-text-muted px-2 py-3",children:"Loading..."}):e.jsxs("div",{className:"flex flex-col gap-0.5",children:[$e.map(n=>e.jsxs("button",{onClick:()=>ze(n),className:`flex items-center justify-between w-full px-3 py-2 rounded-lg text-left hover:bg-sidebar transition-colors ${R===n.code?"bg-primary/10 text-primary":""}`,children:[e.jsx("span",{className:"text-sm",children:n.name}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("span",{className:"text-xs text-text-muted",children:[n.voices.length," voices"]}),R===n.code&&e.jsx("span",{className:"material-symbols-outlined text-[16px] text-primary",children:"check"})]})]},n.code)),$e.length===0&&e.jsx("p",{className:"text-xs text-text-muted px-2 py-3",children:"No languages found."})]})]})]})})]})}function Yt({providerId:t,kind:r}){var z,ie,qe,Je,Qe,Ze,et,tt,st,at,nt,ot,rt,lt,it,ct,dt,ut,mt;const i=Be(t),c=_t(i)===t?i:t,M=bt.find(l=>l.id===r),d=Ct[r],p=d||{},h=pe(t).filter(l=>l.type===r),$=new Set(["image","video","music","imageToText"]).has(r),R=$&&h.length===0,[A,u]=s.useState(((z=h[0])==null?void 0:z.id)??""),v=h.find(l=>l.id===A),U=!!((ie=v==null?void 0:v.capabilities)!=null&&ie.includes("edit")),O=!!((qe=v==null?void 0:v.capabilities)!=null&&qe.includes("mask")),[L,I]=s.useState(p.defaultInput||""),[j,x]=s.useState(""),[N,B]=s.useState(""),[X,Q]=s.useState(()=>(p.extraFields||[]).reduce((l,k)=>(l[k.key]=k.default??"",l),{})),[V,re]=s.useState(""),[ae,H]=s.useState(!1),[W,le]=s.useState(""),[m,o]=s.useState(""),[a,g]=s.useState(null),[P,K]=s.useState(null),[f,D]=s.useState(null),[b,Z]=s.useState("json"),[ne,G]=s.useState(""),[ue,ye]=s.useState(!1),[xe,C]=s.useState(""),[J,ee]=s.useState([]),[ce,fe]=s.useState(""),{copied:Ne,copy:de}=ve(),{copied:Me,copy:ze}=ve();if(s.useEffect(()=>{le(window.location.origin),fetch("/api/keys").then(l=>l.json()).then(l=>{var k;re(((k=(l.keys||[]).find(T=>T.isActive!==!1))==null?void 0:k.key)||"")}).catch(()=>{}),fetch("/api/tunnel/status").then(l=>l.json()).then(l=>{l.publicUrl&&o(l.publicUrl)}).catch(()=>{}),fetch("/api/providers/client").then(l=>l.json()).then(l=>{const k=(l.connections||[]).filter(T=>T.provider===t&&T.isActive!==!1);ee(k)}).catch(()=>{})},[t]),s.useEffect(()=>{v&&Q(l=>{const k={...l};let T=!1;return(p.extraFields||[]).forEach(te=>{const se=Array.isArray(v==null?void 0:v.paramDefs)?v.paramDefs.find(oe=>oe.name===te.key):null,q=(se==null?void 0:se.validValues)||te.options||[],he=l[te.key];if(he&&q.length>0&&!q.includes(he)){const oe=(se==null?void 0:se.default)??q[0]??"";oe!==he&&(k[te.key]=oe,T=!0)}}),T?k:l})},[A,v,p.extraFields]),!M||!d)return null;const $e=ae?m:W,Pe=M.endpoint.path,ge=$?A?`${c}/${A}`:R?"":c:c,je=Ht(t,A),ke=j.trim()||je.image||"",Se=N.trim()||je.mask_image||"",Ke=ht(ke),Te=ht(Se),Fe=Object.entries(X).reduce((l,[k,T])=>(T===""||T===null||T===void 0||typeof T=="number"&&Number.isNaN(T)||(l[k]=T),l),{}),_e={model:ge,[d.bodyKey]:L,...d.extraBody,...Fe,...U&&ke?{image:ke}:{},...O&&Se?{mask_image:Se}:{}},Ce=r==="image"&&b==="binary",Ee=r==="image"&&t==="codex"&&!Ce,Le=`${Pe}${Ce?"?response_format=binary":""}`,Ve=`-H "Content-Type: application/json" \\
46
+ -H "Authorization: Bearer ${V||"YOUR_KEY"}"${ce?` \\
47
+ -H "x-connection-id: ${ce}"`:""}${Ee?` \\
48
+ -H "Accept: text/event-stream"`:""}`,n=`curl -X ${M.endpoint.method} ${$e}${Le} \\
49
+ ${Ve.replace(/\\\n /g,`\\
50
+ `)} \\
51
+ -d '${JSON.stringify(_e)}'${Ce?` \\
52
+ --output image.png`:""}`,Y=async()=>{var k;if(!L.trim()||!ge)return;if(ye(!0),C(""),g(null),K(null),D(null),ne){try{URL.revokeObjectURL(ne)}catch{}G("")}const l=Date.now();try{const T={"Content-Type":"application/json"};V&&(T.Authorization=`Bearer ${V}`),ce&&(T["x-connection-id"]=ce),Ee&&(T.Accept="text/event-stream");const te={..._e,model:ge},se=await fetch(`/api${Le}`,{method:M.endpoint.method,headers:T,body:JSON.stringify(te)});if(!se.ok){const oe=await se.json().catch(()=>({}));C(((k=oe==null?void 0:oe.error)==null?void 0:k.message)||(oe==null?void 0:oe.error)||`HTTP ${se.status}`);return}const q=se.headers.get("content-type")||"";if(q.startsWith("image/")){const oe=await se.blob(),Ie=URL.createObjectURL(oe);G(Ie),g({data:{binary:!0,mime:q,size:oe.size},latencyMs:Date.now()-l});return}if(q.includes("text/event-stream")&&se.body){const oe=se.body.getReader(),Ie=new TextDecoder;let De="",He=null,We=null;for(;;){const{done:Rt,value:At}=await oe.read();if(Rt)break;De+=Ie.decode(At,{stream:!0});let Ge;for(;(Ge=De.indexOf(`
53
+
54
+ `))!==-1;){const Mt=De.slice(0,Ge);De=De.slice(Ge+2);let Re=null,Ye="";for(const me of Mt.split(`
55
+ `))me.startsWith("event:")?Re=me.slice(6).trim():me.startsWith("data:")&&(Ye+=me.slice(5).trim());if(Re)try{const me=Ye?JSON.parse(Ye):{};Re==="progress"?K(me):Re==="partial_image"?D(me):Re==="done"?He=me:Re==="error"&&(We=(me==null?void 0:me.message)||"Stream error")}catch{}}}const Et=Date.now()-l;if(We){C(We);return}He&&g({data:He,latencyMs:Et})}else{const oe=await se.json(),Ie=Date.now()-l;g({data:oe,latencyMs:Ie})}}catch(T){C(T.message||"Network error")}finally{ye(!1)}},E=l=>{if(!l||typeof l!="object")return l;if(Array.isArray(l))return l.map(E);const k={};for(const[T,te]of Object.entries(l))k[T]=T==="b64_json"&&typeof te=="string"&&te.length>100?`<${te.length} chars base64>`:E(te);return k},F=a?JSON.stringify(E(a.data),null,2):"";return e.jsxs(we,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Example"}),e.jsxs("div",{className:"flex flex-col gap-2.5",children:[h.length>0?e.jsx(_,{label:"Model",children:e.jsx("select",{value:A,onChange:l=>u(l.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:h.map(l=>e.jsx("option",{value:l.id,children:l.name||l.id},l.id))})}):R?e.jsx(_,{label:"Model",children:e.jsx("input",{value:A,onChange:l=>u(l.target.value),placeholder:"Enter model id (provider-specific)",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"})}):null,e.jsx(_,{label:"Endpoint",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("span",{className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate",children:[$e,Pe]}),m&&e.jsxs("button",{onClick:()=>H(l=>!l),title:ae?"Using tunnel":"Using local",className:`flex items-center gap-1 text-xs px-2 py-1.5 rounded-lg border shrink-0 transition-colors ${ae?"border-primary/40 bg-primary/10 text-primary":"border-border text-text-muted hover:text-primary"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"wifi_tethering"}),"Tunnel"]})]})}),e.jsx(_,{label:"API Key",children:e.jsx("span",{className:"px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate block",children:V?`${V.slice(0,8)}${"•".repeat(Math.min(20,V.length-8))}`:e.jsx("span",{className:"text-text-muted italic",children:"No key configured"})})}),J.length>0&&e.jsx(_,{label:"Connection",children:e.jsxs("select",{value:ce,onChange:l=>fe(l.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"",children:"Auto (by priority)"}),J.map(l=>{var te;const k=(te=l.providerSpecificData)==null?void 0:te.chatgptPlanType,T=l.email||l.name||l.id.slice(0,8);return e.jsxs("option",{value:l.id,children:[T,k?` [${k}]`:""]},l.id)})]})}),e.jsx(_,{label:d.inputLabel,children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:L,onChange:l=>I(l.target.value),placeholder:d.inputPlaceholder,className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),L&&e.jsx("button",{type:"button",onClick:()=>I(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]})}),U&&e.jsx(_,{label:"Ref Image (URL)",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:j,onChange:l=>x(l.target.value),placeholder:je.image||"https://example.com/source.png",className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),j&&e.jsx("button",{type:"button",onClick:()=>x(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]}),Ke&&e.jsx("img",{src:Ke,alt:"Reference",className:"max-h-40 rounded-lg border border-border object-contain bg-sidebar",onError:l=>{l.currentTarget.style.display="none"},onLoad:l=>{l.currentTarget.style.display="block"}})]})}),O&&e.jsx(_,{label:"Mask (URL)",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:N,onChange:l=>B(l.target.value),placeholder:je.mask_image||"https://example.com/mask.png",className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),N&&e.jsx("button",{type:"button",onClick:()=>B(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]}),Te&&e.jsx("img",{src:Te,alt:"Mask",className:"max-h-40 rounded-lg border border-border object-contain bg-sidebar",onError:l=>{l.currentTarget.style.display="none"},onLoad:l=>{l.currentTarget.style.display="block"}})]})}),(()=>{const l={"1:1":"1:1 Square","9:16":"9:16 Portrait","3:4":"3:4 Portrait","16:9":"16:9 Landscape","4:3":"4:3 Landscape"};return(d.extraFields||[]).filter(k=>h.length===0||Array.isArray(v==null?void 0:v.params)&&v.params.includes(k.key)).map(k=>{const T=Array.isArray(v==null?void 0:v.paramDefs)?v.paramDefs.find(q=>q.name===k.key):null,te=(T==null?void 0:T.validValues)||k.options||[],se=te.length>0&&te.every(q=>q in l);return e.jsx(_,{label:k.label,children:k.type==="select"?e.jsx("select",{value:X[k.key]??"",onChange:q=>Q(he=>({...he,[k.key]:q.target.value})),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:(te||[]).map(q=>e.jsx("option",{value:q,children:q===""?"(default)":se&&l[q]||q},q))}):k.type==="text"?e.jsx("input",{type:"text",value:X[k.key]??"",placeholder:k.placeholder,onChange:q=>Q(he=>({...he,[k.key]:q.target.value})),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}):e.jsx("input",{type:"number",value:X[k.key]??"",min:k.min,max:k.max,onChange:q=>Q(he=>({...he,[k.key]:q.target.value===""?"":Number(q.target.value)})),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})},k.key)})})(),r==="image"&&e.jsx(_,{label:"Output Format",children:e.jsxs("select",{value:b,onChange:l=>Z(l.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"json",children:"JSON (Base64)"}),e.jsx("option",{value:"binary",children:"Binary File"})]})}),e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Request"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("button",{onClick:()=>de(n),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:Ne?"check":"content_copy"}),Ne?"Copied":"Copy"]}),e.jsxs("button",{onClick:Y,disabled:ue||!L.trim()||!ge,className:"flex w-full sm:w-auto items-center justify-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",style:ue?{animation:"spin 1s linear infinite"}:void 0,children:"play_arrow"}),ue?"Running...":"Run"]})]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:n})]}),(ue||P)&&Ee&&e.jsxs("div",{className:"flex flex-col gap-2 px-3 py-2 rounded-lg bg-sidebar border border-border sm:flex-row sm:items-center sm:gap-3",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-primary",style:ue?{animation:"spin 1s linear infinite"}:void 0,children:ue?"progress_activity":"check_circle"}),e.jsxs("span",{className:"text-xs text-text-muted",children:[(P==null?void 0:P.stage)||"starting",!ue&&(P!=null&&P.bytesReceived)?` · ${(P.bytesReceived/1024).toFixed(1)} KB`:""]})]}),(f==null?void 0:f.b64_json)&&!a&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Partial preview"}),e.jsx("img",{src:`data:image/png;base64,${f.b64_json}`,alt:"Partial",className:"max-w-full rounded-lg border border-border mt-1.5 opacity-80"})]}),xe&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:xe}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:["Response ",a&&e.jsxs("span",{className:"font-normal normal-case",children:["⚡ ",a.latencyMs,"ms"]})]}),a&&e.jsxs("button",{onClick:()=>ze(F),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:Me?"check":"content_copy"}),Me?"Copied":"Copy"]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all opacity-70",children:a?F:d.defaultResponse}),r==="image"&&(ne||((Qe=(Je=a==null?void 0:a.data)==null?void 0:Je.data)==null?void 0:Qe[0]))&&e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"flex items-center justify-end mb-1.5",children:e.jsxs("a",{href:ne||((tt=(et=(Ze=a==null?void 0:a.data)==null?void 0:Ze.data)==null?void 0:et[0])!=null&&tt.b64_json?`data:image/png;base64,${a.data.data[0].b64_json}`:((nt=(at=(st=a==null?void 0:a.data)==null?void 0:st.data)==null?void 0:at[0])==null?void 0:nt.url)||""),download:"image.png",className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"download"}),"Download"]})}),e.jsx("img",{src:ne||((lt=(rt=(ot=a==null?void 0:a.data)==null?void 0:ot.data)==null?void 0:rt[0])!=null&&lt.b64_json?`data:image/png;base64,${a.data.data[0].b64_json}`:(dt=(ct=(it=a==null?void 0:a.data)==null?void 0:it.data)==null?void 0:ct[0])==null?void 0:dt.url),alt:"Generated",className:"max-w-full rounded-lg border border-border"})]}),r==="video"&&((mt=(ut=a==null?void 0:a.data)==null?void 0:ut.data)==null?void 0:mt.length)>0&&(()=>{const l=a.data.data,k=l.find(se=>/\.mp4(\?|$)/i.test(se.url||"")||/\/video\//i.test(se.url||""))||l[l.length-1],T=k==null?void 0:k.url;if(!T)return null;const te=`/api/media-proxy?url=${encodeURIComponent(T)}`;return e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"flex items-center justify-end mb-1.5",children:e.jsxs("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"download"}),"Download"]})}),e.jsx("video",{src:te,controls:!0,preload:"metadata",className:"max-w-full rounded-lg border border-border"})]})})()]})]})]})}function Xt({providerId:t}){var xe;const r=Be(t),i=pe(t).filter(C=>C.type==="stt"),[S,c]=s.useState([]),M=[...i,...S],[d,p]=s.useState(((xe=i[0])==null?void 0:xe.id)??""),h=M.find(C=>C.id===d),y=Array.isArray(h==null?void 0:h.params)?h.params:[],[$,R]=s.useState(null),[A,u]=s.useState(""),[v,U]=s.useState(""),[O,L]=s.useState("json"),[I,j]=s.useState(""),[x,N]=s.useState(""),[B,X]=s.useState(!1),[Q,V]=s.useState(""),[re,ae]=s.useState(""),[H,W]=s.useState(null),[le,m]=s.useState(null),[o,a]=s.useState(!1),[g,P]=s.useState(""),{copied:K,copy:f}=ve(),{copied:D,copy:b}=ve();s.useEffect(()=>{V(window.location.origin),fetch("/api/keys").then(J=>J.json()).then(J=>{var ee;N(((ee=(J.keys||[]).find(ce=>ce.isActive!==!1))==null?void 0:ee.key)||"")}).catch(()=>{}),fetch("/api/tunnel/status").then(J=>J.json()).then(J=>{J.publicUrl&&ae(J.publicUrl)}).catch(()=>{});const C=()=>{fetch("/api/models/custom",{cache:"no-store"}).then(J=>J.json()).then(J=>{const ee=(J.models||[]).filter(ce=>ce.type==="stt"&&ce.providerAlias===r);c(ee)}).catch(()=>{})};return C(),window.addEventListener("focus",C),window.addEventListener("customModelChanged",C),()=>{window.removeEventListener("focus",C),window.removeEventListener("customModelChanged",C)}},[r]);const Z=B?re:Q,ne=d?`${r}/${d}`:"",G=`curl -X POST ${Z}/v1/audio/transcriptions \\
56
+ -H "Authorization: Bearer ${x||"YOUR_KEY"}" \\
57
+ -F "file=@${($==null?void 0:$.name)||"audio.mp3"}" \\
58
+ -F "model=${ne}"${y.includes("language")&&A?` \\
59
+ -F "language=${A}"`:""}${y.includes("response_format")?` \\
60
+ -F "response_format=${O}"`:""}${y.includes("temperature")&&I?` \\
61
+ -F "temperature=${I}"`:""}${y.includes("prompt")&&v?` \\
62
+ -F "prompt=${v}"`:""}`,ue=async()=>{var J;if(!$||!ne)return;a(!0),P(""),W(null);const C=Date.now();try{const ee=new FormData;ee.append("file",$),ee.append("model",ne),y.includes("language")&&A&&ee.append("language",A),y.includes("response_format")&&ee.append("response_format",O),y.includes("temperature")&&I&&ee.append("temperature",I),y.includes("prompt")&&v&&ee.append("prompt",v);const ce={};x&&(ce.Authorization=`Bearer ${x}`);const fe=await fetch("/api/v1/audio/transcriptions",{method:"POST",headers:ce,body:ee});m(Date.now()-C);const de=(fe.headers.get("content-type")||"").includes("application/json")?await fe.json():await fe.text();if(!fe.ok){P(((J=de==null?void 0:de.error)==null?void 0:J.message)||(de==null?void 0:de.error)||de||`HTTP ${fe.status}`);return}W(de)}catch(ee){P(ee.message||"Network error")}finally{a(!1)}},ye=typeof H=="string"?H:H?JSON.stringify(H,null,2):`{
63
+ "text": "Hello world..."
64
+ }`;return e.jsxs(we,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Example"}),e.jsxs("div",{className:"flex flex-col gap-2.5",children:[M.length>0?e.jsx(_,{label:"Model",children:e.jsx("select",{value:d,onChange:C=>p(C.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:M.map(C=>e.jsx("option",{value:C.id,children:C.name||C.id},C.id))})}):e.jsx(_,{label:"Model",children:e.jsx("input",{value:d,onChange:C=>p(C.target.value),placeholder:"Enter model id",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"})}),e.jsx(_,{label:"Endpoint",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("span",{className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate",children:[Z,"/v1/audio/transcriptions"]}),re&&e.jsxs("button",{onClick:()=>X(C=>!C),title:B?"Using tunnel":"Using local",className:`flex items-center gap-1 text-xs px-2 py-1.5 rounded-lg border shrink-0 transition-colors ${B?"border-primary/40 bg-primary/10 text-primary":"border-border text-text-muted hover:text-primary"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"wifi_tethering"}),"Tunnel"]})]})}),e.jsx(_,{label:"API Key",children:e.jsx("span",{className:"px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate block",children:x?`${x.slice(0,8)}${"•".repeat(Math.min(20,x.length-8))}`:e.jsx("span",{className:"text-text-muted italic",children:"No key configured"})})}),e.jsx(_,{label:"Audio File",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{type:"file",accept:"audio/*,video/mp4,.m4a,.mp3,.wav,.ogg,.flac,.webm,.opus",onChange:C=>{var J;return R(((J=C.target.files)==null?void 0:J[0])||null)},className:"w-full text-xs text-text-muted file:mr-2 file:py-1 file:px-2.5 file:rounded-lg file:border file:border-border file:bg-background file:text-text-main hover:file:bg-sidebar file:cursor-pointer"}),$&&e.jsxs("span",{className:"text-xs text-text-muted font-mono",children:[$.name," · ",($.size/1024).toFixed(1)," KB"]})]})}),y.includes("language")&&e.jsx(_,{label:"Language",children:e.jsx("input",{value:A,onChange:C=>u(C.target.value),placeholder:"e.g. en, vi, ja (auto-detect if empty)",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"})}),y.includes("prompt")&&e.jsx(_,{label:"Prompt",children:e.jsx("input",{value:v,onChange:C=>U(C.target.value),placeholder:"optional context to improve accuracy",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})}),y.includes("temperature")&&e.jsx(_,{label:"Temperature",children:e.jsx("input",{type:"number",step:"0.1",min:"0",max:"1",value:I,onChange:C=>j(C.target.value),placeholder:"0 - 1 (default 0)",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})}),y.includes("response_format")&&e.jsx(_,{label:"Response Format",children:e.jsxs("select",{value:O,onChange:C=>L(C.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"json",children:"json"}),e.jsx("option",{value:"text",children:"text"}),e.jsx("option",{value:"srt",children:"srt"}),e.jsx("option",{value:"verbose_json",children:"verbose_json"}),e.jsx("option",{value:"vtt",children:"vtt"})]})}),e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Request"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("button",{onClick:()=>f(G),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:K?"check":"content_copy"}),K?"Copied":"Copy"]}),e.jsxs("button",{onClick:ue,disabled:o||!$||!ne,className:"flex w-full sm:w-auto items-center justify-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",style:o?{animation:"spin 1s linear infinite"}:void 0,children:"play_arrow"}),o?"Transcribing...":"Run"]})]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:G})]}),g&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:g}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:["Response ",H&&le&&e.jsxs("span",{className:"font-normal normal-case",children:["⚡ ",le,"ms"]})]}),H&&e.jsxs("button",{onClick:()=>b(ye),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:D?"check":"content_copy"}),D?"Copied":"Copy"]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all opacity-70",children:ye})]})]})]})}function ss(){var U,O,L,I,j,x;const{kind:t,id:r}=Lt(),i=It(),S=bt.find(N=>N.id===t),c=yt(r)&&t==="embedding",M=async()=>{if(confirm("Delete this Custom Embedding node?"))try{(await fetch(`/api/provider-nodes/${r}`,{method:"DELETE"})).ok&&i(`/dashboard/media-providers/${t}`)}catch(N){console.log("Error deleting custom embedding node:",N)}},[d,p]=s.useState(null),[h,y]=s.useState(c),[$,R]=s.useState(!1);if(s.useEffect(()=>{if(!c)return;let N=!1;return fetch("/api/provider-nodes",{cache:"no-store"}).then(B=>B.json()).then(B=>{N||(p((B.nodes||[]).find(X=>X.id===r)||null),y(!1))}).catch(()=>{N||y(!1)}),()=>{N=!0}},[r,c]),!S)return null;const A=Ae[r],u=c?d?{id:r,name:d.name||"Custom Embedding",color:"#6366F1",textIcon:"CE"}:null:A;if(!c&&!A||c&&!h&&!d)return null;if(c&&h)return e.jsx("div",{className:"text-text-muted text-sm py-12 text-center",children:"Loading..."});const v=c?["embedding"]:u.serviceKinds??["llm"];return!c&&!v.includes(t)?null:e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsxs("div",{children:[e.jsxs(Dt,{to:`/dashboard/media-providers/${t}`,className:"inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4",children:[e.jsx("span",{className:"material-symbols-outlined text-lg",children:"arrow_back"}),S.label]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4",children:[e.jsx("div",{className:"size-12 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${u.color}15`},children:e.jsx(Pt,{src:`/providers/${u.id}.png`,alt:u.name,size:48,className:"object-contain rounded-lg max-w-[48px] max-h-[48px]",fallbackText:u.textIcon||u.id.slice(0,2).toUpperCase(),fallbackColor:u.color})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:u.name}),!c&&((U=u.notice)==null?void 0:U.apiKeyUrl)&&e.jsxs("a",{href:u.notice.apiKeyUrl,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"open_in_new"}),"Get API Key"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:[c&&e.jsxs(Oe,{variant:"default",size:"sm",children:["Custom · ",d==null?void 0:d.prefix]}),v.map(N=>e.jsx(Oe,{variant:N===t?"primary":"default",size:"sm",children:N.toUpperCase()},N))]})]}),c&&e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsx(be,{size:"sm",variant:"secondary",icon:"edit",onClick:()=>R(!0),children:"Edit"}),e.jsx(be,{size:"sm",variant:"secondary",icon:"delete",onClick:M,children:"Delete"})]})]})]}),!c&&((O=u.kindNotice)==null?void 0:O[t])&&e.jsxs("div",{className:"flex items-start gap-3 px-4 py-3 rounded-lg bg-amber-500/10 border border-amber-500/30 text-amber-700 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined text-[20px] mt-0.5",children:"warning"}),e.jsx("p",{className:"text-sm",children:u.kindNotice[t]})]}),!c&&((L=u.notice)==null?void 0:L.text)&&!u.deprecated&&e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2 sm:flex-row sm:items-center",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-blue-500 shrink-0",children:"info"}),e.jsx("p",{className:"min-w-0 flex-1 text-xs leading-relaxed text-blue-600 dark:text-blue-400",children:u.notice.text}),u.notice.apiKeyUrl&&e.jsx("a",{href:u.notice.apiKeyUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex justify-center rounded bg-blue-500 px-2 py-1 text-xs font-medium text-white transition-colors hover:bg-blue-600 sm:py-0.5",children:"Get API Key →"})]}),!c&&u.noAuth?e.jsx(Bt,{providerId:r}):e.jsx(Nt,{providerId:r,isOAuth:!1}),t!=="tts"&&t!=="webSearch"&&t!=="webFetch"&&e.jsx(St,{providerId:r,kindFilter:t,providerAliasOverride:c?d==null?void 0:d.prefix:void 0}),!c&&(u.searchConfig||u.fetchConfig||u.ttsConfig||u.sttConfig||u.embeddingConfig||u.searchViaChat)&&e.jsx(Vt,{config:t==="webFetch"?u.fetchConfig:t==="tts"?u.ttsConfig:t==="stt"?u.sttConfig:t==="embedding"?u.embeddingConfig:u.searchConfig||{mode:"chat-completions",defaultModel:(I=u.searchViaChat)==null?void 0:I.defaultModel,pricingUrl:(j=u.searchViaChat)==null?void 0:j.pricingUrl,freeTier:(x=u.searchViaChat)==null?void 0:x.freeTier},provider:u,title:`${S.label} Config`}),t==="embedding"&&e.jsx(Wt,{providerId:r,customAlias:d==null?void 0:d.prefix}),t==="tts"&&e.jsx(Gt,{providerId:r}),t==="stt"&&!c&&e.jsx(Xt,{providerId:r}),!c&&Ct[t]&&e.jsx(Yt,{providerId:r,kind:t}),c&&e.jsx(Kt,{isOpen:$,node:d,onClose:()=>R(!1),onSaved:N=>{p(N),R(!1)}})]})}export{ss as default};
@@ -0,0 +1 @@
1
+ import{j as s,B as Be,k as je,l as Ie,h as Le}from"./index.2a3mqmx-.js";import{b as d}from"./router.Cjj1--8t.js";import{B as qe}from"./NoAuthProxyCard.CrFQ6U88.js";import"./zustand.akaTi5uX.js";const O={sessions:"basic-chat.sessions",activeSessionId:"basic-chat.activeSessionId",activeProviderId:"basic-chat.activeProviderId",draft:"basic-chat.draft"};function J(){var e;return(e=globalThis.crypto)!=null&&e.randomUUID?globalThis.crypto.randomUUID():`chat_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Fe(e,a){try{return JSON.parse(e)}catch{return a}}function S(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(S).filter(Boolean).join(" ");if(typeof e=="object"){if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function He(e=""){return String(e).replace(/[-_]/g," ").replace(/\b\w/g,a=>a.toUpperCase()).trim()||"Unknown"}function Je(e){if(!e)return"Now";const a=new Date(e).getTime();if(Number.isNaN(a))return"Now";const m=Math.max(1,Math.round((Date.now()-a)/6e4));if(m<60)return`${m}m`;const u=Math.round(m/60);return u<24?`${u}h`:`${Math.round(u/24)}d`}function Ne(e=""){const a=S(e).replace(/\s+/g," ").trim();return a?a.length>52?`${a.slice(0,52).trimEnd()}…`:a:"New chat"}function Ke(e){const a=S(e.content).trim(),m=Array.isArray(e.attachments)?e.attachments:[];if(m.length===0)return a;const u=[];a&&u.push({type:"text",text:a});for(const w of m)w!=null&&w.dataUrl&&u.push({type:"image_url",image_url:{url:w.dataUrl}});return u.length>0?u:a}function We(e){var w,A;if(!e||typeof e!="object")return"";const a=(w=e.choices)==null?void 0:w[0];return[((a==null?void 0:a.delta)||{}).content,(A=a==null?void 0:a.message)==null?void 0:A.content,e.output_text,e.text].map(S).filter(Boolean)[0]||""}async function Ye(e){return await new Promise((a,m)=>{const u=new FileReader;u.onload=()=>a(String(u.result||"")),u.onerror=()=>m(u.error||new Error("Failed to read file")),u.readAsDataURL(e)})}function Ve(e){return{...e,messages:Array.isArray(e.messages)?e.messages.map(a=>({...a})):[]}}function de(e){return(e==null?void 0:e.name)||He((e==null?void 0:e.provider)||(e==null?void 0:e.id)||"provider")}function Ge(e,a){return e!=null&&e.id?{id:`${a.provider}/${e.id}`,requestModel:`${a.provider}/${e.id}`,name:e.name||e.id,providerId:a.provider,providerName:de(a),source:"static"}:null}function Qe(e,a){const m=typeof e=="string"?e:(e==null?void 0:e.id)||(e==null?void 0:e.name)||(e==null?void 0:e.model)||"";if(!m)return null;const u=typeof e=="string"?e:(e==null?void 0:e.name)||(e==null?void 0:e.displayName)||m;let w=m;return(je(a.provider)||Ie(a.provider))&&!m.includes("/")&&(w=`${a.provider}/${m}`),{id:w,requestModel:w,name:u,providerId:a.provider,providerName:de(a),source:"live"}}function Xe(e){return Array.isArray(e==null?void 0:e.models)?e.models:Array.isArray(e==null?void 0:e.data)?e.data:Array.isArray(e==null?void 0:e.results)?e.results:Array.isArray(e)?e:[]}function Ze(e){const a=new Map;for(const m of e)m!=null&&m.id&&(a.has(m.id)||a.set(m.id,m));return Array.from(a.values())}function et(){const[e,a]=d.useState([]),[m,u]=d.useState(!0),[w,A]=d.useState(""),[h,D]=d.useState(()=>{if(typeof window>"u")return[];try{const t=Fe(globalThis.localStorage.getItem(O.sessions),[]);return Array.isArray(t)?t.map(r=>({...r,messages:Array.isArray(r.messages)?r.messages:[]})):[]}catch{return[]}}),[g,M]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.activeSessionId)||""),[R,P]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.activeProviderId)||""),[I,U]=d.useState(""),[_,ce]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.draft)||""),[z,Q]=d.useState([]),[me,ue]=d.useState(!1),[Se,pe]=d.useState(""),[fe,X]=d.useState(""),[K,Ae]=d.useState(!1),[Me,Z]=d.useState(!1),[De,ee]=d.useState(!1),xe=d.useRef(null),B=d.useRef(null),te=d.useRef(!1),se=d.useRef(null),re=d.useRef(null);d.useEffect(()=>{Ae(!0)},[]),d.useEffect(()=>{let t=!1;async function r(){u(!0),A("");try{const n=await(await fetch("/api/providers",{cache:"no-store"})).json().catch(()=>({})),o=Array.isArray(n.connections)?n.connections.filter(c=>(c==null?void 0:c.isActive)!==!1):[];if(o.length===0){t||(a([]),A("No providers connected yet."));return}const x=new Map;for(const c of o){const p=c.provider||c.id,b=de(c),$=je(p)?"openai-compatible":Ie(p)?"anthropic-compatible":p;x.has(p)||x.set(p,{providerId:p,providerName:b,providerType:$,connections:[],models:[]});const N=x.get(p);N.providerName=N.providerName||b,N.providerType=N.providerType||$,N.connections.push(c);const W=Le(p).map(Y=>Ge(Y,c)).filter(Boolean);N.models.push(...W)}const k=await Promise.all(o.map(async c=>{try{const p=await fetch(`/api/providers/${c.id}/models`,{cache:"no-store"}),b=await p.json().catch(()=>({}));if(!p.ok)return{connection:c,models:[]};const $=Xe(b).map(N=>Qe(N,c)).filter(Boolean);return{connection:c,models:$}}catch{return{connection:c,models:[]}}}));for(const c of k){const p=c.connection.provider||c.connection.id,b=x.get(p);b&&b.models.push(...c.models)}const q=Array.from(x.values()).map(c=>({...c,models:Ze(c.models).sort((p,b)=>p.name.localeCompare(b.name))})).filter(c=>c.models.length>0).sort((c,p)=>c.providerName.localeCompare(p.providerName));t||(a(q),q.length===0&&A("Providers connected but no models available."))}catch(i){t||(A(S(i==null?void 0:i.message)||"Failed to load providers/models."),a([]))}finally{t||u(!1)}}return r(),()=>{t=!0}},[]),d.useEffect(()=>{const t=r=>{se.current&&!se.current.contains(r.target)&&Z(!1),re.current&&!re.current.contains(r.target)&&ee(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[]);const y=d.useMemo(()=>{const t=new Map;for(const r of e)for(const i of r.models)t.set(i.id,{...i,providerId:r.providerId,providerName:r.providerName});return t},[e]),E=d.useMemo(()=>e.find(t=>t.providerId===R)||e[0]||null,[e,R]),v=d.useMemo(()=>{var t;if(I&&y.has(I))return y.get(I);if(g){const r=h.find(i=>i.id===g);if(r!=null&&r.modelId&&y.has(r.modelId))return y.get(r.modelId)}return((t=E==null?void 0:E.models)==null?void 0:t[0])||null},[I,y,E,h,g]),ie=d.useMemo(()=>h.find(t=>t.id===g)||null,[h,g]),he=(ie==null?void 0:ie.messages)||[],ge=d.useMemo(()=>[...h].sort((t,r)=>new Date(r.updatedAt).getTime()-new Date(t.updatedAt).getTime()),[h]),ae=!me&&!!v&&(_.trim().length>0||z.length>0);d.useEffect(()=>{if(K)try{globalThis.localStorage.setItem(O.sessions,JSON.stringify(h)),globalThis.localStorage.setItem(O.activeSessionId,g),globalThis.localStorage.setItem(O.activeProviderId,R),globalThis.localStorage.setItem(O.draft,_)}catch{}},[K,h,g,R,_]),d.useEffect(()=>{if(!K||m||te.current||e.length===0)return;const t=e.find(n=>n.providerId===R)||e[0],r=I&&y.has(I)?y.get(I):t.models[0];if(h.length>0){const n=h.find(x=>x.id===g)||h[0],o=n!=null&&n.modelId&&y.has(n.modelId)?y.get(n.modelId):r;te.current=!0,M(n.id),P((o==null?void 0:o.providerId)||t.providerId),U((o==null?void 0:o.id)||r.id);return}const i={id:J(),title:"New chat",providerId:t.providerId,providerName:t.providerName,modelId:r.id,modelName:r.name,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]};te.current=!0,D([i]),M(i.id),P(t.providerId),U(r.id)},[K,m,e,y,h,g,R,I]);const L=(t,r)=>{D(i=>i.map(n=>n.id===t?r(Ve(n)):n))},ne=t=>t?{id:J(),title:"New chat",providerId:t.providerId,providerName:t.providerName,modelId:t.id,modelName:t.name,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]}:null,ke=t=>{const r=h.find(i=>i.id===t);r&&(M(t),P(r.providerId||R),U(r.modelId||I),ee(!1))},Te=()=>{if(!g)return;const t=h.filter(i=>i.id!==g),r=t[0]||null;D(t),r?(M(r.id),P(r.providerId),U(r.modelId)):(M(""),P(""),U(""))},Ce=t=>{const r=y.get(t);if(!r)return;const i=h.find(n=>n.id===g);if(i&&i.messages.length>0){const n=ne(r);if(!n)return;D(o=>[n,...o]),M(n.id)}else if(i)D(n=>n.map(o=>o.id===i.id?{...o,providerId:r.providerId,providerName:r.providerName,modelId:r.id,modelName:r.name}:o)),M(i.id);else{const n=ne(r);if(!n)return;D(o=>[n,...o]),M(n.id)}P(r.providerId),U(r.id),Z(!1)},Oe=async t=>{const r=Array.from(t.target.files||[]);if(r.length===0)return;const i=r.filter(o=>o.type.startsWith("image/"));if(i.length===0){t.target.value="";return}const n=await Promise.all(i.map(async o=>({id:J(),name:o.name,type:o.type,size:o.size,dataUrl:await Ye(o)})));Q(o=>[...o,...n]),t.target.value=""},Re=t=>{Q(r=>r.filter(i=>i.id!==t))},Ee=()=>{var t;(t=B.current)==null||t.abort()},$e=(t,r)=>{const i=Ne(r);L(t,n=>({...n,title:n.title==="New chat"?i:n.title,updatedAt:new Date().toISOString()}))},we=async()=>{var p,b,$,N,W,Y;const t=v||((p=E==null?void 0:E.models)==null?void 0:p[0])||null;if(!t)return;const r=_.trim();if(!r&&z.length===0)return;let i=g,n=h.find(l=>l.id===i);if(!n){if(n=ne(t),!n)return;i=n.id,D(l=>[n,...l]),M(i)}const o={id:J(),role:"user",content:r,attachments:z.map(l=>({id:l.id,name:l.name,type:l.type,dataUrl:l.dataUrl})),createdAt:new Date().toISOString()},x=J(),k={id:x,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"},q=[...n.messages||[],o,k];D(l=>l.map(j=>j.id===i?{...j,providerId:t.providerId,providerName:t.providerName,modelId:t.id,modelName:t.name,messages:q,updatedAt:new Date().toISOString(),title:j.title==="New chat"?Ne(r):j.title}:j)),ce(""),Q([]),ue(!0),pe(x),X(""),(b=B.current)==null||b.abort(),B.current=new AbortController;const c=q.filter(l=>!(l.role==="assistant"&&l.id===x)).map(l=>({role:l.role,content:l.role==="user"?Ke(l):l.content}));try{const l=await fetch("/api/dashboard/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({model:t.requestModel||t.id,messages:c,stream:!0}),signal:B.current.signal});if(!l.ok){const f=await l.json().catch(()=>({}));throw new Error(S(f.error||f.message||`Request failed (${l.status})`))}const j=($=l.body)==null?void 0:$.getReader();if(!j){const f=await l.json().catch(()=>({})),C=S(((Y=(W=(N=f==null?void 0:f.choices)==null?void 0:N[0])==null?void 0:W.message)==null?void 0:Y.content)||(f==null?void 0:f.output_text)||(f==null?void 0:f.error)||(f==null?void 0:f.message)||"");L(i,F=>({...F,messages:F.messages.map(H=>H.id===x?{...H,content:C,status:"done"}:H),updatedAt:new Date().toISOString()}));return}const V=new TextDecoder;let T="",G="";for(;;){const{value:f,done:C}=await j.read();if(C)break;T+=V.decode(f,{stream:!0});const F=T.split(/\r?\n/);T=F.pop()||"";for(const H of F){const ve=H.trim();if(!ve.startsWith("data:"))continue;const oe=ve.slice(5).trim();if(!(!oe||oe==="[DONE]"))try{const ze=JSON.parse(oe),be=We(ze);if(!be)continue;G+=be,X(G),L(i,ye=>({...ye,messages:ye.messages.map(le=>le.id===x?{...le,content:G,status:"streaming"}:le),updatedAt:new Date().toISOString()}))}catch{}}}L(i,f=>({...f,messages:f.messages.map(C=>C.id===x?{...C,content:G||C.content,status:"done"}:C),updatedAt:new Date().toISOString()})),$e(i,r)}catch(l){if(l.name!=="AbortError"){const j=S((l==null?void 0:l.message)||l);L(i,V=>({...V,messages:V.messages.map(T=>T.id===x?{...T,content:T.content||`Error: ${j}`,status:"error"}:T),updatedAt:new Date().toISOString()})),A(j||"Failed to send message.")}}finally{ue(!1),pe(""),X(""),B.current=null}},Pe=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),ae&&we())},Ue=v?`${v.name}`:"Select model",_e=v?v.requestModel:"Choose from connected providers";return s.jsx("div",{className:"relative flex-1 flex flex-col h-full min-h-0 min-w-0 bg-[#212121] text-white overflow-hidden",children:s.jsxs("div",{className:"relative mx-auto flex flex-1 h-full min-h-0 w-full max-w-4xl flex-col",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 px-4 py-3 lg:px-6",children:[s.jsxs("div",{ref:se,className:"relative",children:[s.jsx("button",{type:"button",onClick:()=>Z(t=>!t),className:"flex items-center gap-3 rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-left transition hover:bg-white/8",children:s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-white",children:Ue}),s.jsx("span",{className:"material-symbols-outlined text-[18px] text-white/70",children:"expand_more"})]}),s.jsx("p",{className:"truncate text-xs text-white/55",children:_e})]})}),Me?s.jsxs("div",{className:"absolute left-0 top-[calc(100%+10px)] z-30 w-[min(520px,calc(100vw-2rem))] overflow-hidden rounded-[20px] border border-white/10 bg-[#262626] shadow-2xl shadow-black/50",children:[s.jsxs("div",{className:"border-b border-white/10 px-4 py-3",children:[s.jsx("p",{className:"text-xs uppercase tracking-[0.22em] text-white/45",children:"Models"}),s.jsx("p",{className:"text-sm text-white/75",children:"Only from connected providers"})]}),s.jsx("div",{className:"max-h-[60vh] overflow-y-auto p-2 custom-scrollbar",children:e.map(t=>s.jsxs("div",{className:"mb-2 rounded-[16px] border border-white/10 bg-black/20 p-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-2 py-2",children:[s.jsx("p",{className:"text-sm font-semibold text-white",children:t.providerName}),s.jsx(qe,{size:"sm",variant:"default",children:t.models.length})]}),s.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:t.models.map(r=>{const i=r.id===I;return s.jsx("button",{type:"button",onClick:()=>Ce(r.id),className:`rounded-[14px] border px-3 py-3 text-left transition ${i?"border-blue-400/40 bg-blue-500/15":"border-white/10 bg-white/5 hover:bg-white/8"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"truncate text-sm font-medium text-white",children:r.name}),s.jsx("p",{className:"truncate text-[11px] text-white/45",children:r.requestModel})]}),i?s.jsx("span",{className:"material-symbols-outlined text-[18px] text-blue-300",children:"check_circle"}):null]})},r.id)})})]},t.providerId))})]}):null]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>ee(t=>!t),className:"rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/80 transition hover:bg-white/8",children:"History"}),s.jsx(Be,{variant:"ghost",size:"sm",icon:"delete",onClick:Te,disabled:!g||h.length===0,children:"Clear"})]})]}),De?s.jsxs("div",{ref:re,className:"absolute right-4 top-[72px] z-20 w-[min(360px,calc(100vw-2rem))] rounded-[20px] border border-white/10 bg-[#262626] p-2 shadow-2xl shadow-black/50 lg:right-6",children:[s.jsx("div",{className:"px-3 py-2",children:s.jsx("p",{className:"text-xs uppercase tracking-[0.22em] text-white/45",children:"Recent chats"})}),s.jsx("div",{className:"max-h-[48vh] space-y-2 overflow-y-auto p-1 custom-scrollbar",children:ge.length===0?s.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-white/5 p-4 text-sm text-white/55",children:"No conversations yet."}):ge.map(t=>{var n;const r=t.id===g,i=[...t.messages||[]].reverse().find(o=>o.role==="user")||((n=t.messages)==null?void 0:n[0]);return s.jsx("button",{type:"button",onClick:()=>ke(t.id),className:`w-full rounded-[16px] border px-3 py-3 text-left transition ${r?"border-blue-400/40 bg-blue-500/15":"border-white/10 bg-white/5 hover:bg-white/8"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-medium text-white",children:t.title}),s.jsx("p",{className:"mt-1 truncate text-xs text-white/50",children:S(i==null?void 0:i.content)||"Empty chat"})]}),s.jsx("span",{className:"text-[10px] text-white/40 shrink-0",children:Je(t.updatedAt)})]})},t.id)})})]}):null,w?s.jsx("div",{className:"mt-4 rounded-[18px] border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-rose-100",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"error"}),s.jsx("p",{className:"text-sm leading-6",children:w})]})}):null,s.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[s.jsxs("div",{className:"flex-1 overflow-y-auto py-4 custom-scrollbar",children:[he.length===0?s.jsx("div",{className:"flex min-h-[50vh] items-center justify-center px-4 text-center",children:s.jsxs("div",{className:"max-w-xl space-y-4",children:[s.jsx("div",{className:"mx-auto flex size-16 items-center justify-center rounded-[20px] border border-white/10 bg-white/5 text-white/80",children:s.jsx("span",{className:"material-symbols-outlined text-[30px]",children:"chat"})}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("h2",{className:"text-2xl font-semibold text-white",children:"Start a conversation"}),s.jsx("p",{className:"text-sm leading-6 text-white/60",children:"Simple chat interface to interact with any AI model from connected providers. Select a model and start chatting!"})]})]})}):null,s.jsx("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4 px-4",children:he.map(t=>{var x;const r=t.role==="user",i=t.role==="assistant",n=i&&t.id===Se&&t.status==="streaming",o=S(t.content)||(i?fe:"");return s.jsx("div",{className:`flex w-full ${r?"justify-end":"justify-start"} mb-6`,children:s.jsxs("div",{className:`max-w-[min(88%,42rem)] ${r?"rounded-3xl bg-[#2f2f2f] px-5 py-3.5 text-white":"text-white/90"}`,children:[s.jsx("div",{className:"mb-1 flex items-center justify-between gap-3",children:s.jsx("span",{className:"text-xs font-semibold",children:r?"You":(v==null?void 0:v.name)||"Assistant"})}),(x=t.attachments)!=null&&x.length?s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2 sm:grid-cols-3 mt-2",children:t.attachments.map(k=>s.jsx("a",{href:k.dataUrl,target:"_blank",rel:"noreferrer",className:"overflow-hidden rounded-[18px] border border-white/10 bg-black/20",children:s.jsx("img",{src:k.dataUrl,alt:k.name,className:"h-28 w-full object-cover"})},k.id))}):null,s.jsxs("div",{className:"whitespace-pre-wrap break-words text-[15px] leading-7",children:[o,i&&n&&!fe?s.jsx("span",{className:"inline-block animate-pulse",children:"▋"}):null]})]})},t.id)})})]}),s.jsxs("div",{className:"shrink-0 pt-2",children:[z.length>0?s.jsx("div",{className:"mx-auto mb-3 flex w-full max-w-3xl flex-wrap gap-2 px-4",children:z.map(t=>s.jsxs("div",{className:"flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-2",children:[s.jsx("span",{className:"text-xs text-white/80 max-w-[12rem] truncate",children:t.name}),s.jsx("button",{type:"button",onClick:()=>Re(t.id),className:"text-white/55 hover:text-white","aria-label":"Remove attachment",children:s.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"close"})})]},t.id))}):null,s.jsx("div",{className:"mx-auto w-full max-w-3xl px-4 pb-2",children:s.jsxs("div",{className:"rounded-[26px] bg-[#2f2f2f] px-3 pt-3 pb-2 shadow-[0_0_15px_rgba(0,0,0,0.10)] ring-1 ring-white/5",children:[s.jsx("textarea",{value:_,onChange:t=>ce(t.target.value),onKeyDown:Pe,placeholder:"Message AI",rows:1,className:"w-full resize-none bg-transparent px-2 text-[15px] leading-6 text-white outline-none placeholder:text-white/40 custom-scrollbar max-h-[25vh] overflow-y-auto"}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{var t;return(t=xe.current)==null?void 0:t.click()},disabled:!v||m,className:"p-2 text-white/50 hover:text-white transition rounded-full hover:bg-white/5",children:s.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"attach_file"})}),s.jsx("input",{ref:xe,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:Oe}),s.jsx("span",{className:"text-xs font-medium text-white/30 truncate max-w-[120px]",children:v?v.name:"No model"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[me?s.jsx("button",{type:"button",onClick:Ee,className:"p-2 text-white bg-white/10 hover:bg-white/20 transition rounded-full h-8 w-8 flex items-center justify-center",children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"stop"})}):null,s.jsx("button",{onClick:we,disabled:!ae,className:`h-8 w-8 rounded-full flex items-center justify-center transition ${ae?"bg-white text-black hover:opacity-90":"bg-white/10 text-white/30 cursor-not-allowed"}`,children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"arrow_upward"})})]})]})]})})]}),s.jsx("p",{className:"mx-auto mt-2 max-w-3xl px-4 pb-4 text-center text-[11px] text-white/30",children:"Model list is filtered from connected providers."})]})]})})}function at(){return s.jsx(et,{})}export{at as default};
@@ -0,0 +1 @@
1
+ import{g as v,j as e,B as c,m as j}from"./index.2a3mqmx-.js";import{d as N,b as u,L as h}from"./router.Cjj1--8t.js";import{C as p,S as k,I as x,T as A}from"./NoAuthProxyCard.CrFQ6U88.js";import"./zustand.akaTi5uX.js";const P=Object.values(v).map(a=>({value:a.id,label:a.name})),S=Object.values(j).map(a=>({value:a.id,label:a.name}));function E(){const a=N(),[b,m]=u.useState(!1),[t,y]=u.useState({provider:"",authMethod:"api_key",apiKey:"",displayName:"",isActive:!0}),[s,n]=u.useState({}),i=(r,o)=>{y(l=>({...l,[r]:o})),s[r]&&n(l=>({...l,[r]:null}))},f=()=>{const r={};return t.provider||(r.provider="Please select a provider"),t.authMethod==="api_key"&&!t.apiKey&&(r.apiKey="API Key is required"),n(r),Object.keys(r).length===0},g=async r=>{if(r.preventDefault(),!!f()){m(!0);try{const o=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(o.ok)a("/dashboard/providers");else{const l=await o.json();n({submit:l.error||"Failed to create provider"})}}catch{n({submit:"An error occurred. Please try again."})}finally{m(!1)}}},d=v[t.provider];return e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("div",{className:"mb-8",children:[e.jsxs(h,{to:"/dashboard/providers",className:"inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4",children:[e.jsx("span",{className:"material-symbols-outlined text-lg",children:"arrow_back"}),"Back to Providers"]}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Add New Provider"}),e.jsx("p",{className:"text-text-muted mt-2",children:"Configure a new AI provider to use with your applications."})]}),e.jsx(p,{children:e.jsxs("form",{onSubmit:g,className:"flex flex-col gap-6",children:[e.jsx(k,{label:"Provider",options:P,value:t.provider,onChange:r=>i("provider",r.target.value),placeholder:"Select a provider",error:s.provider,required:!0}),d&&e.jsxs(p.Section,{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 rounded-lg flex items-center justify-center bg-bg border border-border",children:e.jsx("span",{className:"material-symbols-outlined text-xl",style:{color:d.color},children:d.icon})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:d.name}),e.jsx("p",{className:"text-sm text-text-muted",children:"Selected provider"})]})]}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("label",{className:"text-sm font-medium",children:["Authentication Method ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("div",{className:"flex gap-3",children:S.map(r=>e.jsxs("button",{type:"button",onClick:()=>i("authMethod",r.value),className:`flex-1 flex items-center justify-center gap-2 p-4 rounded-lg border transition-all ${t.authMethod===r.value?"border-primary bg-primary/5 text-primary":"border-border hover:border-primary/50"}`,children:[e.jsx("span",{className:"material-symbols-outlined",children:r.value==="api_key"?"key":"lock"}),e.jsx("span",{className:"font-medium",children:r.label})]},r.value))})]}),t.authMethod==="api_key"&&e.jsx(x,{label:"API Key",type:"password",placeholder:"Enter your API key",value:t.apiKey,onChange:r=>i("apiKey",r.target.value),error:s.apiKey,hint:"Your API key will be encrypted and stored securely.",required:!0}),t.authMethod==="oauth2"&&e.jsxs(p.Section,{children:[e.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Connect your account using OAuth2 authentication."}),e.jsx(c,{type:"button",variant:"secondary",icon:"link",children:"Connect with OAuth2"})]}),e.jsx(x,{label:"Display Name",placeholder:"e.g., Production API, Dev Environment",value:t.displayName,onChange:r=>i("displayName",r.target.value),hint:"Optional. A friendly name to identify this configuration."}),e.jsx(A,{checked:t.isActive,onChange:r=>i("isActive",r),label:"Active",description:"Enable this provider for use in your applications"}),s.submit&&e.jsx("div",{className:"p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 text-sm",children:s.submit}),e.jsxs("div",{className:"flex gap-3 pt-4 border-t border-border",children:[e.jsx(h,{to:"/dashboard/providers",className:"flex-1",children:e.jsx(c,{type:"button",variant:"ghost",fullWidth:!0,children:"Cancel"})}),e.jsx(c,{type:"submit",loading:b,fullWidth:!0,className:"flex-1",children:"Create Provider"})]})]})})]})}export{E as default};
@@ -0,0 +1 @@
1
+ import{j as e}from"./index.2a3mqmx-.js";import{b as t,d as H}from"./router.Cjj1--8t.js";import"./zustand.akaTi5uX.js";function z(){const[x,N]=t.useState(""),[m,c]=t.useState(""),[W,b]=t.useState(""),[r,f]=t.useState(0),[g,w]=t.useState(!1),[y,u]=t.useState(null),[n,k]=t.useState("password"),[i,L]=t.useState(!1),[S,C]=t.useState("Sign in with OIDC"),[h,M]=t.useState(!1),l=H();t.useEffect(()=>{if(r<=0)return;const a=setInterval(()=>f(s=>s>0?s-1:0),1e3);return()=>clearInterval(a)},[r]),t.useEffect(()=>{async function a(){const s=new AbortController,o=setTimeout(()=>s.abort(),5e3),R=typeof window<"u"?window.location.origin:"";try{const v=await fetch(`${R}/api/auth/status`,{signal:s.signal});if(clearTimeout(o),v.ok){const d=await v.json(),j=new URLSearchParams(window.location.search),E=j.get("force")==="true"||j.get("force")==="1";if(d.requireLogin===!1&&!E){localStorage.setItem("9r_authed","1"),l("/dashboard"),l(0);return}u(!!d.hasPassword),k(d.authMode||"password"),L(d.oidcConfigured===!0),C(d.oidcLoginLabel||"Sign in with OIDC")}else u(!0)}catch{clearTimeout(o),u(!0)}}a()},[l]);const P=async a=>{a.preventDefault(),w(!0),c(""),b("");try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:x})});if(s.ok)localStorage.setItem("9r_authed","1"),l("/dashboard"),l(0);else{const o=await s.json();c(o.error||"Invalid password"),o.resetHint&&b(o.resetHint),o.retryAfter&&f(Number(o.retryAfter))}}catch{c("An error occurred. Please try again.")}finally{w(!1)}},I=()=>{window.location.href="/api/auth/oidc/start"},A=i&&["oidc","both"].includes(n),p=n!=="oidc"||!i,O=n==="oidc"&&!i||n==="both"&&!i,D=n==="both"&&i;return y===null?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-slate-400"})}):e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-slate-100 p-4",children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute -top-40 -right-40 w-80 h-80 bg-violet-200/30 rounded-full blur-3xl"}),e.jsx("div",{className:"absolute -bottom-40 -left-40 w-80 h-80 bg-blue-200/30 rounded-full blur-3xl"})]}),e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-200/60 p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-gradient-to-br from-violet-500 to-blue-500 mb-4 shadow-lg shadow-violet-500/25",children:e.jsx("svg",{className:"w-6 h-6 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900 tracking-tight",children:"FSRouter"}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:n==="oidc"&&i?"Sign in with your OIDC provider":"Enter your password to continue"})]}),O&&e.jsx("div",{className:"mb-4 p-3 rounded-lg bg-amber-50 border border-amber-200 text-xs text-amber-700",children:"OIDC not configured yet. Password login is available."}),D&&e.jsx("div",{className:"mb-4 p-3 rounded-lg bg-violet-50 border border-violet-200 text-xs text-violet-700 text-center",children:"Password and OIDC login are both enabled."}),p&&e.jsxs("form",{onSubmit:P,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-slate-600 block mb-1.5",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{name:"password",type:h?"text":"password",placeholder:"••••••••",value:x,onChange:a=>N(a.target.value),required:!0,autoFocus:!0,className:"w-full bg-slate-50 border border-slate-200 text-slate-900 text-sm p-3 pr-10 rounded-xl focus:outline-none focus:border-violet-400 focus:ring-2 focus:ring-violet-100 placeholder-slate-400 transition-all"}),e.jsx("button",{type:"button",onClick:()=>M(!h),className:"absolute inset-y-0 right-3 flex items-center text-slate-400 hover:text-slate-600",children:h?e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878l4.242 4.242M21 21l-3.122-3.122"})}):e.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})})]}),m&&e.jsx("p",{className:"text-xs text-red-500 mt-1.5",children:m}),r>0&&e.jsxs("p",{className:"text-xs text-amber-600 mt-1.5",children:["Locked. Retry in ",r,"s."]})]}),e.jsx("button",{type:"submit",disabled:g||r>0,className:"w-full bg-gradient-to-r from-violet-500 to-blue-500 hover:from-violet-600 hover:to-blue-600 text-white font-medium text-sm py-3 rounded-xl transition-all shadow-lg shadow-violet-500/25 disabled:opacity-50 cursor-pointer",children:g?"Logging in...":r>0?`Wait ${r}s`:"Login"}),e.jsxs("p",{className:"text-center text-xs text-slate-400",children:["Default password is ",e.jsx("code",{className:"bg-slate-100 px-1.5 py-0.5 rounded text-slate-500 font-mono",children:"123456"})]})]}),A&&e.jsxs(e.Fragment,{children:[p&&e.jsxs("div",{className:"relative flex items-center justify-center py-4",children:[e.jsx("span",{className:"w-full border-t border-slate-200"}),e.jsx("span",{className:"px-3 text-xs text-slate-400 bg-white absolute",children:"or"})]}),e.jsxs("button",{onClick:I,type:"button",className:"w-full flex items-center justify-center gap-2 border border-slate-200 rounded-xl py-3 hover:bg-slate-50 transition-colors text-slate-600 text-sm cursor-pointer",children:[e.jsx("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M15 3h4a2 2 0 012 2v14a2 2 0 01-2 2h-4M10 17l5-5-5-5M15 12H3"})}),S]})]})]}),e.jsx("p",{className:"text-center text-xs text-slate-400 mt-6",children:"Powered by FSRouter"})]})]})}export{z as default};
@@ -0,0 +1 @@
1
+ import{F as le,j as e,g as Y,n as k,B as q,o as oe}from"./index.2a3mqmx-.js";import{d as se,f as re,b as x}from"./router.Cjj1--8t.js";import{B as I,f as D,c as M,d as ie,P as de,U as ce,e as xe,C as V}from"./NoAuthProxyCard.CrFQ6U88.js";import{C as ae}from"./Loading.C1s7rolj.js";import"./zustand.akaTi5uX.js";function Q(s){if(s==="leonardo"||s==="weavy")return!0;const t=Y[s];return t!=null&&t.serviceKinds?t.serviceKinds.includes("llm"):!0}function me(s){const t=Math.floor((Date.now()-new Date(s))/1e3);return t<60?`${t}s ago`:t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`}function ue({timestamp:s}){const[,t]=x.useState(0);return x.useEffect(()=>{const r=setInterval(()=>t(a=>a+1),1e3);return()=>clearInterval(r)},[]),e.jsx(e.Fragment,{children:me(s)})}function pe({requests:s=[]}){return e.jsxs(V,{className:"flex min-w-0 flex-col overflow-hidden",padding:"sm",style:{height:480},children:[e.jsx("div",{className:"px-1 py-2 border-b border-border shrink-0",children:e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wide",children:"Recent Requests"})}),s.length?e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsxs("table",{className:"w-full min-w-[300px] border-collapse text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-bg z-10",children:e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("th",{className:"py-1.5 text-left font-semibold text-text-muted w-2"}),e.jsx("th",{className:"py-1.5 text-left font-semibold text-text-muted",children:"Model"}),e.jsx("th",{className:"py-1.5 text-right font-semibold text-text-muted whitespace-nowrap",children:"In / Out"}),e.jsx("th",{className:"py-1.5 text-right font-semibold text-text-muted",children:"When"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:s.map((t,r)=>{const a=t.status==="streaming",i=!t.status||t.status==="ok"||t.status==="success";return e.jsxs("tr",{className:"hover:bg-bg-subtle transition-colors",children:[e.jsx("td",{className:"py-1.5",children:a?e.jsx("span",{className:"block w-1.5 h-1.5 rounded-full bg-warning animate-pulse",title:"Streaming…"}):e.jsx("span",{className:`block w-1.5 h-1.5 rounded-full ${i?"bg-success":"bg-error"}`})}),e.jsx("td",{className:"py-1.5 font-mono truncate max-w-[120px]",title:t.model,children:t.model}),e.jsx("td",{className:"py-1.5 text-right whitespace-nowrap",children:a?e.jsx("span",{className:"text-warning italic text-[10px]",children:"streaming…"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary",children:[D(t.promptTokens),"↑"]})," ",e.jsxs("span",{className:"text-success",children:[D(t.completionTokens),"↓"]})]})}),e.jsx("td",{className:"py-1.5 text-right text-text-muted whitespace-nowrap",children:e.jsx(ue,{timestamp:t.timestamp})})]},r)})})]})}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-text-muted text-sm",children:"No requests yet."})]})}function _(s,t={},r,a){return Object.entries(s||{}).map(([i,o])=>{const n=(o.promptTokens||0)+(o.completionTokens||0),l=o.cost||0,b=n>0?(o.promptTokens||0)*(l/n):0,p=n>0?(o.completionTokens||0)*(l/n):0;return{...o,key:i,totalTokens:n,totalCost:l,inputCost:b,outputCost:p,pending:t[i]||0}}).sort((i,o)=>{let n=i[r],l=o[r];return typeof n=="string"&&(n=n.toLowerCase()),typeof l=="string"&&(l=l.toLowerCase()),n<l?a==="asc"?-1:1:n>l?a==="asc"?1:-1:0})}function he(s,t){var r;switch(t){case"rawModel":return s.rawModel||"Unknown Model";case"accountName":return s.accountName||`Account ${(r=s.connectionId)==null?void 0:r.slice(0,8)}...`||"Unknown Account";case"keyName":return s.keyName||"Unknown Key";case"endpoint":return s.endpoint||"Unknown Endpoint";default:return s[t]||"Unknown"}}function K(s,t){if(!Array.isArray(s))return[];const r={};return s.forEach(a=>{const i=he(a,t);r[i]||(r[i]={groupKey:i,summary:{requests:0,promptTokens:0,completionTokens:0,totalTokens:0,cost:0,inputCost:0,outputCost:0,lastUsed:null,pending:0},items:[]});const o=r[i].summary;o.requests+=a.requests||0,o.promptTokens+=a.promptTokens||0,o.completionTokens+=a.completionTokens||0,o.totalTokens+=a.totalTokens||0,o.cost+=a.cost||0,o.inputCost+=a.inputCost||0,o.outputCost+=a.outputCost||0,o.pending+=a.pending||0,a.lastUsed&&(!o.lastUsed||new Date(a.lastUsed)>new Date(o.lastUsed))&&(o.lastUsed=a.lastUsed),r[i].items.push(a)}),Object.values(r)}const fe=[{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],be=[{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"accountName",label:"Account"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],ge=[{field:"keyName",label:"API Key Name"},{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],je=[{field:"endpoint",label:"Endpoint"},{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],ve=[{value:"model",label:"Usage by Model"},{value:"account",label:"Usage by Account"},{value:"apiKey",label:"Usage by API Key"},{value:"endpoint",label:"Usage by Endpoint"}],ye=[{value:"today",label:"Today"},{value:"24h",label:"24h"},{value:"7d",label:"7D"},{value:"30d",label:"30D"},{value:"60d",label:"60D"}];function X(s){if(!s)return s;const t={...s};if(t.byProvider&&(t.byProvider={...t.byProvider},t.byProvider.cb)){if(!t.byProvider.codebuddy)t.byProvider.codebuddy=t.byProvider.cb;else{const r=t.byProvider.cb,a=t.byProvider.codebuddy;t.byProvider.codebuddy={requests:(a.requests||0)+(r.requests||0),promptTokens:(a.promptTokens||0)+(r.promptTokens||0),completionTokens:(a.completionTokens||0)+(r.completionTokens||0),cost:(a.cost||0)+(r.cost||0)}}delete t.byProvider.cb}return t.byModel&&(t.byModel=Object.fromEntries(Object.entries(t.byModel).map(([r,a])=>r.endsWith(" (cb)")?[r.slice(0,-5)+" (codebuddy)",{...a,provider:"CodeBuddy"}]:[r,a]))),t.byAccount&&(t.byAccount=Object.fromEntries(Object.entries(t.byAccount).map(([r,a])=>a.provider==="cb"||a.provider==="Codebuddy"||a.provider==="codebuddy"?[r,{...a,provider:"CodeBuddy"}]:[r,a]))),Array.isArray(t.recentRequests)&&(t.recentRequests=t.recentRequests.map(r=>r.provider==="cb"?{...r,provider:"codebuddy"}:r)),t}function Ne({period:s,setPeriod:t,hidePeriodSelector:r=!1}={}){var E,c,w,C;const a=se(),[i]=re(),o=i.get("sortBy")||"rawModel",n=i.get("sortOrder")||"asc",[l,b]=x.useState(null),[p,j]=x.useState(!0),[f,P]=x.useState(!1),[y,h]=x.useState("model"),[N,L]=x.useState("costs"),[O,J]=x.useState([]),[G,W]=x.useState("today"),A=x.useRef(!0),T=s??G,F=t??W;x.useEffect(()=>{fetch("/api/providers").then(m=>m.ok?m.json():null).then(m=>{const v=new Set,d=((m==null?void 0:m.connections)||[]).filter(g=>g.isActive===!1||!Q(g.provider)||v.has(g.provider)?!1:(v.add(g.provider),!0)),u=Object.values(le).filter(g=>g.noAuth&&!v.has(g.id)&&Q(g.id)).map(g=>({provider:g.id,name:g.name}));J([...d,...u])}).catch(()=>{})},[]),x.useEffect(()=>{A.current?(A.current=!1,j(!0)):P(!0),fetch(`/api/usage/stats?period=${T}`).then(m=>m.ok?m.json():null).then(m=>{if(m){const v=X(m);b(d=>({...d,...v}))}}).catch(()=>{}).finally(()=>{j(!1),P(!1)})},[T]),x.useEffect(()=>{const m=new EventSource(`/api/usage/stream?period=${T}`);return m.onmessage=v=>{try{const d=JSON.parse(v.data),u=X(d);b(u),j(!1)}catch(d){console.error("[SSE CLIENT] parse error:",d)}},m.onerror=()=>j(!1),()=>m.close()},[T]);const $=x.useCallback((m,v)=>{const d=new URLSearchParams(i.toString());d.get("sortBy")===v?d.set("sortOrder",d.get("sortOrder")==="asc"?"desc":"asc"):(d.set("sortBy",v),d.set("sortOrder","asc")),a(`?${d.toString()}`,{scroll:!1})},[i,a]),S=x.useMemo(()=>{var m,v;if(!l)return null;switch(y){case"model":{const d=((m=l.pending)==null?void 0:m.byModel)||{};return{columns:fe,groupedData:K(_(l.byModel,d,o,n),"rawModel"),storageKey:"usage-stats:expanded-models",emptyMessage:"No usage recorded yet.",renderSummaryCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.summary.lastUsed)})]}),renderDetailCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:u.pending>0?"primary":"neutral",size:"sm",children:u.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.lastUsed)})]})}}case"account":{const d={};return(v=l==null?void 0:l.pending)!=null&&v.byAccount&&Object.entries(l.byAccount||{}).forEach(([u,g])=>{const H=l.pending.byAccount[g.connectionId];if(H){const ne=g.provider?`${g.rawModel} (${g.provider})`:g.rawModel;d[u]=H[ne]||0}}),{columns:be,groupedData:K(_(l.byAccount,d,o,n),"accountName"),storageKey:"usage-stats:expanded-accounts",emptyMessage:"No account-specific usage recorded yet.",renderSummaryCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.summary.lastUsed)})]}),renderDetailCells:u=>{var g;return e.jsxs(e.Fragment,{children:[e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.accountName||`Account ${(g=u.connectionId)==null?void 0:g.slice(0,8)}...`}),e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:u.pending>0?"primary":"neutral",size:"sm",children:u.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.lastUsed)})]})}}}case"apiKey":return{columns:ge,groupedData:K(_(l.byApiKey,{},o,n),"keyName"),storageKey:"usage-stats:expanded-apikeys",emptyMessage:"No API key usage recorded yet.",renderSummaryCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.summary.lastUsed)})]}),renderDetailCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 font-medium",children:d.keyName}),e.jsx("td",{className:"px-6 py-3",children:d.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:"neutral",size:"sm",children:d.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.lastUsed)})]})};case"endpoint":default:return{columns:je,groupedData:K(_(l.byEndpoint,{},o,n),"endpoint"),storageKey:"usage-stats:expanded-endpoints",emptyMessage:"No endpoint usage recorded yet.",renderSummaryCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.summary.lastUsed)})]}),renderDetailCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 font-medium font-mono text-sm",children:d.endpoint}),e.jsx("td",{className:"px-6 py-3",children:d.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:"neutral",size:"sm",children:d.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.lastUsed)})]})}}},[l,y,o,n]);if(!l&&!p)return e.jsx("div",{className:"text-text-muted",children:"Failed to load usage statistics."});const R=e.jsx("div",{className:"flex items-center justify-center py-12 text-text-muted",children:e.jsx("span",{className:"material-symbols-outlined text-[32px] animate-spin",children:"progress_activity"})});return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[!r&&e.jsxs("div",{className:"flex w-full items-center gap-2 sm:w-auto sm:self-end",children:[e.jsx("div",{className:"grid flex-1 grid-cols-5 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1 sm:flex sm:flex-none",children:ye.map(m=>e.jsx("button",{onClick:()=>F(m.value),disabled:f,className:`rounded-md px-3 py-1 text-sm font-medium transition-colors ${T===m.value?"bg-primary text-white shadow-sm":"text-text-muted hover:bg-bg-hover hover:text-text"}`,children:m.label},m.value))}),f&&e.jsx("span",{className:"material-symbols-outlined text-[16px] text-text-muted animate-spin",children:"progress_activity"})]}),p?R:e.jsx(ie,{stats:l}),p?R:e.jsxs("div",{className:"grid min-w-0 grid-cols-1 items-stretch gap-2 lg:grid-cols-[minmax(0,2fr)_minmax(280px,1fr)]",children:[e.jsx(de,{providers:O,activeRequests:l.activeRequests||[],lastProvider:((c=(E=l.recentRequests)==null?void 0:E[0])==null?void 0:c.provider)||"",errorProvider:l.errorProvider||""}),e.jsx(pe,{requests:l.recentRequests||[]})]}),p?R:e.jsx(ce,{period:T,lastRequestTime:(C=(w=l==null?void 0:l.recentRequests)==null?void 0:w[0])==null?void 0:C.timestamp}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("select",{value:y,onChange:m=>h(m.target.value),className:"w-full rounded-lg border border-border bg-surface px-3 py-1.5 text-sm font-medium text-text-main focus:outline-none focus:ring-2 focus:ring-primary/50 sm:w-auto",style:{colorScheme:"auto"},children:ve.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))}),e.jsxs("div",{className:"grid grid-cols-2 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1 sm:flex",children:[e.jsx("button",{onClick:()=>L("costs"),className:`px-3 py-1 rounded-md text-sm font-medium transition-colors ${N==="costs"?"bg-primary text-white shadow-sm":"text-text-muted hover:text-text hover:bg-bg-hover"}`,children:"Costs"}),e.jsx("button",{onClick:()=>L("tokens"),className:`px-3 py-1 rounded-md text-sm font-medium transition-colors ${N==="tokens"?"bg-primary text-white shadow-sm":"text-text-muted hover:text-text hover:bg-bg-hover"}`,children:"Tokens"})]})]}),p?R:S&&e.jsx(xe,{title:"",columns:S.columns,groupedData:S.groupedData,tableType:y,sortBy:o,sortOrder:n,onToggleSort:$,viewMode:N,storageKey:S.storageKey,renderSummaryCells:S.renderSummaryCells,renderDetailCells:S.renderDetailCells,emptyMessage:S.emptyMessage})]})]})}function we(){const[s,t]=x.useState([]),[r,a]=x.useState(!0),[i,o]=x.useState(!0);x.useEffect(()=>{n()},[]),x.useEffect(()=>{let l;return i&&(l=setInterval(()=>{n(!1)},3e3)),()=>clearInterval(l)},[i]);const n=async(l=!0)=>{l&&a(!0);try{const b=await fetch("/api/usage/request-logs");if(b.ok){const p=await b.json();t(p)}}catch(b){console.error("Failed to fetch logs:",b)}finally{l&&a(!1)}};return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Request Logs"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("label",{className:"text-sm font-medium text-text-muted flex items-center gap-2 cursor-pointer",children:[e.jsx("span",{children:"Auto Refresh (3s)"}),e.jsx("div",{onClick:()=>o(!i),className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none ${i?"bg-primary":"bg-bg-subtle border border-border"}`,children:e.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white transition-transform ${i?"translate-x-5":"translate-x-1"}`})})]})})]}),e.jsx(V,{className:"overflow-hidden bg-black/5 dark:bg-black/20",children:e.jsx("div",{className:"p-0 overflow-x-auto max-h-[600px] overflow-y-auto font-mono text-xs",children:r&&s.length===0?e.jsx("div",{className:"p-8 text-center text-text-muted",children:"Loading logs..."}):s.length===0?e.jsx("div",{className:"p-8 text-center text-text-muted",children:"No logs recorded yet."}):e.jsxs("table",{className:"w-full text-left border-collapse whitespace-nowrap",children:[e.jsx("thead",{className:"sticky top-0 bg-bg-subtle border-b border-border z-10",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"DateTime"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Model"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Provider"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Account"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"In"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Out"}),e.jsx("th",{className:"px-3 py-2",children:"Status"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:s.map((l,b)=>{const p=l.split(" | ");if(p.length<7)return null;const j=p[6],f=j.includes("PENDING"),P=j.includes("FAILED"),y=j.includes("OK");return e.jsxs("tr",{className:`hover:bg-primary/5 transition-colors ${f?"bg-primary/5":""}`,children:[e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-text-muted",children:p[0]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border font-medium",children:p[1]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border",children:e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-subtle border border-border text-[10px] uppercase font-bold",children:p[2]})}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border truncate max-w-[150px]",title:p[3],children:p[3]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-right text-primary",children:p[4]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-right text-success",children:p[5]}),e.jsx("td",{className:`px-3 py-1.5 font-bold ${y?"text-success":P?"text-error":"text-primary animate-pulse"}`,children:j})]},b)})})]})})}),e.jsx("div",{className:"text-[10px] text-text-muted italic",children:"Logs are loaded from the request history database."})]})}function Z({options:s=[],value:t,onChange:r,size:a="md",className:i}){const o={sm:"h-7 text-xs",md:"h-9 text-sm",lg:"h-11 text-base"};return e.jsx("div",{className:k("inline-flex items-center p-1 rounded-[10px] overflow-x-auto","bg-surface-2",i),children:s.map(n=>e.jsxs("button",{onClick:()=>r(n.value),className:k("shrink-0 px-4 rounded-[8px] font-medium transition-all",o[a],t===n.value?"bg-surface text-text-main shadow-sm":"text-text-muted hover:text-text-main"),children:[n.icon&&e.jsx("span",{className:"material-symbols-outlined text-[16px] mr-1.5",children:n.icon}),n.label]},n.value))})}function ke({isOpen:s,onClose:t,title:r,children:a,width:i="md",className:o}){const n={sm:"w-[400px]",md:"w-[500px]",lg:"w-[600px]",xl:"w-[800px]",full:"w-full"};return x.useEffect(()=>(s?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[s]),x.useEffect(()=>{const l=b=>{b.key==="Escape"&&s&&t()};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[s,t]),s?e.jsxs("div",{className:"fixed inset-0 z-50",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[2px] fade-in cursor-pointer",onClick:t,"aria-hidden":"true"}),e.jsxs("div",{className:k("absolute right-0 top-0 h-full bg-surface flex flex-col","shadow-[var(--shadow-elev)]","slide-in-right","border-l border-border-subtle",n[i]||n.md,o),children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border-subtle flex-shrink-0",children:[e.jsx("div",{className:"flex items-center gap-3",children:r&&e.jsx("h2",{className:"text-lg font-semibold text-text-main",children:r})}),e.jsx("button",{type:"button",onClick:t,className:"p-1.5 rounded-[10px] text-text-muted hover:bg-surface-2 hover:text-text-main transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"close"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6 custom-scrollbar",children:a})]})]}):null}function Se({currentPage:s,pageSize:t,totalItems:r,onPageChange:a,onPageSizeChange:i,className:o}){const n=Math.ceil(r/t),l=r>0?(s-1)*t+1:0,b=Math.min(s*t,r),j=(()=>{const f=[];let y=Math.max(1,s-2),h=Math.min(n,y+5-1);h-y+1<5&&(y=Math.max(1,h-5+1));for(let N=y;N<=h;N++)f.push(N);return f})();return e.jsxs("div",{className:k("flex flex-col sm:flex-row items-center justify-between gap-4 py-4 px-2",o),children:[r>0&&e.jsxs("div",{className:"text-sm text-text-muted",children:["Showing ",e.jsx("span",{className:"font-medium text-text-main",children:l})," to"," ",e.jsx("span",{className:"font-medium text-text-main",children:b})," of"," ",e.jsx("span",{className:"font-medium text-text-main",children:r})," results"]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2 sm:gap-4",children:[i&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-text-muted",children:"Rows:"}),e.jsx("select",{value:t,onChange:f=>i(Number(f.target.value)),className:k("h-9 rounded-lg border border-black/10 dark:border-white/10 bg-surface","text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20","cursor-pointer"),style:{colorScheme:"auto"},children:[10,20,50].map(f=>e.jsx("option",{value:f,children:f},f))})]}),n>1&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"outline",size:"sm",onClick:()=>a(s-1),disabled:s===1,className:"w-9 px-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"chevron_left"})}),j[0]>1&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>a(1),className:"w-9 px-0 hidden sm:inline-flex",children:"1"}),j[0]>2&&e.jsx("span",{className:"text-text-muted px-1 hidden sm:inline",children:"..."})]}),j.map(f=>e.jsx(q,{variant:s===f?"primary":"ghost",size:"sm",onClick:()=>a(f),className:k("w-9 px-0",s===f?"inline-flex":"hidden sm:inline-flex"),children:f},f)),j[j.length-1]<n&&e.jsxs(e.Fragment,{children:[j[j.length-1]<n-1&&e.jsx("span",{className:"text-text-muted px-1 hidden sm:inline",children:"..."}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>a(n),className:"w-9 px-0 hidden sm:inline-flex",children:n})]}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>a(s+1),disabled:s===n,className:"w-9 px-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"chevron_right"})})]})]})]})}let z=null,U=null;async function Ce(){if(z&&U)return{providerNameCache:z,providerNodesCache:U};const r=(await(await fetch("/api/provider-nodes")).json()).nodes||[];U={};for(const a of r)U[a.id]=a.name;return z={...Y,...U},{providerNameCache:z,providerNodesCache:U}}function ee(s,t){if(!s||!t)return s;const r=t[s];if(typeof r=="string")return r;if(r!=null&&r.name)return r.name;const a=oe(s)||Y[s];return(a==null?void 0:a.name)||s}function B({title:s,children:t,defaultOpen:r=!1,icon:a=null}){const[i,o]=x.useState(r);return e.jsxs("div",{className:"border border-black/5 dark:border-white/5 rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>o(!i),className:"w-full flex items-center justify-between p-3 bg-black/[0.02] dark:bg-white/[0.02] hover:bg-black/[0.04] dark:hover:bg-white/[0.04] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a&&e.jsx("span",{className:"material-symbols-outlined text-[18px] text-text-muted",children:a}),e.jsx("span",{className:"font-semibold text-sm text-text-main",children:s})]}),e.jsx("span",{className:k("material-symbols-outlined text-[20px] text-text-muted transition-transform duration-200",i?"rotate-90":""),children:"chevron_right"})]}),i&&e.jsx("div",{className:"p-4 border-t border-black/5 dark:border-white/5",children:t})]})}function te(s){const t=(s==null?void 0:s.prompt_tokens)||(s==null?void 0:s.input_tokens)||0,r=(s==null?void 0:s.cached_tokens)||(s==null?void 0:s.cache_read_input_tokens)||0;return t<r?r:t}function De(){var T,F,$,S,R,E;const[s,t]=x.useState([]),[r,a]=x.useState({page:1,pageSize:20,totalItems:0,totalPages:0}),[i,o]=x.useState(!1),[n,l]=x.useState(null),[b,p]=x.useState(!1),[j,f]=x.useState([]),[P,y]=x.useState(null),[h,N]=x.useState({provider:"",startDate:"",endDate:""}),L=x.useCallback(async()=>{try{const w=await(await fetch("/api/usage/providers")).json();f(w.providers||[]);const C=await Ce();y(C.providerNameCache)}catch(c){console.error("Failed to fetch providers:",c)}},[]),O=x.useCallback(async()=>{o(!0);try{const c=new URLSearchParams({page:r.page.toString(),pageSize:r.pageSize.toString()});h.provider&&c.append("provider",h.provider),h.startDate&&c.append("startDate",h.startDate),h.endDate&&c.append("endDate",h.endDate);const C=await(await fetch(`/api/usage/request-details?${c}`)).json();t(C.details||[]),a(m=>({...m,...C.pagination}))}catch(c){console.error("Failed to fetch request details:",c)}finally{o(!1)}},[r.page,r.pageSize,h]);x.useEffect(()=>{L()},[L]),x.useEffect(()=>{O()},[O]);const J=c=>{l(c),p(!0)},G=c=>{a(w=>({...w,page:c}))},W=c=>{a(w=>({...w,pageSize:c,page:1}))},A=()=>{N({provider:"",startDate:"",endDate:""})};return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[e.jsx(V,{padding:"md",children:e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"provider-filter",className:"text-sm font-medium text-text-main",children:"Provider"}),e.jsxs("select",{id:"provider-filter",value:h.provider,onChange:c=>N({...h,provider:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20","w-full min-w-0 cursor-pointer"),style:{colorScheme:"auto"},children:[e.jsx("option",{value:"",children:"All Providers"}),j.map(c=>e.jsx("option",{value:c.id,children:c.name},c.id))]})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"start-date-filter",className:"text-sm font-medium text-text-main",children:"Start Date"}),e.jsx("input",{id:"start-date-filter",type:"datetime-local",value:h.startDate,onChange:c=>N({...h,startDate:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","w-full min-w-0 text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20")})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"end-date-filter",className:"text-sm font-medium text-text-main",children:"End Date"}),e.jsx("input",{id:"end-date-filter",type:"datetime-local",value:h.endDate,onChange:c=>N({...h,endDate:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","w-full min-w-0 text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20")})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:col-span-2 lg:col-span-1",children:[e.jsx("span",{className:"hidden text-sm font-medium text-text-main opacity-0 lg:block","aria-hidden":"true",children:"Clear"}),e.jsx(q,{variant:"ghost",onClick:A,disabled:!h.provider&&!h.startDate&&!h.endDate,className:"w-full",children:"Clear Filters"})]})]})}),e.jsxs(V,{padding:"none",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[880px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-black/5 dark:border-white/5",children:[e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Timestamp"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Model"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Provider"}),e.jsx("th",{className:"text-right p-4 text-sm font-semibold text-text-main",children:"Input Tokens"}),e.jsx("th",{className:"text-right p-4 text-sm font-semibold text-text-main",children:"Output Tokens"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Latency"}),e.jsx("th",{className:"text-center p-4 text-sm font-semibold text-text-main",children:"Action"})]})}),e.jsx("tbody",{children:i?e.jsx("tr",{children:e.jsx("td",{colSpan:"7",className:"p-8 text-center text-text-muted",children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-[20px]",children:"progress_activity"}),"Loading..."]})})}):s.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:"7",className:"p-8 text-center text-text-muted",children:"No request details found"})}):s.map((c,w)=>{var C,m,v,d;return e.jsxs("tr",{className:"border-b border-black/5 dark:border-white/5 last:border-b-0 hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors",children:[e.jsx("td",{className:"whitespace-nowrap p-4 text-sm text-text-main",children:new Date(c.timestamp).toLocaleString()}),e.jsx("td",{className:"max-w-[260px] truncate p-4 font-mono text-sm text-text-main",children:c.model}),e.jsx("td",{className:"max-w-[180px] truncate p-4 text-sm text-text-main",children:e.jsx("span",{className:"font-medium",children:ee(c.provider,P)})}),e.jsx("td",{className:"p-4 text-sm text-text-main text-right font-mono",children:te(c.tokens).toLocaleString()}),e.jsx("td",{className:"p-4 text-sm text-text-main text-right font-mono",children:((m=(C=c.tokens)==null?void 0:C.completion_tokens)==null?void 0:m.toLocaleString())||0}),e.jsx("td",{className:"p-4 text-sm text-text-muted",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{children:["TTFT: ",e.jsxs("span",{className:"font-mono",children:[((v=c.latency)==null?void 0:v.ttft)||0,"ms"]})]}),e.jsxs("div",{children:["Total: ",e.jsxs("span",{className:"font-mono",children:[((d=c.latency)==null?void 0:d.total)||0,"ms"]})]})]})}),e.jsx("td",{className:"p-4 text-center",children:e.jsx(q,{variant:"outline",size:"sm",onClick:()=>J(c),children:"Detail"})})]},`${c.id}-${w}`)})})]})}),!i&&s.length>0&&e.jsx("div",{className:"border-t border-black/5 dark:border-white/5",children:e.jsx(Se,{currentPage:r.page,pageSize:r.pageSize,totalItems:r.totalItems,onPageChange:G,onPageSizeChange:W})})]}),e.jsx(ke,{isOpen:b,onClose:()=>p(!1),title:"Request Details",width:"lg",children:n&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-4 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"ID:"})," ",e.jsx("span",{className:"break-all font-mono text-text-main",children:n.id})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Timestamp:"})," ",e.jsx("span",{className:"text-text-main",children:new Date(n.timestamp).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Provider:"})," ",e.jsx("span",{className:"text-text-main font-medium",children:ee(n.provider,P)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Model:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:n.model})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Status:"})," ",e.jsx("span",{className:k("font-medium",n.status==="success"?"text-green-600":"text-red-600"),children:n.status})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Latency:"})," ",e.jsxs("span",{className:"text-text-main font-mono",children:["TTFT ",((T=n.latency)==null?void 0:T.ttft)||0,"ms / Total ",((F=n.latency)==null?void 0:F.total)||0,"ms"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Input Tokens:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:te(n.tokens).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Output Tokens:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:((S=($=n.tokens)==null?void 0:$.completion_tokens)==null?void 0:S.toLocaleString())||0})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(B,{title:"1. Client Request (Input)",defaultOpen:!0,icon:"input",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:JSON.stringify(n.request,null,2)})}),n.providerRequest&&e.jsx(B,{title:"2. Provider Request (Translated)",icon:"translate",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:JSON.stringify(n.providerRequest,null,2)})}),n.providerResponse&&e.jsx(B,{title:"3. Provider Response (Raw)",icon:"data_object",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:typeof n.providerResponse=="object"?JSON.stringify(n.providerResponse,null,2):n.providerResponse})}),e.jsxs(B,{title:"4. Client Response (Final)",defaultOpen:!0,icon:"output",children:[((R=n.response)==null?void 0:R.thinking)&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("h4",{className:"font-semibold text-text-main mb-2 flex items-center gap-2 text-xs uppercase tracking-wide opacity-70",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"psychology"}),"Thinking Process"]}),e.jsx("pre",{className:"max-h-[200px] max-w-full overflow-auto rounded-lg border border-amber-200 bg-amber-50 p-3 font-mono text-xs text-amber-900 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100 sm:p-4",children:n.response.thinking})]}),e.jsx("h4",{className:"font-semibold text-text-main mb-2 text-xs uppercase tracking-wide opacity-70",children:"Content"}),e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:((E=n.response)==null?void 0:E.content)||"[No content]"})]})]})]})})]})}const Te=[{value:"today",label:"Today"},{value:"24h",label:"24h"},{value:"7d",label:"7D"},{value:"30d",label:"30D"},{value:"60d",label:"60D"}];function Ee(){return e.jsx(x.Suspense,{fallback:e.jsx(ae,{}),children:e.jsx(Pe,{})})}function Pe(){const[s]=re(),t=se(),[r,a]=x.useState("today"),i=s.get("tab"),o=i&&["overview","logs","details"].includes(i)?i:"overview",n=l=>{if(l===o)return;const b=new URLSearchParams(s);b.set("tab",l),t(`/dashboard/usage?${b.toString()}`,{scroll:!1})};return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6 px-1 sm:px-0",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(Z,{options:[{value:"overview",label:"Overview"},{value:"details",label:"Details"}],value:o,onChange:n,className:"w-full sm:w-auto"}),o==="overview"&&e.jsx(Z,{options:Te,value:r,onChange:a,size:"sm",className:"w-full sm:w-auto"})]}),o==="overview"&&e.jsx(x.Suspense,{fallback:e.jsx(ae,{}),children:e.jsx(Ne,{period:r,setPeriod:a,hidePeriodSelector:!0})}),o==="logs"&&e.jsx(we,{}),o==="details"&&e.jsx(De,{})]})}export{Ee as default};
@@ -0,0 +1,6 @@
1
+ import{a as ot,j as e,B as i,M as I,C as lt}from"./index.2a3mqmx-.js";import{b as l}from"./router.Cjj1--8t.js";import{C as Pe,B as k,T as ie,I as y}from"./NoAuthProxyCard.CrFQ6U88.js";import{C as Se}from"./Loading.C1s7rolj.js";import"./zustand.akaTi5uX.js";function at(x){return x==="active"?"success":x==="error"?"error":"default"}function nt(x){if(!x)return"Never";const W=new Date(x);return Number.isNaN(W.getTime())?"Never":W.toLocaleString()}function ce(x={}){return{name:x.name||"",proxyUrl:x.proxyUrl||"",noProxy:x.noProxy||"",isActive:x.isActive!==!1,strictProxy:x.strictProxy===!0}}function ht(){const[x,W]=l.useState([]),[De,A]=l.useState(!1),[$,B]=l.useState(""),[b,L]=l.useState([]),[E,Y]=l.useState(null),[c,U]=l.useState([]),[Te,Ie]=l.useState(!0),[Ae,K]=l.useState(!1),[$e,Q]=l.useState(!1),[Ee,de]=l.useState(!1),[Ue,xe]=l.useState(!1),[Oe,me]=l.useState(!1),[O,M]=l.useState(!1),[V,he]=l.useState(null),[u,C]=l.useState(ce()),[X,ue]=l.useState(""),[F,Z]=l.useState({vercelToken:"",projectName:"vercel-relay"}),[j,_]=l.useState({accountId:"",apiToken:"",projectName:"cloudflare-relay"}),[N,q]=l.useState({denoToken:"",orgDomain:"",projectName:""}),[R,pe]=l.useState(!1),[J,fe]=l.useState(!1),[p,S]=l.useState(!1),[ee,ye]=l.useState(null),[h,H]=l.useState([]),[v,ge]=l.useState(!1),[be,te]=l.useState({current:0,total:0}),[z,D]=l.useState(!1),[g,w]=l.useState(null),se=l.useRef(null),n=ot();l.useEffect(()=>{const t=s=>{se.current&&!se.current.contains(s.target)&&M(!1)};return O&&document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[O]);const f=l.useCallback(async()=>{try{const t=await fetch("/api/proxy-pools?includeUsage=true",{cache:"no-store"}),s=await t.json();t.ok&&U(s.proxyPools||[])}catch(t){console.log("Error fetching proxy pools:",t)}finally{Ie(!1)}},[]),G=l.useCallback(async()=>{try{const t=await fetch("/api/proxy-combos",{cache:"no-store"}),s=await t.json();t.ok&&W(s.combos||[])}catch{}},[]);l.useEffect(()=>{f(),G()},[f,G]);const je=()=>{he(null),C(ce())},ve=()=>{je(),K(!0)},Me=t=>{he(t),C(ce(t)),K(!0)},re=()=>{K(!1),je()},Fe=async()=>{const t={name:u.name.trim(),proxyUrl:u.proxyUrl.trim(),noProxy:u.noProxy.trim(),isActive:u.isActive===!0,strictProxy:u.strictProxy===!0};if(!(!t.name||!t.proxyUrl)){pe(!0);try{const s=!!V,r=await fetch(s?`/api/proxy-pools/${V.id}`:"/api/proxy-pools",{method:s?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(r.ok)await f(),re(),n.success(V?"Proxy pool updated":"Proxy pool created");else{const o=await r.json();n.error(o.error||"Failed to save proxy pool")}}catch(s){console.log("Error saving proxy pool:",s)}finally{pe(!1)}}},Re=async t=>{w({title:"Delete Proxy Pool",message:`Delete proxy pool "${t.name}"?`,onConfirm:async()=>{w(null);try{const s=await fetch(`/api/proxy-pools/${t.id}`,{method:"DELETE"});if(s.ok){U(o=>o.filter(a=>a.id!==t.id)),n.success("Proxy pool deleted");return}const r=await s.json();s.status===409?n.warning(`Cannot delete: ${r.boundConnectionCount||0} connection(s) are still using this pool.`):n.error(r.error||"Failed to delete proxy pool")}catch(s){console.log("Error deleting proxy pool:",s),n.error("Failed to delete proxy pool")}}})},ze=async t=>{ye(t);try{const s=await fetch(`/api/proxy-pools/${t}/test`,{method:"POST"}),r=await s.json();if(!s.ok){n.error(r.error||"Failed to test proxy");return}await f(),n.success(r.ok?"Proxy test passed":"Proxy test failed")}catch(s){console.log("Error testing proxy pool:",s),n.error("Failed to test proxy")}finally{ye(null)}},We=async t=>{const s=!t.isActive;U(r=>r.map(o=>o.id===t.id?{...o,isActive:s}:o));try{(await fetch(`/api/proxy-pools/${t.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:s})})).ok||(U(o=>o.map(a=>a.id===t.id?{...a,isActive:t.isActive}:a)),n.error("Failed to update active state"))}catch(r){console.log("Error toggling active:",r),U(o=>o.map(a=>a.id===t.id?{...a,isActive:t.isActive}:a))}},oe=c.length>0&&h.length===c.length,Be=t=>H(s=>s.includes(t)?s.filter(r=>r!==t):[...s,t]),Le=()=>H(oe?[]:c.map(t=>t.id)),ke=()=>H([]),Ce=async t=>{const s=h.length>0?h:c.map(r=>r.id);if(s.length!==0){D(!0);try{let r=0,o=0;for(const a of s)try{(await fetch(`/api/proxy-pools/${a}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:t})})).ok?r+=1:o+=1}catch{o+=1}await f(),n.success(`${t?"Activated":"Deactivated"} ${r}${o?`, failed ${o}`:""}`)}finally{D(!1)}}},Ve=async()=>{h.length!==0&&w({title:"Delete Proxy Pools",message:`Delete ${h.length} proxy pool(s)?`,onConfirm:async()=>{w(null),D(!0);try{let t=0,s=0,r=0;for(const o of h)try{const a=await fetch(`/api/proxy-pools/${o}`,{method:"DELETE"});a.ok?t+=1:a.status===409?s+=1:r+=1}catch{r+=1}await f(),ke(),n.success(`Deleted ${t}${s?`, ${s} bound`:""}${r?`, ${r} failed`:""}`)}finally{D(!1)}}})},_e=async()=>{const t=h.length>0?c.filter(d=>h.includes(d.id)):c;if(t.length===0)return;ge(!0),te({current:0,total:t.length});let s=0;const r=[];let o=0;const a=10,m=[...t],P=async()=>{for(;m.length>0;){const d=m.shift();if(!d)break;try{const T=await fetch(`/api/proxy-pools/${d.id}/test`,{method:"POST"}),we=await T.json();T.ok&&we.ok?s+=1:r.push(d.id)}catch{r.push(d.id)}finally{o+=1,te({current:o,total:t.length})}}};await Promise.all(Array.from({length:Math.min(a,t.length)},P)),await f(),ge(!1),te({current:0,total:0}),r.length>0?w({title:"Disable Dead Proxies",message:`Alive: ${s}, Dead: ${r.length}.
2
+
3
+ Disable ${r.length} dead proxies?`,onConfirm:async()=>{w(null),D(!0);try{for(const d of r)try{await fetch(`/api/proxy-pools/${d}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:!1})})}catch{}await f(),n.success(`Disabled ${r.length} dead proxies`)}finally{D(!1)}}}):n.success(`Health check done. Alive: ${s}, Dead: ${r.length}`)};l.useEffect(()=>{H(t=>t.filter(s=>c.some(r=>r.id===s)))},[c]);const qe=()=>{ue(""),Q(!0)},Ne=()=>{J||Q(!1)},Je=()=>{Z({vercelToken:"",projectName:"vercel-relay"}),de(!0)},le=()=>{p||de(!1)},He=()=>{_({accountId:"",apiToken:"",projectName:"cloudflare-relay"}),xe(!0)},ae=()=>{p||xe(!1)},Ge=()=>{q({denoToken:"",orgDomain:"",projectName:""}),me(!0)},ne=()=>{p||me(!1)},Ye=async()=>{if(F.vercelToken.trim()){S(!0);try{const t=await fetch("/api/proxy-pools/vercel-deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)}),s=await t.json();t.ok?(await f(),le(),n.success(`Deployed: ${s.deployUrl}`)):n.error(s.error||"Deploy failed")}catch(t){console.log("Error deploying Vercel relay:",t),n.error("Deploy failed")}finally{S(!1)}}},Ke=async()=>{if(!(!j.accountId.trim()||!j.apiToken.trim())){S(!0);try{const t=await fetch("/api/proxy-pools/cloudflare-deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)}),s=await t.json();t.ok?(await f(),ae(),n.success(`Deployed: ${s.deployUrl}`)):n.error(s.error||"Deploy failed")}catch(t){console.log("Error deploying Cloudflare relay:",t),n.error("Deploy failed")}finally{S(!1)}}},Qe=async()=>{if(N.denoToken.trim()){S(!0);try{const t=await fetch("/api/proxy-pools/deno-deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)}),s=await t.json();t.ok?(await f(),ne(),n.success(`Deployed: ${s.deployUrl}`)):n.error(s.error||"Deploy failed")}catch(t){console.log("Error deploying Deno relay:",t),n.error("Deploy failed")}finally{S(!1)}}},Xe=t=>{const s=t.trim();if(!s)return null;if(s.includes("://")){const o=new URL(s),a=o.port?`${o.hostname}:${o.port}`:o.hostname;return{proxyUrl:o.toString(),name:`Imported ${a}`}}const r=s.split(":");if(r.length===4){const[o,a,m,P]=r;if(!o||!a||!m||!P)throw new Error("Invalid host:port:user:pass format");const d=`http://${encodeURIComponent(m)}:${encodeURIComponent(P)}@${o}:${a}`;return{proxyUrl:new URL(d).toString(),name:`Imported ${o}:${a}`}}throw new Error("Unsupported format")},Ze=async()=>{const t=X.split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(t.length===0){n.warning("Please paste at least one proxy line.");return}const s=[],r=[];if(t.forEach((o,a)=>{try{const m=Xe(o);m&&s.push({...m,lineNumber:a+1})}catch(m){r.push(`Line ${a+1}: ${m.message}`)}}),r.length>0){n.error(`Invalid proxy format:
4
+ ${r.join(`
5
+ `)}`);return}fe(!0);try{const o=new Set(c.map(d=>`${(d.proxyUrl||"").trim()}|||${(d.noProxy||"").trim()}`));let a=0,m=0,P=0;for(const d of s){const T=`${d.proxyUrl}|||`;if(o.has(T)){m+=1;continue}(await fetch("/api/proxy-pools",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d.name,proxyUrl:d.proxyUrl,noProxy:"",isActive:!0})})).ok?(a+=1,o.add(T)):P+=1}await f(),Q(!1),n.success(`Batch import completed: Created ${a}, Skipped ${m}, Failed ${P}`)}catch(o){console.log("Error batch importing proxies:",o),n.error("Batch import failed")}finally{fe(!1)}},et=l.useMemo(()=>c.filter(t=>t.isActive===!0).length,[c]);if(Te)return e.jsxs("div",{className:"mx-auto flex w-full max-w-5xl flex-col gap-4 px-1 sm:gap-6 sm:px-0",children:[e.jsx(Se,{}),e.jsx(Se,{})]});const tt=async()=>{if(!$.trim()||b.length===0)return;const t=E?"PUT":"POST",s=E?{id:E.id,name:$,poolIds:b}:{name:$,poolIds:b};await fetch("/api/proxy-combos",{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),A(!1),B(""),L([]),Y(null),G()},st=async t=>{await fetch("/api/proxy-combos",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:t})}),G()},rt=t=>{var s;return((s=c.find(r=>r.id===t))==null?void 0:s.name)||t.slice(0,8)};return e.jsxs("div",{className:"mx-auto flex w-full max-w-5xl flex-col gap-4 px-1 sm:gap-6 sm:px-0",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsx("div",{className:"min-w-0",children:e.jsx("h1",{className:"text-xl font-semibold sm:text-2xl",children:"Proxy Pools"})}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:flex sm:items-center",children:[e.jsxs("div",{className:"relative",ref:se,children:[e.jsxs(i,{size:"sm",variant:"secondary",icon:"rocket_launch",onClick:()=>M(!O),children:["Deploy Relay",e.jsx("span",{className:"material-symbols-outlined ml-1 text-[18px]",children:O?"expand_less":"expand_more"})]}),O&&e.jsxs("div",{className:"absolute left-0 top-full z-50 mt-1 w-48 rounded-xl border border-black/10 bg-white p-1 shadow-xl dark:border-white/10 dark:bg-zinc-900 sm:left-auto sm:right-0",children:[e.jsxs("button",{onClick:()=>{He(),M(!1)},className:"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm text-text-main transition-colors hover:bg-black/5 dark:hover:bg-white/5",children:[e.jsx("span",{className:"material-symbols-outlined text-[20px] text-orange-500",children:"cloud"}),"Cloudflare Relay"]}),e.jsxs("button",{onClick:()=>{Je(),M(!1)},className:"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm text-text-main transition-colors hover:bg-black/5 dark:hover:bg-white/5",children:[e.jsx("span",{className:"material-symbols-outlined text-[20px] text-blue-500",children:"cloud_upload"}),"Vercel Relay"]}),e.jsxs("button",{onClick:()=>{Ge(),M(!1)},className:"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm text-text-main transition-colors hover:bg-black/5 dark:hover:bg-white/5",children:[e.jsx("span",{className:"material-symbols-outlined text-[20px] text-green-500",children:"terminal"}),"Deno Relay"]})]})]}),e.jsx(i,{size:"sm",variant:"secondary",icon:"upload",onClick:qe,children:"Batch Import"}),e.jsx(i,{size:"sm",icon:"add",onClick:ve,children:"Add Proxy Pool"})]})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[c.length>0&&e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-muted cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:oe,onChange:Le,className:"size-4 rounded border-black/20 dark:border-white/20"}),oe?"Unselect all":"Select all"]}),e.jsxs(k,{variant:"default",children:["Total: ",c.length]}),e.jsxs(k,{variant:"success",children:["Active: ",et]})]}),(h.length>0||v)&&e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px] text-primary",children:"checklist"}),e.jsx("span",{className:"text-xs font-medium text-primary",children:h.length>0?`${h.length} selected`:"All pools"}),e.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2",children:[e.jsx(i,{size:"sm",icon:v?"progress_activity":"health_and_safety",onClick:_e,disabled:v||z||c.length===0,children:v?`Checking ${be.current}/${be.total}`:"Health Check"}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(i,{size:"sm",variant:"secondary",icon:"toggle_on",onClick:()=>Ce(!0),disabled:z||v,children:"Activate"}),e.jsx(i,{size:"sm",variant:"secondary",icon:"toggle_off",onClick:()=>Ce(!1),disabled:z||v,children:"Deactivate"}),e.jsx(i,{size:"sm",variant:"secondary",icon:"delete",onClick:Ve,disabled:z||v,children:"Delete"}),e.jsx(i,{size:"sm",variant:"ghost",onClick:ke,disabled:z||v,children:"Clear"})]})]})]}),c.length===0?e.jsxs("div",{className:"text-center py-10",children:[e.jsx("p",{className:"text-text-main font-medium mb-1",children:"No proxy pool entries yet"}),e.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Create a proxy pool entry, then assign it to connections."}),e.jsx(i,{icon:"add",onClick:ve,children:"Add Proxy Pool"})]}):e.jsx("div",{className:"flex flex-col divide-y divide-black/[0.04] dark:divide-white/[0.05]",children:c.map(t=>e.jsxs("div",{className:"flex flex-col gap-3 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0 flex-1",children:[e.jsx("input",{type:"checkbox",checked:h.includes(t.id),onChange:()=>Be(t.id),className:"mt-1 size-4 shrink-0 rounded border-black/20 dark:border-white/20"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"min-w-0 max-w-full truncate text-sm font-medium sm:max-w-[18rem]",children:t.name}),e.jsx(k,{variant:at(t.testStatus),size:"sm",dot:!0,children:t.testStatus||"unknown"}),e.jsx(k,{variant:t.isActive?"success":"default",size:"sm",children:t.isActive?"active":"inactive"}),t.type==="vercel"&&e.jsx(k,{variant:"default",size:"sm",children:"vercel relay"}),t.type==="cloudflare"&&e.jsx(k,{variant:"default",size:"sm",children:"cloudflare relay"}),e.jsxs(k,{variant:"default",size:"sm",children:[t.boundConnectionCount||0," bound"]})]}),e.jsx("p",{className:"text-xs text-text-muted truncate mt-1",children:t.proxyUrl}),t.noProxy?e.jsxs("p",{className:"text-xs text-text-muted truncate",children:["No proxy: ",t.noProxy]}):null,e.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:["Last tested: ",nt(t.lastTestedAt),t.lastError?` · ${t.lastError}`:""]})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(ie,{size:"sm",checked:t.isActive===!0,onChange:()=>We(t),title:t.isActive?"Disable":"Enable"}),e.jsx("button",{onClick:()=>ze(t.id),className:"p-2 rounded hover:bg-black/5 dark:hover:bg-white/5 text-text-muted hover:text-primary",title:"Test proxy",disabled:ee===t.id,children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",style:ee===t.id?{animation:"spin 1s linear infinite"}:void 0,children:ee===t.id?"progress_activity":"science"})}),e.jsx("button",{onClick:()=>Me(t),className:"p-2 rounded hover:bg-black/5 dark:hover:bg-white/5 text-text-muted hover:text-primary",title:"Edit",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"edit"})}),e.jsx("button",{onClick:()=>Re(t),className:"p-2 rounded hover:bg-red-500/10 text-red-500",title:"Delete",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"delete"})})]})]},t.id))})]}),e.jsx(I,{isOpen:$e,title:"Batch Import Proxies",onClose:Ne,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-text-main mb-1 block",children:"Paste Proxy List (One per line)"}),e.jsx("textarea",{value:X,onChange:t=>ue(t.target.value),placeholder:`http://user:pass@127.0.0.1:7897
6
+ 127.0.0.1:7897:user:pass`,className:"w-full min-h-[180px] py-2 px-3 text-sm text-text-main bg-white dark:bg-white/5 border border-black/10 dark:border-white/10 rounded-md focus:ring-1 focus:ring-primary/30 focus:border-primary/50 focus:outline-none transition-all"}),e.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Supported formats: protocol://user:pass@host:port, host:port:user:pass"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(i,{fullWidth:!0,onClick:Ze,disabled:!X.trim()||J,children:J?"Importing...":"Import"}),e.jsx(i,{fullWidth:!0,variant:"ghost",onClick:Ne,disabled:J,children:"Cancel"})]})]})}),e.jsx(I,{isOpen:Ee,title:"Deploy Vercel Relay",onClose:le,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-lg bg-blue-500/5 border border-blue-500/10 p-3 flex flex-col gap-1.5",children:[e.jsx("p",{className:"text-sm text-text-main font-medium",children:"What is Vercel Relay?"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Deploys an edge relay function to Vercel. All AI provider requests will be forwarded through Vercel's edge network, masking your real IP from providers."}),e.jsxs("ul",{className:"text-xs text-text-muted list-disc pl-4 space-y-0.5",children:[e.jsx("li",{children:"Your IP is replaced by Vercel's dynamic edge IPs (hundreds of IPs across 20+ global regions)"}),e.jsx("li",{children:"Vercel serves millions of apps — providers can't block Vercel IPs without affecting legitimate traffic"}),e.jsx("li",{children:"Free tier: 100GB bandwidth/month, 500K edge invocations"}),e.jsx("li",{children:"Deploy multiple relays on different accounts for more IP diversity"})]})]}),e.jsx(y,{label:"Vercel API Token",value:F.vercelToken,onChange:t=>Z(s=>({...s,vercelToken:t.target.value})),placeholder:"your-vercel-api-token",hint:e.jsxs(e.Fragment,{children:["Token is used once for deployment and not stored. ",e.jsx("a",{href:"https://vercel.com/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"Get token →"})]}),type:"password"}),e.jsx(y,{label:"Project Name",value:F.projectName,onChange:t=>Z(s=>({...s,projectName:t.target.value})),placeholder:"my-relay",hint:"Unique name for your Vercel project. Leave empty for auto-generated name."}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(i,{fullWidth:!0,onClick:Ye,disabled:!F.vercelToken.trim()||p,children:p?"Deploying... (may take ~1 min)":"Deploy"}),e.jsx(i,{fullWidth:!0,variant:"ghost",onClick:le,disabled:p,children:"Cancel"})]})]})}),e.jsx(I,{isOpen:Ue,title:"Deploy Cloudflare Relay",onClose:ae,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-lg bg-orange-500/5 border border-orange-500/10 p-3 flex flex-col gap-1.5",children:[e.jsx("p",{className:"text-sm text-text-main font-medium",children:"What is Cloudflare Relay?"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Deploys a Cloudflare Worker as a proxy relay. All AI provider requests will be forwarded through Cloudflare's global edge network."}),e.jsxs("ul",{className:"text-xs text-text-muted list-disc pl-4 space-y-0.5",children:[e.jsx("li",{children:"High performance global routing and IP masking via Cloudflare Workers"}),e.jsx("li",{children:"Free tier: 100,000 requests per day"}),e.jsx("li",{children:"Requires Cloudflare Account ID and a Workers API Token (Edit Workers permission)"})]}),e.jsxs("div",{className:"mt-2 pt-2 border-t border-orange-500/10 text-xs text-text-muted",children:[e.jsx("p",{className:"font-medium text-text-main mb-1",children:"How to generate your API Token:"}),e.jsxs("ol",{className:"list-decimal pl-4 space-y-0.5",children:[e.jsxs("li",{children:["Go to ",e.jsx("b",{children:"My Profile"})," → ",e.jsx("b",{children:"API Tokens"})," → ",e.jsx("b",{children:"Create Token"})]}),e.jsxs("li",{children:["Scroll down to ",e.jsx("b",{children:"Custom Token"})," and click ",e.jsx("b",{children:"Get started"})]}),e.jsxs("li",{children:["Under ",e.jsx("b",{children:"Permissions"}),": Account | Workers Scripts | Edit"]}),e.jsxs("li",{children:["Under ",e.jsx("b",{children:"Account Resources"}),": Include | Account | ",e.jsx("i",{children:"Your Account Name"})]}),e.jsxs("li",{children:["Click ",e.jsx("b",{children:"Continue to summary"})," → ",e.jsx("b",{children:"Create Token"})]})]})]})]}),e.jsx(y,{label:"Account ID",value:j.accountId,onChange:t=>_(s=>({...s,accountId:t.target.value})),placeholder:"your-cloudflare-account-id",hint:e.jsx(e.Fragment,{children:"Found on the right side of the Cloudflare dashboard overview page."})}),e.jsx(y,{label:"API Token",value:j.apiToken,onChange:t=>_(s=>({...s,apiToken:t.target.value})),placeholder:"your-cloudflare-api-token",hint:e.jsxs(e.Fragment,{children:['Requires "Workers Scripts: Edit" permission. ',e.jsx("a",{href:"https://dash.cloudflare.com/profile/api-tokens",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"Get token →"})]}),type:"password"}),e.jsx(y,{label:"Worker Name",value:j.projectName,onChange:t=>_(s=>({...s,projectName:t.target.value})),placeholder:"my-relay",hint:"Unique name for your Cloudflare Worker. Leave empty for auto-generated name."}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(i,{fullWidth:!0,onClick:Ke,disabled:!j.accountId.trim()||!j.apiToken.trim()||p,children:p?"Deploying...":"Deploy Worker"}),e.jsx(i,{fullWidth:!0,variant:"ghost",onClick:ae,disabled:p,children:"Cancel"})]})]})}),e.jsx(I,{isOpen:Oe,title:"Deploy Deno Relay",onClose:ne,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-lg bg-black/5 dark:bg-white/5 border border-black/10 dark:border-white/10 p-3 flex flex-col gap-1.5",children:[e.jsx("p",{className:"text-sm text-text-main font-medium",children:"What is Deno Relay?"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Deploys a relay worker to Deno Deploy's global edge network. All AI provider requests are forwarded through Deno's edge, masking your real IP."}),e.jsxs("ul",{className:"text-xs text-text-muted list-disc pl-4 space-y-0.5",children:[e.jsx("li",{children:"Deno Deploy v2 runs on a high-performance global edge network"}),e.jsx("li",{children:"Free tier: 1M requests & 100GiB outbound traffic per month"}),e.jsx("li",{children:"No per-request CPU time limits (unlike Vercel/Cloudflare)"}),e.jsx("li",{children:"Support up to 20 active apps & 50 custom domains"}),e.jsx("li",{children:"Deploy multiple relays for maximum IP diversity"})]}),e.jsxs("div",{className:"mt-2 pt-2 border-t border-black/10 dark:border-white/10 text-xs text-text-muted",children:[e.jsx("p",{className:"font-medium text-text-main mb-1",children:"How to generate API token:"}),e.jsxs("ol",{className:"list-decimal pl-4 space-y-0.5",children:[e.jsxs("li",{children:["Go to ",e.jsx("b",{children:"console.deno.com"})]}),e.jsxs("li",{children:["Select your ",e.jsx("b",{children:"Organization"})," → ",e.jsx("b",{children:"Settings"})," → ",e.jsx("b",{children:"Organization Tokens"})]}),e.jsxs("li",{children:["Create a ",e.jsx("b",{children:"Organization Token"})," (prefix ",e.jsx("b",{children:"ddo_"}),")"]})]})]})]}),e.jsx(y,{label:"Deno Deploy API Token",value:N.denoToken,onChange:t=>q(s=>({...s,denoToken:t.target.value})),placeholder:"ddo_xxxxxxxxxxxxxxxx",hint:e.jsx(e.Fragment,{children:"Token is used once for deployment, not stored. Found in Organization Settings."}),type:"password"}),e.jsx(y,{label:"Organization Domain",value:N.orgDomain,onChange:t=>q(s=>({...s,orgDomain:t.target.value})),placeholder:"your-org.deno.net",hint:"Organization's default domain. Your relay URL will be in the format: https://my-relay.your-org.deno.net"}),e.jsx(y,{label:"App Name",value:N.projectName,onChange:t=>q(s=>({...s,projectName:t.target.value})),placeholder:"deno-relay",hint:"Unique app name. Leave empty for auto-generated name."}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(i,{fullWidth:!0,onClick:Qe,disabled:!N.denoToken.trim()||!N.orgDomain.trim()||p,children:p?"Deploying...":"Deploy Relay"}),e.jsx(i,{fullWidth:!0,variant:"ghost",onClick:ne,disabled:p,children:"Cancel"})]})]})}),e.jsx(I,{isOpen:Ae,title:V?"Edit Proxy Pool":"Add Proxy Pool",onClose:re,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(y,{label:"Name",value:u.name,onChange:t=>C(s=>({...s,name:t.target.value})),placeholder:"Office Proxy"}),e.jsx(y,{label:"Proxy URL",value:u.proxyUrl,onChange:t=>C(s=>({...s,proxyUrl:t.target.value})),placeholder:"http://127.0.0.1:7897"}),e.jsx(y,{label:"No Proxy",value:u.noProxy,onChange:t=>C(s=>({...s,noProxy:t.target.value})),placeholder:"localhost,127.0.0.1,.internal",hint:"Comma-separated hosts/domains to bypass proxy"}),e.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border border-border/50 p-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Active"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Inactive pools are ignored by runtime resolution."})]}),e.jsx(ie,{checked:u.isActive===!0,onChange:()=>C(t=>({...t,isActive:!t.isActive})),disabled:R})]}),e.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border border-border/50 p-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Strict Proxy"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Fail request if proxy is unreachable instead of falling back to direct."})]}),e.jsx(ie,{checked:u.strictProxy===!0,onChange:()=>C(t=>({...t,strictProxy:!t.strictProxy})),disabled:R})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(i,{fullWidth:!0,onClick:Fe,disabled:!u.name.trim()||!u.proxyUrl.trim()||R,children:R?"Saving...":"Save"}),e.jsx(i,{fullWidth:!0,variant:"ghost",onClick:re,disabled:R,children:"Cancel"})]})]})}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Proxy Combos"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Round-robin rotation across multiple pools"})]}),e.jsx(i,{size:"sm",icon:"add",onClick:()=>{Y(null),B(""),L([]),A(!0)},children:"Add Combo"})]}),x.length===0?e.jsx("p",{className:"text-sm text-text-muted py-4 text-center",children:"No combos yet. Create one to rotate proxies automatically."}):e.jsx("div",{className:"space-y-2",children:x.map(t=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border-subtle bg-surface hover:bg-surface/50",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm text-text-main",children:t.name}),e.jsx("p",{className:"text-xs text-text-muted mt-0.5",children:(t.poolIds||[]).map((s,r)=>e.jsxs("span",{children:[r>0?" → ":"",rt(s)]},s))})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-3",children:[e.jsxs(k,{variant:"success",size:"sm",children:[(t.poolIds||[]).length," pools"]}),e.jsx("button",{onClick:()=>{Y(t),B(t.name),L(t.poolIds||[]),A(!0)},className:"text-xs text-brand-400 hover:text-brand-300 cursor-pointer",children:"Edit"}),e.jsx("button",{onClick:()=>st(t.id),className:"text-xs text-red-400 hover:text-red-300 cursor-pointer",children:"Delete"})]})]},t.id))})]}),e.jsx(I,{isOpen:De,onClose:()=>A(!1),title:E?"Edit Combo":"Create Proxy Combo",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-text-muted block mb-1",children:"Combo Name"}),e.jsx(y,{value:$,onChange:t=>B(t.target.value),placeholder:"e.g. Free Proxy Round Robin"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-text-muted block mb-2",children:"Select Pools (click to toggle)"}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1 rounded-lg border border-border-subtle p-2",children:c.map(t=>e.jsxs("label",{className:`flex items-center gap-2 p-2 rounded cursor-pointer text-sm transition-colors ${b.includes(t.id)?"bg-primary/10 text-primary":"hover:bg-surface-2 text-text-main"}`,children:[e.jsx("input",{type:"checkbox",checked:b.includes(t.id),onChange:s=>{L(s.target.checked?[...b,t.id]:b.filter(r=>r!==t.id))},className:"rounded"}),t.name]},t.id))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(i,{fullWidth:!0,onClick:tt,disabled:!$.trim()||b.length===0,children:E?"Save Changes":"Create Combo"}),e.jsx(i,{fullWidth:!0,variant:"ghost",onClick:()=>A(!1),children:"Cancel"})]})]})}),e.jsx(lt,{isOpen:!!g,onClose:()=>w(null),onConfirm:g==null?void 0:g.onConfirm,title:(g==null?void 0:g.title)||"Confirm",message:g==null?void 0:g.message,variant:"danger"})]})}export{ht as default};