@epam/statgpt-dial-toolkit 0.5.0-rc.37 → 0.5.0-rc.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.cjs +3 -3
  2. package/index.mjs +367 -357
  3. package/package.json +2 -2
package/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",S=`/${l}/ops/resource/share`,d={VERSION:`/${l}`,BUCKET:`/${l}/bucket`,CONVERSATIONS:`/${l}/metadata/conversations`,CONVERSATION_BY_ID:s=>`/${l}/metadata/conversations/${s}`,CHAT:s=>`/openai/deployments/${s}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:s=>`/${l}/deployments/${s}/configuration`,DATASETS_METADATA:s=>`/v1/deployments/${s}/route/metadata/datasets`,PYTHON_ATTACHMENT:s=>`/v1/deployments/${s}/route/python-attachment`,SHARE_CONVERSATION:`${S}/create`,SHARE_CONVERSATION_ACCEPT:s=>`/${l}/invitations/${s}?accept=true`,SHARE_CONVERSATION_DETAILS:s=>`/${l}/invitations/${s}`,SHARE_CONVERSATION_LIST:`${S}/list`,SHARE_CONVERSATION_DISCARD:`${S}/discard`,SHARE_CONVERSATION_REVOKE:`${S}/revoke`,RATE:s=>`/${l}/${s}/rate`,RENAME:`/${l}/ops/resource/move`},H={LENGTH:"length",STOP:"stop"},R={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},U={CONTENT_FILTER:"content_filter",500:"500"},V={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},x=[R.MINUTE,R.DAILY,R.WEEKLY,R.MONTHLY],F="statgpt",N={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var O=(s=>(s.CONVERSATION="CONVERSATION",s))(O||{}),g=(s=>(s.ME="me",s.OTHERS="others",s))(g||{}),y=(s=>(s.CSV="text/csv",s.TABLE="application/dial-ttyd-table",s.PLOTLY="application/vnd.plotly.v1+json",s.MARKDOWN="text/markdown",s.JSON="application/json",s.JPEG="image/jpeg",s.PNG="image/png",s.CROSS_DATASET_GRID="cross_dataset_grid",s.CUSTOM_DATA_GRID="custom_data_grid",s.CUSTOM_CHART="custom_chart",s.CUSTOM_CODE_SAMPLE="custom_code_sample",s))(y||{}),$=(s=>(s.LINK="link",s))($||{});const K=s=>s.content?(console.info(`Using direct content format: ${s.content}`),s.content):s.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`),s.choices[0].delta.content):s.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${s.choices[0].message.content}`),s.choices[0].message.content):(console.info("Unknown SSE data format:",s),null),D=(s,t,n)=>{if(t?.(s),n){const e=K(s);e&&n(e)}},v=(s,t)=>s.error||s.message||`${t.status} ${t.statusText}`,j=(s,t)=>{const n=s?.reduce((e,r)=>(e[r.index]=r,e),{});return t.forEach(e=>{n[e.index]?(e.attachments&&(n[e.index].attachments=(n[e.index].attachments||[]).concat(e.attachments)),e.content&&(n[e.index].content=(n[e.index].content||"")+e.content),e.name&&(n[e.index].name=(n[e.index].name||"")+e.name),e.status&&(n[e.index].status=e.status)):n[e.index]=e}),Object.values(n)},k=(s,t)=>{const n=structuredClone(s);return t.forEach(e=>{e.errorMessage&&(n.errorMessage=e.errorMessage),e.role&&(n.role=e.role),e.responseId&&(n.responseId=e.responseId),e.content&&Y(n,e),e.custom_content&&(n.custom_content||(n.custom_content={}),e.custom_content.attachments&&(n.custom_content.attachments||(n.custom_content.attachments=[]),n.custom_content.attachments=n.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(n.custom_content.stages||(n.custom_content.stages=[]),n.custom_content.stages=j(n.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(n.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(n.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(n.custom_content.form_value=e.custom_content.form_value))}),n};function Y(s,t){if(t.content){const n=B(t.content);n!=null?s.content=s.content.slice(0,-n):s.content=`${s.content||""}${t.content}`}}function B(s){const t=s.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const G={CHAT:"/api/chat"},J="application/json",X="Content-Type",T="Api-Key",z="X-CONVERSATION-ID",I="Ocp-Apim-Subscription-Key";class C extends Error{constructor(t){super(t.message),this.isHttpError=!0,this.name="HttpError",this.code=t.code,this.status=t.status,this.details=t.details,this.displayMessage=t.displayMessage}}const W=s=>new RegExp("\\p{L}","u").test(s)||new RegExp("\\p{N}","u").test(s),Q=s=>{if(!s)return"";const t=s.toLowerCase(),n=[];let e="";for(const r of t)W(r)?e+=r:e&&(n.push(e),e="");return e&&n.push(e),n.join(" ")},p=(s,t,n)=>{const e={};return t?.contentType!==null&&(e[X]=t?.contentType||J),t?.jwt?e.Authorization=`Bearer ${t.jwt}`:s&&(e[T]=s),t?.chatReference&&(e[z]=t.chatReference),{...e,...n}},Z=s=>{const t={...s};return t[T]&&(t[T]=t[T].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[I]&&(t[I]=t[I].substring(0,8)+"...[REDACTED]"),t},ee=s=>({"Content-Type":`multipart/form-data; boundary=${s}`}),w=s=>{const t=s.name?.split("__")||[],n=t.length>1?t.slice(1).join("__"):s.name;return{modelId:t[0],conversationName:n}},L=s=>{const t=Date.now(),n=Q(s.name);return`${s.folderId}/${n}-${t}`},te=s=>({resourceTypes:[O.CONVERSATION],with:s}),f=async(s,t,n)=>{const e=n?.body===void 0?void 0:n?.isFormData?n.body:JSON.stringify(n.body);return await fetch(s,{method:n.method||"GET",headers:t,body:e,signal:n?.signal})};function E(s){return s.split("/").map(t=>encodeURIComponent(t)).join("/")}function ne(s){return s.split("/").map(t=>decodeURIComponent(t)).join("/")}function b(s){if(s?.kind!==N.RATE_LIMIT||typeof s.retryAfterSeconds!="number")return null;const t=new Date(s.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+s.retryAfterSeconds*1e3)}function se(s,t=Date.now()){const n=b(s);return n?n.getTime()>t:!1}function re(s,t="en-GB"){return{date:s.toLocaleDateString(t),time:s.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class q{constructor(){this.decoder=new TextDecoder}async streamChat(t,n,e={},r){const{onMessage:a,onError:o,onComplete:i,signal:c}=e;try{const u=await this.initializeStreamRequest(t,n,c,r);await this.processStreamData(u,a),i?.()}catch(u){this.handleStreamError(u,o)}}async initializeStreamRequest(t,n,e,r){const a=p(void 0,{jwt:r}),o=await f(t,{Accept:"text/event-stream",...a},{method:"POST",body:n,signal:e});if(!o.ok){const i=await o.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new C({status:o.status,message:c.error??"No response body"})}if(!o.body)throw new C({message:"No response body",status:o.status});return o.body.getReader()}async processStreamData(t,n){let e="";try{for(;;){const{done:r,value:a}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,n);break}const o=this.decoder.decode(a,{stream:!0});e+=o;const i=e.split(`
2
- `);e=i.pop()||"";for(const c of i)this.parseSSEDataLine(c,n)}}finally{t.releaseLock()}}handleStreamError(t,n){const e=t instanceof Error?t:new Error(String(t));throw n?.(e),e}parseSSEDataLine(t,n){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const r=e.slice(6);if(r==="[DONE]"){console.info("SSE: Stream completed");return}let a;try{a=JSON.parse(r)}catch(o){console.error(`Failed to parse SSE data: ${r} ${o}`)}n?.(a)}}}const M=new q,oe=async(s,t,n,e,r)=>{const{onMessage:a,onToken:o,onComplete:i,onError:c,model:u,signal:h}=n,A={conversationId:s,messages:t,model:u,custom_fields:r};await M.streamChat(G.CHAT,A,{onMessage:P=>D(P,a,o),onComplete:i,onError:c,signal:h},e)},m=s=>s instanceof Error&&s.message.includes("404"),_=s=>`/v1/conversations/${E(s)}`;class ae{constructor(t){this.client=t}async getConversations(t,n,e){const r=`${n?e?`${n}/${e}`:`${n}`:""}`,a=`${d.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(a+"/?limit=1000&recursive=false",t).then(i=>i.items||[])).map(i=>{const{conversationName:c,modelId:u}=w(i);return{id:i.url?.replace("conversations/","")||i.name,name:c,folderId:r,createdAt:i.createdAt,updatedAt:i.updatedAt,model:{id:u,name:u}}})}catch(o){if(m(o))return[];throw o}}async getConversation(t,n){try{return await this.client.getRequest(_(t),n)}catch(e){if(m(e))return null;throw e}}async getFile(t,n){try{const e=`${d.VERSION}/${E(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return null;throw e}}async putOnboardingFile(t,n,e,r){try{const a=`${d.VERSION}/${E(n)}`,o="----NodeMultipartBoundary",c=[`--${o}`,`Content-Disposition: form-data; name="file"; filename="${t}"`,"Content-Type: application/json","",JSON.stringify(e),`--${o}--`,""].join(`\r
3
- `);return await this.client.request(a,r,{method:"PUT",body:c,headers:ee(o),isFormData:!0})}catch(a){if(m(a))return null;throw a}}async getOnboardingFile(t,n){try{const e=`${d.VERSION}/${E(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return null;throw e}}async getFileBlob(t,n){try{const e=`${d.VERSION}/${E(t)}`;return await this.client.requestBlob(e,n,{method:"GET"})}catch(e){if(m(e))return null;throw e}}async deleteFile(t,n){try{const e=`${d.VERSION}/${E(t)}`;await this.client.request(e,n,{method:"DELETE"})}catch(e){if(m(e))return;throw e}}async putFile(t,n,e){try{const r=`${d.VERSION}/${E(t)}`,a=new FormData,o=decodeURIComponent(t.split("/").at(-1)??"file");a.append("attachment",n,o),await this.client.request(r,e,{method:"PUT",body:a,isFormData:!0})}catch(r){if(m(r))return;throw r}}async createConversation(t,n){const e=t?.id||L(t),{name:r,folderId:a,model:o,messages:i,custom_fields:c}=t,u={id:e,name:r,folderId:a,model:o,messages:i||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:c};return await this.client.request(_(e),n,{method:"PUT",body:u}),{id:e,name:r,folderId:a,model:o,createdAt:u.createdAt,updatedAt:u.updatedAt}}async generateConversationLink(t,n){return await this.client.postRequest(d.SHARE_CONVERSATION,t,{body:n})}async getSharedConversations(t,n){return await this.client.postRequest(d.SHARE_CONVERSATION_LIST,t,{body:n})}async revokeSharedConversations(t,n){await this.client.postRequest(d.SHARE_CONVERSATION_REVOKE,t,{body:n})}async updateConversation(t,n,e){const r=await this.getConversation(t,e);if(!r)throw new Error(`Conversation with id ${t} not found`);const a={...r,...n,updatedAt:Date.now()};return await this.client.request(_(t),e,{method:"PUT",body:a})}async deleteConversation(t,n,e){n?.isShared?await this.client.postRequest(d.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:n?.url}]}}):await this.client.request(_(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,n){const e=t.model.id,r=encodeURIComponent(e),a=`${d.CHAT(r)}?api-version=${this.client.config.version}`,o={messages:t.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:t.custom_fields};return await this.client.stream(a,n,{method:"POST",body:o,chatReference:t.conversationId})}async rateResponse(t,n,e,r){return await this.client.postRequest(d.RATE(t),r,{body:{responseId:n,rate:e}})}async renameConversation(t,n,e){return await this.client.postRequest(d.RENAME,e,{body:{sourceUrl:t,destinationUrl:n,overwrite:!0}})}}class ie{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,n,e){return this.request(t,n,{...e,method:"GET"})}async postRequest(t,n,e){return this.request(t,n,{...e,method:"POST"})}async requestBlob(t,n,e){const r=`${this.config.host}${t}`,a={...p(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};try{return(await f(r,a,e)).blob()}catch(o){throw console.error("API Request Exception",{method:e.method,url:r,error:o instanceof Error?o.message:String(o)}),o}}async request(t,n,e){const r=Date.now(),a=`${this.config.host}${t}`,o={...p(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};this.addInfoRequestLog("API Request",a,e,o);try{const i=await f(a,o,e),c=Date.now()-r;let u;const h=await i.text();try{u=h?JSON.parse(h):{}}catch{if(this.addErrorRequestParsing(a,e,i,c,h),!i.ok)throw new Error(`API request failed: ${i.status} ${i.statusText} - ${h.substring(0,100)}`);u={data:h}}if(!i.ok){this.addErrorRequestLog(a,e,i,c,u);const A=v(u,i);throw new Error(`API request failed: ${A}`)}return u}catch(i){const c=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:a,duration:`${c}ms`,error:i instanceof Error?i.message:String(i)}),i}}async stream(t,n,e){const r=`${this.config.host}${t}`,a=p(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0},e.headers);this.addInfoRequestLog("Stream Request",r,e,a);const o=await f(r,a,e);if(!o.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:r,status:o.status,statusText:o.statusText}),new Error(`Stream request failed: ${o.status} ${o.statusText}`);if(!o.body)throw new Error("No response body for stream");return o.body}addInfoRequestLog(t,n,e,r){const a={method:e.method||"GET",url:n,headers:Z(r)};e.body&&(a.body=e.body),console.info(t,a)}addErrorRequestLog(t,n,e,r,a){console.error("API Request Failed",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:a})}addErrorRequestParsing(t,n,e,r,a){console.error("API Response Parse Error",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:a.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=y;exports.COMPLETION_FINISH_REASON=H;exports.CUSTOM_VIEW_STATE_KEY=F;exports.ChatStreamSSEClient=q;exports.ConversationApi=ae;exports.DIAL_API_ROUTES=d;exports.DIAL_ERROR_CODES=U;exports.DIAL_ERROR_TYPES=V;exports.DialApiClient=ie;exports.ERROR_CONTEXT_KIND=N;exports.EXCEEDED_LIMIT=R;exports.EXCEEDED_LIMIT_ORDER=x;exports.InvitationType=$;exports.ResourceTypes=O;exports.ShareTarget=g;exports.chatStreamSSEClient=M;exports.decodeApiUrl=ne;exports.encodeApiUrl=E;exports.formatDateTime=re;exports.generateConversationId=L;exports.getErrorMessage=v;exports.getRateLimitRestoreDate=b;exports.getSharedConversationsRequest=te;exports.handleStreamMessage=D;exports.isRateLimitStillActive=se;exports.mergeMessages=k;exports.parseConversationName=w;exports.sendRequest=f;exports.streamChatResponse=oe;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",T=`/${l}/ops/resource/share`,d={VERSION:`/${l}`,BUCKET:`/${l}/bucket`,CONVERSATIONS:`/${l}/metadata/conversations`,CONVERSATION_BY_ID:s=>`/${l}/metadata/conversations/${s}`,CHAT:s=>`/openai/deployments/${s}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:s=>`/${l}/deployments/${s}/configuration`,DATASETS_METADATA:s=>`/v1/deployments/${s}/route/metadata/datasets`,PYTHON_ATTACHMENT:s=>`/v1/deployments/${s}/route/python-attachment`,SHARE_CONVERSATION:`${T}/create`,SHARE_CONVERSATION_ACCEPT:s=>`/${l}/invitations/${s}?accept=true`,SHARE_CONVERSATION_DETAILS:s=>`/${l}/invitations/${s}`,SHARE_CONVERSATION_LIST:`${T}/list`,SHARE_CONVERSATION_DISCARD:`${T}/discard`,SHARE_CONVERSATION_REVOKE:`${T}/revoke`,RATE:s=>`/${l}/${s}/rate`,RENAME:`/${l}/ops/resource/move`},U={LENGTH:"length",STOP:"stop"},f={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},V={CONTENT_FILTER:"content_filter",500:"500"},x={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},F=[f.MINUTE,f.DAILY,f.WEEKLY,f.MONTHLY],K="statgpt",g={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var C=(s=>(s.CONVERSATION="CONVERSATION",s))(C||{}),y=(s=>(s.ME="me",s.OTHERS="others",s))(y||{}),$=(s=>(s.CSV="text/csv",s.TABLE="application/dial-ttyd-table",s.PLOTLY="application/vnd.plotly.v1+json",s.MARKDOWN="text/markdown",s.JSON="application/json",s.JPEG="image/jpeg",s.PNG="image/png",s.CROSS_DATASET_GRID="cross_dataset_grid",s.CUSTOM_DATA_GRID="custom_data_grid",s.CUSTOM_CHART="custom_chart",s.CUSTOM_CODE_SAMPLE="custom_code_sample",s))($||{}),D=(s=>(s.LINK="link",s))(D||{});const j=s=>s.content?(console.info(`Using direct content format: ${s.content}`),s.content):s.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`),s.choices[0].delta.content):s.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${s.choices[0].message.content}`),s.choices[0].message.content):(console.info("Unknown SSE data format:",s),null),v=(s,t,n)=>{if(t?.(s),n){const e=j(s);e&&n(e)}},w=(s,t)=>s.error||s.message||`${t.status} ${t.statusText}`,k=(s,t)=>{const n=s?.reduce((e,r)=>(e[r.index]=r,e),{});return t.forEach(e=>{n[e.index]?(e.attachments&&(n[e.index].attachments=(n[e.index].attachments||[]).concat(e.attachments)),e.content&&(n[e.index].content=(n[e.index].content||"")+e.content),e.name&&(n[e.index].name=(n[e.index].name||"")+e.name),e.status&&(n[e.index].status=e.status)):n[e.index]=e}),Object.values(n)},Y=(s,t)=>{const n=structuredClone(s);return t.forEach(e=>{e.errorMessage&&(n.errorMessage=e.errorMessage),e.role&&(n.role=e.role),e.responseId&&(n.responseId=e.responseId),e.content&&B(n,e),e.custom_content&&(n.custom_content||(n.custom_content={}),e.custom_content.attachments&&(n.custom_content.attachments||(n.custom_content.attachments=[]),n.custom_content.attachments=n.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(n.custom_content.stages||(n.custom_content.stages=[]),n.custom_content.stages=k(n.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(n.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(n.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(n.custom_content.form_value=e.custom_content.form_value))}),n};function B(s,t){if(t.content){const n=G(t.content);n!=null?s.content=s.content.slice(0,-n):s.content=`${s.content||""}${t.content}`}}function G(s){const t=s.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const J={CHAT:"/api/chat"},X="application/json",z="Content-Type",p="Api-Key",W="X-CONVERSATION-ID",O="Ocp-Apim-Subscription-Key";class N extends Error{constructor(t){super(t.message),this.isHttpError=!0,this.name="HttpError",this.code=t.code,this.status=t.status,this.details=t.details,this.displayMessage=t.displayMessage}}const Q=s=>new RegExp("\\p{L}","u").test(s)||new RegExp("\\p{N}","u").test(s),Z=s=>{if(!s)return"";const t=s.toLowerCase(),n=[];let e="";for(const r of t)Q(r)?e+=r:e&&(n.push(e),e="");return e&&n.push(e),n.join(" ")},A=(s,t,n)=>{const e={};return t?.contentType!==null&&(e[z]=t?.contentType||X),t?.jwt?e.Authorization=`Bearer ${t.jwt}`:s&&(e[p]=s),t?.chatReference&&(e[W]=t.chatReference),{...e,...n}},ee=s=>{const t={...s};return t[p]&&(t[p]=t[p].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[O]&&(t[O]=t[O].substring(0,8)+"...[REDACTED]"),t},te=s=>({"Content-Type":`multipart/form-data; boundary=${s}`}),L=s=>{const t=s.name?.split("__")||[],n=t.length>1?t.slice(1).join("__"):s.name;return{modelId:t[0],conversationName:n}},b=s=>{const t=Date.now(),n=Z(s.name);return`${s.folderId}/${n}-${t}`},ne=s=>({resourceTypes:[C.CONVERSATION],with:s}),_=async(s,t,n)=>{const e=n?.body===void 0?void 0:n?.isFormData?n.body:JSON.stringify(n.body);return await fetch(s,{method:n.method||"GET",headers:t,body:e,signal:n?.signal})};function h(s){return s.split("/").map(t=>encodeURIComponent(t)).join("/")}function se(s){return s.split("/").map(t=>decodeURIComponent(t)).join("/")}function q(s){if(s?.kind!==g.RATE_LIMIT||typeof s.retryAfterSeconds!="number")return null;const t=new Date(s.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+s.retryAfterSeconds*1e3)}function re(s,t=Date.now()){const n=q(s);return n?n.getTime()>t:!1}function oe(s,t="en-GB"){return{date:s.toLocaleDateString(t),time:s.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class M{constructor(){this.decoder=new TextDecoder}async streamChat(t,n,e={},r){const{onMessage:o,onError:a,onComplete:i,signal:c}=e;try{const u=await this.initializeStreamRequest(t,n,c,r);await this.processStreamData(u,o),i?.()}catch(u){this.handleStreamError(u,a)}}async initializeStreamRequest(t,n,e,r){const o=A(void 0,{jwt:r}),a=await _(t,{Accept:"text/event-stream",...o},{method:"POST",body:n,signal:e});if(!a.ok){const i=await a.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new N({status:a.status,message:c.error??"No response body"})}if(!a.body)throw new N({message:"No response body",status:a.status});return a.body.getReader()}async processStreamData(t,n){let e="";try{for(;;){const{done:r,value:o}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,n);break}const a=this.decoder.decode(o,{stream:!0});e+=a;const i=e.split(`
2
+ `);e=i.pop()||"";for(const c of i)this.parseSSEDataLine(c,n)}}finally{t.releaseLock()}}handleStreamError(t,n){const e=t instanceof Error?t:new Error(String(t));throw n?.(e),e}parseSSEDataLine(t,n){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const r=e.slice(6);if(r==="[DONE]"){console.info("SSE: Stream completed");return}let o;try{o=JSON.parse(r)}catch(a){console.error(`Failed to parse SSE data: ${r} ${a}`)}n?.(o)}}}const H=new M,ae=async(s,t,n,e,r)=>{const{onMessage:o,onToken:a,onComplete:i,onError:c,model:u,signal:R}=n,I={conversationId:s,messages:t,model:u,custom_fields:r};await H.streamChat(J.CHAT,I,{onMessage:P=>v(P,o,a),onComplete:i,onError:c,signal:R},e)},m=s=>s instanceof Error&&s.message.includes("404"),S=s=>`/v1/conversations/${h(s)}`;function E(s){console.warn("[ConversationApi] suppressed error, returning empty result",s)}class ie{constructor(t){this.client=t}async getConversations(t,n,e){const r=`${n?e?`${n}/${e}`:`${n}`:""}`,o=`${d.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(o+"/?limit=1000&recursive=false",t).then(i=>i.items||[])).map(i=>{const{conversationName:c,modelId:u}=L(i);return{id:i.url?.replace("conversations/","")||i.name,name:c,folderId:r,createdAt:i.createdAt,updatedAt:i.updatedAt,model:{id:u,name:u}}})}catch(a){if(m(a))return E({endpoint:o,error:a}),[];throw a}}async getConversation(t,n){try{return await this.client.getRequest(S(t),n)}catch(e){if(m(e))return E({endpoint:S(t),error:e}),null;throw e}}async getFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async putOnboardingFile(t,n,e,r){try{const o=`${d.VERSION}/${h(n)}`,a="----NodeMultipartBoundary",c=[`--${a}`,`Content-Disposition: form-data; name="file"; filename="${t}"`,"Content-Type: application/json","",JSON.stringify(e),`--${a}--`,""].join(`\r
3
+ `);return await this.client.request(o,r,{method:"PUT",body:c,headers:te(a),isFormData:!0})}catch(o){if(m(o))return E({filePath:n,error:o}),null;throw o}}async getOnboardingFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async getFileBlob(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.requestBlob(e,n,{method:"GET"})}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async deleteFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;await this.client.request(e,n,{method:"DELETE"})}catch(e){if(m(e)){E({filePath:t,error:e});return}throw e}}async putFile(t,n,e){try{const r=`${d.VERSION}/${h(t)}`,o=new FormData,a=decodeURIComponent(t.split("/").at(-1)??"file");o.append("attachment",n,a),await this.client.request(r,e,{method:"PUT",body:o,isFormData:!0})}catch(r){if(m(r)){E({filePath:t,error:r});return}throw r}}async createConversation(t,n){const e=t?.id||b(t),{name:r,folderId:o,model:a,messages:i,custom_fields:c}=t,u={id:e,name:r,folderId:o,model:a,messages:i||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:c};return await this.client.request(S(e),n,{method:"PUT",body:u}),{id:e,name:r,folderId:o,model:a,createdAt:u.createdAt,updatedAt:u.updatedAt}}async generateConversationLink(t,n){return await this.client.postRequest(d.SHARE_CONVERSATION,t,{body:n})}async getSharedConversations(t,n){return await this.client.postRequest(d.SHARE_CONVERSATION_LIST,t,{body:n})}async revokeSharedConversations(t,n){await this.client.postRequest(d.SHARE_CONVERSATION_REVOKE,t,{body:n})}async updateConversation(t,n,e){const r=await this.getConversation(t,e);if(!r)throw new Error(`Conversation with id ${t} not found`);const o={...r,...n,updatedAt:Date.now()};return await this.client.request(S(t),e,{method:"PUT",body:o})}async deleteConversation(t,n,e){n?.isShared?await this.client.postRequest(d.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:n?.url}]}}):await this.client.request(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,n){const e=t.model.id,r=encodeURIComponent(e),o=`${d.CHAT(r)}?api-version=${this.client.config.version}`,a={messages:t.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:t.custom_fields};return await this.client.stream(o,n,{method:"POST",body:a,chatReference:t.conversationId})}async rateResponse(t,n,e,r){return await this.client.postRequest(d.RATE(t),r,{body:{responseId:n,rate:e}})}async renameConversation(t,n,e){return await this.client.postRequest(d.RENAME,e,{body:{sourceUrl:t,destinationUrl:n,overwrite:!0}})}}class ce{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,n,e){return this.request(t,n,{...e,method:"GET"})}async postRequest(t,n,e){return this.request(t,n,{...e,method:"POST"})}async requestBlob(t,n,e){const r=`${this.config.host}${t}`,o={...A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};try{return(await _(r,o,e)).blob()}catch(a){throw console.error("API Request Exception",{method:e.method,url:r,error:a instanceof Error?a.message:String(a)}),a}}async request(t,n,e){const r=Date.now(),o=`${this.config.host}${t}`,a={...A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};this.addInfoRequestLog("API Request",o,e,a);try{const i=await _(o,a,e),c=Date.now()-r;let u;const R=await i.text();try{u=R?JSON.parse(R):{}}catch{if(this.addErrorRequestParsing(o,e,i,c,R),!i.ok)throw new Error(`API request failed: ${i.status} ${i.statusText} - ${R.substring(0,100)}`);u={data:R}}if(!i.ok){this.addErrorRequestLog(o,e,i,c,u);const I=w(u,i);throw new Error(`API request failed: ${I}`)}return u}catch(i){const c=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:o,duration:`${c}ms`,error:i instanceof Error?i.message:String(i)}),i}}async stream(t,n,e){const r=`${this.config.host}${t}`,o=A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0},e.headers);this.addInfoRequestLog("Stream Request",r,e,o);const a=await _(r,o,e);if(!a.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:r,status:a.status,statusText:a.statusText}),new Error(`Stream request failed: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("No response body for stream");return a.body}addInfoRequestLog(t,n,e,r){const o={method:e.method||"GET",url:n,headers:ee(r)};e.body&&(o.body=e.body),console.info(t,o)}addErrorRequestLog(t,n,e,r,o){console.error("API Request Failed",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:o})}addErrorRequestParsing(t,n,e,r,o){console.error("API Response Parse Error",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:o.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=$;exports.COMPLETION_FINISH_REASON=U;exports.CUSTOM_VIEW_STATE_KEY=K;exports.ChatStreamSSEClient=M;exports.ConversationApi=ie;exports.DIAL_API_ROUTES=d;exports.DIAL_ERROR_CODES=V;exports.DIAL_ERROR_TYPES=x;exports.DialApiClient=ce;exports.ERROR_CONTEXT_KIND=g;exports.EXCEEDED_LIMIT=f;exports.EXCEEDED_LIMIT_ORDER=F;exports.InvitationType=D;exports.ResourceTypes=C;exports.ShareTarget=y;exports.chatStreamSSEClient=H;exports.decodeApiUrl=se;exports.encodeApiUrl=h;exports.formatDateTime=oe;exports.generateConversationId=b;exports.getErrorMessage=w;exports.getRateLimitRestoreDate=q;exports.getSharedConversationsRequest=ne;exports.handleStreamMessage=v;exports.isRateLimitStillActive=re;exports.mergeMessages=Y;exports.parseConversationName=L;exports.sendRequest=_;exports.streamChatResponse=ae;
package/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- const h = "/v1/ops/resource/share", d = {
1
+ const f = "/v1/ops/resource/share", d = {
2
2
  VERSION: "/v1",
3
3
  BUCKET: "/v1/bucket",
4
4
  CONVERSATIONS: "/v1/metadata/conversations",
@@ -8,445 +8,455 @@ const h = "/v1/ops/resource/share", d = {
8
8
  CONFIGURATION: (s) => `/v1/deployments/${s}/configuration`,
9
9
  DATASETS_METADATA: (s) => `/v1/deployments/${s}/route/metadata/datasets`,
10
10
  PYTHON_ATTACHMENT: (s) => `/v1/deployments/${s}/route/python-attachment`,
11
- SHARE_CONVERSATION: `${h}/create`,
11
+ SHARE_CONVERSATION: `${f}/create`,
12
12
  SHARE_CONVERSATION_ACCEPT: (s) => `/v1/invitations/${s}?accept=true`,
13
13
  SHARE_CONVERSATION_DETAILS: (s) => `/v1/invitations/${s}`,
14
- SHARE_CONVERSATION_LIST: `${h}/list`,
15
- SHARE_CONVERSATION_DISCARD: `${h}/discard`,
16
- SHARE_CONVERSATION_REVOKE: `${h}/revoke`,
14
+ SHARE_CONVERSATION_LIST: `${f}/list`,
15
+ SHARE_CONVERSATION_DISCARD: `${f}/discard`,
16
+ SHARE_CONVERSATION_REVOKE: `${f}/revoke`,
17
17
  RATE: (s) => `/v1/${s}/rate`,
18
18
  RENAME: "/v1/ops/resource/move"
19
- }, J = {
19
+ }, z = {
20
20
  LENGTH: "length",
21
21
  STOP: "stop"
22
- }, R = {
22
+ }, S = {
23
23
  MINUTE: "minute",
24
24
  DAILY: "daily",
25
25
  WEEKLY: "weekly",
26
26
  MONTHLY: "monthly"
27
- }, z = {
27
+ }, W = {
28
28
  CONTENT_FILTER: "content_filter",
29
29
  500: "500"
30
- }, W = {
30
+ }, X = {
31
31
  RUNTIME_ERROR: "runtime_error",
32
32
  RATE_LIMIT_EXCEEDED: "rate_limit_exceeded"
33
- }, X = [
34
- R.MINUTE,
35
- R.DAILY,
36
- R.WEEKLY,
37
- R.MONTHLY
38
- ], Q = "statgpt", y = {
33
+ }, Q = [
34
+ S.MINUTE,
35
+ S.DAILY,
36
+ S.WEEKLY,
37
+ S.MONTHLY
38
+ ], Z = "statgpt", C = {
39
39
  RATE_LIMIT: "rate_limit",
40
40
  UNKNOWN: "unknown"
41
41
  };
42
- var A = /* @__PURE__ */ ((s) => (s.CONVERSATION = "CONVERSATION", s))(A || {}), C = /* @__PURE__ */ ((s) => (s.ME = "me", s.OTHERS = "others", s))(C || {}), g = /* @__PURE__ */ ((s) => (s.CSV = "text/csv", s.TABLE = "application/dial-ttyd-table", s.PLOTLY = "application/vnd.plotly.v1+json", s.MARKDOWN = "text/markdown", s.JSON = "application/json", s.JPEG = "image/jpeg", s.PNG = "image/png", s.CROSS_DATASET_GRID = "cross_dataset_grid", s.CUSTOM_DATA_GRID = "custom_data_grid", s.CUSTOM_CHART = "custom_chart", s.CUSTOM_CODE_SAMPLE = "custom_code_sample", s))(g || {}), $ = /* @__PURE__ */ ((s) => (s.LINK = "link", s))($ || {});
43
- const w = (s) => s.content ? (console.info(`Using direct content format: ${s.content}`), s.content) : s.choices?.[0]?.delta?.content ? (console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`), s.choices[0].delta.content) : s.choices?.[0]?.message?.content ? (console.info(
42
+ var N = /* @__PURE__ */ ((s) => (s.CONVERSATION = "CONVERSATION", s))(N || {}), g = /* @__PURE__ */ ((s) => (s.ME = "me", s.OTHERS = "others", s))(g || {}), $ = /* @__PURE__ */ ((s) => (s.CSV = "text/csv", s.TABLE = "application/dial-ttyd-table", s.PLOTLY = "application/vnd.plotly.v1+json", s.MARKDOWN = "text/markdown", s.JSON = "application/json", s.JPEG = "image/jpeg", s.PNG = "image/png", s.CROSS_DATASET_GRID = "cross_dataset_grid", s.CUSTOM_DATA_GRID = "custom_data_grid", s.CUSTOM_CHART = "custom_chart", s.CUSTOM_CODE_SAMPLE = "custom_code_sample", s))($ || {}), w = /* @__PURE__ */ ((s) => (s.LINK = "link", s))(w || {});
43
+ const v = (s) => s.content ? (console.info(`Using direct content format: ${s.content}`), s.content) : s.choices?.[0]?.delta?.content ? (console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`), s.choices[0].delta.content) : s.choices?.[0]?.message?.content ? (console.info(
44
44
  `Using complete message format: ${s.choices[0].message.content}`
45
- ), s.choices[0].message.content) : (console.info("Unknown SSE data format:", s), null), v = (s, e, n) => {
46
- if (e?.(s), n) {
47
- const t = w(s);
48
- t && n(t);
45
+ ), s.choices[0].message.content) : (console.info("Unknown SSE data format:", s), null), D = (s, t, n) => {
46
+ if (t?.(s), n) {
47
+ const e = v(s);
48
+ e && n(e);
49
49
  }
50
- }, D = (s, e) => s.error || s.message || `${e.status} ${e.statusText}`, b = (s, e) => {
50
+ }, b = (s, t) => s.error || s.message || `${t.status} ${t.statusText}`, q = (s, t) => {
51
51
  const n = s?.reduce(
52
- (t, o) => (t[o.index] = o, t),
52
+ (e, r) => (e[r.index] = r, e),
53
53
  {}
54
54
  );
55
- return e.forEach((t) => {
56
- n[t.index] ? (t.attachments && (n[t.index].attachments = (n[t.index].attachments || []).concat(t.attachments)), t.content && (n[t.index].content = (n[t.index].content || "") + t.content), t.name && (n[t.index].name = (n[t.index].name || "") + t.name), t.status && (n[t.index].status = t.status)) : n[t.index] = t;
55
+ return t.forEach((e) => {
56
+ n[e.index] ? (e.attachments && (n[e.index].attachments = (n[e.index].attachments || []).concat(e.attachments)), e.content && (n[e.index].content = (n[e.index].content || "") + e.content), e.name && (n[e.index].name = (n[e.index].name || "") + e.name), e.status && (n[e.index].status = e.status)) : n[e.index] = e;
57
57
  }), Object.values(n);
58
- }, Z = (s, e) => {
58
+ }, ee = (s, t) => {
59
59
  const n = structuredClone(s);
60
- return e.forEach((t) => {
61
- t.errorMessage && (n.errorMessage = t.errorMessage), t.role && (n.role = t.role), t.responseId && (n.responseId = t.responseId), t.content && q(n, t), t.custom_content && (n.custom_content || (n.custom_content = {}), t.custom_content.attachments && (n.custom_content.attachments || (n.custom_content.attachments = []), n.custom_content.attachments = n.custom_content.attachments.concat(
62
- t.custom_content.attachments
63
- )), t.custom_content.stages && (n.custom_content.stages || (n.custom_content.stages = []), n.custom_content.stages = b(
60
+ return t.forEach((e) => {
61
+ e.errorMessage && (n.errorMessage = e.errorMessage), e.role && (n.role = e.role), e.responseId && (n.responseId = e.responseId), e.content && L(n, e), e.custom_content && (n.custom_content || (n.custom_content = {}), e.custom_content.attachments && (n.custom_content.attachments || (n.custom_content.attachments = []), n.custom_content.attachments = n.custom_content.attachments.concat(
62
+ e.custom_content.attachments
63
+ )), e.custom_content.stages && (n.custom_content.stages || (n.custom_content.stages = []), n.custom_content.stages = q(
64
64
  n.custom_content.stages,
65
- t.custom_content.stages
66
- )), t.custom_content.state && (n.custom_content.state = t.custom_content.state), t.custom_content.form_schema && (n.custom_content.form_schema = t.custom_content.form_schema), t.custom_content.form_value && (n.custom_content.form_value = t.custom_content.form_value));
65
+ e.custom_content.stages
66
+ )), e.custom_content.state && (n.custom_content.state = e.custom_content.state), e.custom_content.form_schema && (n.custom_content.form_schema = e.custom_content.form_schema), e.custom_content.form_value && (n.custom_content.form_value = e.custom_content.form_value));
67
67
  }), n;
68
68
  };
69
- function q(s, e) {
70
- if (e.content) {
71
- const n = L(e.content);
72
- n != null ? s.content = s.content.slice(0, -n) : s.content = `${s.content || ""}${e.content}`;
69
+ function L(s, t) {
70
+ if (t.content) {
71
+ const n = V(t.content);
72
+ n != null ? s.content = s.content.slice(0, -n) : s.content = `${s.content || ""}${t.content}`;
73
73
  }
74
74
  }
75
- function L(s) {
76
- const e = s.match(/delete_chars\((\d+)\)/);
77
- return e != null ? parseInt(e[1], 10) : null;
75
+ function V(s) {
76
+ const t = s.match(/delete_chars\((\d+)\)/);
77
+ return t != null ? parseInt(t[1], 10) : null;
78
78
  }
79
- const V = {
79
+ const M = {
80
80
  CHAT: "/api/chat"
81
- }, M = "application/json", P = "Content-Type", S = "Api-Key", H = "X-CONVERSATION-ID", I = "Ocp-Apim-Subscription-Key";
82
- class p extends Error {
83
- constructor(e) {
84
- super(e.message), this.isHttpError = !0, this.name = "HttpError", this.code = e.code, this.status = e.status, this.details = e.details, this.displayMessage = e.displayMessage;
81
+ }, H = "application/json", x = "Content-Type", p = "Api-Key", P = "X-CONVERSATION-ID", I = "Ocp-Apim-Subscription-Key";
82
+ class A extends Error {
83
+ constructor(t) {
84
+ super(t.message), this.isHttpError = !0, this.name = "HttpError", this.code = t.code, this.status = t.status, this.details = t.details, this.displayMessage = t.displayMessage;
85
85
  }
86
86
  }
87
- const x = (s) => new RegExp("\\p{L}", "u").test(s) || new RegExp("\\p{N}", "u").test(s), U = (s) => {
87
+ const U = (s) => new RegExp("\\p{L}", "u").test(s) || new RegExp("\\p{N}", "u").test(s), F = (s) => {
88
88
  if (!s) return "";
89
- const e = s.toLowerCase(), n = [];
90
- let t = "";
91
- for (const o of e)
92
- x(o) ? t += o : t && (n.push(t), t = "");
93
- return t && n.push(t), n.join(" ");
94
- }, _ = (s, e, n) => {
95
- const t = {};
96
- return e?.contentType !== null && (t[P] = e?.contentType || M), e?.jwt ? t.Authorization = `Bearer ${e.jwt}` : s && (t[S] = s), e?.chatReference && (t[H] = e.chatReference), { ...t, ...n };
97
- }, F = (s) => {
98
- const e = { ...s };
99
- return e[S] && (e[S] = e[S].substring(0, 8) + "...[REDACTED]"), e.Authorization && (e.Authorization = "Bearer [REDACTED]"), e[I] && (e[I] = e[I].substring(0, 8) + "...[REDACTED]"), e;
100
- }, K = (s) => ({
89
+ const t = s.toLowerCase(), n = [];
90
+ let e = "";
91
+ for (const r of t)
92
+ U(r) ? e += r : e && (n.push(e), e = "");
93
+ return e && n.push(e), n.join(" ");
94
+ }, _ = (s, t, n) => {
95
+ const e = {};
96
+ return t?.contentType !== null && (e[x] = t?.contentType || H), t?.jwt ? e.Authorization = `Bearer ${t.jwt}` : s && (e[p] = s), t?.chatReference && (e[P] = t.chatReference), { ...e, ...n };
97
+ }, K = (s) => {
98
+ const t = { ...s };
99
+ return t[p] && (t[p] = t[p].substring(0, 8) + "...[REDACTED]"), t.Authorization && (t.Authorization = "Bearer [REDACTED]"), t[I] && (t[I] = t[I].substring(0, 8) + "...[REDACTED]"), t;
100
+ }, j = (s) => ({
101
101
  "Content-Type": `multipart/form-data; boundary=${s}`
102
- }), j = (s) => {
103
- const e = s.name?.split("__") || [], n = e.length > 1 ? e.slice(1).join("__") : s.name;
104
- return { modelId: e[0], conversationName: n };
105
- }, k = (s) => {
106
- const e = Date.now(), n = U(s.name);
107
- return `${s.folderId}/${n}-${e}`;
108
- }, tt = (s) => ({ resourceTypes: [A.CONVERSATION], with: s }), T = async (s, e, n) => {
109
- const t = n?.body === void 0 ? void 0 : n?.isFormData ? n.body : JSON.stringify(n.body);
102
+ }), k = (s) => {
103
+ const t = s.name?.split("__") || [], n = t.length > 1 ? t.slice(1).join("__") : s.name;
104
+ return { modelId: t[0], conversationName: n };
105
+ }, Y = (s) => {
106
+ const t = Date.now(), n = F(s.name);
107
+ return `${s.folderId}/${n}-${t}`;
108
+ }, te = (s) => ({ resourceTypes: [N.CONVERSATION], with: s }), T = async (s, t, n) => {
109
+ const e = n?.body === void 0 ? void 0 : n?.isFormData ? n.body : JSON.stringify(n.body);
110
110
  return await fetch(s, {
111
111
  method: n.method || "GET",
112
- headers: e,
113
- body: t,
112
+ headers: t,
113
+ body: e,
114
114
  signal: n?.signal
115
115
  });
116
116
  };
117
- function E(s) {
118
- return s.split("/").map((e) => encodeURIComponent(e)).join("/");
117
+ function h(s) {
118
+ return s.split("/").map((t) => encodeURIComponent(t)).join("/");
119
119
  }
120
- function et(s) {
121
- return s.split("/").map((e) => decodeURIComponent(e)).join("/");
120
+ function ne(s) {
121
+ return s.split("/").map((t) => decodeURIComponent(t)).join("/");
122
122
  }
123
- function Y(s) {
124
- if (s?.kind !== y.RATE_LIMIT || typeof s.retryAfterSeconds != "number")
123
+ function B(s) {
124
+ if (s?.kind !== C.RATE_LIMIT || typeof s.retryAfterSeconds != "number")
125
125
  return null;
126
- const e = new Date(s.occurredAt).getTime();
127
- return Number.isNaN(e) ? null : new Date(e + s.retryAfterSeconds * 1e3);
126
+ const t = new Date(s.occurredAt).getTime();
127
+ return Number.isNaN(t) ? null : new Date(t + s.retryAfterSeconds * 1e3);
128
128
  }
129
- function nt(s, e = Date.now()) {
130
- const n = Y(s);
131
- return n ? n.getTime() > e : !1;
129
+ function se(s, t = Date.now()) {
130
+ const n = B(s);
131
+ return n ? n.getTime() > t : !1;
132
132
  }
133
- function st(s, e = "en-GB") {
133
+ function re(s, t = "en-GB") {
134
134
  return {
135
- date: s.toLocaleDateString(e),
136
- time: s.toLocaleTimeString(e, {
135
+ date: s.toLocaleDateString(t),
136
+ time: s.toLocaleTimeString(t, {
137
137
  hour: "2-digit",
138
138
  minute: "2-digit"
139
139
  })
140
140
  };
141
141
  }
142
- class B {
142
+ class G {
143
143
  constructor() {
144
144
  this.decoder = new TextDecoder();
145
145
  }
146
- async streamChat(e, n, t = {}, o) {
147
- const { onMessage: a, onError: r, onComplete: c, signal: i } = t;
146
+ async streamChat(t, n, e = {}, r) {
147
+ const { onMessage: o, onError: c, onComplete: a, signal: i } = e;
148
148
  try {
149
149
  const u = await this.initializeStreamRequest(
150
- e,
150
+ t,
151
151
  n,
152
152
  i,
153
- o
153
+ r
154
154
  );
155
- await this.processStreamData(u, a), c?.();
155
+ await this.processStreamData(u, o), a?.();
156
156
  } catch (u) {
157
- this.handleStreamError(u, r);
157
+ this.handleStreamError(u, c);
158
158
  }
159
159
  }
160
- async initializeStreamRequest(e, n, t, o) {
161
- const a = _(void 0, {
162
- jwt: o
163
- }), r = await T(
164
- e,
160
+ async initializeStreamRequest(t, n, e, r) {
161
+ const o = _(void 0, {
162
+ jwt: r
163
+ }), c = await T(
164
+ t,
165
165
  {
166
166
  Accept: "text/event-stream",
167
- ...a
167
+ ...o
168
168
  },
169
169
  {
170
170
  method: "POST",
171
171
  body: n,
172
- signal: t
172
+ signal: e
173
173
  }
174
174
  );
175
- if (!r.ok) {
176
- const c = await r.text();
175
+ if (!c.ok) {
176
+ const a = await c.text();
177
177
  let i = {};
178
178
  try {
179
- i = JSON.parse(c);
179
+ i = JSON.parse(a);
180
180
  } catch {
181
181
  i.error = "Failed to parse error body";
182
182
  }
183
- throw new p({
184
- status: r.status,
183
+ throw new A({
184
+ status: c.status,
185
185
  message: i.error ?? "No response body"
186
186
  });
187
187
  }
188
- if (!r.body)
189
- throw new p({
188
+ if (!c.body)
189
+ throw new A({
190
190
  message: "No response body",
191
- status: r.status
191
+ status: c.status
192
192
  });
193
- return r.body.getReader();
193
+ return c.body.getReader();
194
194
  }
195
- async processStreamData(e, n) {
196
- let t = "";
195
+ async processStreamData(t, n) {
196
+ let e = "";
197
197
  try {
198
198
  for (; ; ) {
199
- const { done: o, value: a } = await e.read();
200
- if (o) {
201
- t.trim() && this.parseSSEDataLine(t, n);
199
+ const { done: r, value: o } = await t.read();
200
+ if (r) {
201
+ e.trim() && this.parseSSEDataLine(e, n);
202
202
  break;
203
203
  }
204
- const r = this.decoder.decode(a, { stream: !0 });
205
- t += r;
206
- const c = t.split(`
204
+ const c = this.decoder.decode(o, { stream: !0 });
205
+ e += c;
206
+ const a = e.split(`
207
207
  `);
208
- t = c.pop() || "";
209
- for (const i of c)
208
+ e = a.pop() || "";
209
+ for (const i of a)
210
210
  this.parseSSEDataLine(i, n);
211
211
  }
212
212
  } finally {
213
- e.releaseLock();
213
+ t.releaseLock();
214
214
  }
215
215
  }
