@schmitech/chatbot-api 0.5.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var S=Object.create;var p=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var P=Object.getPrototypeOf,T=Object.prototype.hasOwnProperty;var K=(t,e,r)=>e in t?p(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var U=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of O(e))!T.call(t,s)&&s!==r&&p(t,s,{get:()=>e[s],enumerable:!(n=x(e,s))||n.enumerable});return t};var I=(t,e,r)=>(r=t!=null?S(P(t)):{},U(e||!t||!t.__esModule?p(r,"default",{value:t,enumerable:!0}):r,t));var h=(t,e,r)=>K(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let A=null,m=null;typeof window>"u"&&Promise.all([import("http").catch(()=>null),import("https").catch(()=>null)]).then(([t,e])=>{var r,n;(r=t==null?void 0:t.default)!=null&&r.Agent?A=new t.default.Agent({keepAlive:!0}):t!=null&&t.Agent&&(A=new t.Agent({keepAlive:!0})),(n=e==null?void 0:e.default)!=null&&n.Agent?m=new e.default.Agent({keepAlive:!0}):e!=null&&e.Agent&&(m=new e.Agent({keepAlive:!0}))}).catch(t=>{console.warn("Failed to initialize HTTP agents:",t.message)});class b{constructor(e){h(this,"apiUrl");h(this,"apiKey");h(this,"sessionId");if(!e.apiUrl||typeof e.apiUrl!="string")throw new Error("API URL must be a valid string");if(e.apiKey!==void 0&&e.apiKey!==null&&typeof e.apiKey!="string")throw new Error("API key must be a valid string or null");if(e.sessionId!==void 0&&e.sessionId!==null&&typeof e.sessionId!="string")throw new Error("Session ID must be a valid string or null");this.apiUrl=e.apiUrl,this.apiKey=e.apiKey??null,this.sessionId=e.sessionId??null}setSessionId(e){if(e!==null&&typeof e!="string")throw new Error("Session ID must be a valid string or null");this.sessionId=e}getSessionId(){return this.sessionId}getFetchOptions(e={}){const r={};if(typeof window>"u"){const d=this.apiUrl.startsWith("https:")?m:A;d&&(r.agent=d)}else r.headers={Connection:"keep-alive"};const n={"X-Request-ID":Date.now().toString(36)+Math.random().toString(36).substring(2)};return r.headers&&Object.assign(n,r.headers),e.headers&&Object.assign(n,e.headers),this.apiKey&&(n["X-API-Key"]=this.apiKey),this.sessionId&&(n["X-Session-ID"]=this.sessionId),{...e,...r,headers:n}}createChatRequest(e,r=!0){return{messages:[{role:"user",content:e}],stream:r}}async*streamChat(e,r=!0){var n;try{const s=new AbortController,d=setTimeout(()=>s.abort(),6e4),l=await fetch(`${this.apiUrl}/v1/chat`,{...this.getFetchOptions({method:"POST",headers:{"Content-Type":"application/json",Accept:r?"text/event-stream":"application/json"},body:JSON.stringify(this.createChatRequest(e,r))}),signal:s.signal});if(clearTimeout(d),!l.ok){const a=await l.text();throw new Error(`Network response was not ok: ${l.status} ${a}`)}if(!r){const a=await l.json();a.response&&(yield{text:a.response,done:!0});return}const w=(n=l.body)==null?void 0:n.getReader();if(!w)throw new Error("No reader available");const k=new TextDecoder;let i="",g=!1;try{for(;;){const{done:a,value:C}=await w.read();if(a)break;const E=k.decode(C,{stream:!0});i+=E;let c=0,y;for(;(y=i.indexOf(`
2
- `,c))!==-1;){const u=i.slice(c,y).trim();if(c=y+1,u&&u.startsWith("data: ")){const f=u.slice(6).trim();if(!f||f==="[DONE]"){yield{text:"",done:!0};return}try{const o=JSON.parse(f);if(o.error)throw new Error(`Server Error: ${o.error.message}`);if(o.response&&(g=!0,yield{text:o.response,done:o.done||!1}),o.done){yield{text:"",done:!0};return}}catch(o){console.warn("Error parsing JSON chunk:",o,"Chunk:",f)}}else u&&(g=!0,yield{text:u,done:!1})}i=i.slice(c),i.length>1e6&&(console.warn("Buffer too large, truncating..."),i=i.slice(-5e5))}g&&(yield{text:"",done:!0})}finally{w.releaseLock()}}catch(s){throw s.name==="AbortError"?new Error("Connection timed out. Please check if the server is running."):s.name==="TypeError"&&s.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):s}}}let v=null;const j=(t,e=null,r=null)=>{v=new b({apiUrl:t,apiKey:e,sessionId:r})};async function*D(t,e=!0){if(!v)throw new Error("API not configured. Please call configureApi() with your server URL before using any API functions.");yield*v.streamChat(t,e)}exports.ApiClient=b;exports.configureApi=j;exports.streamChat=D;
1
+ "use strict";var b=Object.create;var v=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,S=Object.prototype.hasOwnProperty;var j=(i,t,e)=>t in i?v(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var U=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of O(t))!S.call(i,r)&&r!==e&&v(i,r,{get:()=>t[r],enumerable:!(s=x(t,r))||s.enumerable});return i};var T=(i,t,e)=>(e=i!=null?b(K(i)):{},U(t||!i||!i.__esModule?v(e,"default",{value:i,enumerable:!0}):e,i));var y=(i,t,e)=>j(i,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let k=null,E=null;typeof window>"u"&&Promise.all([import("http").catch(()=>null),import("https").catch(()=>null)]).then(([i,t])=>{var e,s;(e=i==null?void 0:i.default)!=null&&e.Agent?k=new i.default.Agent({keepAlive:!0}):i!=null&&i.Agent&&(k=new i.Agent({keepAlive:!0})),(s=t==null?void 0:t.default)!=null&&s.Agent?E=new t.default.Agent({keepAlive:!0}):t!=null&&t.Agent&&(E=new t.Agent({keepAlive:!0}))}).catch(i=>{console.warn("Failed to initialize HTTP agents:",i.message)});class I{constructor(t){y(this,"apiUrl");y(this,"apiKey");y(this,"sessionId");if(!t.apiUrl||typeof t.apiUrl!="string")throw new Error("API URL must be a valid string");if(t.apiKey!==void 0&&t.apiKey!==null&&typeof t.apiKey!="string")throw new Error("API key must be a valid string or null");if(t.sessionId!==void 0&&t.sessionId!==null&&typeof t.sessionId!="string")throw new Error("Session ID must be a valid string or null");this.apiUrl=t.apiUrl,this.apiKey=t.apiKey??null,this.sessionId=t.sessionId??null}setSessionId(t){if(t!==null&&typeof t!="string")throw new Error("Session ID must be a valid string or null");this.sessionId=t}getSessionId(){return this.sessionId}async validateApiKey(){var t;if(!this.apiKey)throw new Error("API key is required for validation");try{const e=await fetch(`${this.apiUrl}/admin/api-keys/${this.apiKey}/status`,{...this.getFetchOptions({method:"GET"})}).catch(r=>{throw r.name==="TypeError"&&r.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):r});if(!e.ok){let r="";try{r=await e.text()}catch{r=`HTTP ${e.status}`}let n,o;try{const a=JSON.parse(r);n=a.detail||a.message||r}catch{n=r||`HTTP ${e.status}`}switch(e.status){case 401:o="API key is invalid or expired";break;case 403:o="Access denied: API key does not have required permissions";break;case 404:o="API key not found";break;case 503:o="API key management is not available in inference-only mode";break;default:o=`Failed to validate API key: ${n}`;break}throw new Error(o)}const s=await e.json();if(!s.exists){const r="API key does not exist";throw new Error(r)}if(!s.active){const r="API key is inactive";throw new Error(r)}return s}catch(e){let s;throw e instanceof Error&&e.message?e.message.includes("API key")||e.message.includes("Access denied")||e.message.includes("invalid")||e.message.includes("expired")||e.message.includes("inactive")||e.message.includes("not found")||e.message.includes("Could not connect")?s=e.message:s=`API key validation failed: ${e.message}`:e.name==="TypeError"&&((t=e.message)!=null&&t.includes("Failed to fetch"))?s="Could not connect to the server. Please check if the server is running.":s="API key validation failed. Please check your API key and try again.",console.warn(`[ApiClient] ${s}`),new Error(s)}}async getAdapterInfo(){var t;if(!this.apiKey)throw new Error("API key is required to get adapter information");try{const e=await fetch(`${this.apiUrl}/admin/api-keys/info`,{...this.getFetchOptions({method:"GET"})}).catch(r=>{throw r.name==="TypeError"&&r.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):r});if(!e.ok){let r="";try{r=await e.text()}catch{r=`HTTP ${e.status}`}let n,o;try{const a=JSON.parse(r);n=a.detail||a.message||r}catch{n=r||`HTTP ${e.status}`}switch(e.status){case 401:o="API key is invalid, disabled, or has no associated adapter";break;case 404:o="Adapter configuration not found";break;case 503:o="Service is not available";break;default:o=`Failed to get adapter info: ${n}`;break}throw new Error(o)}return await e.json()}catch(e){let s;throw e instanceof Error&&e.message?e.message.includes("API key")||e.message.includes("Adapter")||e.message.includes("invalid")||e.message.includes("disabled")||e.message.includes("not found")||e.message.includes("Could not connect")?s=e.message:s=`Failed to get adapter info: ${e.message}`:e.name==="TypeError"&&((t=e.message)!=null&&t.includes("Failed to fetch"))?s="Could not connect to the server. Please check if the server is running.":s="Failed to get adapter information. Please try again.",console.warn(`[ApiClient] ${s}`),new Error(s)}}getFetchOptions(t={}){const e={};if(typeof window>"u"){const n=this.apiUrl.startsWith("https:")?E:k;n&&(e.agent=n)}else e.headers={Connection:"keep-alive"};const s={"X-Request-ID":Date.now().toString(36)+Math.random().toString(36).substring(2)};if(e.headers&&Object.assign(s,e.headers),t.headers){const r=t.headers;for(const[n,o]of Object.entries(r))(n.toLowerCase()!=="x-api-key"||!this.apiKey)&&(s[n]=o)}return this.apiKey&&(s["X-API-Key"]=this.apiKey),this.sessionId&&(s["X-Session-ID"]=this.sessionId),{...t,...e,headers:s}}createChatRequest(t,e=!0,s){const r={messages:[{role:"user",content:t}],stream:e};return s&&s.length>0&&(r.file_ids=s),r}async*streamChat(t,e=!0,s){var r,n;try{const o=new AbortController,a=setTimeout(()=>o.abort(),6e4),l=await fetch(`${this.apiUrl}/v1/chat`,{...this.getFetchOptions({method:"POST",headers:{"Content-Type":"application/json",Accept:e?"text/event-stream":"application/json"},body:JSON.stringify(this.createChatRequest(t,e,s))}),signal:o.signal});if(clearTimeout(a),!l.ok){const h=await l.text();throw new Error(`Network response was not ok: ${l.status} ${h}`)}if(!e){const h=await l.json();h.response&&(yield{text:h.response,done:!0});return}const u=(r=l.body)==null?void 0:r.getReader();if(!u)throw new Error("No reader available");const $=new TextDecoder;let c="",p=!1;try{for(;;){const{done:h,value:F}=await u.read();if(h)break;const C=$.decode(F,{stream:!0});c+=C;let w=0,g;for(;(g=c.indexOf(`
2
+ `,w))!==-1;){const f=c.slice(w,g).trim();if(w=g+1,f&&f.startsWith("data: ")){const m=f.slice(6).trim();if(!m||m==="[DONE]"){yield{text:"",done:!0};return}try{const d=JSON.parse(m);if(d.error){const P=`Server error: ${((n=d.error)==null?void 0:n.message)||d.error||"Unknown server error"}`;throw console.warn(`[ApiClient] ${P}`),new Error(P)}if(d.response&&(p=!0,yield{text:d.response,done:d.done||!1}),d.done){yield{text:"",done:!0};return}}catch{console.warn("[ApiClient] Unable to parse server response. This may be a temporary issue.")}}else f&&(p=!0,yield{text:f,done:!1})}c=c.slice(w),c.length>1e6&&(console.warn("Buffer too large, truncating..."),c=c.slice(-5e5))}p&&(yield{text:"",done:!0})}finally{u.releaseLock()}}catch(o){throw o.name==="AbortError"?new Error("Connection timed out. Please check if the server is running."):o.name==="TypeError"&&o.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):o}}async clearConversationHistory(t){const e=t||this.sessionId;if(!e)throw new Error("No session ID provided and no current session available");if(!this.apiKey)throw new Error("API key is required for clearing conversation history");const s={"Content-Type":"application/json","X-Session-ID":e,"X-API-Key":this.apiKey};try{const r=await fetch(`${this.apiUrl}/admin/chat-history/${e}`,{...this.getFetchOptions({method:"DELETE",headers:s})});if(!r.ok){const o=await r.text();throw new Error(`Failed to clear conversation history: ${r.status} ${o}`)}return await r.json()}catch(r){throw r.name==="TypeError"&&r.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):r}}async deleteConversationWithFiles(t,e){const s=t||this.sessionId;if(!s)throw new Error("No session ID provided and no current session available");if(!this.apiKey)throw new Error("API key is required for deleting conversation");const r={"Content-Type":"application/json","X-Session-ID":s,"X-API-Key":this.apiKey},n=e&&e.length>0?`?file_ids=${e.join(",")}`:"",o=`${this.apiUrl}/admin/conversations/${s}${n}`;try{const a=await fetch(o,{...this.getFetchOptions({method:"DELETE",headers:r})});if(!a.ok){const u=await a.text();throw new Error(`Failed to delete conversation: ${a.status} ${u}`)}return await a.json()}catch(a){throw a.name==="TypeError"&&a.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):a}}async uploadFile(t){if(!this.apiKey)throw new Error("API key is required for file upload");const e=new FormData;e.append("file",t);try{const s=await fetch(`${this.apiUrl}/api/files/upload`,{...this.getFetchOptions({method:"POST",body:e})});if(!s.ok){const r=await s.text();throw new Error(`Failed to upload file: ${s.status} ${r}`)}return await s.json()}catch(s){throw s.name==="TypeError"&&s.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):s}}async listFiles(){if(!this.apiKey)throw new Error("API key is required for listing files");try{const t=await fetch(`${this.apiUrl}/api/files`,{...this.getFetchOptions({method:"GET"})});if(!t.ok){const e=await t.text();throw new Error(`Failed to list files: ${t.status} ${e}`)}return await t.json()}catch(t){throw t.name==="TypeError"&&t.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):t}}async getFileInfo(t){if(!this.apiKey)throw new Error("API key is required for getting file info");try{const e=await fetch(`${this.apiUrl}/api/files/${t}`,{...this.getFetchOptions({method:"GET"})});if(!e.ok){const s=await e.text();throw new Error(`Failed to get file info: ${e.status} ${s}`)}return await e.json()}catch(e){throw e.name==="TypeError"&&e.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):e}}async queryFile(t,e,s=10){if(!this.apiKey)throw new Error("API key is required for querying files");try{const r=await fetch(`${this.apiUrl}/api/files/${t}/query`,{...this.getFetchOptions({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e,max_results:s})})});if(!r.ok){const n=await r.text();throw new Error(`Failed to query file: ${r.status} ${n}`)}return await r.json()}catch(r){throw r.name==="TypeError"&&r.message.includes("Failed to fetch")?new Error("Could not connect to the server. Please check if the server is running."):r}}async deleteFile(t){if(!this.apiKey)throw new Error("API key is required for deleting files");const e=`${this.apiUrl}/api/files/${t}`,s=this.getFetchOptions({method:"DELETE"});try{const r=await fetch(e,s);if(!r.ok){const o=await r.text();let a;try{const l=JSON.parse(o);a=l.detail||l.message||`Failed to delete file (HTTP ${r.status})`}catch{a=`Failed to delete file (HTTP ${r.status})`}throw console.warn(`[ApiClient] ${a}`),new Error(a)}return await r.json()}catch(r){let n;throw r.name==="TypeError"&&r.message.includes("Failed to fetch")?n="Could not connect to the server. Please check if the server is running.":r.message&&!r.message.includes("Failed to delete file")?n=r.message:n="Failed to delete file. Please try again.",console.warn(`[ApiClient] ${n}`),new Error(n)}}}let A=null;const q=(i,t=null,e=null)=>{A=new I({apiUrl:i,apiKey:t,sessionId:e})};async function*D(i,t=!0,e){if(!A)throw new Error("API not configured. Please call configureApi() with your server URL before using any API functions.");yield*A.streamChat(i,t,e)}exports.ApiClient=I;exports.configureApi=q;exports.streamChat=D;
3
3
  //# sourceMappingURL=api.cjs.map
package/dist/api.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.cjs","sources":["../api.ts"],"sourcesContent":["// For Node.js environments, we can use http.Agent for connection pooling\nlet httpAgent: any = null;\nlet httpsAgent: any = null;\n\n// Initialize agents for connection pooling in Node.js environments\nif (typeof window === 'undefined') {\n // Lazy load to avoid including 'http' in browser bundles\n Promise.all([\n import('http').catch(() => null),\n import('https').catch(() => null)\n ]).then(([http, https]) => {\n if (http?.default?.Agent) {\n httpAgent = new http.default.Agent({ keepAlive: true });\n } else if (http?.Agent) {\n httpAgent = new http.Agent({ keepAlive: true });\n }\n \n if (https?.default?.Agent) {\n httpsAgent = new https.default.Agent({ keepAlive: true });\n } else if (https?.Agent) {\n httpsAgent = new https.Agent({ keepAlive: true });\n }\n }).catch(err => {\n // Silently fail - connection pooling is optional\n console.warn('Failed to initialize HTTP agents:', err.message);\n });\n}\n\n// Define the StreamResponse interface\nexport interface StreamResponse {\n text: string;\n done: boolean;\n}\n\n// The server now returns this directly for non-streaming chat\nexport interface ChatResponse {\n response: string;\n sources?: any[];\n}\n\n// The request body for the /v1/chat endpoint\ninterface ChatRequest {\n messages: Array<{ role: string; content: string; }>;\n stream: boolean;\n}\n\nexport class ApiClient {\n private readonly apiUrl: string;\n private readonly apiKey: string | null;\n private sessionId: string | null; // Session ID can be mutable\n\n constructor(config: { apiUrl: string; apiKey?: string | null; sessionId?: string | null }) {\n if (!config.apiUrl || typeof config.apiUrl !== 'string') {\n throw new Error('API URL must be a valid string');\n }\n if (config.apiKey !== undefined && config.apiKey !== null && typeof config.apiKey !== 'string') {\n throw new Error('API key must be a valid string or null');\n }\n if (config.sessionId !== undefined && config.sessionId !== null && typeof config.sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n \n this.apiUrl = config.apiUrl;\n this.apiKey = config.apiKey ?? null;\n this.sessionId = config.sessionId ?? null;\n }\n\n public setSessionId(sessionId: string | null): void {\n if (sessionId !== null && typeof sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n this.sessionId = sessionId;\n }\n\n public getSessionId(): string | null {\n return this.sessionId;\n }\n\n // Helper to get fetch options with connection pooling if available\n private getFetchOptions(options: RequestInit = {}): RequestInit {\n const baseOptions: RequestInit = {};\n \n // Environment-specific options\n if (typeof window === 'undefined') {\n // Node.js: Use connection pooling agent\n const isHttps = this.apiUrl.startsWith('https:');\n const agent = isHttps ? httpsAgent : httpAgent;\n if (agent) {\n (baseOptions as any).agent = agent;\n }\n } else {\n // Browser: Use keep-alive header\n baseOptions.headers = { 'Connection': 'keep-alive' };\n }\n\n // Common headers\n const headers: Record<string, string> = {\n 'X-Request-ID': Date.now().toString(36) + Math.random().toString(36).substring(2),\n };\n\n // Merge base options headers (for browser keep-alive)\n if (baseOptions.headers) {\n Object.assign(headers, baseOptions.headers);\n }\n\n // Merge original request headers\n if (options.headers) {\n Object.assign(headers, options.headers);\n }\n\n if (this.apiKey) {\n headers['X-API-Key'] = this.apiKey;\n }\n\n if (this.sessionId) {\n headers['X-Session-ID'] = this.sessionId;\n }\n\n return {\n ...options,\n ...baseOptions,\n headers,\n };\n }\n\n // Create Chat request\n private createChatRequest(message: string, stream: boolean = true): ChatRequest {\n return {\n messages: [\n { role: \"user\", content: message }\n ],\n stream\n };\n }\n\n public async *streamChat(\n message: string,\n stream: boolean = true\n ): AsyncGenerator<StreamResponse> {\n try {\n // Add timeout to the fetch request\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 second timeout\n\n const response = await fetch(`${this.apiUrl}/v1/chat`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': stream ? 'text/event-stream' : 'application/json'\n },\n body: JSON.stringify(this.createChatRequest(message, stream)),\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Network response was not ok: ${response.status} ${errorText}`);\n }\n\n if (!stream) {\n // Handle non-streaming response\n const data = await response.json() as ChatResponse;\n if (data.response) {\n yield {\n text: data.response,\n done: true\n };\n }\n return;\n }\n \n const reader = response.body?.getReader();\n if (!reader) throw new Error('No reader available');\n\n const decoder = new TextDecoder();\n let buffer = '';\n let hasReceivedContent = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n \n // Process complete lines immediately as they arrive\n let lineStartIndex = 0;\n let newlineIndex;\n \n while ((newlineIndex = buffer.indexOf('\\n', lineStartIndex)) !== -1) {\n const line = buffer.slice(lineStartIndex, newlineIndex).trim();\n lineStartIndex = newlineIndex + 1;\n \n if (line && line.startsWith('data: ')) {\n const jsonText = line.slice(6).trim();\n \n if (!jsonText || jsonText === '[DONE]') {\n yield { text: '', done: true };\n return;\n }\n\n try {\n const data = JSON.parse(jsonText);\n \n if (data.error) {\n throw new Error(`Server Error: ${data.error.message}`);\n }\n \n if (data.response) {\n hasReceivedContent = true;\n yield { text: data.response, done: data.done || false };\n }\n\n if (data.done) {\n yield { text: '', done: true };\n return;\n }\n \n } catch (parseError) {\n console.warn('Error parsing JSON chunk:', parseError, 'Chunk:', jsonText);\n }\n } else if (line) {\n // Handle raw text chunks that are not in SSE format\n hasReceivedContent = true;\n yield { text: line, done: false };\n }\n }\n \n buffer = buffer.slice(lineStartIndex);\n \n if (buffer.length > 1000000) { // 1MB limit\n console.warn('Buffer too large, truncating...');\n buffer = buffer.slice(-500000); // Keep last 500KB\n }\n }\n \n if (hasReceivedContent) {\n yield { text: '', done: true };\n }\n \n } finally {\n reader.releaseLock();\n }\n \n } catch (error: any) {\n if (error.name === 'AbortError') {\n throw new Error('Connection timed out. Please check if the server is running.');\n } else if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n}\n\n// Legacy compatibility functions - these create a default client instance\n// These are kept for backward compatibility but should be deprecated in favor of the class-based approach\n\nlet defaultClient: ApiClient | null = null;\n\n// Configure the API with a custom URL, API key (optional), and session ID (optional)\nexport const configureApi = (apiUrl: string, apiKey: string | null = null, sessionId: string | null = null): void => {\n defaultClient = new ApiClient({ apiUrl, apiKey, sessionId });\n}\n\n// Legacy streamChat function that uses the default client\nexport async function* streamChat(\n message: string,\n stream: boolean = true\n): AsyncGenerator<StreamResponse> {\n if (!defaultClient) {\n throw new Error('API not configured. Please call configureApi() with your server URL before using any API functions.');\n }\n \n yield* defaultClient.streamChat(message, stream);\n}\n"],"names":["httpAgent","httpsAgent","http","https","_a","_b","err","ApiClient","config","__publicField","sessionId","options","baseOptions","agent","headers","message","stream","controller","timeoutId","response","errorText","data","reader","decoder","buffer","hasReceivedContent","done","value","chunk","lineStartIndex","newlineIndex","line","jsonText","parseError","error","defaultClient","configureApi","apiUrl","apiKey","streamChat"],"mappings":"mqBACA,IAAIA,EAAiB,KACjBC,EAAkB,KAGlB,O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,QAAQ,KAAK,4BAA6BA,EAAY,SAAUD,CAAQ,CAC1E,CACF,MAAWD,IAEPN,EAAqB,GACrB,KAAM,CAAE,KAAMM,EAAM,KAAM,EAAA,EAEhC,CAEAP,EAASA,EAAO,MAAMK,CAAc,EAEhCL,EAAO,OAAS,MAClB,QAAQ,KAAK,iCAAiC,EAC9CA,EAASA,EAAO,MAAM,IAAO,EAEjC,CAEIC,IACF,KAAM,CAAE,KAAM,GAAI,KAAM,EAAA,EAG5B,QAAA,CACEH,EAAO,YAAA,CACT,CAEF,OAASY,EAAY,CACnB,MAAIA,EAAM,OAAS,aACX,IAAI,MAAM,8DAA8D,EACrEA,EAAM,OAAS,aAAeA,EAAM,QAAQ,SAAS,iBAAiB,EACzE,IAAI,MAAM,yEAAyE,EAEnFA,CAEV,CACF,CACF,CAKA,IAAIC,EAAkC,KAG/B,MAAMC,EAAe,CAACC,EAAgBC,EAAwB,KAAM5B,EAA2B,OAAe,CACnHyB,EAAgB,IAAI5B,EAAU,CAAE,OAAA8B,EAAQ,OAAAC,EAAQ,UAAA5B,EAAW,CAC7D,EAGA,eAAuB6B,EACrBxB,EACAC,EAAkB,GACc,CAChC,GAAI,CAACmB,EACH,MAAM,IAAI,MAAM,qGAAqG,EAGvH,MAAOA,EAAc,WAAWpB,EAASC,CAAM,CACjD"}
1
+ {"version":3,"file":"api.cjs","sources":["../api.ts"],"sourcesContent":["// For Node.js environments, we can use http.Agent for connection pooling\nlet httpAgent: any = null;\nlet httpsAgent: any = null;\n\n// Initialize agents for connection pooling in Node.js environments\nif (typeof window === 'undefined') {\n // Lazy load to avoid including 'http' in browser bundles\n Promise.all([\n import('http').catch(() => null),\n import('https').catch(() => null)\n ]).then(([http, https]) => {\n if (http?.default?.Agent) {\n httpAgent = new http.default.Agent({ keepAlive: true });\n } else if (http?.Agent) {\n httpAgent = new http.Agent({ keepAlive: true });\n }\n \n if (https?.default?.Agent) {\n httpsAgent = new https.default.Agent({ keepAlive: true });\n } else if (https?.Agent) {\n httpsAgent = new https.Agent({ keepAlive: true });\n }\n }).catch(err => {\n // Silently fail - connection pooling is optional\n console.warn('Failed to initialize HTTP agents:', err.message);\n });\n}\n\n// Define the StreamResponse interface\nexport interface StreamResponse {\n text: string;\n done: boolean;\n}\n\n// The server now returns this directly for non-streaming chat\nexport interface ChatResponse {\n response: string;\n sources?: any[];\n}\n\n// The request body for the /v1/chat endpoint\ninterface ChatRequest {\n messages: Array<{ role: string; content: string; }>;\n stream: boolean;\n file_ids?: string[]; // Optional list of file IDs for file context\n}\n\n// File-related interfaces\nexport interface FileUploadResponse {\n file_id: string;\n filename: string;\n mime_type: string;\n file_size: number;\n status: string;\n chunk_count: number;\n message: string;\n}\n\nexport interface FileInfo {\n file_id: string;\n filename: string;\n mime_type: string;\n file_size: number;\n upload_timestamp: string;\n processing_status: string;\n chunk_count: number;\n storage_type: string;\n}\n\nexport interface FileQueryRequest {\n query: string;\n max_results?: number;\n}\n\nexport interface FileQueryResponse {\n file_id: string;\n filename: string;\n results: Array<{\n content: string;\n metadata: {\n chunk_id: string;\n file_id: string;\n chunk_index: number;\n confidence: number;\n };\n }>;\n}\n\n// API key status interface\nexport interface ApiKeyStatus {\n exists: boolean;\n active: boolean;\n adapter_name?: string | null;\n client_name?: string | null;\n created_at?: string | number | null;\n system_prompt?: {\n id: string;\n exists: boolean;\n } | null;\n message?: string;\n}\n\n// Adapter information interface\nexport interface AdapterInfo {\n client_name: string;\n adapter_name: string;\n model: string | null;\n}\n\nexport class ApiClient {\n private readonly apiUrl: string;\n private readonly apiKey: string | null;\n private sessionId: string | null; // Session ID can be mutable\n\n constructor(config: { apiUrl: string; apiKey?: string | null; sessionId?: string | null }) {\n if (!config.apiUrl || typeof config.apiUrl !== 'string') {\n throw new Error('API URL must be a valid string');\n }\n if (config.apiKey !== undefined && config.apiKey !== null && typeof config.apiKey !== 'string') {\n throw new Error('API key must be a valid string or null');\n }\n if (config.sessionId !== undefined && config.sessionId !== null && typeof config.sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n \n this.apiUrl = config.apiUrl;\n this.apiKey = config.apiKey ?? null;\n this.sessionId = config.sessionId ?? null;\n }\n\n public setSessionId(sessionId: string | null): void {\n if (sessionId !== null && typeof sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n this.sessionId = sessionId;\n }\n\n public getSessionId(): string | null {\n return this.sessionId;\n }\n\n /**\n * Validate that the API key exists and is active.\n *\n * @returns Promise resolving to API key status information\n * @throws Error if API key is not provided, invalid, inactive, or validation fails\n */\n public async validateApiKey(): Promise<ApiKeyStatus> {\n if (!this.apiKey) {\n throw new Error('API key is required for validation');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/api-keys/${this.apiKey}/status`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n }).catch((fetchError: any) => {\n // Catch network errors before they bubble up\n if (fetchError.name === 'TypeError' && fetchError.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n }\n throw fetchError;\n });\n\n if (!response.ok) {\n // Read error response body\n let errorText = '';\n try {\n errorText = await response.text();\n } catch {\n // If we can't read the body, fall back to status code\n errorText = `HTTP ${response.status}`;\n }\n\n let errorDetail: string;\n let friendlyMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorDetail = errorJson.detail || errorJson.message || errorText;\n } catch {\n // If parsing fails, use the error text or status code\n errorDetail = errorText || `HTTP ${response.status}`;\n }\n\n // Generate user-friendly error messages based on HTTP status code\n switch (response.status) {\n case 401:\n friendlyMessage = 'API key is invalid or expired';\n break;\n case 403:\n friendlyMessage = 'Access denied: API key does not have required permissions';\n break;\n case 404:\n friendlyMessage = 'API key not found';\n break;\n case 503:\n friendlyMessage = 'API key management is not available in inference-only mode';\n break;\n default:\n friendlyMessage = `Failed to validate API key: ${errorDetail}`;\n break;\n }\n\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n const status: ApiKeyStatus = await response.json();\n\n // Check if the key exists\n if (!status.exists) {\n const friendlyMessage = 'API key does not exist';\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n // Check if the key is active\n if (!status.active) {\n const friendlyMessage = 'API key is inactive';\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n return status;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n\n if (error instanceof Error && error.message) {\n // If it's already a user-friendly Error from above, use it directly\n if (error.message.includes('API key') ||\n error.message.includes('Access denied') ||\n error.message.includes('invalid') ||\n error.message.includes('expired') ||\n error.message.includes('inactive') ||\n error.message.includes('not found') ||\n error.message.includes('Could not connect')) {\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `API key validation failed: ${error.message}`;\n }\n } else if (error.name === 'TypeError' && error.message?.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else {\n friendlyMessage = 'API key validation failed. Please check your API key and try again.';\n }\n\n // Only log warning if it's not a network error (those are already logged by browser)\n // For validation errors, we log once with a friendly message\n // Note: Browser will still log HTTP errors (401, 404, etc.) - this is unavoidable\n console.warn(`[ApiClient] ${friendlyMessage}`);\n\n // Throw the friendly error message\n throw new Error(friendlyMessage);\n }\n }\n\n /**\n * Get adapter information for the current API key.\n *\n * Returns information about the adapter and model being used by the API key.\n * This is useful for displaying configuration details to users.\n *\n * @returns Promise resolving to adapter information\n * @throws Error if API key is not provided, invalid, disabled, or request fails\n */\n public async getAdapterInfo(): Promise<AdapterInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required to get adapter information');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/api-keys/info`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n }).catch((fetchError: any) => {\n // Catch network errors before they bubble up\n if (fetchError.name === 'TypeError' && fetchError.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n }\n throw fetchError;\n });\n\n if (!response.ok) {\n // Read error response body\n let errorText = '';\n try {\n errorText = await response.text();\n } catch {\n // If we can't read the body, fall back to status code\n errorText = `HTTP ${response.status}`;\n }\n\n let errorDetail: string;\n let friendlyMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorDetail = errorJson.detail || errorJson.message || errorText;\n } catch {\n // If parsing fails, use the error text or status code\n errorDetail = errorText || `HTTP ${response.status}`;\n }\n\n // Generate user-friendly error messages based on HTTP status code\n switch (response.status) {\n case 401:\n friendlyMessage = 'API key is invalid, disabled, or has no associated adapter';\n break;\n case 404:\n friendlyMessage = 'Adapter configuration not found';\n break;\n case 503:\n friendlyMessage = 'Service is not available';\n break;\n default:\n friendlyMessage = `Failed to get adapter info: ${errorDetail}`;\n break;\n }\n\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n const adapterInfo: AdapterInfo = await response.json();\n return adapterInfo;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n\n if (error instanceof Error && error.message) {\n // If it's already a user-friendly Error from above, use it directly\n if (error.message.includes('API key') ||\n error.message.includes('Adapter') ||\n error.message.includes('invalid') ||\n error.message.includes('disabled') ||\n error.message.includes('not found') ||\n error.message.includes('Could not connect')) {\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `Failed to get adapter info: ${error.message}`;\n }\n } else if (error.name === 'TypeError' && error.message?.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else {\n friendlyMessage = 'Failed to get adapter information. Please try again.';\n }\n\n console.warn(`[ApiClient] ${friendlyMessage}`);\n\n // Throw the friendly error message\n throw new Error(friendlyMessage);\n }\n }\n\n // Helper to get fetch options with connection pooling if available\n private getFetchOptions(options: RequestInit = {}): RequestInit {\n const baseOptions: RequestInit = {};\n \n // Environment-specific options\n if (typeof window === 'undefined') {\n // Node.js: Use connection pooling agent\n const isHttps = this.apiUrl.startsWith('https:');\n const agent = isHttps ? httpsAgent : httpAgent;\n if (agent) {\n (baseOptions as any).agent = agent;\n }\n } else {\n // Browser: Use keep-alive header\n baseOptions.headers = { 'Connection': 'keep-alive' };\n }\n\n // Common headers\n const headers: Record<string, string> = {\n 'X-Request-ID': Date.now().toString(36) + Math.random().toString(36).substring(2),\n };\n\n // Merge base options headers (for browser keep-alive)\n if (baseOptions.headers) {\n Object.assign(headers, baseOptions.headers);\n }\n\n // Merge original request headers (but don't overwrite API key)\n if (options.headers) {\n const incomingHeaders = options.headers as Record<string, string>;\n for (const [key, value] of Object.entries(incomingHeaders)) {\n // Don't overwrite X-API-Key if we have one\n if (key.toLowerCase() !== 'x-api-key' || !this.apiKey) {\n headers[key] = value;\n }\n }\n }\n\n if (this.apiKey) {\n headers['X-API-Key'] = this.apiKey;\n }\n\n if (this.sessionId) {\n headers['X-Session-ID'] = this.sessionId;\n }\n\n return {\n ...options,\n ...baseOptions,\n headers,\n };\n }\n\n // Create Chat request\n private createChatRequest(message: string, stream: boolean = true, fileIds?: string[]): ChatRequest {\n const request: ChatRequest = {\n messages: [\n { role: \"user\", content: message }\n ],\n stream\n };\n if (fileIds && fileIds.length > 0) {\n request.file_ids = fileIds;\n }\n return request;\n }\n\n public async *streamChat(\n message: string,\n stream: boolean = true,\n fileIds?: string[]\n ): AsyncGenerator<StreamResponse> {\n try {\n // Add timeout to the fetch request\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 second timeout\n\n const response = await fetch(`${this.apiUrl}/v1/chat`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': stream ? 'text/event-stream' : 'application/json'\n },\n body: JSON.stringify(this.createChatRequest(message, stream, fileIds)),\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Network response was not ok: ${response.status} ${errorText}`);\n }\n\n if (!stream) {\n // Handle non-streaming response\n const data = await response.json() as ChatResponse;\n if (data.response) {\n yield {\n text: data.response,\n done: true\n };\n }\n return;\n }\n \n const reader = response.body?.getReader();\n if (!reader) throw new Error('No reader available');\n\n const decoder = new TextDecoder();\n let buffer = '';\n let hasReceivedContent = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n \n // Process complete lines immediately as they arrive\n let lineStartIndex = 0;\n let newlineIndex;\n \n while ((newlineIndex = buffer.indexOf('\\n', lineStartIndex)) !== -1) {\n const line = buffer.slice(lineStartIndex, newlineIndex).trim();\n lineStartIndex = newlineIndex + 1;\n \n if (line && line.startsWith('data: ')) {\n const jsonText = line.slice(6).trim();\n \n if (!jsonText || jsonText === '[DONE]') {\n yield { text: '', done: true };\n return;\n }\n\n try {\n const data = JSON.parse(jsonText);\n \n if (data.error) {\n const errorMessage = data.error?.message || data.error || 'Unknown server error';\n const friendlyMessage = `Server error: ${errorMessage}`;\n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n \n if (data.response) {\n hasReceivedContent = true;\n yield { text: data.response, done: data.done || false };\n }\n\n if (data.done) {\n yield { text: '', done: true };\n return;\n }\n \n } catch (parseError) {\n // Only log parse errors in debug scenarios, with friendly message\n console.warn('[ApiClient] Unable to parse server response. This may be a temporary issue.');\n }\n } else if (line) {\n // Handle raw text chunks that are not in SSE format\n hasReceivedContent = true;\n yield { text: line, done: false };\n }\n }\n \n buffer = buffer.slice(lineStartIndex);\n \n if (buffer.length > 1000000) { // 1MB limit\n console.warn('Buffer too large, truncating...');\n buffer = buffer.slice(-500000); // Keep last 500KB\n }\n }\n \n if (hasReceivedContent) {\n yield { text: '', done: true };\n }\n \n } finally {\n reader.releaseLock();\n }\n \n } catch (error: any) {\n if (error.name === 'AbortError') {\n throw new Error('Connection timed out. Please check if the server is running.');\n } else if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async clearConversationHistory(sessionId?: string): Promise<{\n status: string;\n message: string;\n session_id: string;\n deleted_count: number;\n timestamp: string;\n }> {\n /**\n * Clear conversation history for a session.\n *\n * @param sessionId - Optional session ID to clear. If not provided, uses current session.\n * @returns Promise resolving to operation result\n * @throws Error if the operation fails\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n if (!this.apiKey) {\n throw new Error('API key is required for clearing conversation history');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Session-ID': targetSessionId,\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/chat-history/${targetSessionId}`, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to clear conversation history: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async deleteConversationWithFiles(sessionId?: string, fileIds?: string[]): Promise<{\n status: string;\n message: string;\n session_id: string;\n deleted_messages: number;\n deleted_files: number;\n file_deletion_errors: string[] | null;\n timestamp: string;\n }> {\n /**\n * Delete a conversation and all associated files.\n *\n * This method performs a complete conversation deletion:\n * - Deletes each file provided in fileIds (metadata, content, and vector store chunks)\n * - Clears conversation history\n *\n * File tracking is managed by the frontend (localStorage). The backend is stateless\n * and requires fileIds to be provided explicitly.\n *\n * @param sessionId - Optional session ID to delete. If not provided, uses current session.\n * @param fileIds - Optional list of file IDs to delete (from conversation's attachedFiles)\n * @returns Promise resolving to deletion result with counts\n * @throws Error if the operation fails\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n if (!this.apiKey) {\n throw new Error('API key is required for deleting conversation');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Session-ID': targetSessionId,\n 'X-API-Key': this.apiKey\n };\n\n // Build URL with file_ids query parameter\n const fileIdsParam = fileIds && fileIds.length > 0 ? `?file_ids=${fileIds.join(',')}` : '';\n const url = `${this.apiUrl}/admin/conversations/${targetSessionId}${fileIdsParam}`;\n\n try {\n const response = await fetch(url, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to delete conversation: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Upload a file for processing and indexing.\n *\n * @param file - The file to upload\n * @returns Promise resolving to upload response with file_id\n * @throws Error if upload fails\n */\n public async uploadFile(file: File): Promise<FileUploadResponse> {\n if (!this.apiKey) {\n throw new Error('API key is required for file upload');\n }\n\n const formData = new FormData();\n formData.append('file', file);\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/upload`, {\n ...this.getFetchOptions({\n method: 'POST',\n body: formData\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to upload file: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * List all files for the current API key.\n * \n * @returns Promise resolving to list of file information\n * @throws Error if request fails\n */\n public async listFiles(): Promise<FileInfo[]> {\n if (!this.apiKey) {\n throw new Error('API key is required for listing files');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to list files: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get information about a specific file.\n * \n * @param fileId - The file ID\n * @returns Promise resolving to file information\n * @throws Error if file not found or request fails\n */\n public async getFileInfo(fileId: string): Promise<FileInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required for getting file info');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/${fileId}`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get file info: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Query a specific file using semantic search.\n * \n * @param fileId - The file ID\n * @param query - The search query\n * @param maxResults - Maximum number of results (default: 10)\n * @returns Promise resolving to query results\n * @throws Error if query fails\n */\n public async queryFile(fileId: string, query: string, maxResults: number = 10): Promise<FileQueryResponse> {\n if (!this.apiKey) {\n throw new Error('API key is required for querying files');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/${fileId}/query`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ query, max_results: maxResults })\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to query file: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Delete a specific file.\n * \n * @param fileId - The file ID\n * @returns Promise resolving to deletion result\n * @throws Error if deletion fails\n */\n public async deleteFile(fileId: string): Promise<{ message: string; file_id: string }> {\n if (!this.apiKey) {\n throw new Error('API key is required for deleting files');\n }\n\n const url = `${this.apiUrl}/api/files/${fileId}`;\n const fetchOptions = this.getFetchOptions({\n method: 'DELETE'\n });\n\n try {\n const response = await fetch(url, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n let friendlyMessage: string;\n try {\n const errorJson = JSON.parse(errorText);\n friendlyMessage = errorJson.detail || errorJson.message || `Failed to delete file (HTTP ${response.status})`;\n } catch {\n friendlyMessage = `Failed to delete file (HTTP ${response.status})`;\n }\n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n\n const result = await response.json();\n return result;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n \n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else if (error.message && !error.message.includes('Failed to delete file')) {\n // Use existing message if it's already user-friendly\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `Failed to delete file. Please try again.`;\n }\n \n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n }\n}\n\n// Legacy compatibility functions - these create a default client instance\n// These are kept for backward compatibility but should be deprecated in favor of the class-based approach\n\nlet defaultClient: ApiClient | null = null;\n\n// Configure the API with a custom URL, API key (optional), and session ID (optional)\nexport const configureApi = (apiUrl: string, apiKey: string | null = null, sessionId: string | null = null): void => {\n defaultClient = new ApiClient({ apiUrl, apiKey, sessionId });\n}\n\n// Legacy streamChat function that uses the default client\nexport async function* streamChat(\n message: string,\n stream: boolean = true,\n fileIds?: string[]\n): AsyncGenerator<StreamResponse> {\n if (!defaultClient) {\n throw new Error('API not configured. Please call configureApi() with your server URL before using any API functions.');\n }\n \n yield* defaultClient.streamChat(message, stream, fileIds);\n}\n\n"],"names":["httpAgent","httpsAgent","http","https","_a","_b","err","ApiClient","config","__publicField","sessionId","response","fetchError","errorText","errorDetail","friendlyMessage","errorJson","status","error","options","baseOptions","agent","headers","incomingHeaders","key","value","message","stream","fileIds","request","controller","timeoutId","data","reader","decoder","buffer","hasReceivedContent","done","chunk","lineStartIndex","newlineIndex","line","jsonText","targetSessionId","fileIdsParam","url","file","formData","fileId","query","maxResults","fetchOptions","defaultClient","configureApi","apiUrl","apiKey","streamChat"],"mappings":"mqBACA,IAAIA,EAAiB,KACjBC,EAAkB,KAGlB,OAAO,OAAW,KAEpB,QAAQ,IAAI,CACV,OAAO,MAAM,EAAE,MAAM,IAAM,IAAI,EAC/B,OAAO,OAAO,EAAE,MAAM,IAAM,IAAI,CAAA,CACjC,EAAE,KAAK,CAAC,CAACC,EAAMC,CAAK,IAAM,UACrBC,EAAAF,GAAA,YAAAA,EAAM,UAAN,MAAAE,EAAe,MACjBJ,EAAY,IAAIE,EAAK,QAAQ,MAAM,CAAE,UAAW,GAAM,EAC7CA,GAAA,MAAAA,EAAM,QACfF,EAAY,IAAIE,EAAK,MAAM,CAAE,UAAW,GAAM,IAG5CG,EAAAF,GAAA,YAAAA,EAAO,UAAP,MAAAE,EAAgB,MAClBJ,EAAa,IAAIE,EAAM,QAAQ,MAAM,CAAE,UAAW,GAAM,EAC/CA,GAAA,MAAAA,EAAO,QAChBF,EAAa,IAAIE,EAAM,MAAM,CAAE,UAAW,GAAM,EAEpD,CAAC,EAAE,MAAMG,GAAO,CAEd,QAAQ,KAAK,oCAAqCA,EAAI,OAAO,CAC/D,CAAC,EAoFI,MAAMC,CAAU,CAKrB,YAAYC,EAA+E,CAJ1EC,EAAA,eACAA,EAAA,eACTA,EAAA,kBAGN,GAAI,CAACD,EAAO,QAAU,OAAOA,EAAO,QAAW,SAC7C,MAAM,IAAI,MAAM,gCAAgC,EAElD,GAAIA,EAAO,SAAW,QAAaA,EAAO,SAAW,MAAQ,OAAOA,EAAO,QAAW,SACpF,MAAM,IAAI,MAAM,wCAAwC,EAE1D,GAAIA,EAAO,YAAc,QAAaA,EAAO,YAAc,MAAQ,OAAOA,EAAO,WAAc,SAC7F,MAAM,IAAI,MAAM,2C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,EAAkBG,EAAM,QAExBH,EAAkB,2CAGpB,QAAQ,KAAK,eAAeA,CAAe,EAAE,EACvC,IAAI,MAAMA,CAAe,CACjC,CACF,CACF,CAKA,IAAIqC,EAAkC,KAG/B,MAAMC,EAAe,CAACC,EAAgBC,EAAwB,KAAM7C,EAA2B,OAAe,CACnH0C,EAAgB,IAAI7C,EAAU,CAAE,OAAA+C,EAAQ,OAAAC,EAAQ,UAAA7C,EAAW,CAC7D,EAGA,eAAuB8C,EACrB9B,EACAC,EAAkB,GAClBC,EACgC,CAChC,GAAI,CAACwB,EACH,MAAM,IAAI,MAAM,qGAAqG,EAGvH,MAAOA,EAAc,WAAW1B,EAASC,EAAQC,CAAO,CAC1D"}
package/dist/api.d.ts CHANGED
@@ -6,6 +6,59 @@ export interface ChatResponse {
6
6
  response: string;
7
7
  sources?: any[];
8
8
  }