216
- handleStreamError(e, n) {
217
- const t = e instanceof Error ? e : new Error(String(e));
218
- throw n?.(t), t;
216
+ handleStreamError(t, n) {
217
+ const e = t instanceof Error ? t : new Error(String(t));
218
+ throw n?.(e), e;
219
219
  }
220
- parseSSEDataLine(e, n) {
221
- const t = e.trim();
222
- if (!(!t || t.startsWith(":")) && t.startsWith("data: ")) {
223
- const o = t.slice(6);
224
- if (o === "[DONE]") {
220
+ parseSSEDataLine(t, n) {
221
+ const e = t.trim();
222
+ if (!(!e || e.startsWith(":")) && e.startsWith("data: ")) {
223
+ const r = e.slice(6);
224
+ if (r === "[DONE]") {
225
225
  console.info("SSE: Stream completed");
226
226
  return;
227
227
  }
228
- let a;
228
+ let o;
229
229
  try {
230
- a = JSON.parse(o);
231
- } catch (r) {
232
- console.error(`Failed to parse SSE data: ${o} ${r}`);
230
+ o = JSON.parse(r);
231
+ } catch (c) {
232
+ console.error(`Failed to parse SSE data: ${r} ${c}`);
233
233
  }
234
- n?.(a);
234
+ n?.(o);
235
235
  }
236
236
  }
237
237
  }
238
- const G = new B(), ot = async (s, e, n, t, o) => {
239
- const { onMessage: a, onToken: r, onComplete: c, onError: i, model: u, signal: m } = n, O = {
238
+ const J = new G(), oe = async (s, t, n, e, r) => {
239
+ const { onMessage: o, onToken: c, onComplete: a, onError: i, model: u, signal: E } = n, O = {
240
240
  conversationId: s,
241
- messages: e,
241
+ messages: t,
242
242
  model: u,
243
- custom_fields: o
243
+ custom_fields: r
244
244
  };
245
- await G.streamChat(
246
- V.CHAT,
245
+ await J.streamChat(
246
+ M.CHAT,
247
247
  O,
248
248
  {
249
- onMessage: (N) => v(N, a, r),
250
- onComplete: c,
249
+ onMessage: (y) => D(y, o, c),
250
+ onComplete: a,
251
251
  onError: i,
252
- signal: m
252
+ signal: E
253
253
  },
254
- t
254
+ e
255
255
  );
256
- }, l = (s) => s instanceof Error && s.message.includes("404"), f = (s) => `/v1/conversations/${E(s)}`;
257
- class rt {
258
- constructor(e) {
259
- this.client = e;
256
+ }, l = (s) => s instanceof Error && s.message.includes("404"), R = (s) => `/v1/conversations/${h(s)}`;
257
+ function m(s) {
258
+ console.warn(
259
+ "[ConversationApi] suppressed error, returning empty result",
260
+ s
261
+ );
262
+ }
263
+ class ce {
264
+ constructor(t) {
265
+ this.client = t;
260
266
  }
261
- async getConversations(e, n, t) {
262
- const o = `${n ? t ? `${n}/${t}` : `${n}` : ""}`, a = `${d.CONVERSATIONS}/${o}`;
267
+ async getConversations(t, n, e) {
268
+ const r = `${n ? e ? `${n}/${e}` : `${n}` : ""}`, o = `${d.CONVERSATIONS}/${r}`;
263
269
  try {
264
- return (await this.client.getRequest(a + "/?limit=1000&recursive=false", e).then((c) => c.items || [])).map((c) => {
265
- const { conversationName: i, modelId: u } = j(c);
270
+ return (await this.client.getRequest(o + "/?limit=1000&recursive=false", t).then((a) => a.items || [])).map((a) => {
271
+ const { conversationName: i, modelId: u } = k(a);
266
272
  return {
267
- id: c.url?.replace("conversations/", "") || c.name,
273
+ id: a.url?.replace("conversations/", "") || a.name,
268
274
  name: i,
269
- folderId: o,
270
- createdAt: c.createdAt,
271
- updatedAt: c.updatedAt,
275
+ folderId: r,
276
+ createdAt: a.createdAt,
277
+ updatedAt: a.updatedAt,
272
278
  model: { id: u, name: u }
273
279
  };
274
280
  });
275
- } catch (r) {
276
- if (l(r))
277
- return [];
278
- throw r;
281
+ } catch (c) {
282
+ if (l(c))
283
+ return m({ endpoint: o, error: c }), [];
284
+ throw c;
279
285
  }
280
286
  }
281
- async getConversation(e, n) {
287
+ async getConversation(t, n) {
282
288
  try {
283
289
  return await this.client.getRequest(
284
- f(e),
290
+ R(t),
285
291
  n
286
292
  );
287
- } catch (t) {
288
- if (l(t))
289
- return null;
290
- throw t;
293
+ } catch (e) {
294
+ if (l(e))
295
+ return m({ endpoint: R(t), error: e }), null;
296
+ throw e;
291
297
  }
292
298
  }
293
- async getFile(e, n) {
299
+ async getFile(t, n) {
294
300
  try {
295
- const t = `${d.VERSION}/${E(e)}`;
296
- return await this.client.getRequest(t, n);
297
- } catch (t) {
298
- if (l(t))
299
- return null;
300
- throw t;
301
+ const e = `${d.VERSION}/${h(t)}`;
302
+ return await this.client.getRequest(e, n);
303
+ } catch (e) {
304
+ if (l(e))
305
+ return m({ filePath: t, error: e }), null;
306
+ throw e;
301
307
  }
302
308
  }
303
- async putOnboardingFile(e, n, t, o) {
309
+ async putOnboardingFile(t, n, e, r) {
304
310
  try {
305
- const a = `${d.VERSION}/${E(n)}`, r = "----NodeMultipartBoundary", i = [
306
- `--${r}`,
307
- `Content-Disposition: form-data; name="file"; filename="${e}"`,
311
+ const o = `${d.VERSION}/${h(n)}`, c = "----NodeMultipartBoundary", i = [
312
+ `--${c}`,
313
+ `Content-Disposition: form-data; name="file"; filename="${t}"`,
308
314
  "Content-Type: application/json",
309
315
  "",
310
- JSON.stringify(t),
311
- `--${r}--`,
316
+ JSON.stringify(e),
317
+ `--${c}--`,
312
318
  ""
313
319
  ].join(`\r
314
320
  `);
315
- return await this.client.request(a, o, {
321
+ return await this.client.request(o, r, {
316
322
  method: "PUT",
317
323
  body: i,
318
- headers: K(r),
324
+ headers: j(c),
319
325
  isFormData: !0
320
326
  });
321
- } catch (a) {
322
- if (l(a))
323
- return null;
324
- throw a;
327
+ } catch (o) {
328
+ if (l(o))
329
+ return m({ filePath: n, error: o }), null;
330
+ throw o;
325
331
  }
326
332
  }
327
- async getOnboardingFile(e, n) {
333
+ async getOnboardingFile(t, n) {
328
334
  try {
329
- const t = `${d.VERSION}/${E(e)}`;
330
- return await this.client.getRequest(t, n);
331
- } catch (t) {
332
- if (l(t))
333
- return null;
334
- throw t;
335
+ const e = `${d.VERSION}/${h(t)}`;
336
+ return await this.client.getRequest(e, n);
337
+ } catch (e) {
338
+ if (l(e))
339
+ return m({ filePath: t, error: e }), null;
340
+ throw e;
335
341
  }
336
342
  }
337
- async getFileBlob(e, n) {
343
+ async getFileBlob(t, n) {
338
344
  try {
339
- const t = `${d.VERSION}/${E(e)}`;
340
- return await this.client.requestBlob(t, n, { method: "GET" });
341
- } catch (t) {
342
- if (l(t))
343
- return null;
344
- throw t;
345
+ const e = `${d.VERSION}/${h(t)}`;
346
+ return await this.client.requestBlob(e, n, { method: "GET" });
347
+ } catch (e) {
348
+ if (l(e))
349
+ return m({ filePath: t, error: e }), null;
350
+ throw e;
345
351
  }
346
352
  }
347
- async deleteFile(e, n) {
353
+ async deleteFile(t, n) {
348
354
  try {
349
- const t = `${d.VERSION}/${E(e)}`;
350
- await this.client.request(t, n, { method: "DELETE" });
351
- } catch (t) {
352
- if (l(t))
355
+ const e = `${d.VERSION}/${h(t)}`;
356
+ await this.client.request(e, n, { method: "DELETE" });
357
+ } catch (e) {
358
+ if (l(e)) {
359
+ m({ filePath: t, error: e });
353
360
  return;
354
- throw t;
361
+ }
362
+ throw e;
355
363
  }
356
364
  }
357
- async putFile(e, n, t) {
365
+ async putFile(t, n, e) {
358
366
  try {
359
- const o = `${d.VERSION}/${E(e)}`, a = new FormData(), r = decodeURIComponent(e.split("/").at(-1) ?? "file");
360
- a.append("attachment", n, r), await this.client.request(o, t, {
367
+ const r = `${d.VERSION}/${h(t)}`, o = new FormData(), c = decodeURIComponent(t.split("/").at(-1) ?? "file");
368
+ o.append("attachment", n, c), await this.client.request(r, e, {
361
369
  method: "PUT",
362
- body: a,
370
+ body: o,
363
371
  isFormData: !0
364
372
  });
365
- } catch (o) {
366
- if (l(o))
373
+ } catch (r) {
374
+ if (l(r)) {
375
+ m({ filePath: t, error: r });
367
376
  return;
368
- throw o;
377
+ }
378
+ throw r;
369
379
  }
370
380
  }
371
- async createConversation(e, n) {
372
- const t = e?.id || k(e), { name: o, folderId: a, model: r, messages: c, custom_fields: i } = e, u = {
373
- id: t,
374
- name: o,
375
- folderId: a,
376
- model: r,
377
- messages: c || [],
378
- selectedAddons: e.selectedAddons || [],
379
- prompt: e.prompt || "",
380
- temperature: e.temperature || 0.7,
381
+ async createConversation(t, n) {
382
+ const e = t?.id || Y(t), { name: r, folderId: o, model: c, messages: a, custom_fields: i } = t, u = {
383
+ id: e,
384
+ name: r,
385
+ folderId: o,
386
+ model: c,
387
+ messages: a || [],
388
+ selectedAddons: t.selectedAddons || [],
389
+ prompt: t.prompt || "",
390
+ temperature: t.temperature || 0.7,
381
391
  createdAt: Date.now(),
382
392
  updatedAt: Date.now(),
383
393
  custom_fields: i
384
394
  };
385
395
  return await this.client.request(
386
- f(t),
396
+ R(e),
387
397
  n,
388
398
  {
389
399
  method: "PUT",
390
400
  body: u
391
401
  }
392
402
  ), {
393
- id: t,
394
- name: o,
395
- folderId: a,
396
- model: r,
403
+ id: e,
404
+ name: r,
405
+ folderId: o,
406
+ model: c,
397
407
  createdAt: u.createdAt,
398
408
  updatedAt: u.updatedAt
399
409
  };
400
410
  }
401
- async generateConversationLink(e, n) {
411
+ async generateConversationLink(t, n) {
402
412
  return await this.client.postRequest(
403
413
  d.SHARE_CONVERSATION,
404
- e,
414
+ t,
405
415
  {
406
416
  body: n
407
417
  }
408
418
  );
409
419
  }
410
- async getSharedConversations(e, n) {
420
+ async getSharedConversations(t, n) {
411
421
  return await this.client.postRequest(
412
422
  d.SHARE_CONVERSATION_LIST,
413
- e,
423
+ t,
414
424
  {
415
425
  body: n
416
426
  }
417
427
  );
418
428
  }
419
- async revokeSharedConversations(e, n) {
429
+ async revokeSharedConversations(t, n) {
420
430
  await this.client.postRequest(
421
431
  d.SHARE_CONVERSATION_REVOKE,
422
- e,
432
+ t,
423
433
  {
424
434
  body: n
425
435
  }
426
436
  );
427
437
  }
428
- async updateConversation(e, n, t) {
429
- const o = await this.getConversation(e, t);
430
- if (!o)
431
- throw new Error(`Conversation with id ${e} not found`);
432
- const a = {
433
- ...o,
438
+ async updateConversation(t, n, e) {
439
+ const r = await this.getConversation(t, e);
440
+ if (!r)
441
+ throw new Error(`Conversation with id ${t} not found`);
442
+ const o = {
443
+ ...r,
434
444
  ...n,
435
445
  updatedAt: Date.now()
436
446
  };
437
447
  return await this.client.request(
438
- f(e),
439
- t,
448
+ R(t),
449
+ e,
440
450
  {
441
451
  method: "PUT",
442
- body: a
452
+ body: o
443
453
  }
444
454
  );
445
455
  }
446
- async deleteConversation(e, n, t) {
456
+ async deleteConversation(t, n, e) {
447
457
  n?.isShared ? await this.client.postRequest(
448
458
  d.SHARE_CONVERSATION_DISCARD,
449
- t,
459
+ e,
450
460
  {
451
461
  body: {
452
462
  resources: [
@@ -456,208 +466,208 @@ class rt {
456
466
  ]
457
467
  }
458
468
  }
459
- ) : await this.client.request(f(decodeURI(e)), t, {
469
+ ) : await this.client.request(R(decodeURI(t)), e, {
460
470
  method: "DELETE"
461
471
  });
462
472
  }
463
- async streamChat(e, n) {
464
- const t = e.model.id, o = encodeURIComponent(t), a = `${d.CHAT(o)}?api-version=${this.client.config.version}`, r = {
465
- messages: e.messages,
473
+ async streamChat(t, n) {
474
+ const e = t.model.id, r = encodeURIComponent(e), o = `${d.CHAT(r)}?api-version=${this.client.config.version}`, c = {
475
+ messages: t.messages,
466
476
  stream: !0,
467
477
  temperature: 0.7,
468
478
  max_tokens: 4096,
469
- custom_fields: e.custom_fields
479
+ custom_fields: t.custom_fields
470
480
  };
471
- return await this.client.stream(a, n, {
481
+ return await this.client.stream(o, n, {
472
482
  method: "POST",
473
- body: r,
474
- chatReference: e.conversationId
483
+ body: c,
484
+ chatReference: t.conversationId
475
485
  });
476
486
  }
477
- async rateResponse(e, n, t, o) {
487
+ async rateResponse(t, n, e, r) {
478
488
  return await this.client.postRequest(
479
- d.RATE(e),
480
- o,
489
+ d.RATE(t),
490
+ r,
481
491
  {
482
492
  body: {
483
493
  responseId: n,
484
- rate: t
494
+ rate: e
485
495
  }
486
496
  }
487
497
  );
488
498
  }
489
- async renameConversation(e, n, t) {
490
- return await this.client.postRequest(d.RENAME, t, {
499
+ async renameConversation(t, n, e) {
500
+ return await this.client.postRequest(d.RENAME, e, {
491
501
  body: {
492
- sourceUrl: e,
502
+ sourceUrl: t,
493
503
  destinationUrl: n,
494
504
  overwrite: !0
495
505
  }
496
506
  });
497
507
  }
498
508
  }
499
- class at {
500
- constructor(e) {
501
- this.config = e, console.info("DialApiClient initialized", {
502
- host: e.host || "NOT SET",
503
- hasApiKey: !!e.apiKey,
504
- version: e.version
509
+ class ae {
510
+ constructor(t) {
511
+ this.config = t, console.info("DialApiClient initialized", {
512
+ host: t.host || "NOT SET",
513
+ hasApiKey: !!t.apiKey,
514
+ version: t.version
505
515
  });
506
516
  }
507
- async getRequest(e, n, t) {
508
- return this.request(e, n, { ...t, method: "GET" });
517
+ async getRequest(t, n, e) {
518
+ return this.request(t, n, { ...e, method: "GET" });
509
519
  }
510
- async postRequest(e, n, t) {
511
- return this.request(e, n, { ...t, method: "POST" });
520
+ async postRequest(t, n, e) {
521
+ return this.request(t, n, { ...e, method: "POST" });
512
522
  }
513
- async requestBlob(e, n, t) {
514
- const o = `${this.config.host}${e}`, a = {
523
+ async requestBlob(t, n, e) {
524
+ const r = `${this.config.host}${t}`, o = {
515
525
  ..._(this.config.apiKey, {
516
526
  jwt: n,
517
- chatReference: t.chatReference,
518
- contentType: t.isFormData ? null : void 0
527
+ chatReference: e.chatReference,
528
+ contentType: e.isFormData ? null : void 0
519
529
  }),
520
- ...t.headers
530
+ ...e.headers
521
531
  };
522
532
  try {
523
- return (await T(o, a, t)).blob();
524
- } catch (r) {
533
+ return (await T(r, o, e)).blob();
534
+ } catch (c) {
525
535
  throw console.error("API Request Exception", {
526
- method: t.method,
527
- url: o,
528
- error: r instanceof Error ? r.message : String(r)
529
- }), r;
536
+ method: e.method,
537
+ url: r,
538
+ error: c instanceof Error ? c.message : String(c)
539
+ }), c;
530
540
  }
531
541
  }
532
- async request(e, n, t) {
533
- const o = Date.now(), a = `${this.config.host}${e}`, r = {
542
+ async request(t, n, e) {
543
+ const r = Date.now(), o = `${this.config.host}${t}`, c = {
534
544
  ..._(this.config.apiKey, {
535
545
  jwt: n,
536
- chatReference: t.chatReference,
537
- contentType: t.isFormData ? null : void 0
546
+ chatReference: e.chatReference,
547
+ contentType: e.isFormData ? null : void 0
538
548
  }),
539
- ...t.headers
549
+ ...e.headers
540
550
  };
541
- this.addInfoRequestLog("API Request", a, t, r);
551
+ this.addInfoRequestLog("API Request", o, e, c);
542
552
  try {
543
- const c = await T(a, r, t), i = Date.now() - o;
553
+ const a = await T(o, c, e), i = Date.now() - r;
544
554
  let u;
545
- const m = await c.text();
555
+ const E = await a.text();
546
556
  try {
547
- u = m ? JSON.parse(m) : {};
557
+ u = E ? JSON.parse(E) : {};
548
558
  } catch {
549
559
  if (this.addErrorRequestParsing(
560
+ o,
561
+ e,
550
562
  a,
551
- t,
552
- c,
553
563
  i,
554
- m
555
- ), !c.ok)
564
+ E
565
+ ), !a.ok)
556
566
  throw new Error(
557
- `API request failed: ${c.status} ${c.statusText} - ${m.substring(0, 100)}`
567
+ `API request failed: ${a.status} ${a.statusText} - ${E.substring(0, 100)}`
558
568
  );
559
- u = { data: m };
569
+ u = { data: E };
560
570
  }
561
- if (!c.ok) {
562
- this.addErrorRequestLog(a, t, c, i, u);
563
- const O = D(u, c);
571
+ if (!a.ok) {
572
+ this.addErrorRequestLog(o, e, a, i, u);
573
+ const O = b(u, a);
564
574
  throw new Error(`API request failed: ${O}`);
565
575
  }
566
576
  return u;
567
- } catch (c) {
568
- const i = Date.now() - o;
577
+ } catch (a) {
578
+ const i = Date.now() - r;
569
579
  throw console.error("API Request Exception", {
570
- method: t.method,
571
- url: a,
580
+ method: e.method,
581
+ url: o,
572
582
  duration: `${i}ms`,
573
- error: c instanceof Error ? c.message : String(c)
574
- }), c;
583
+ error: a instanceof Error ? a.message : String(a)
584
+ }), a;
575
585
  }
576
586
  }
577
- async stream(e, n, t) {
578
- const o = `${this.config.host}${e}`, a = _(
587
+ async stream(t, n, e) {
588
+ const r = `${this.config.host}${t}`, o = _(
579
589
  this.config.apiKey,
580
590
  {
581
591
  jwt: n,
582
- chatReference: t.chatReference,
583
- contentType: t.isFormData ? null : void 0
592
+ chatReference: e.chatReference,
593
+ contentType: e.isFormData ? null : void 0
584
594
  },
585
- t.headers
595
+ e.headers
586
596
  );
587
- this.addInfoRequestLog("Stream Request", o, t, a);
588
- const r = await T(o, a, t);
589
- if (!r.ok)
597
+ this.addInfoRequestLog("Stream Request", r, e, o);
598
+ const c = await T(r, o, e);
599
+ if (!c.ok)
590
600
  throw console.error("Stream Request Failed", {
591
- method: t.method || "POST",
592
- url: o,
593
- status: r.status,
594
- statusText: r.statusText
601
+ method: e.method || "POST",
602
+ url: r,
603
+ status: c.status,
604
+ statusText: c.statusText
595
605
  }), new Error(
596
- `Stream request failed: ${r.status} ${r.statusText}`
606
+ `Stream request failed: ${c.status} ${c.statusText}`
597
607
  );
598
- if (!r.body)
608
+ if (!c.body)
599
609
  throw new Error("No response body for stream");
600
- return r.body;
610
+ return c.body;
601
611
  }
602
- addInfoRequestLog(e, n, t, o) {
603
- const a = {
604
- method: t.method || "GET",
612
+ addInfoRequestLog(t, n, e, r) {
613
+ const o = {
614
+ method: e.method || "GET",
605
615
  url: n,
606
- headers: F(o)
616
+ headers: K(r)
607
617
  };
608
- t.body && (a.body = t.body), console.info(e, a);
618
+ e.body && (o.body = e.body), console.info(t, o);
609
619
  }
610
- addErrorRequestLog(e, n, t, o, a) {
620
+ addErrorRequestLog(t, n, e, r, o) {
611
621
  console.error("API Request Failed", {
612
622
  method: n.method,
613
- url: e,
614
- status: t.status,
615
- statusText: t.statusText,
616
- duration: `${o}ms`,
617
- response: a
623
+ url: t,
624
+ status: e.status,
625
+ statusText: e.statusText,
626
+ duration: `${r}ms`,
627
+ response: o
618
628
  });
619
629
  }
620
- addErrorRequestParsing(e, n, t, o, a) {
630
+ addErrorRequestParsing(t, n, e, r, o) {
621
631
  console.error("API Response Parse Error", {
622
632
  method: n.method,
623
- url: e,
624
- status: t.status,
625
- statusText: t.statusText,
626
- duration: `${o}ms`,
627
- responseText: a.substring(0, 200),
633
+ url: t,
634
+ status: e.status,
635
+ statusText: e.statusText,
636
+ duration: `${r}ms`,
637
+ responseText: o.substring(0, 200),
628
638
  // First 200 chars
629
639
  error: "Response is not valid JSON"
630
640
  });
631
641
  }
632
642
  }
633
643
  export {
634
- g as AttachmentType,
635
- J as COMPLETION_FINISH_REASON,
636
- Q as CUSTOM_VIEW_STATE_KEY,
637
- B as ChatStreamSSEClient,
638
- rt as ConversationApi,
644
+ $ as AttachmentType,
645
+ z as COMPLETION_FINISH_REASON,
646
+ Z as CUSTOM_VIEW_STATE_KEY,
647
+ G as ChatStreamSSEClient,
648
+ ce as ConversationApi,
639
649
  d as DIAL_API_ROUTES,
640
- z as DIAL_ERROR_CODES,
641
- W as DIAL_ERROR_TYPES,
642
- at as DialApiClient,
643
- y as ERROR_CONTEXT_KIND,
644
- R as EXCEEDED_LIMIT,
645
- X as EXCEEDED_LIMIT_ORDER,
646
- $ as InvitationType,
647
- A as ResourceTypes,
648
- C as ShareTarget,
649
- G as chatStreamSSEClient,
650
- et as decodeApiUrl,
651
- E as encodeApiUrl,
652
- st as formatDateTime,
653
- k as generateConversationId,
654
- D as getErrorMessage,
655
- Y as getRateLimitRestoreDate,
656
- tt as getSharedConversationsRequest,
657
- v as handleStreamMessage,
658
- nt as isRateLimitStillActive,
659
- Z as mergeMessages,
660
- j as parseConversationName,
650
+ W as DIAL_ERROR_CODES,
651
+ X as DIAL_ERROR_TYPES,
652
+ ae as DialApiClient,
653
+ C as ERROR_CONTEXT_KIND,
654
+ S as EXCEEDED_LIMIT,
655
+ Q as EXCEEDED_LIMIT_ORDER,
656
+ w as InvitationType,
657
+ N as ResourceTypes,
658
+ g as ShareTarget,
659
+ J as chatStreamSSEClient,
660
+ ne as decodeApiUrl,
661
+ h as encodeApiUrl,
662
+ re as formatDateTime,
663
+ Y as generateConversationId,
664
+ b as getErrorMessage,
665
+ B as getRateLimitRestoreDate,
666
+ te as getSharedConversationsRequest,
667
+ D as handleStreamMessage,
668
+ se as isRateLimitStillActive,
669
+ ee as mergeMessages,
670
+ k as parseConversationName,
661
671
  T as sendRequest,
662
- ot as streamChatResponse
672
+ oe as streamChatResponse
663
673
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@epam/statgpt-dial-toolkit",
3
- "version": "0.5.0-rc.37",
3
+ "version": "0.5.0-rc.39",
4
4
  "license": "MIT",
5
5
  "exports": {
6
6
  ".": {
@@ -14,7 +14,7 @@
14
14
  "module": "./index.mjs",
15
15
  "types": "./index.d.ts",
16
16
  "dependencies": {
17
- "@epam/statgpt-shared-toolkit": "0.5.0-rc.37",
17
+ "@epam/statgpt-shared-toolkit": "0.5.0-rc.39",
18
18
  "@epam/ai-dial-shared": "^0.43.3"
19
19
  }
20
20
  }