9
+ export interface FileUploadResponse {
10
+ file_id: string;
11
+ filename: string;
12
+ mime_type: string;
13
+ file_size: number;
14
+ status: string;
15
+ chunk_count: number;
16
+ message: string;
17
+ }
18
+ export interface FileInfo {
19
+ file_id: string;
20
+ filename: string;
21
+ mime_type: string;
22
+ file_size: number;
23
+ upload_timestamp: string;
24
+ processing_status: string;
25
+ chunk_count: number;
26
+ storage_type: string;
27
+ }
28
+ export interface FileQueryRequest {
29
+ query: string;
30
+ max_results?: number;
31
+ }
32
+ export interface FileQueryResponse {
33
+ file_id: string;
34
+ filename: string;
35
+ results: Array<{
36
+ content: string;
37
+ metadata: {
38
+ chunk_id: string;
39
+ file_id: string;
40
+ chunk_index: number;
41
+ confidence: number;
42
+ };
43
+ }>;
44
+ }
45
+ export interface ApiKeyStatus {
46
+ exists: boolean;
47
+ active: boolean;
48
+ adapter_name?: string | null;
49
+ client_name?: string | null;
50
+ created_at?: string | number | null;
51
+ system_prompt?: {
52
+ id: string;
53
+ exists: boolean;
54
+ } | null;
55
+ message?: string;
56
+ }
57
+ export interface AdapterInfo {
58
+ client_name: string;
59
+ adapter_name: string;
60
+ model: string | null;
61
+ }
9
62
  export declare class ApiClient {
10
63
  private readonly apiUrl;
11
64
  private readonly apiKey;
@@ -17,9 +70,86 @@ export declare class ApiClient {
17
70
  });
18
71
  setSessionId(sessionId: string | null): void;
19
72
  getSessionId(): string | null;
73
+ /**
74
+ * Validate that the API key exists and is active.
75
+ *
76
+ * @returns Promise resolving to API key status information
77
+ * @throws Error if API key is not provided, invalid, inactive, or validation fails
78
+ */
79
+ validateApiKey(): Promise<ApiKeyStatus>;
80
+ /**
81
+ * Get adapter information for the current API key.
82
+ *
83
+ * Returns information about the adapter and model being used by the API key.
84
+ * This is useful for displaying configuration details to users.
85
+ *
86
+ * @returns Promise resolving to adapter information
87
+ * @throws Error if API key is not provided, invalid, disabled, or request fails
88
+ */
89
+ getAdapterInfo(): Promise<AdapterInfo>;
20
90
  private getFetchOptions;
21
91
  private createChatRequest;
22
- streamChat(message: string, stream?: boolean): AsyncGenerator<StreamResponse>;
92
+ streamChat(message: string, stream?: boolean, fileIds?: string[]): AsyncGenerator<StreamResponse>;
93
+ clearConversationHistory(sessionId?: string): Promise<{
94
+ status: string;
95
+ message: string;
96
+ session_id: string;
97
+ deleted_count: number;
98
+ timestamp: string;
99
+ }>;
100
+ deleteConversationWithFiles(sessionId?: string, fileIds?: string[]): Promise<{
101
+ status: string;
102
+ message: string;
103
+ session_id: string;
104
+ deleted_messages: number;
105
+ deleted_files: number;
106
+ file_deletion_errors: string[] | null;
107
+ timestamp: string;
108
+ }>;
109
+ /**
110
+ * Upload a file for processing and indexing.
111
+ *
112
+ * @param file - The file to upload
113
+ * @returns Promise resolving to upload response with file_id
114
+ * @throws Error if upload fails
115
+ */
116
+ uploadFile(file: File): Promise<FileUploadResponse>;
117
+ /**
118
+ * List all files for the current API key.
119
+ *
120
+ * @returns Promise resolving to list of file information
121
+ * @throws Error if request fails
122
+ */
123
+ listFiles(): Promise<FileInfo[]>;
124
+ /**
125
+ * Get information about a specific file.
126
+ *
127
+ * @param fileId - The file ID
128
+ * @returns Promise resolving to file information
129
+ * @throws Error if file not found or request fails
130
+ */
131
+ getFileInfo(fileId: string): Promise<FileInfo>;
132
+ /**
133
+ * Query a specific file using semantic search.
134
+ *
135
+ * @param fileId - The file ID
136
+ * @param query - The search query
137
+ * @param maxResults - Maximum number of results (default: 10)
138
+ * @returns Promise resolving to query results
139
+ * @throws Error if query fails
140
+ */
141
+ queryFile(fileId: string, query: string, maxResults?: number): Promise<FileQueryResponse>;
142
+ /**
143
+ * Delete a specific file.
144
+ *
145
+ * @param fileId - The file ID
146
+ * @returns Promise resolving to deletion result
147
+ * @throws Error if deletion fails
148
+ */
149
+ deleteFile(fileId: string): Promise<{
150
+ message: string;
151
+ file_id: string;
152
+ }>;
23
153
  }
24
154
  export declare const configureApi: (apiUrl: string, apiKey?: string | null, sessionId?: string | null) => void;
25
- export declare function streamChat(message: string, stream?: boolean): AsyncGenerator<StreamResponse>;
155
+ export declare function streamChat(message: string, stream?: boolean, fileIds?: string[]): AsyncGenerator<StreamResponse>;
package/dist/api.mjs CHANGED
@@ -1,147 +1,472 @@
1
- var k = Object.defineProperty;
2
- var E = (t, e, r) => e in t ? k(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
- var w = (t, e, r) => E(t, typeof e != "symbol" ? e + "" : e, r);
4
- let p = null, A = null;
1
+ var $ = Object.defineProperty;
2
+ var F = (o, t, e) => t in o ? $(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
+ var y = (o, t, e) => F(o, typeof t != "symbol" ? t + "" : t, e);
4
+ let v = null, k = null;
5
5
  typeof window > "u" && Promise.all([
6
6
  import("http").catch(() => null),
7
7
  import("https").catch(() => null)
8
- ]).then(([t, e]) => {
9
- var r, n;
10
- (r = t == null ? void 0 : t.default) != null && r.Agent ? p = new t.default.Agent({ keepAlive: !0 }) : t != null && t.Agent && (p = new t.Agent({ keepAlive: !0 })), (n = e == null ? void 0 : e.default) != null && n.Agent ? A = new e.default.Agent({ keepAlive: !0 }) : e != null && e.Agent && (A = new e.Agent({ keepAlive: !0 }));
11
- }).catch((t) => {
12
- console.warn("Failed to initialize HTTP agents:", t.message);
8
+ ]).then(([o, t]) => {
9
+ var e, s;
10
+ (e = o == null ? void 0 : o.default) != null && e.Agent ? v = new o.default.Agent({ keepAlive: !0 }) : o != null && o.Agent && (v = new o.Agent({ keepAlive: !0 })), (s = t == null ? void 0 : t.default) != null && s.Agent ? k = new t.default.Agent({ keepAlive: !0 }) : t != null && t.Agent && (k = new t.Agent({ keepAlive: !0 }));
11
+ }).catch((o) => {
12
+ console.warn("Failed to initialize HTTP agents:", o.message);
13
13
  });
14
14
  class x {
15
15
  // Session ID can be mutable
16
- constructor(e) {
17
- w(this, "apiUrl");
18
- w(this, "apiKey");
19
- w(this, "sessionId");
20
- if (!e.apiUrl || typeof e.apiUrl != "string")
16
+ constructor(t) {
17
+ y(this, "apiUrl");
18
+ y(this, "apiKey");
19
+ y(this, "sessionId");
20
+ if (!t.apiUrl || typeof t.apiUrl != "string")
21
21
  throw new Error("API URL must be a valid string");
22
- if (e.apiKey !== void 0 && e.apiKey !== null && typeof e.apiKey != "string")
22
+ if (t.apiKey !== void 0 && t.apiKey !== null && typeof t.apiKey != "string")
23
23
  throw new Error("API key must be a valid string or null");
24
- if (e.sessionId !== void 0 && e.sessionId !== null && typeof e.sessionId != "string")
24
+ if (t.sessionId !== void 0 && t.sessionId !== null && typeof t.sessionId != "string")
25
25
  throw new Error("Session ID must be a valid string or null");
26
- this.apiUrl = e.apiUrl, this.apiKey = e.apiKey ?? null, this.sessionId = e.sessionId ?? null;
26
+ this.apiUrl = t.apiUrl, this.apiKey = t.apiKey ?? null, this.sessionId = t.sessionId ?? null;
27
27
  }
28
- setSessionId(e) {
29
- if (e !== null && typeof e != "string")
28
+ setSessionId(t) {
29
+ if (t !== null && typeof t != "string")
30
30
  throw new Error("Session ID must be a valid string or null");
31
- this.sessionId = e;
31
+ this.sessionId = t;
32
32
  }
33
33
  getSessionId() {
34
34
  return this.sessionId;
35
35
  }
36
+ /**
37
+ * Validate that the API key exists and is active.
38
+ *
39
+ * @returns Promise resolving to API key status information
40
+ * @throws Error if API key is not provided, invalid, inactive, or validation fails
41
+ */
42
+ async validateApiKey() {
43
+ var t;
44
+ if (!this.apiKey)
45
+ throw new Error("API key is required for validation");
46
+ try {
47
+ const e = await fetch(`${this.apiUrl}/admin/api-keys/${this.apiKey}/status`, {
48
+ ...this.getFetchOptions({
49
+ method: "GET"
50
+ })
51
+ }).catch((r) => {
52
+ throw r.name === "TypeError" && r.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : r;
53
+ });
54
+ if (!e.ok) {
55
+ let r = "";
56
+ try {
57
+ r = await e.text();
58
+ } catch {
59
+ r = `HTTP ${e.status}`;
60
+ }
61
+ let i, n;
62
+ try {
63
+ const a = JSON.parse(r);
64
+ i = a.detail || a.message || r;
65
+ } catch {
66
+ i = r || `HTTP ${e.status}`;
67
+ }
68
+ switch (e.status) {
69
+ case 401:
70
+ n = "API key is invalid or expired";
71
+ break;
72
+ case 403:
73
+ n = "Access denied: API key does not have required permissions";
74
+ break;
75
+ case 404:
76
+ n = "API key not found";
77
+ break;
78
+ case 503:
79
+ n = "API key management is not available in inference-only mode";
80
+ break;
81
+ default:
82
+ n = `Failed to validate API key: ${i}`;
83
+ break;
84
+ }
85
+ throw new Error(n);
86
+ }
87
+ const s = await e.json();
88
+ if (!s.exists) {
89
+ const r = "API key does not exist";
90
+ throw new Error(r);
91
+ }
92
+ if (!s.active) {
93
+ const r = "API key is inactive";
94
+ throw new Error(r);
95
+ }
96
+ return s;
97
+ } catch (e) {
98
+ let s;
99
+ throw e instanceof Error && e.message ? e.message.includes("API key") || e.message.includes("Access denied") || e.message.includes("invalid") || e.message.includes("expired") || e.message.includes("inactive") || e.message.includes("not found") || e.message.includes("Could not connect") ? s = e.message : s = `API key validation failed: ${e.message}` : e.name === "TypeError" && ((t = e.message) != null && t.includes("Failed to fetch")) ? s = "Could not connect to the server. Please check if the server is running." : s = "API key validation failed. Please check your API key and try again.", console.warn(`[ApiClient] ${s}`), new Error(s);
100
+ }
101
+ }
102
+ /**
103
+ * Get adapter information for the current API key.
104
+ *
105
+ * Returns information about the adapter and model being used by the API key.
106
+ * This is useful for displaying configuration details to users.
107
+ *
108
+ * @returns Promise resolving to adapter information
109
+ * @throws Error if API key is not provided, invalid, disabled, or request fails
110
+ */
111
+ async getAdapterInfo() {
112
+ var t;
113
+ if (!this.apiKey)
114
+ throw new Error("API key is required to get adapter information");
115
+ try {
116
+ const e = await fetch(`${this.apiUrl}/admin/api-keys/info`, {
117
+ ...this.getFetchOptions({
118
+ method: "GET"
119
+ })
120
+ }).catch((r) => {
121
+ throw r.name === "TypeError" && r.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : r;
122
+ });
123
+ if (!e.ok) {
124
+ let r = "";
125
+ try {
126
+ r = await e.text();
127
+ } catch {
128
+ r = `HTTP ${e.status}`;
129
+ }
130
+ let i, n;
131
+ try {
132
+ const a = JSON.parse(r);
133
+ i = a.detail || a.message || r;
134
+ } catch {
135
+ i = r || `HTTP ${e.status}`;
136
+ }
137
+ switch (e.status) {
138
+ case 401:
139
+ n = "API key is invalid, disabled, or has no associated adapter";
140
+ break;
141
+ case 404:
142
+ n = "Adapter configuration not found";
143
+ break;
144
+ case 503:
145
+ n = "Service is not available";
146
+ break;
147
+ default:
148
+ n = `Failed to get adapter info: ${i}`;
149
+ break;
150
+ }
151
+ throw new Error(n);
152
+ }
153
+ return await e.json();
154
+ } catch (e) {
155
+ let s;
156
+ throw e instanceof Error && e.message ? e.message.includes("API key") || e.message.includes("Adapter") || e.message.includes("invalid") || e.message.includes("disabled") || e.message.includes("not found") || e.message.includes("Could not connect") ? s = e.message : s = `Failed to get adapter info: ${e.message}` : e.name === "TypeError" && ((t = e.message) != null && t.includes("Failed to fetch")) ? s = "Could not connect to the server. Please check if the server is running." : s = "Failed to get adapter information. Please try again.", console.warn(`[ApiClient] ${s}`), new Error(s);
157
+ }
158
+ }
36
159
  // Helper to get fetch options with connection pooling if available
37
- getFetchOptions(e = {}) {
38
- const r = {};
160
+ getFetchOptions(t = {}) {
161
+ const e = {};
39
162
  if (typeof window > "u") {
40
- const u = this.apiUrl.startsWith("https:") ? A : p;
41
- u && (r.agent = u);
163
+ const i = this.apiUrl.startsWith("https:") ? k : v;
164
+ i && (e.agent = i);
42
165
  } else
43
- r.headers = { Connection: "keep-alive" };
44
- const n = {
166
+ e.headers = { Connection: "keep-alive" };
167
+ const s = {
45
168
  "X-Request-ID": Date.now().toString(36) + Math.random().toString(36).substring(2)
46
169
  };
47
- return r.headers && Object.assign(n, r.headers), e.headers && Object.assign(n, e.headers), this.apiKey && (n["X-API-Key"] = this.apiKey), this.sessionId && (n["X-Session-ID"] = this.sessionId), {
170
+ if (e.headers && Object.assign(s, e.headers), t.headers) {
171
+ const r = t.headers;
172
+ for (const [i, n] of Object.entries(r))
173
+ (i.toLowerCase() !== "x-api-key" || !this.apiKey) && (s[i] = n);
174
+ }
175
+ return this.apiKey && (s["X-API-Key"] = this.apiKey), this.sessionId && (s["X-Session-ID"] = this.sessionId), {
176
+ ...t,
48
177
  ...e,
49
- ...r,
50
- headers: n
178
+ headers: s
51
179
  };
52
180
  }
53
181
  // Create Chat request
54
- createChatRequest(e, r = !0) {
55
- return {
182
+ createChatRequest(t, e = !0, s) {
183
+ const r = {
56
184
  messages: [
57
- { role: "user", content: e }
185
+ { role: "user", content: t }
58
186
  ],
59
- stream: r
187
+ stream: e
60
188
  };
189
+ return s && s.length > 0 && (r.file_ids = s), r;
61
190
  }
62
- async *streamChat(e, r = !0) {
63
- var n;
191
+ async *streamChat(t, e = !0, s) {
192
+ var r, i;
64
193
  try {
65
- const s = new AbortController(), u = setTimeout(() => s.abort(), 6e4), l = await fetch(`${this.apiUrl}/v1/chat`, {
194
+ const n = new AbortController(), a = setTimeout(() => n.abort(), 6e4), l = await fetch(`${this.apiUrl}/v1/chat`, {
66
195
  ...this.getFetchOptions({
67
196
  method: "POST",
68
197
  headers: {
69
198
  "Content-Type": "application/json",
70
- Accept: r ? "text/event-stream" : "application/json"
199
+ Accept: e ? "text/event-stream" : "application/json"
71
200
  },
72
- body: JSON.stringify(this.createChatRequest(e, r))
201
+ body: JSON.stringify(this.createChatRequest(t, e, s))
73
202
  }),
74
- signal: s.signal
203
+ signal: n.signal
75
204
  });
76
- if (clearTimeout(u), !l.ok) {
77
- const a = await l.text();
78
- throw new Error(`Network response was not ok: ${l.status} ${a}`);
205
+ if (clearTimeout(a), !l.ok) {
206
+ const h = await l.text();
207
+ throw new Error(`Network response was not ok: ${l.status} ${h}`);
79
208
  }
80
- if (!r) {
81
- const a = await l.json();
82
- a.response && (yield {
83
- text: a.response,
209
+ if (!e) {
210
+ const h = await l.json();
211
+ h.response && (yield {
212
+ text: h.response,
84
213
  done: !0
85
214
  });
86
215
  return;
87
216
  }
88
- const h = (n = l.body) == null ? void 0 : n.getReader();
89
- if (!h) throw new Error("No reader available");
90
- const I = new TextDecoder();
91
- let i = "", g = !1;
217
+ const u = (r = l.body) == null ? void 0 : r.getReader();
218
+ if (!u) throw new Error("No reader available");
219
+ const P = new TextDecoder();
220
+ let c = "", p = !1;
92
221
  try {
93
222
  for (; ; ) {
94
- const { done: a, value: v } = await h.read();
95
- if (a)
223
+ const { done: h, value: I } = await u.read();
224
+ if (h)
96
225
  break;
97
- const b = I.decode(v, { stream: !0 });
98
- i += b;
99
- let c = 0, y;
100
- for (; (y = i.indexOf(`
101
- `, c)) !== -1; ) {
102
- const d = i.slice(c, y).trim();
103
- if (c = y + 1, d && d.startsWith("data: ")) {
104
- const f = d.slice(6).trim();
105
- if (!f || f === "[DONE]") {
226
+ const T = P.decode(I, { stream: !0 });
227
+ c += T;
228
+ let w = 0, g;
229
+ for (; (g = c.indexOf(`
230
+ `, w)) !== -1; ) {
231
+ const f = c.slice(w, g).trim();
232
+ if (w = g + 1, f && f.startsWith("data: ")) {
233
+ const m = f.slice(6).trim();
234
+ if (!m || m === "[DONE]") {
106
235
  yield { text: "", done: !0 };
107
236
  return;
108
237
  }
109
238
  try {
110
- const o = JSON.parse(f);
111
- if (o.error)
112
- throw new Error(`Server Error: ${o.error.message}`);
113
- if (o.response && (g = !0, yield { text: o.response, done: o.done || !1 }), o.done) {
239
+ const d = JSON.parse(m);
240
+ if (d.error) {
241
+ const A = `Server error: ${((i = d.error) == null ? void 0 : i.message) || d.error || "Unknown server error"}`;
242
+ throw console.warn(`[ApiClient] ${A}`), new Error(A);
243
+ }
244
+ if (d.response && (p = !0, yield { text: d.response, done: d.done || !1 }), d.done) {
114
245
  yield { text: "", done: !0 };
115
246
  return;
116
247
  }
117
- } catch (o) {
118
- console.warn("Error parsing JSON chunk:", o, "Chunk:", f);
248
+ } catch {
249
+ console.warn("[ApiClient] Unable to parse server response. This may be a temporary issue.");
119
250
  }
120
- } else d && (g = !0, yield { text: d, done: !1 });
251
+ } else f && (p = !0, yield { text: f, done: !1 });
121
252
  }
122
- i = i.slice(c), i.length > 1e6 && (console.warn("Buffer too large, truncating..."), i = i.slice(-5e5));
253
+ c = c.slice(w), c.length > 1e6 && (console.warn("Buffer too large, truncating..."), c = c.slice(-5e5));
123
254
  }
124
- g && (yield { text: "", done: !0 });
255
+ p && (yield { text: "", done: !0 });
125
256
  } finally {
126
- h.releaseLock();
257
+ u.releaseLock();
127
258
  }
259
+ } catch (n) {
260
+ throw n.name === "AbortError" ? new Error("Connection timed out. Please check if the server is running.") : n.name === "TypeError" && n.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : n;
261
+ }
262
+ }
263
+ async clearConversationHistory(t) {
264
+ const e = t || this.sessionId;
265
+ if (!e)
266
+ throw new Error("No session ID provided and no current session available");
267
+ if (!this.apiKey)
268
+ throw new Error("API key is required for clearing conversation history");
269
+ const s = {
270
+ "Content-Type": "application/json",
271
+ "X-Session-ID": e,
272
+ "X-API-Key": this.apiKey
273
+ };
274
+ try {
275
+ const r = await fetch(`${this.apiUrl}/admin/chat-history/${e}`, {
276
+ ...this.getFetchOptions({
277
+ method: "DELETE",
278
+ headers: s
279
+ })
280
+ });
281
+ if (!r.ok) {
282
+ const n = await r.text();
283
+ throw new Error(`Failed to clear conversation history: ${r.status} ${n}`);
284
+ }
285
+ return await r.json();
286
+ } catch (r) {
287
+ throw r.name === "TypeError" && r.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : r;
288
+ }
289
+ }
290
+ async deleteConversationWithFiles(t, e) {
291
+ const s = t || this.sessionId;
292
+ if (!s)
293
+ throw new Error("No session ID provided and no current session available");
294
+ if (!this.apiKey)
295
+ throw new Error("API key is required for deleting conversation");
296
+ const r = {
297
+ "Content-Type": "application/json",
298
+ "X-Session-ID": s,
299
+ "X-API-Key": this.apiKey
300
+ }, i = e && e.length > 0 ? `?file_ids=${e.join(",")}` : "", n = `${this.apiUrl}/admin/conversations/${s}${i}`;
301
+ try {
302
+ const a = await fetch(n, {
303
+ ...this.getFetchOptions({
304
+ method: "DELETE",
305
+ headers: r
306
+ })
307
+ });
308
+ if (!a.ok) {
309
+ const u = await a.text();
310
+ throw new Error(`Failed to delete conversation: ${a.status} ${u}`);
311
+ }
312
+ return await a.json();
313
+ } catch (a) {
314
+ throw a.name === "TypeError" && a.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : a;
315
+ }
316
+ }
317
+ /**
318
+ * Upload a file for processing and indexing.
319
+ *
320
+ * @param file - The file to upload
321
+ * @returns Promise resolving to upload response with file_id
322
+ * @throws Error if upload fails
323
+ */
324
+ async uploadFile(t) {
325
+ if (!this.apiKey)
326
+ throw new Error("API key is required for file upload");
327
+ const e = new FormData();
328
+ e.append("file", t);
329
+ try {
330
+ const s = await fetch(`${this.apiUrl}/api/files/upload`, {
331
+ ...this.getFetchOptions({
332
+ method: "POST",
333
+ body: e
334
+ })
335
+ });
336
+ if (!s.ok) {
337
+ const r = await s.text();
338
+ throw new Error(`Failed to upload file: ${s.status} ${r}`);
339
+ }
340
+ return await s.json();
128
341
  } catch (s) {
129
- throw s.name === "AbortError" ? new Error("Connection timed out. Please check if the server is running.") : s.name === "TypeError" && s.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : s;
342
+ throw s.name === "TypeError" && s.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : s;
343
+ }
344
+ }
345
+ /**
346
+ * List all files for the current API key.
347
+ *
348
+ * @returns Promise resolving to list of file information
349
+ * @throws Error if request fails
350
+ */
351
+ async listFiles() {
352
+ if (!this.apiKey)
353
+ throw new Error("API key is required for listing files");
354
+ try {
355
+ const t = await fetch(`${this.apiUrl}/api/files`, {
356
+ ...this.getFetchOptions({
357
+ method: "GET"
358
+ })
359
+ });
360
+ if (!t.ok) {
361
+ const e = await t.text();
362
+ throw new Error(`Failed to list files: ${t.status} ${e}`);
363
+ }
364
+ return await t.json();
365
+ } catch (t) {
366
+ throw t.name === "TypeError" && t.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : t;
367
+ }
368
+ }
369
+ /**
370
+ * Get information about a specific file.
371
+ *
372
+ * @param fileId - The file ID
373
+ * @returns Promise resolving to file information
374
+ * @throws Error if file not found or request fails
375
+ */
376
+ async getFileInfo(t) {
377
+ if (!this.apiKey)
378
+ throw new Error("API key is required for getting file info");
379
+ try {
380
+ const e = await fetch(`${this.apiUrl}/api/files/${t}`, {
381
+ ...this.getFetchOptions({
382
+ method: "GET"
383
+ })
384
+ });
385
+ if (!e.ok) {
386
+ const s = await e.text();
387
+ throw new Error(`Failed to get file info: ${e.status} ${s}`);
388
+ }
389
+ return await e.json();
390
+ } catch (e) {
391
+ throw e.name === "TypeError" && e.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : e;
392
+ }
393
+ }
394
+ /**
395
+ * Query a specific file using semantic search.
396
+ *
397
+ * @param fileId - The file ID
398
+ * @param query - The search query
399
+ * @param maxResults - Maximum number of results (default: 10)
400
+ * @returns Promise resolving to query results
401
+ * @throws Error if query fails
402
+ */
403
+ async queryFile(t, e, s = 10) {
404
+ if (!this.apiKey)
405
+ throw new Error("API key is required for querying files");
406
+ try {
407
+ const r = await fetch(`${this.apiUrl}/api/files/${t}/query`, {
408
+ ...this.getFetchOptions({
409
+ method: "POST",
410
+ headers: {
411
+ "Content-Type": "application/json"
412
+ },
413
+ body: JSON.stringify({ query: e, max_results: s })
414
+ })
415
+ });
416
+ if (!r.ok) {
417
+ const i = await r.text();
418
+ throw new Error(`Failed to query file: ${r.status} ${i}`);
419
+ }
420
+ return await r.json();
421
+ } catch (r) {
422
+ throw r.name === "TypeError" && r.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : r;
423
+ }
424
+ }
425
+ /**
426
+ * Delete a specific file.
427
+ *
428
+ * @param fileId - The file ID
429
+ * @returns Promise resolving to deletion result
430
+ * @throws Error if deletion fails
431
+ */
432
+ async deleteFile(t) {
433
+ if (!this.apiKey)
434
+ throw new Error("API key is required for deleting files");
435
+ const e = `${this.apiUrl}/api/files/${t}`, s = this.getFetchOptions({
436
+ method: "DELETE"
437
+ });
438
+ try {
439
+ const r = await fetch(e, s);
440
+ if (!r.ok) {
441
+ const n = await r.text();
442
+ let a;
443
+ try {
444
+ const l = JSON.parse(n);
445
+ a = l.detail || l.message || `Failed to delete file (HTTP ${r.status})`;
446
+ } catch {
447
+ a = `Failed to delete file (HTTP ${r.status})`;
448
+ }
449
+ throw console.warn(`[ApiClient] ${a}`), new Error(a);
450
+ }
451
+ return await r.json();
452
+ } catch (r) {
453
+ let i;
454
+ throw r.name === "TypeError" && r.message.includes("Failed to fetch") ? i = "Could not connect to the server. Please check if the server is running." : r.message && !r.message.includes("Failed to delete file") ? i = r.message : i = "Failed to delete file. Please try again.", console.warn(`[ApiClient] ${i}`), new Error(i);
130
455
  }
131
456
  }
132
457
  }
133
- let m = null;
134
- const S = (t, e = null, r = null) => {
135
- m = new x({ apiUrl: t, apiKey: e, sessionId: r });
458
+ let E = null;
459
+ const O = (o, t = null, e = null) => {
460
+ E = new x({ apiUrl: o, apiKey: t, sessionId: e });
136
461
  };
137
- async function* O(t, e = !0) {
138
- if (!m)
462
+ async function* K(o, t = !0, e) {
463
+ if (!E)
139
464
  throw new Error("API not configured. Please call configureApi() with your server URL before using any API functions.");
140
- yield* m.streamChat(t, e);
465
+ yield* E.streamChat(o, t, e);
141
466
  }
142
467
  export {
143
468
  x as ApiClient,
144
- S as configureApi,
145
- O as streamChat
469
+ O as configureApi,
470
+ K as streamChat
146
471
  };
147
472
  //# sourceMappingURL=api.mjs.map
package/dist/api.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.mjs","sources":["../api.ts"],"sourcesContent":["// For Node.js environments, we can use http.Agent for connection pooling\nlet httpAgent: any = null;\nlet httpsAgent: any = null;\n\n// Initialize agents for connection pooling in Node.js environments\nif (typeof window === 'undefined') {\n // Lazy load to avoid including 'http' in browser bundles\n Promise.all([\n import('http').catch(() => null),\n import('https').catch(() => null)\n ]).then(([http, https]) => {\n if (http?.default?.Agent) {\n httpAgent = new http.default.Agent({ keepAlive: true });\n } else if (http?.Agent) {\n httpAgent = new http.Agent({ keepAlive: true });\n }\n \n if (https?.default?.Agent) {\n httpsAgent = new https.default.Agent({ keepAlive: true });\n } else if (https?.Agent) {\n httpsAgent = new https.Agent({ keepAlive: true });\n }\n }).catch(err => {\n // Silently fail - connection pooling is optional\n console.warn('Failed to initialize HTTP agents:', err.message);\n });\n}\n\n// Define the StreamResponse interface\nexport interface StreamResponse {\n text: string;\n done: boolean;\n}\n\n// The server now returns this directly for non-streaming chat\nexport interface ChatResponse {\n response: string;\n sources?: any[];\n}\n\n// The request body for the /v1/chat endpoint\ninterface ChatRequest {\n messages: Array<{ role: string; content: string; }>;\n stream: boolean;\n}\n\nexport class ApiClient {\n private readonly apiUrl: string;\n private readonly apiKey: string | null;\n private sessionId: string | null; // Session ID can be mutable\n\n constructor(config: { apiUrl: string; apiKey?: string | null; sessionId?: string | null }) {\n if (!config.apiUrl || typeof config.apiUrl !== 'string') {\n throw new Error('API URL must be a valid string');\n }\n if (config.apiKey !== undefined && config.apiKey !== null && typeof config.apiKey !== 'string') {\n throw new Error('API key must be a valid string or null');\n }\n if (config.sessionId !== undefined && config.sessionId !== null && typeof config.sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n \n this.apiUrl = config.apiUrl;\n this.apiKey = config.apiKey ?? null;\n this.sessionId = config.sessionId ?? null;\n }\n\n public setSessionId(sessionId: string | null): void {\n if (sessionId !== null && typeof sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n this.sessionId = sessionId;\n }\n\n public getSessionId(): string | null {\n return this.sessionId;\n }\n\n // Helper to get fetch options with connection pooling if available\n private getFetchOptions(options: RequestInit = {}): RequestInit {\n const baseOptions: RequestInit = {};\n \n // Environment-specific options\n if (typeof window === 'undefined') {\n // Node.js: Use connection pooling agent\n const isHttps = this.apiUrl.startsWith('https:');\n const agent = isHttps ? httpsAgent : httpAgent;\n if (agent) {\n (baseOptions as any).agent = agent;\n }\n } else {\n // Browser: Use keep-alive header\n baseOptions.headers = { 'Connection': 'keep-alive' };\n }\n\n // Common headers\n const headers: Record<string, string> = {\n 'X-Request-ID': Date.now().toString(36) + Math.random().toString(36).substring(2),\n };\n\n // Merge base options headers (for browser keep-alive)\n if (baseOptions.headers) {\n Object.assign(headers, baseOptions.headers);\n }\n\n // Merge original request headers\n if (options.headers) {\n Object.assign(headers, options.headers);\n }\n\n if (this.apiKey) {\n headers['X-API-Key'] = this.apiKey;\n }\n\n if (this.sessionId) {\n headers['X-Session-ID'] = this.sessionId;\n }\n\n return {\n ...options,\n ...baseOptions,\n headers,\n };\n }\n\n // Create Chat request\n private createChatRequest(message: string, stream: boolean = true): ChatRequest {\n return {\n messages: [\n { role: \"user\", content: message }\n ],\n stream\n };\n }\n\n public async *streamChat(\n message: string,\n stream: boolean = true\n ): AsyncGenerator<StreamResponse> {\n try {\n // Add timeout to the fetch request\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 second timeout\n\n const response = await fetch(`${this.apiUrl}/v1/chat`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': stream ? 'text/event-stream' : 'application/json'\n },\n body: JSON.stringify(this.createChatRequest(message, stream)),\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Network response was not ok: ${response.status} ${errorText}`);\n }\n\n if (!stream) {\n // Handle non-streaming response\n const data = await response.json() as ChatResponse;\n if (data.response) {\n yield {\n text: data.response,\n done: true\n };\n }\n return;\n }\n \n const reader = response.body?.getReader();\n if (!reader) throw new Error('No reader available');\n\n const decoder = new TextDecoder();\n let buffer = '';\n let hasReceivedContent = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n \n // Process complete lines immediately as they arrive\n let lineStartIndex = 0;\n let newlineIndex;\n \n while ((newlineIndex = buffer.indexOf('\\n', lineStartIndex)) !== -1) {\n const line = buffer.slice(lineStartIndex, newlineIndex).trim();\n lineStartIndex = newlineIndex + 1;\n \n if (line && line.startsWith('data: ')) {\n const jsonText = line.slice(6).trim();\n \n if (!jsonText || jsonText === '[DONE]') {\n yield { text: '', done: true };\n return;\n }\n\n try {\n const data = JSON.parse(jsonText);\n \n if (data.error) {\n throw new Error(`Server Error: ${data.error.message}`);\n }\n \n if (data.response) {\n hasReceivedContent = true;\n yield { text: data.response, done: data.done || false };\n }\n\n if (data.done) {\n yield { text: '', done: true };\n return;\n }\n \n } catch (parseError) {\n console.warn('Error parsing JSON chunk:', parseError, 'Chunk:', jsonText);\n }\n } else if (line) {\n // Handle raw text chunks that are not in SSE format\n hasReceivedContent = true;\n yield { text: line, done: false };\n }\n }\n \n buffer = buffer.slice(lineStartIndex);\n \n if (buffer.length > 1000000) { // 1MB limit\n console.warn('Buffer too large, truncating...');\n buffer = buffer.slice(-500000); // Keep last 500KB\n }\n }\n \n if (hasReceivedContent) {\n yield { text: '', done: true };\n }\n \n } finally {\n reader.releaseLock();\n }\n \n } catch (error: any) {\n if (error.name === 'AbortError') {\n throw new Error('Connection timed out. Please check if the server is running.');\n } else if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n}\n\n// Legacy compatibility functions - these create a default client instance\n// These are kept for backward compatibility but should be deprecated in favor of the class-based approach\n\nlet defaultClient: ApiClient | null = null;\n\n// Configure the API with a custom URL, API key (optional), and session ID (optional)\nexport const configureApi = (apiUrl: string, apiKey: string | null = null, sessionId: string | null = null): void => {\n defaultClient = new ApiClient({ apiUrl, apiKey, sessionId });\n}\n\n// Legacy streamChat function that uses the default client\nexport async function* streamChat(\n message: string,\n stream: boolean = true\n): AsyncGenerator<StreamResponse> {\n if (!defaultClient) {\n throw new Error('API not configured. Please call configureApi() with your server URL before using any API functions.');\n }\n \n yield* defaultClient.streamChat(message, stream);\n}\n"],"names":["httpAgent","httpsAgent","http","https","_a","_b","err","ApiClient","config","__publicField","sessionId","options","baseOptions","agent","headers","message","stream","controller","timeoutId","response","errorText","data","reader","decoder","buffer","hasReceivedContent","done","value","chunk","lineStartIndex","newlineIndex","line","jsonText","parseError","error","defaultClient","configureApi","apiUrl","apiKey","streamChat"],"mappings":";;;AACA,IAAIA,IAAiB,MACjBC,IAAkB;AAGlB,OAAO,SAAW,OAEpB,QAAQ,IAAI;AAAA,EACV,OAAO,MAAM,EAAE,MAAM,MAAM,IAAI;AAAA,EAC/B,OAAO,OAAO,EAAE,MAAM,MAAM,IAAI;AAAA,CACjC,EAAE,KAAK,CAAC,CAACC,GAAMC,CAAK,MAAM;AAT7B,MAAAC,GAAAC;AAUI,GAAID,IAAAF,KAAA,gBAAAA,EAAM,YAA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AAMJ,EAAK,UAAU,MAAMA,EAAK,QAAQ,GAAA,IAG9CA,EAAK,MAAM;AACX,wBAAM,EAAE,MAAM,IAAI,MAAM,GAAA;AACxB;AAAA,gBACJ;AAAA,cAEF,SAASY,GAAY;AACnB,wBAAQ,KAAK,6BAA6BA,GAAY,UAAUD,CAAQ;AAAA,cAC1E;AAAA,YACF,OAAWD,MAEPN,IAAqB,IACrB,MAAM,EAAE,MAAMM,GAAM,MAAM,GAAA;AAAA,UAEhC;AAEA,UAAAP,IAASA,EAAO,MAAMK,CAAc,GAEhCL,EAAO,SAAS,QAClB,QAAQ,KAAK,iCAAiC,GAC9CA,IAASA,EAAO,MAAM,IAAO;AAAA,QAEjC;AAEA,QAAIC,MACF,MAAM,EAAE,MAAM,IAAI,MAAM,GAAA;AAAA,MAG5B,UAAA;AACE,QAAAH,EAAO,YAAA;AAAA,MACT;AAAA,IAEF,SAASY,GAAY;AACnB,YAAIA,EAAM,SAAS,eACX,IAAI,MAAM,8DAA8D,IACrEA,EAAM,SAAS,eAAeA,EAAM,QAAQ,SAAS,iBAAiB,IACzE,IAAI,MAAM,yEAAyE,IAEnFA;AAAA,IAEV;AAAA,EACF;AACF;AAKA,IAAIC,IAAkC;AAG/B,MAAMC,IAAe,CAACC,GAAgBC,IAAwB,MAAM5B,IAA2B,SAAe;AACnH,EAAAyB,IAAgB,IAAI5B,EAAU,EAAE,QAAA8B,GAAQ,QAAAC,GAAQ,WAAA5B,GAAW;AAC7D;AAGA,gBAAuB6B,EACrBxB,GACAC,IAAkB,IACc;AAChC,MAAI,CAACmB;AACH,UAAM,IAAI,MAAM,qGAAqG;AAGvH,SAAOA,EAAc,WAAWpB,GAASC,CAAM;AACjD;"}
1
+ {"version":3,"file":"api.mjs","sources":["../api.ts"],"sourcesContent":["// For Node.js environments, we can use http.Agent for connection pooling\nlet httpAgent: any = null;\nlet httpsAgent: any = null;\n\n// Initialize agents for connection pooling in Node.js environments\nif (typeof window === 'undefined') {\n // Lazy load to avoid including 'http' in browser bundles\n Promise.all([\n import('http').catch(() => null),\n import('https').catch(() => null)\n ]).then(([http, https]) => {\n if (http?.default?.Agent) {\n httpAgent = new http.default.Agent({ keepAlive: true });\n } else if (http?.Agent) {\n httpAgent = new http.Agent({ keepAlive: true });\n }\n \n if (https?.default?.Agent) {\n httpsAgent = new https.default.Agent({ keepAlive: true });\n } else if (https?.Agent) {\n httpsAgent = new https.Agent({ keepAlive: true });\n }\n }).catch(err => {\n // Silently fail - connection pooling is optional\n console.warn('Failed to initialize HTTP agents:', err.message);\n });\n}\n\n// Define the StreamResponse interface\nexport interface StreamResponse {\n text: string;\n done: boolean;\n}\n\n// The server now returns this directly for non-streaming chat\nexport interface ChatResponse {\n response: string;\n sources?: any[];\n}\n\n// The request body for the /v1/chat endpoint\ninterface ChatRequest {\n messages: Array<{ role: string; content: string; }>;\n stream: boolean;\n file_ids?: string[]; // Optional list of file IDs for file context\n}\n\n// File-related interfaces\nexport interface FileUploadResponse {\n file_id: string;\n filename: string;\n mime_type: string;\n file_size: number;\n status: string;\n chunk_count: number;\n message: string;\n}\n\nexport interface FileInfo {\n file_id: string;\n filename: string;\n mime_type: string;\n file_size: number;\n upload_timestamp: string;\n processing_status: string;\n chunk_count: number;\n storage_type: string;\n}\n\nexport interface FileQueryRequest {\n query: string;\n max_results?: number;\n}\n\nexport interface FileQueryResponse {\n file_id: string;\n filename: string;\n results: Array<{\n content: string;\n metadata: {\n chunk_id: string;\n file_id: string;\n chunk_index: number;\n confidence: number;\n };\n }>;\n}\n\n// API key status interface\nexport interface ApiKeyStatus {\n exists: boolean;\n active: boolean;\n adapter_name?: string | null;\n client_name?: string | null;\n created_at?: string | number | null;\n system_prompt?: {\n id: string;\n exists: boolean;\n } | null;\n message?: string;\n}\n\n// Adapter information interface\nexport interface AdapterInfo {\n client_name: string;\n adapter_name: string;\n model: string | null;\n}\n\nexport class ApiClient {\n private readonly apiUrl: string;\n private readonly apiKey: string | null;\n private sessionId: string | null; // Session ID can be mutable\n\n constructor(config: { apiUrl: string; apiKey?: string | null; sessionId?: string | null }) {\n if (!config.apiUrl || typeof config.apiUrl !== 'string') {\n throw new Error('API URL must be a valid string');\n }\n if (config.apiKey !== undefined && config.apiKey !== null && typeof config.apiKey !== 'string') {\n throw new Error('API key must be a valid string or null');\n }\n if (config.sessionId !== undefined && config.sessionId !== null && typeof config.sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n \n this.apiUrl = config.apiUrl;\n this.apiKey = config.apiKey ?? null;\n this.sessionId = config.sessionId ?? null;\n }\n\n public setSessionId(sessionId: string | null): void {\n if (sessionId !== null && typeof sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n this.sessionId = sessionId;\n }\n\n public getSessionId(): string | null {\n return this.sessionId;\n }\n\n /**\n * Validate that the API key exists and is active.\n *\n * @returns Promise resolving to API key status information\n * @throws Error if API key is not provided, invalid, inactive, or validation fails\n */\n public async validateApiKey(): Promise<ApiKeyStatus> {\n if (!this.apiKey) {\n throw new Error('API key is required for validation');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/api-keys/${this.apiKey}/status`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n }).catch((fetchError: any) => {\n // Catch network errors before they bubble up\n if (fetchError.name === 'TypeError' && fetchError.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n }\n throw fetchError;\n });\n\n if (!response.ok) {\n // Read error response body\n let errorText = '';\n try {\n errorText = await response.text();\n } catch {\n // If we can't read the body, fall back to status code\n errorText = `HTTP ${response.status}`;\n }\n\n let errorDetail: string;\n let friendlyMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorDetail = errorJson.detail || errorJson.message || errorText;\n } catch {\n // If parsing fails, use the error text or status code\n errorDetail = errorText || `HTTP ${response.status}`;\n }\n\n // Generate user-friendly error messages based on HTTP status code\n switch (response.status) {\n case 401:\n friendlyMessage = 'API key is invalid or expired';\n break;\n case 403:\n friendlyMessage = 'Access denied: API key does not have required permissions';\n break;\n case 404:\n friendlyMessage = 'API key not found';\n break;\n case 503:\n friendlyMessage = 'API key management is not available in inference-only mode';\n break;\n default:\n friendlyMessage = `Failed to validate API key: ${errorDetail}`;\n break;\n }\n\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n const status: ApiKeyStatus = await response.json();\n\n // Check if the key exists\n if (!status.exists) {\n const friendlyMessage = 'API key does not exist';\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n // Check if the key is active\n if (!status.active) {\n const friendlyMessage = 'API key is inactive';\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n return status;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n\n if (error instanceof Error && error.message) {\n // If it's already a user-friendly Error from above, use it directly\n if (error.message.includes('API key') ||\n error.message.includes('Access denied') ||\n error.message.includes('invalid') ||\n error.message.includes('expired') ||\n error.message.includes('inactive') ||\n error.message.includes('not found') ||\n error.message.includes('Could not connect')) {\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `API key validation failed: ${error.message}`;\n }\n } else if (error.name === 'TypeError' && error.message?.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else {\n friendlyMessage = 'API key validation failed. Please check your API key and try again.';\n }\n\n // Only log warning if it's not a network error (those are already logged by browser)\n // For validation errors, we log once with a friendly message\n // Note: Browser will still log HTTP errors (401, 404, etc.) - this is unavoidable\n console.warn(`[ApiClient] ${friendlyMessage}`);\n\n // Throw the friendly error message\n throw new Error(friendlyMessage);\n }\n }\n\n /**\n * Get adapter information for the current API key.\n *\n * Returns information about the adapter and model being used by the API key.\n * This is useful for displaying configuration details to users.\n *\n * @returns Promise resolving to adapter information\n * @throws Error if API key is not provided, invalid, disabled, or request fails\n */\n public async getAdapterInfo(): Promise<AdapterInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required to get adapter information');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/api-keys/info`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n }).catch((fetchError: any) => {\n // Catch network errors before they bubble up\n if (fetchError.name === 'TypeError' && fetchError.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n }\n throw fetchError;\n });\n\n if (!response.ok) {\n // Read error response body\n let errorText = '';\n try {\n errorText = await response.text();\n } catch {\n // If we can't read the body, fall back to status code\n errorText = `HTTP ${response.status}`;\n }\n\n let errorDetail: string;\n let friendlyMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorDetail = errorJson.detail || errorJson.message || errorText;\n } catch {\n // If parsing fails, use the error text or status code\n errorDetail = errorText || `HTTP ${response.status}`;\n }\n\n // Generate user-friendly error messages based on HTTP status code\n switch (response.status) {\n case 401:\n friendlyMessage = 'API key is invalid, disabled, or has no associated adapter';\n break;\n case 404:\n friendlyMessage = 'Adapter configuration not found';\n break;\n case 503:\n friendlyMessage = 'Service is not available';\n break;\n default:\n friendlyMessage = `Failed to get adapter info: ${errorDetail}`;\n break;\n }\n\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n const adapterInfo: AdapterInfo = await response.json();\n return adapterInfo;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n\n if (error instanceof Error && error.message) {\n // If it's already a user-friendly Error from above, use it directly\n if (error.message.includes('API key') ||\n error.message.includes('Adapter') ||\n error.message.includes('invalid') ||\n error.message.includes('disabled') ||\n error.message.includes('not found') ||\n error.message.includes('Could not connect')) {\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `Failed to get adapter info: ${error.message}`;\n }\n } else if (error.name === 'TypeError' && error.message?.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else {\n friendlyMessage = 'Failed to get adapter information. Please try again.';\n }\n\n console.warn(`[ApiClient] ${friendlyMessage}`);\n\n // Throw the friendly error message\n throw new Error(friendlyMessage);\n }\n }\n\n // Helper to get fetch options with connection pooling if available\n private getFetchOptions(options: RequestInit = {}): RequestInit {\n const baseOptions: RequestInit = {};\n \n // Environment-specific options\n if (typeof window === 'undefined') {\n // Node.js: Use connection pooling agent\n const isHttps = this.apiUrl.startsWith('https:');\n const agent = isHttps ? httpsAgent : httpAgent;\n if (agent) {\n (baseOptions as any).agent = agent;\n }\n } else {\n // Browser: Use keep-alive header\n baseOptions.headers = { 'Connection': 'keep-alive' };\n }\n\n // Common headers\n const headers: Record<string, string> = {\n 'X-Request-ID': Date.now().toString(36) + Math.random().toString(36).substring(2),\n };\n\n // Merge base options headers (for browser keep-alive)\n if (baseOptions.headers) {\n Object.assign(headers, baseOptions.headers);\n }\n\n // Merge original request headers (but don't overwrite API key)\n if (options.headers) {\n const incomingHeaders = options.headers as Record<string, string>;\n for (const [key, value] of Object.entries(incomingHeaders)) {\n // Don't overwrite X-API-Key if we have one\n if (key.toLowerCase() !== 'x-api-key' || !this.apiKey) {\n headers[key] = value;\n }\n }\n }\n\n if (this.apiKey) {\n headers['X-API-Key'] = this.apiKey;\n }\n\n if (this.sessionId) {\n headers['X-Session-ID'] = this.sessionId;\n }\n\n return {\n ...options,\n ...baseOptions,\n headers,\n };\n }\n\n // Create Chat request\n private createChatRequest(message: string, stream: boolean = true, fileIds?: string[]): ChatRequest {\n const request: ChatRequest = {\n messages: [\n { role: \"user\", content: message }\n ],\n stream\n };\n if (fileIds && fileIds.length > 0) {\n request.file_ids = fileIds;\n }\n return request;\n }\n\n public async *streamChat(\n message: string,\n stream: boolean = true,\n fileIds?: string[]\n ): AsyncGenerator<StreamResponse> {\n try {\n // Add timeout to the fetch request\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 second timeout\n\n const response = await fetch(`${this.apiUrl}/v1/chat`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': stream ? 'text/event-stream' : 'application/json'\n },\n body: JSON.stringify(this.createChatRequest(message, stream, fileIds)),\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Network response was not ok: ${response.status} ${errorText}`);\n }\n\n if (!stream) {\n // Handle non-streaming response\n const data = await response.json() as ChatResponse;\n if (data.response) {\n yield {\n text: data.response,\n done: true\n };\n }\n return;\n }\n \n const reader = response.body?.getReader();\n if (!reader) throw new Error('No reader available');\n\n const decoder = new TextDecoder();\n let buffer = '';\n let hasReceivedContent = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n \n // Process complete lines immediately as they arrive\n let lineStartIndex = 0;\n let newlineIndex;\n \n while ((newlineIndex = buffer.indexOf('\\n', lineStartIndex)) !== -1) {\n const line = buffer.slice(lineStartIndex, newlineIndex).trim();\n lineStartIndex = newlineIndex + 1;\n \n if (line && line.startsWith('data: ')) {\n const jsonText = line.slice(6).trim();\n \n if (!jsonText || jsonText === '[DONE]') {\n yield { text: '', done: true };\n return;\n }\n\n try {\n const data = JSON.parse(jsonText);\n \n if (data.error) {\n const errorMessage = data.error?.message || data.error || 'Unknown server error';\n const friendlyMessage = `Server error: ${errorMessage}`;\n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n \n if (data.response) {\n hasReceivedContent = true;\n yield { text: data.response, done: data.done || false };\n }\n\n if (data.done) {\n yield { text: '', done: true };\n return;\n }\n \n } catch (parseError) {\n // Only log parse errors in debug scenarios, with friendly message\n console.warn('[ApiClient] Unable to parse server response. This may be a temporary issue.');\n }\n } else if (line) {\n // Handle raw text chunks that are not in SSE format\n hasReceivedContent = true;\n yield { text: line, done: false };\n }\n }\n \n buffer = buffer.slice(lineStartIndex);\n \n if (buffer.length > 1000000) { // 1MB limit\n console.warn('Buffer too large, truncating...');\n buffer = buffer.slice(-500000); // Keep last 500KB\n }\n }\n \n if (hasReceivedContent) {\n yield { text: '', done: true };\n }\n \n } finally {\n reader.releaseLock();\n }\n \n } catch (error: any) {\n if (error.name === 'AbortError') {\n throw new Error('Connection timed out. Please check if the server is running.');\n } else if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async clearConversationHistory(sessionId?: string): Promise<{\n status: string;\n message: string;\n session_id: string;\n deleted_count: number;\n timestamp: string;\n }> {\n /**\n * Clear conversation history for a session.\n *\n * @param sessionId - Optional session ID to clear. If not provided, uses current session.\n * @returns Promise resolving to operation result\n * @throws Error if the operation fails\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n if (!this.apiKey) {\n throw new Error('API key is required for clearing conversation history');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Session-ID': targetSessionId,\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/chat-history/${targetSessionId}`, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to clear conversation history: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async deleteConversationWithFiles(sessionId?: string, fileIds?: string[]): Promise<{\n status: string;\n message: string;\n session_id: string;\n deleted_messages: number;\n deleted_files: number;\n file_deletion_errors: string[] | null;\n timestamp: string;\n }> {\n /**\n * Delete a conversation and all associated files.\n *\n * This method performs a complete conversation deletion:\n * - Deletes each file provided in fileIds (metadata, content, and vector store chunks)\n * - Clears conversation history\n *\n * File tracking is managed by the frontend (localStorage). The backend is stateless\n * and requires fileIds to be provided explicitly.\n *\n * @param sessionId - Optional session ID to delete. If not provided, uses current session.\n * @param fileIds - Optional list of file IDs to delete (from conversation's attachedFiles)\n * @returns Promise resolving to deletion result with counts\n * @throws Error if the operation fails\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n if (!this.apiKey) {\n throw new Error('API key is required for deleting conversation');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Session-ID': targetSessionId,\n 'X-API-Key': this.apiKey\n };\n\n // Build URL with file_ids query parameter\n const fileIdsParam = fileIds && fileIds.length > 0 ? `?file_ids=${fileIds.join(',')}` : '';\n const url = `${this.apiUrl}/admin/conversations/${targetSessionId}${fileIdsParam}`;\n\n try {\n const response = await fetch(url, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to delete conversation: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Upload a file for processing and indexing.\n *\n * @param file - The file to upload\n * @returns Promise resolving to upload response with file_id\n * @throws Error if upload fails\n */\n public async uploadFile(file: File): Promise<FileUploadResponse> {\n if (!this.apiKey) {\n throw new Error('API key is required for file upload');\n }\n\n const formData = new FormData();\n formData.append('file', file);\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/upload`, {\n ...this.getFetchOptions({\n method: 'POST',\n body: formData\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to upload file: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * List all files for the current API key.\n * \n * @returns Promise resolving to list of file information\n * @throws Error if request fails\n */\n public async listFiles(): Promise<FileInfo[]> {\n if (!this.apiKey) {\n throw new Error('API key is required for listing files');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to list files: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get information about a specific file.\n * \n * @param fileId - The file ID\n * @returns Promise resolving to file information\n * @throws Error if file not found or request fails\n */\n public async getFileInfo(fileId: string): Promise<FileInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required for getting file info');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/${fileId}`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get file info: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Query a specific file using semantic search.\n * \n * @param fileId - The file ID\n * @param query - The search query\n * @param maxResults - Maximum number of results (default: 10)\n * @returns Promise resolving to query results\n * @throws Error if query fails\n */\n public async queryFile(fileId: string, query: string, maxResults: number = 10): Promise<FileQueryResponse> {\n if (!this.apiKey) {\n throw new Error('API key is required for querying files');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/${fileId}/query`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ query, max_results: maxResults })\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to query file: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Delete a specific file.\n * \n * @param fileId - The file ID\n * @returns Promise resolving to deletion result\n * @throws Error if deletion fails\n */\n public async deleteFile(fileId: string): Promise<{ message: string; file_id: string }> {\n if (!this.apiKey) {\n throw new Error('API key is required for deleting files');\n }\n\n const url = `${this.apiUrl}/api/files/${fileId}`;\n const fetchOptions = this.getFetchOptions({\n method: 'DELETE'\n });\n\n try {\n const response = await fetch(url, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n let friendlyMessage: string;\n try {\n const errorJson = JSON.parse(errorText);\n friendlyMessage = errorJson.detail || errorJson.message || `Failed to delete file (HTTP ${response.status})`;\n } catch {\n friendlyMessage = `Failed to delete file (HTTP ${response.status})`;\n }\n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n\n const result = await response.json();\n return result;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n \n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else if (error.message && !error.message.includes('Failed to delete file')) {\n // Use existing message if it's already user-friendly\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `Failed to delete file. Please try again.`;\n }\n \n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n }\n}\n\n// Legacy compatibility functions - these create a default client instance\n// These are kept for backward compatibility but should be deprecated in favor of the class-based approach\n\nlet defaultClient: ApiClient | null = null;\n\n// Configure the API with a custom URL, API key (optional), and session ID (optional)\nexport const configureApi = (apiUrl: string, apiKey: string | null = null, sessionId: string | null = null): void => {\n defaultClient = new ApiClient({ apiUrl, apiKey, sessionId });\n}\n\n// Legacy streamChat function that uses the default client\nexport async function* streamChat(\n message: string,\n stream: boolean = true,\n fileIds?: string[]\n): AsyncGenerator<StreamResponse> {\n if (!defaultClient) {\n throw new Error('API not configured. Please call configureApi() with your server URL before using any API functions.');\n }\n \n yield* defaultClient.streamChat(message, stream, fileIds);\n}\n\n"],"names":["httpAgent","httpsAgent","http","https","_a","_b","err","ApiClient","config","__publicField","sessionId","response","fetchError","errorText","errorDetail","friendlyMessage","errorJson","status","error","options","baseOptions","agent","headers","incomingHeaders","key","value","message","stream","fileIds","request","controller","timeoutId","data","reader","decoder","buffer","hasReceivedContent","done","chunk","lineStartIndex","newlineIndex","line","jsonText","targetSessionId","fileIdsParam","url","file","formData","fileId","query","maxResults","fetchOptions","defaultClient","configureApi","apiUrl","apiKey","streamChat"],"mappings":";;;AACA,IAAIA,IAAiB,MACjBC,IAAkB;AAGlB,OAAO,SAAW,OAEpB,QAAQ,IAAI;AAAA,EACV,OAAO,MAAM,EAAE,MAAM,MAAM,IAAI;AAAA,EAC/B,OAAO,OAAO,EAAE,MAAM,MAAM,IAAI;AAAA,CACjC,EAAE,KAAK,CAAC,CAACC,GAAMC,CAAK,MAAM;AAT7B,MAAAC,GAAAC;AAUI,GAAID,IAAAF,KAAA,gBAAAA,EAAM,YAAN,QAAAE,EAAe,QACjBJ,IAAY,IAAIE,EAAK,QAAQ,MAAM,EAAE,WAAW,IAAM,IAC7CA,KAAA,QAAAA,EAAM,UACfF,IAAY,IAAIE,EAAK,MAAM,EAAE,WAAW,IAAM,KAG5CG,IAAAF,KAAA,gBAAAA,EAAO,YAAP,QAAAE,EAAgB,QAClBJ,IAAa,IAAIE,EAAM,QAAQ,MAAM,EAAE,WAAW,IAAM,IAC/CA,KAAA,QAAAA,EAAO,UAChBF,IAAa,IAAIE,EAAM,MAAM,EAAE,WAAW,IAAM;AAEpD,CAAC,EAAE,MAAM,CAAAG,MAAO;AAEd,UAAQ,KAAK,qCAAqCA,EAAI,OAAO;AAC/D,CAAC;AAoFI,MAAMC,EAAU;AAAA;AAAA,EAKrB,YAAYC,GAA+E;AAJ1E,IAAAC,EAAA;AACA,IAA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",
3
3
  "private": false,
4
- "version": "0.5.2",
4
+ "version": "1.0.0",
5
5
  "description": "API client for the ORBIT MCP server",
6
6
  "type": "module",
7
7
  "main": "./dist/api.cjs",
@@ -25,10 +25,12 @@
25
25
  "scripts": {
26
26
  "dev": "vite",
27
27
  "build": "vite build",
28
+ "build:chat-app": "vite build && mkdir -p ../chat-app/src/api/local && cp dist/api.mjs ../chat-app/src/api/local/api.mjs && cp dist/api.mjs.map ../chat-app/src/api/local/api.mjs.map && cp dist/api.d.ts ../chat-app/src/api/local/api.d.ts",
28
29
  "lint": "eslint .",
29
30
  "preview": "vite preview",
30
- "test": "vitest",
31
+ "test": "vitest run",
31
32
  "test:watch": "vitest",
33
+ "test:npm": "node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"ts-node/esm\", pathToFileURL(\"./\"));' ./test/test-npm-package.ts",
32
34
  "test-query": "node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"ts-node/esm\", pathToFileURL(\"./\"));' ./test/run-query.js",
33
35
  "test-query-from-pairs": "node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"ts-node/esm\", pathToFileURL(\"./\"));' ./test/run-query-from-pairs.js"
34
36
  },