@opencx/widget-core 4.0.22 → 4.0.24-prerelease.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/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +113 -96
- package/dist/index.js.map +1 -1
- package/dist/src/translation/ar.d.ts +1 -1
- package/dist/src/translation/ar.d.ts.map +1 -1
- package/dist/src/translation/de.d.ts +1 -1
- package/dist/src/translation/de.d.ts.map +1 -1
- package/dist/src/translation/en.d.ts +1 -1
- package/dist/src/translation/en.d.ts.map +1 -1
- package/dist/src/translation/es.d.ts +1 -1
- package/dist/src/translation/es.d.ts.map +1 -1
- package/dist/src/translation/fr.d.ts +1 -1
- package/dist/src/translation/fr.d.ts.map +1 -1
- package/dist/src/translation/index.d.ts +1 -0
- package/dist/src/translation/index.d.ts.map +1 -1
- package/dist/src/translation/nl.d.ts +1 -1
- package/dist/src/translation/nl.d.ts.map +1 -1
- package/dist/src/translation/pl.d.ts +3 -0
- package/dist/src/translation/pl.d.ts.map +1 -0
- package/dist/src/translation/pt.d.ts +1 -1
- package/dist/src/translation/pt.d.ts.map +1 -1
- package/dist/src/translation/tr.d.ts +1 -1
- package/dist/src/translation/tr.d.ts.map +1 -1
- package/dist/src/types/widget-config.d.ts.map +1 -1
- package/package.json +1 -4
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("openapi-fetch"),z=require("lodash.isequal"),O=require("uuid"),B=h=>{console.log(h.error)},q=h=>{const i=N({baseUrl:h.baseUrl}),a={onRequest:h.onRequest,onResponse:h.onResponse,onError:h.onError||B};return i.use(a),i};class U{constructor({config:i}){var d,s;this.userToken=null,this.constructClientOptions=e=>{const t=this.config.apiUrl||"https://api.open.cx",n={"X-Bot-Token":this.config.token,"Content-Type":"application/json",Accept:"application/json",Authorization:e?`Bearer ${e}`:void 0};return{baseUrl:t,headers:n}},this.createOpenAPIClient=({baseUrl:e,headers:t})=>q({baseUrl:e,onRequest:({request:n})=>{Object.entries(t).forEach(([o,r])=>{r&&n.headers.set(o,r)})}}),this.setAuthToken=e=>{this.userToken=e;const{baseUrl:t,headers:n}=this.constructClientOptions(e);this.client=this.createOpenAPIClient({baseUrl:t,headers:n})},this.getExternalWidgetConfig=async()=>await this.client.GET("/backend/widget/v2/config",{params:{header:{"X-Bot-Token":this.config.token}}}),this.sendMessage=async(e,t)=>await this.client.POST("/backend/widget/v2/chat/send",{body:e,signal:t}),this.createUnverifiedContact=async e=>await this.client.POST("/backend/widget/v2/contact/create-unverified",{params:{header:{"x-bot-token":this.config.token}},body:e}),this.createSession=async e=>await this.client.POST("/backend/widget/v2/create-session",{body:e}),this.pollSessionAndHistory=async({sessionId:e,lastMessageTimestamp:t,abortSignal:n})=>{const o=t?{lastMessageTimestamp:t}:void 0;return await this.client.GET("/backend/widget/v2/poll/{sessionId}",{params:{path:{sessionId:e},query:o},signal:n})},this.getSessions=async({cursor:e,filters:t,abortSignal:n})=>await this.client.GET("/backend/widget/v2/sessions",{params:{query:{cursor:e,filters:JSON.stringify(t)}},signal:n}),this.uploadFile=async({file:e,abortSignal:t,onProgress:n})=>new Promise((o,r)=>{var w;const l=new FormData;l.append("file",e);const u=new XMLHttpRequest;if(t&&(t.addEventListener("abort",()=>{u.abort(),r(new DOMException("Aborted","AbortError"))}),t.aborted)){r(new DOMException("Aborted","AbortError"));return}u.upload.addEventListener("progress",p=>{if(p.lengthComputable&&n){const C=Math.round(p.loaded/p.total*100);n(C)}}),u.addEventListener("load",()=>{if(u.status>=200&&u.status<300)try{const p=JSON.parse(u.responseText);o(p)}catch(p){r(new Error(`Failed to parse response: ${p}`))}else r(new Error(`Upload failed with status: ${u.status}`))}),u.addEventListener("error",()=>{r(new Error("Network error occurred"))}),u.addEventListener("timeout",()=>{r(new Error("Upload timed out"))});const{baseUrl:_}=this.constructClientOptions(this.userToken),f=`${_}/backend/widget/v2/upload`;u.open("POST",f),u.setRequestHeader("X-Bot-Token",this.config.token),this.userToken??((w=this.config.user)==null?void 0:w.token)?u.setRequestHeader("Authorization",`Bearer ${this.userToken}`):console.error("User token not set"),u.send(l)}),this.vote=async e=>await this.client.POST("/backend/widget/v2/chat/vote",{body:e}),this.resolveSession=async(e,t)=>await this.client.POST("/backend/widget/v2/session/resolve",{body:e,signal:t}),this.createStateCheckpoint=async e=>await this.client.POST("/backend/widget/v2/checkpoint",{body:e}),this.submitCsat=async e=>await this.client.POST("/backend/widget/v2/submit-csat",{body:e}),this.config=i,this.userToken=((d=i.user)==null?void 0:d.token)||null;const{baseUrl:a,headers:c}=this.constructClientOptions((s=i.user)==null?void 0:s.token);this.client=this.createOpenAPIClient({baseUrl:a,headers:c})}}function R(h,i){console.error(`Missing case for ${h} in ${i}`)}class y{constructor(i){this.subscribers=new Set,this.get=()=>this.state,this.set=a=>{z(this.state,a)||(this.state=a,this.notifySubscribers(a))},this.setPartial=a=>{if(a==null)return;const c={...this.state,...a};this.set(c)},this.reset=()=>{this.set(this.initialState)},this.notifySubscribers=a=>{Array.from(this.subscribers).forEach(d=>{try{d(a)}catch(s){console.error(s)}})},this.subscribe=a=>(this.subscribers.add(a),()=>{this.subscribers.delete(a)}),this.state=i,this.initialState=i}}class F{constructor(){this.state=new y({isPolling:!1,isError:!1}),this.abortController=new AbortController,this.reset=()=>{var i;this.abortController.abort("Resetting poller"),(i=this.stopPolling)==null||i.call(this),this.stopPolling=null},this.stopPolling=null,this.startPolling=(i,a)=>{if(this.stopPolling)return;const c=[],d=async()=>{this.abortController=new AbortController,this.state.setPartial({isPolling:!0});try{await i(this.abortController.signal)}catch(s){if(this.abortController.signal.aborted)return;console.error("Failed to poll:",s),this.state.setPartial({isError:!0})}finally{this.state.setPartial({isPolling:!1})}this.abortController.signal.aborted?console.log("Poller aborted, not scheduling anymore"):c.push(setTimeout(d,a))};d(),this.stopPolling=()=>{c.forEach(clearTimeout),this.state.reset()}}}}function H(h){try{const i=h();return i instanceof Promise?i.then(a=>({data:a})).catch(a=>({error:a})):{data:i}}catch(i){return{error:i}}}class j{constructor({api:i,config:a,sessionCtx:c,messageCtx:d,sessionPollingIntervalSeconds:s}){this.poller=new F,this.fetchSessionAndFullHistoryAbortController=new AbortController,this.registerPolling=()=>{this.sessionCtx.sessionState.subscribe(({session:e})=>{e!=null&&e.id?this.poller.startPolling(async t=>{this.fetchSessionAndHistory({sessionId:e.id,abortSignal:t})},this.sessionPollingIntervalSeconds*1e3):this.poller.reset()}),this.sessionCtx.sessionState.subscribe(({session:e})=>{if(e!=null&&e.id&&!e.isOpened)try{this.fetchSessionAndFullHistoryAbortController=new AbortController,this.fetchSessionAndHistory({sessionId:e.id,abortSignal:this.fetchSessionAndFullHistoryAbortController.signal,fetchFullHistory:!0})}catch(t){this.fetchSessionAndFullHistoryAbortController.signal.aborted||console.error("Failed to fetch session and full history:",t)}else this.fetchSessionAndFullHistoryAbortController.abort()})},this.fetchSessionAndHistory=async({sessionId:e,abortSignal:t,fetchFullHistory:n=!1})=>{var u;this.messageCtx.state.get().messages.length===0&&this.messageCtx.state.setPartial({isInitialFetchLoading:!0});const o=this.messageCtx.state.get().messages,r=o.length>0?((u=o[o.length-1])==null?void 0:u.timestamp)??void 0:void 0,{data:l}=await this.api.pollSessionAndHistory({sessionId:e,abortSignal:t,lastMessageTimestamp:n?void 0:r});if(l!=null&&l.session&&(this.sessionCtx.sessionState.setPartial({session:l.session}),this.sessionCtx.setSessions([l.session])),l!=null&&l.history&&l.history.length>0){const _=this.messageCtx.state.get().messages,b=l.history.map(this.mapHistoryToMessage).filter(f=>f!==null).filter(f=>!_.some(S=>S.id===f.id));this.messageCtx.state.setPartial({messages:[..._,...b]})}this.messageCtx.state.get().isInitialFetchLoading&&this.messageCtx.state.setPartial({isInitialFetchLoading:!1})},this.mapHistoryToMessage=e=>{var n,o;const t={id:e.publicId,timestamp:e.sentAt||"",attachments:e.attachments||void 0};if(e.sender.kind==="user")return{...t,type:"USER",content:e.content.text||"",deliveredAt:e.sentAt||""};if(e.sender.kind==="agent")return{...t,type:"AGENT",component:"agent_message",data:{message:e.content.text||""},agent:{name:e.sender.name||"",avatar:e.sender.avatar||"",id:null,isAi:!1}};if(e.sender.kind==="ai"){const r=e.actionCalls&&e.actionCalls.length>0?e.actionCalls[e.actionCalls.length-1]:void 0;return{...t,type:"AI",component:"bot_message",agent:{id:null,name:((n=this.config.bot)==null?void 0:n.name)||"",isAi:!0,avatar:((o=this.config.bot)==null?void 0:o.avatar)||""},data:{message:e.content.text||"",action:r?{name:r.actionName,data:this.extractActionResult(r)}:void 0}}}if(e.sender.kind==="system"){const r=this.constructSystemMessage(e);return r===null?null:{...r}}return null},this.constructSystemMessage=e=>{if(!e||!e.systemMessagePayload)return null;switch(e.systemMessagePayload.type){case"state_checkpoint":return{id:e.publicId,type:"SYSTEM",subtype:"state_checkpoint",data:{payload:e.systemMessagePayload.payload},timestamp:e.sentAt||"",attachments:void 0};case"csat_requested":return{id:e.publicId,type:"SYSTEM",subtype:"csat_requested",data:{payload:void 0},timestamp:e.sentAt||"",attachments:void 0};case"csat_submitted":return{id:e.publicId,type:"SYSTEM",subtype:"csat_submitted",data:{payload:{score:e.systemMessagePayload.payload.score??void 0,feedback:e.systemMessagePayload.payload.feedback??void 0}},timestamp:e.sentAt||"",attachments:void 0};case"none":return null;default:return R(e.systemMessagePayload,this.constructSystemMessage.name),null}},this.extractActionResult=e=>{const t=e.result;if(t===null||typeof t!="object")return t;if("responseBodyText"in t&&typeof t.responseBodyText=="string"){const n=t.responseBodyText,o=H(()=>JSON.parse(n)).data;if(o)return o}return e.result},this.api=i,this.config=a,this.sessionCtx=c,this.messageCtx=d,this.sessionPollingIntervalSeconds=s,this.registerPolling()}}class Y{constructor({config:i,api:a,storageCtx:c}){var d;this.shouldCollectData=()=>{var s;return!!(!((s=this.state.get().contact)!=null&&s.token)&&this.config.collectUserData)},this.autoCreateUnverifiedUserIfNotExists=async()=>{var s,e,t,n,o,r,l,u,_,b,f,S,w,p;if(!((s=this.config.user)!=null&&s.token)){if(this.config.collectUserData&&!((t=(e=this.config.user)==null?void 0:e.data)!=null&&t.email)){if((n=this.config.extraDataCollectionFields)!=null&&n.length)return;const C=await((o=this.storageCtx)==null?void 0:o.getContactToken());C&&await this.setUnverifiedContact(C);return}if(!((l=(r=this.config.user)==null?void 0:r.data)!=null&&l.email)){const C=await((u=this.storageCtx)==null?void 0:u.getContactToken());if(C){await this.setUnverifiedContact(C);return}}await this.createUnverifiedContact({email:(b=(_=this.config.user)==null?void 0:_.data)==null?void 0:b.email,non_verified_name:(S=(f=this.config.user)==null?void 0:f.data)==null?void 0:S.name,non_verified_custom_data:(p=(w=this.config.user)==null?void 0:w.data)==null?void 0:p.customData})}},this.createUnverifiedContact=async(s,e)=>{this.state.setPartial({extraCollectedData:e});try{this.state.setPartial({isCreatingUnverifiedContact:!0,isErrorCreatingUnverifiedContact:!1});const{data:t}=await this.api.createUnverifiedContact(s);t!=null&&t.token?await this.setUnverifiedContact(t.token):this.state.setPartial({isErrorCreatingUnverifiedContact:!0})}finally{this.state.setPartial({isCreatingUnverifiedContact:!1})}},this.setUnverifiedContact=async s=>{var n,o,r,l;const e=await((n=this.storageCtx)==null?void 0:n.getExternalContactId()),t=((o=this.config.user)==null?void 0:o.externalId)||e||O.v4();this.api.setAuthToken(s),await((r=this.storageCtx)==null?void 0:r.setContactToken(s)),await((l=this.storageCtx)==null?void 0:l.setExternalContactId(t)),this.state.setPartial({contact:{token:s,externalId:t}})},this.config=i,this.storageCtx=c,this.api=a,this.state=new y({contact:(d=i.user)!=null&&d.token?{token:i.user.token,externalId:i.user.externalId}:null,extraCollectedData:void 0,isCreatingUnverifiedContact:!1,isErrorCreatingUnverifiedContact:!1}),this.autoCreateUnverifiedUserIfNotExists()}}function x(){return O.v4()}class ${constructor({config:i,api:a,sessionCtx:c,messageCtx:d}){this.submitCsat=async s=>{var r;const e=(r=this.sessionCtx.sessionState.get().session)==null?void 0:r.id;if(!e)return{data:null,error:"No session id found"};const t=x();this.messageCtx.state.setPartial({messages:[...this.messageCtx.state.get().messages,{id:t,type:"SYSTEM",subtype:"csat_submitted",timestamp:new Date().toISOString(),data:{payload:{score:s.score,feedback:s.feedback}}}]});const{data:n,error:o}=await this.api.submitCsat({...s,system_message_uuid:t,session_id:e});return{data:n,error:o}},this.config=i,this.api=a,this.sessionCtx=c,this.messageCtx=d}}class K{constructor({config:i,api:a,contactCtx:c,sessionsPollingIntervalSeconds:d}){this.sessionsRefresher=new F,this.sessionState=new y({session:null,isCreatingSession:!1,isResolvingSession:!1}),this.sessionsState=new y({data:[],cursor:void 0,isLastPage:!1,didStartInitialFetch:!1,isInitialFetchLoading:!0}),this.reset=async()=>{this.sessionState.reset()},this.registerSessionsRefresherWrapper=()=>{var s;(s=this.contactCtx.state.get().contact)!=null&&s.token&&!this.sessionsState.get().didStartInitialFetch?this.registerSessionsRefresher():this.contactCtx.state.subscribe(({contact:e})=>{e!=null&&e.token&&!this.sessionsState.get().didStartInitialFetch&&this.registerSessionsRefresher()})},this.registerSessionsRefresher=()=>{this.sessionsRefresher.startPolling(async()=>{this.sessionsState.get().didStartInitialFetch===!1&&this.sessionsState.setPartial({didStartInitialFetch:!0}),await this.refreshSessions(),this.sessionsState.get().isInitialFetchLoading===!0&&this.sessionsState.setPartial({isInitialFetchLoading:!1})},this.sessionsPollingIntervalSeconds*1e3)},this.createSession=async()=>{var o;this.sessionState.setPartial({session:null,isCreatingSession:!0});const s=(o=this.contactCtx.state.get().contact)==null?void 0:o.externalId,e={...this.config.sessionCustomData,...s?{external_id:s}:{}},{data:t,error:n}=await this.api.createSession({customData:Object.keys(e).length>0?e:void 0});return t?(this.sessionState.setPartial({session:t,isCreatingSession:!1}),t):(this.sessionState.setPartial({isCreatingSession:!1}),console.error("Failed to create session:",n),null)},this.loadMoreSessions=async()=>{if(this.sessionsState.get().isLastPage)return;const{data:s}=await this.getSessions({cursor:this.sessionsState.get().cursor});if(s){const t=[...this.sessionsState.get().data,...s.items].filter((n,o,r)=>o===r.findIndex(l=>n.id===l.id));this.sessionsState.setPartial({data:t,cursor:s.next||void 0,isLastPage:s.next===null})}},this.getSessions=async({cursor:s})=>{var t,n;if(!((t=this.contactCtx.state.get().contact)!=null&&t.token))return{data:null};const e=(n=this.contactCtx.state.get().contact)==null?void 0:n.externalId;return await this.api.getSessions({cursor:s,filters:e?{external_id:e}:{}})},this.setSessions=s=>{const e=[...s,...this.sessionsState.get().data].filter((t,n,o)=>n===o.findIndex(r=>t.id===r.id));this.sessionsState.setPartial({data:e})},this.refreshSessions=async()=>{const{data:s}=await this.getSessions({cursor:void 0});s&&this.setSessions(s.items)},this.resolveSession=async()=>{const s=this.sessionState.get().session;if(!s||!s.isOpened)return{success:!1,error:"Session is not opened"};this.sessionState.setPartial({isResolvingSession:!0});const{data:e,error:t}=await this.api.resolveSession({session_id:s.id});return e?(this.sessionState.setPartial({session:e,isResolvingSession:!1}),{success:!0,data:e}):(this.sessionState.setPartial({isResolvingSession:!1}),{success:!1,error:t})},this.createStateCheckpoint=async s=>{var o;const e=(o=this.sessionState.get().session)==null?void 0:o.id;if(!e)return;const{data:t,error:n}=await this.api.createStateCheckpoint({session_id:e,payload:s});return t!=null&&t.success?{success:!0}:{success:!1}},this.config=i,this.api=a,this.contactCtx=c,this.sessionsPollingIntervalSeconds=d,this.registerSessionsRefresherWrapper()}}class W{constructor({config:i,api:a,sessionCtx:c,contactCtx:d}){this.state=new y({messages:[],isSendingMessage:!1,lastAIResMightSolveUserIssue:!1,isInitialFetchLoading:!1}),this.sendMessageAbortController=new AbortController,this.reset=()=>{this.sendMessageAbortController.abort("Resetting chat"),this.state.reset()},this.sendMessage=async s=>{var e,t,n,o,r,l,u,_,b,f;try{if(!s.content.trim()&&(!s.attachments||s.attachments.length===0)){console.warn("Cannot send an empty message of no content or attachments");return}const S=this.state.get().isSendingMessage,w=((e=this.sessionCtx.sessionState.get().session)==null?void 0:e.assignee.kind)==="ai",p=this.state.get().messages,C=p.length>0?p[p.length-1]:void 0;if(w&&S||w&&(C==null?void 0:C.type)==="USER"){console.warn("Cannot send messages while awaiting AI response");return}this.sendMessageAbortController=new AbortController,this.state.setPartial({lastAIResMightSolveUserIssue:!1}),this.state.setPartial({isSendingMessage:!0});const A=this.state.get().messages,E=!((t=this.sessionCtx.sessionState.get().session)!=null&&t.id)&&A.length===0&&((n=this.config.advancedInitialMessages)==null?void 0:n.some(g=>g.persistent)),T=E?(this.config.advancedInitialMessages||[]).filter(g=>g.persistent).map(g=>({id:x(),component:"bot_message",type:"AI",timestamp:new Date().toISOString(),data:{message:g.message}})):[],I=this.toUserMessage(s.content.trim(),s.attachments||void 0);if(this.state.setPartial({messages:[...T,...A,I]}),!((o=this.sessionCtx.sessionState.get().session)!=null&&o.id)){if(!await this.sessionCtx.createSession()){console.error("Failed to create session");return}this.sessionCtx.refreshSessions()}const M=(r=this.sessionCtx.sessionState.get().session)==null?void 0:r.id;if(!M)return;const{data:m}=await this.api.sendMessage({uuid:I.id,bot_token:this.config.token,headers:this.config.headers,query_params:this.config.queryParams,body_properties:this.config.bodyProperties,session_id:M,content:I.content,attachments:s.attachments,clientContext:this.config.context,custom_data:{...this.config.messageCustomData||{},...s.customData||{}},language:this.config.language,exit_mode_prompt:s.exitModePrompt,initial_messages:E?T.map(g=>({uuid:g.id,content:g.data.message})):void 0},this.sendMessageAbortController.signal);if(m!=null&&m.success){const g=this.toBotMessage(m);if(g){const k=this.state.get().messages;if(!!k.some(D=>D.id===g.id)){this.state.setPartial({lastAIResMightSolveUserIssue:((l=m.autopilotResponse)==null?void 0:l.mightSolveUserIssue)||((u=m.uiResponse)==null?void 0:u.mightSolveUserIssue)});return}this.state.setPartial({messages:[...k,g],lastAIResMightSolveUserIssue:((_=m.autopilotResponse)==null?void 0:_.mightSolveUserIssue)||((b=m.uiResponse)==null?void 0:b.mightSolveUserIssue)})}m.session&&this.sessionCtx.sessionState.setPartial({session:m.session})}else{const g=this.toBotErrorMessage(((f=m==null?void 0:m.error)==null?void 0:f.message)||"Unknown error occurred"),k=this.state.get().messages;this.state.setPartial({messages:[...k,g]})}}catch(S){this.sendMessageAbortController.signal.aborted||console.error("Failed to send message:",S)}finally{this.state.setPartial({isSendingMessage:!1})}},this.toUserMessage=(s,e)=>{const t=(()=>{const n=this.contactCtx.state.get().extraCollectedData;return this.state.get().messages.length===0&&n&&Object.keys(n).length>0?`${Object.entries(n).filter(([r,l])=>!!l).map(([r,l])=>`${r}: ${l}`).join(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("openapi-fetch"),j=require("lodash.isequal"),O=require("uuid"),N=h=>{console.log(h.error)},B=h=>{const i=D({baseUrl:h.baseUrl}),a={onRequest:h.onRequest,onResponse:h.onResponse,onError:h.onError||N};return i.use(a),i};class U{constructor({config:i}){var d,s;this.userToken=null,this.constructClientOptions=e=>{const t=this.config.apiUrl||"https://api.open.cx",n={"X-Bot-Token":this.config.token,"Content-Type":"application/json",Accept:"application/json",Authorization:e?`Bearer ${e}`:void 0};return{baseUrl:t,headers:n}},this.createOpenAPIClient=({baseUrl:e,headers:t})=>B({baseUrl:e,onRequest:({request:n})=>{Object.entries(t).forEach(([o,r])=>{r&&n.headers.set(o,r)})}}),this.setAuthToken=e=>{this.userToken=e;const{baseUrl:t,headers:n}=this.constructClientOptions(e);this.client=this.createOpenAPIClient({baseUrl:t,headers:n})},this.getExternalWidgetConfig=async()=>await this.client.GET("/backend/widget/v2/config",{params:{header:{"X-Bot-Token":this.config.token}}}),this.sendMessage=async(e,t)=>await this.client.POST("/backend/widget/v2/chat/send",{body:e,signal:t}),this.createUnverifiedContact=async e=>await this.client.POST("/backend/widget/v2/contact/create-unverified",{params:{header:{"x-bot-token":this.config.token}},body:e}),this.createSession=async e=>await this.client.POST("/backend/widget/v2/create-session",{body:e}),this.pollSessionAndHistory=async({sessionId:e,lastMessageTimestamp:t,abortSignal:n})=>{const o=t?{lastMessageTimestamp:t}:void 0;return await this.client.GET("/backend/widget/v2/poll/{sessionId}",{params:{path:{sessionId:e},query:o},signal:n})},this.getSessions=async({cursor:e,filters:t,abortSignal:n})=>await this.client.GET("/backend/widget/v2/sessions",{params:{query:{cursor:e,filters:JSON.stringify(t)}},signal:n}),this.uploadFile=async({file:e,abortSignal:t,onProgress:n})=>new Promise((o,r)=>{var w;const l=new FormData;l.append("file",e);const u=new XMLHttpRequest;if(t&&(t.addEventListener("abort",()=>{u.abort(),r(new DOMException("Aborted","AbortError"))}),t.aborted)){r(new DOMException("Aborted","AbortError"));return}u.upload.addEventListener("progress",p=>{if(p.lengthComputable&&n){const C=Math.round(p.loaded/p.total*100);n(C)}}),u.addEventListener("load",()=>{if(u.status>=200&&u.status<300)try{const p=JSON.parse(u.responseText);o(p)}catch(p){r(new Error(`Failed to parse response: ${p}`))}else r(new Error(`Upload failed with status: ${u.status}`))}),u.addEventListener("error",()=>{r(new Error("Network error occurred"))}),u.addEventListener("timeout",()=>{r(new Error("Upload timed out"))});const{baseUrl:_}=this.constructClientOptions(this.userToken),f=`${_}/backend/widget/v2/upload`;u.open("POST",f),u.setRequestHeader("X-Bot-Token",this.config.token),this.userToken??((w=this.config.user)==null?void 0:w.token)?u.setRequestHeader("Authorization",`Bearer ${this.userToken}`):console.error("User token not set"),u.send(l)}),this.vote=async e=>await this.client.POST("/backend/widget/v2/chat/vote",{body:e}),this.resolveSession=async(e,t)=>await this.client.POST("/backend/widget/v2/session/resolve",{body:e,signal:t}),this.createStateCheckpoint=async e=>await this.client.POST("/backend/widget/v2/checkpoint",{body:e}),this.submitCsat=async e=>await this.client.POST("/backend/widget/v2/submit-csat",{body:e}),this.config=i,this.userToken=((d=i.user)==null?void 0:d.token)||null;const{baseUrl:a,headers:c}=this.constructClientOptions((s=i.user)==null?void 0:s.token);this.client=this.createOpenAPIClient({baseUrl:a,headers:c})}}function R(h,i){console.error(`Missing case for ${h} in ${i}`)}class y{constructor(i){this.subscribers=new Set,this.get=()=>this.state,this.set=a=>{j(this.state,a)||(this.state=a,this.notifySubscribers(a))},this.setPartial=a=>{if(a==null)return;const c={...this.state,...a};this.set(c)},this.reset=()=>{this.set(this.initialState)},this.notifySubscribers=a=>{Array.from(this.subscribers).forEach(d=>{try{d(a)}catch(s){console.error(s)}})},this.subscribe=a=>(this.subscribers.add(a),()=>{this.subscribers.delete(a)}),this.state=i,this.initialState=i}}class z{constructor(){this.state=new y({isPolling:!1,isError:!1}),this.abortController=new AbortController,this.reset=()=>{var i;this.abortController.abort("Resetting poller"),(i=this.stopPolling)==null||i.call(this),this.stopPolling=null},this.stopPolling=null,this.startPolling=(i,a)=>{if(this.stopPolling)return;const c=[],d=async()=>{this.abortController=new AbortController,this.state.setPartial({isPolling:!0});try{await i(this.abortController.signal)}catch(s){if(this.abortController.signal.aborted)return;console.error("Failed to poll:",s),this.state.setPartial({isError:!0})}finally{this.state.setPartial({isPolling:!1})}this.abortController.signal.aborted?console.log("Poller aborted, not scheduling anymore"):c.push(setTimeout(d,a))};d(),this.stopPolling=()=>{c.forEach(clearTimeout),this.state.reset()}}}}function q(h){try{const i=h();return i instanceof Promise?i.then(a=>({data:a})).catch(a=>({error:a})):{data:i}}catch(i){return{error:i}}}class H{constructor({api:i,config:a,sessionCtx:c,messageCtx:d,sessionPollingIntervalSeconds:s}){this.poller=new z,this.fetchSessionAndFullHistoryAbortController=new AbortController,this.registerPolling=()=>{this.sessionCtx.sessionState.subscribe(({session:e})=>{e!=null&&e.id?this.poller.startPolling(async t=>{this.fetchSessionAndHistory({sessionId:e.id,abortSignal:t})},this.sessionPollingIntervalSeconds*1e3):this.poller.reset()}),this.sessionCtx.sessionState.subscribe(({session:e})=>{if(e!=null&&e.id&&!e.isOpened)try{this.fetchSessionAndFullHistoryAbortController=new AbortController,this.fetchSessionAndHistory({sessionId:e.id,abortSignal:this.fetchSessionAndFullHistoryAbortController.signal,fetchFullHistory:!0})}catch(t){this.fetchSessionAndFullHistoryAbortController.signal.aborted||console.error("Failed to fetch session and full history:",t)}else this.fetchSessionAndFullHistoryAbortController.abort()})},this.fetchSessionAndHistory=async({sessionId:e,abortSignal:t,fetchFullHistory:n=!1})=>{var u;this.messageCtx.state.get().messages.length===0&&this.messageCtx.state.setPartial({isInitialFetchLoading:!0});const o=this.messageCtx.state.get().messages,r=o.length>0?((u=o[o.length-1])==null?void 0:u.timestamp)??void 0:void 0,{data:l}=await this.api.pollSessionAndHistory({sessionId:e,abortSignal:t,lastMessageTimestamp:n?void 0:r});if(l!=null&&l.session&&(this.sessionCtx.sessionState.setPartial({session:l.session}),this.sessionCtx.setSessions([l.session])),l!=null&&l.history&&l.history.length>0){const _=this.messageCtx.state.get().messages,b=l.history.map(this.mapHistoryToMessage).filter(f=>f!==null).filter(f=>!_.some(v=>v.id===f.id));this.messageCtx.state.setPartial({messages:[..._,...b]})}this.messageCtx.state.get().isInitialFetchLoading&&this.messageCtx.state.setPartial({isInitialFetchLoading:!1})},this.mapHistoryToMessage=e=>{var n,o;const t={id:e.publicId,timestamp:e.sentAt||"",attachments:e.attachments||void 0};if(e.sender.kind==="user")return{...t,type:"USER",content:e.content.text||"",deliveredAt:e.sentAt||""};if(e.sender.kind==="agent")return{...t,type:"AGENT",component:"agent_message",data:{message:e.content.text||""},agent:{name:e.sender.name||"",avatar:e.sender.avatar||"",id:null,isAi:!1}};if(e.sender.kind==="ai"){const r=e.actionCalls&&e.actionCalls.length>0?e.actionCalls[e.actionCalls.length-1]:void 0;return{...t,type:"AI",component:"bot_message",agent:{id:null,name:((n=this.config.bot)==null?void 0:n.name)||"",isAi:!0,avatar:((o=this.config.bot)==null?void 0:o.avatar)||""},data:{message:e.content.text||"",action:r?{name:r.actionName,data:this.extractActionResult(r)}:void 0}}}if(e.sender.kind==="system"){const r=this.constructSystemMessage(e);return r===null?null:{...r}}return null},this.constructSystemMessage=e=>{if(!e||!e.systemMessagePayload)return null;switch(e.systemMessagePayload.type){case"state_checkpoint":return{id:e.publicId,type:"SYSTEM",subtype:"state_checkpoint",data:{payload:e.systemMessagePayload.payload},timestamp:e.sentAt||"",attachments:void 0};case"csat_requested":return{id:e.publicId,type:"SYSTEM",subtype:"csat_requested",data:{payload:void 0},timestamp:e.sentAt||"",attachments:void 0};case"csat_submitted":return{id:e.publicId,type:"SYSTEM",subtype:"csat_submitted",data:{payload:{score:e.systemMessagePayload.payload.score??void 0,feedback:e.systemMessagePayload.payload.feedback??void 0}},timestamp:e.sentAt||"",attachments:void 0};case"none":return null;default:return R(e.systemMessagePayload,this.constructSystemMessage.name),null}},this.extractActionResult=e=>{const t=e.result;if(t===null||typeof t!="object")return t;if("responseBodyText"in t&&typeof t.responseBodyText=="string"){const n=t.responseBodyText,o=q(()=>JSON.parse(n)).data;if(o)return o}return e.result},this.api=i,this.config=a,this.sessionCtx=c,this.messageCtx=d,this.sessionPollingIntervalSeconds=s,this.registerPolling()}}class Y{constructor({config:i,api:a,storageCtx:c}){var d;this.shouldCollectData=()=>{var s;return!!(!((s=this.state.get().contact)!=null&&s.token)&&this.config.collectUserData)},this.autoCreateUnverifiedUserIfNotExists=async()=>{var s,e,t,n,o,r,l,u,_,b,f,v,w,p;if(!((s=this.config.user)!=null&&s.token)){if(this.config.collectUserData&&!((t=(e=this.config.user)==null?void 0:e.data)!=null&&t.email)){if((n=this.config.extraDataCollectionFields)!=null&&n.length)return;const C=await((o=this.storageCtx)==null?void 0:o.getContactToken());C&&await this.setUnverifiedContact(C);return}if(!((l=(r=this.config.user)==null?void 0:r.data)!=null&&l.email)){const C=await((u=this.storageCtx)==null?void 0:u.getContactToken());if(C){await this.setUnverifiedContact(C);return}}await this.createUnverifiedContact({email:(b=(_=this.config.user)==null?void 0:_.data)==null?void 0:b.email,non_verified_name:(v=(f=this.config.user)==null?void 0:f.data)==null?void 0:v.name,non_verified_custom_data:(p=(w=this.config.user)==null?void 0:w.data)==null?void 0:p.customData})}},this.createUnverifiedContact=async(s,e)=>{this.state.setPartial({extraCollectedData:e});try{this.state.setPartial({isCreatingUnverifiedContact:!0,isErrorCreatingUnverifiedContact:!1});const{data:t}=await this.api.createUnverifiedContact(s);t!=null&&t.token?await this.setUnverifiedContact(t.token):this.state.setPartial({isErrorCreatingUnverifiedContact:!0})}finally{this.state.setPartial({isCreatingUnverifiedContact:!1})}},this.setUnverifiedContact=async s=>{var n,o,r,l;const e=await((n=this.storageCtx)==null?void 0:n.getExternalContactId()),t=((o=this.config.user)==null?void 0:o.externalId)||e||O.v4();this.api.setAuthToken(s),await((r=this.storageCtx)==null?void 0:r.setContactToken(s)),await((l=this.storageCtx)==null?void 0:l.setExternalContactId(t)),this.state.setPartial({contact:{token:s,externalId:t}})},this.config=i,this.storageCtx=c,this.api=a,this.state=new y({contact:(d=i.user)!=null&&d.token?{token:i.user.token,externalId:i.user.externalId}:null,extraCollectedData:void 0,isCreatingUnverifiedContact:!1,isErrorCreatingUnverifiedContact:!1}),this.autoCreateUnverifiedUserIfNotExists()}}function x(){return O.v4()}class ${constructor({config:i,api:a,sessionCtx:c,messageCtx:d}){this.submitCsat=async s=>{var r;const e=(r=this.sessionCtx.sessionState.get().session)==null?void 0:r.id;if(!e)return{data:null,error:"No session id found"};const t=x();this.messageCtx.state.setPartial({messages:[...this.messageCtx.state.get().messages,{id:t,type:"SYSTEM",subtype:"csat_submitted",timestamp:new Date().toISOString(),data:{payload:{score:s.score,feedback:s.feedback}}}]});const{data:n,error:o}=await this.api.submitCsat({...s,system_message_uuid:t,session_id:e});return{data:n,error:o}},this.config=i,this.api=a,this.sessionCtx=c,this.messageCtx=d}}class W{constructor({config:i,api:a,contactCtx:c,sessionsPollingIntervalSeconds:d}){this.sessionsRefresher=new z,this.sessionState=new y({session:null,isCreatingSession:!1,isResolvingSession:!1}),this.sessionsState=new y({data:[],cursor:void 0,isLastPage:!1,didStartInitialFetch:!1,isInitialFetchLoading:!0}),this.reset=async()=>{this.sessionState.reset()},this.registerSessionsRefresherWrapper=()=>{var s;(s=this.contactCtx.state.get().contact)!=null&&s.token&&!this.sessionsState.get().didStartInitialFetch?this.registerSessionsRefresher():this.contactCtx.state.subscribe(({contact:e})=>{e!=null&&e.token&&!this.sessionsState.get().didStartInitialFetch&&this.registerSessionsRefresher()})},this.registerSessionsRefresher=()=>{this.sessionsRefresher.startPolling(async()=>{this.sessionsState.get().didStartInitialFetch===!1&&this.sessionsState.setPartial({didStartInitialFetch:!0}),await this.refreshSessions(),this.sessionsState.get().isInitialFetchLoading===!0&&this.sessionsState.setPartial({isInitialFetchLoading:!1})},this.sessionsPollingIntervalSeconds*1e3)},this.createSession=async()=>{var o;this.sessionState.setPartial({session:null,isCreatingSession:!0});const s=(o=this.contactCtx.state.get().contact)==null?void 0:o.externalId,e={...this.config.sessionCustomData,...s?{external_id:s}:{}},{data:t,error:n}=await this.api.createSession({customData:Object.keys(e).length>0?e:void 0});return t?(this.sessionState.setPartial({session:t,isCreatingSession:!1}),t):(this.sessionState.setPartial({isCreatingSession:!1}),console.error("Failed to create session:",n),null)},this.loadMoreSessions=async()=>{if(this.sessionsState.get().isLastPage)return;const{data:s}=await this.getSessions({cursor:this.sessionsState.get().cursor});if(s){const t=[...this.sessionsState.get().data,...s.items].filter((n,o,r)=>o===r.findIndex(l=>n.id===l.id));this.sessionsState.setPartial({data:t,cursor:s.next||void 0,isLastPage:s.next===null})}},this.getSessions=async({cursor:s})=>{var t,n;if(!((t=this.contactCtx.state.get().contact)!=null&&t.token))return{data:null};const e=(n=this.contactCtx.state.get().contact)==null?void 0:n.externalId;return await this.api.getSessions({cursor:s,filters:e?{external_id:e}:{}})},this.setSessions=s=>{const e=[...s,...this.sessionsState.get().data].filter((t,n,o)=>n===o.findIndex(r=>t.id===r.id));this.sessionsState.setPartial({data:e})},this.refreshSessions=async()=>{const{data:s}=await this.getSessions({cursor:void 0});s&&this.setSessions(s.items)},this.resolveSession=async()=>{const s=this.sessionState.get().session;if(!s||!s.isOpened)return{success:!1,error:"Session is not opened"};this.sessionState.setPartial({isResolvingSession:!0});const{data:e,error:t}=await this.api.resolveSession({session_id:s.id});return e?(this.sessionState.setPartial({session:e,isResolvingSession:!1}),{success:!0,data:e}):(this.sessionState.setPartial({isResolvingSession:!1}),{success:!1,error:t})},this.createStateCheckpoint=async s=>{var o;const e=(o=this.sessionState.get().session)==null?void 0:o.id;if(!e)return;const{data:t,error:n}=await this.api.createStateCheckpoint({session_id:e,payload:s});return t!=null&&t.success?{success:!0}:{success:!1}},this.config=i,this.api=a,this.contactCtx=c,this.sessionsPollingIntervalSeconds=d,this.registerSessionsRefresherWrapper()}}class G{constructor({config:i,api:a,sessionCtx:c,contactCtx:d}){this.state=new y({messages:[],isSendingMessage:!1,lastAIResMightSolveUserIssue:!1,isInitialFetchLoading:!1}),this.sendMessageAbortController=new AbortController,this.reset=()=>{this.sendMessageAbortController.abort("Resetting chat"),this.state.reset()},this.sendMessage=async s=>{var e,t,n,o,r,l,u,_,b,f;try{if(!s.content.trim()&&(!s.attachments||s.attachments.length===0)){console.warn("Cannot send an empty message of no content or attachments");return}const v=this.state.get().isSendingMessage,w=((e=this.sessionCtx.sessionState.get().session)==null?void 0:e.assignee.kind)==="ai",p=this.state.get().messages,C=p.length>0?p[p.length-1]:void 0;if(w&&v||w&&(C==null?void 0:C.type)==="USER"){console.warn("Cannot send messages while awaiting AI response");return}this.sendMessageAbortController=new AbortController,this.state.setPartial({lastAIResMightSolveUserIssue:!1}),this.state.setPartial({isSendingMessage:!0});const A=this.state.get().messages,T=!((t=this.sessionCtx.sessionState.get().session)!=null&&t.id)&&A.length===0&&((n=this.config.advancedInitialMessages)==null?void 0:n.some(g=>g.persistent)),E=T?(this.config.advancedInitialMessages||[]).filter(g=>g.persistent).map(g=>({id:x(),component:"bot_message",type:"AI",timestamp:new Date().toISOString(),data:{message:g.message}})):[],I=this.toUserMessage(s.content.trim(),s.attachments||void 0);if(this.state.setPartial({messages:[...E,...A,I]}),!((o=this.sessionCtx.sessionState.get().session)!=null&&o.id)){if(!await this.sessionCtx.createSession()){console.error("Failed to create session");return}this.sessionCtx.refreshSessions()}const M=(r=this.sessionCtx.sessionState.get().session)==null?void 0:r.id;if(!M)return;const{data:m}=await this.api.sendMessage({uuid:I.id,bot_token:this.config.token,headers:this.config.headers,query_params:this.config.queryParams,body_properties:this.config.bodyProperties,session_id:M,content:I.content,attachments:s.attachments,clientContext:this.config.context,custom_data:{...this.config.messageCustomData||{},...s.customData||{}},language:this.config.language,exit_mode_prompt:s.exitModePrompt,initial_messages:T?E.map(g=>({uuid:g.id,content:g.data.message})):void 0},this.sendMessageAbortController.signal);if(m!=null&&m.success){const g=this.toBotMessage(m);if(g){const k=this.state.get().messages;if(!!k.some(L=>L.id===g.id)){this.state.setPartial({lastAIResMightSolveUserIssue:((l=m.autopilotResponse)==null?void 0:l.mightSolveUserIssue)||((u=m.uiResponse)==null?void 0:u.mightSolveUserIssue)});return}this.state.setPartial({messages:[...k,g],lastAIResMightSolveUserIssue:((_=m.autopilotResponse)==null?void 0:_.mightSolveUserIssue)||((b=m.uiResponse)==null?void 0:b.mightSolveUserIssue)})}m.session&&this.sessionCtx.sessionState.setPartial({session:m.session})}else{const g=this.toBotErrorMessage(((f=m==null?void 0:m.error)==null?void 0:f.message)||"Unknown error occurred"),k=this.state.get().messages;this.state.setPartial({messages:[...k,g]})}}catch(v){this.sendMessageAbortController.signal.aborted||console.error("Failed to send message:",v)}finally{this.state.setPartial({isSendingMessage:!1})}},this.toUserMessage=(s,e)=>{const t=(()=>{const n=this.contactCtx.state.get().extraCollectedData;return this.state.get().messages.length===0&&n&&Object.keys(n).length>0?`${Object.entries(n).filter(([r,l])=>!!l).map(([r,l])=>`${r}: ${l}`).join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
|
-
${s}`:s})();return{id:x(),type:"USER",content:t,deliveredAt:new Date().toISOString(),attachments:e,timestamp:new Date().toISOString()}},this.toBotMessage=s=>{var e;return s.success&&s.autopilotResponse?{type:"AI",id:s.autopilotResponse.id||x(),timestamp:new Date().toISOString(),component:"bot_message",agent:this.config.bot?{name:this.config.bot.name||"",isAi:!0,avatar:this.config.bot.avatar||"",id:null}:void 0,data:{message:s.autopilotResponse.value.content,action:(e=s.uiResponse)!=null&&e.value.name?{name:s.uiResponse.value.name,data:s.uiResponse.value.request_response}:void 0}}:null},this.toBotErrorMessage=s=>({type:"AI",id:x(),timestamp:new Date().toISOString(),component:"TEXT",data:{message:s,variant:"error",action:void 0}}),this.config=i,this.api=a,this.sessionCtx=c,this.contactCtx=d}}class G{constructor({config:i,contactCtx:a,sessionCtx:c,resetChat:d}){var s;this.registerRoutingListener=()=>{this.contactCtx.state.subscribe(({contact:e})=>{var t;e!=null&&e.token&&this.state.get().screen==="welcome"&&this.state.setPartial({screen:(t=this.config.router)!=null&&t.chatScreenOnly?"chat":"sessions"})}),this.sessionCtx.sessionsState.subscribe(({isInitialFetchLoading:e,data:t})=>{var n,o,r,l;if((n=this.config.router)!=null&&n.chatScreenOnly&&!((o=this.sessionCtx.sessionState.get().session)!=null&&o.id)){const u=(r=t.find(_=>_.isOpened))==null?void 0:r.id;return u?this.toChatScreen(u):void 0}t.length||((l=this.config.router)==null?void 0:l.goToChatIfNoSessions)!==!1&&!e&&this.state.get().screen!=="chat"&&this.toChatScreen()})},this.toSessionsScreen=()=>{this.resetChat(),this.state.setPartial({screen:"sessions"})},this.toChatScreen=e=>{if(this.resetChat(),e){const t=this.sessionCtx.sessionsState.get().data.find(n=>n.id===e);if(!t)return;this.sessionCtx.sessionState.setPartial({session:t})}this.state.setPartial({screen:"chat"})},this.config=i,this.contactCtx=a,this.sessionCtx=c,this.resetChat=d,this.state=new y({screen:this.contactCtx.shouldCollectData()?"welcome":(s=this.config.router)!=null&&s.chatScreenOnly?"chat":"sessions"}),this.registerRoutingListener()}}class V{constructor({storage:i,config:a}){this.KEYS={contactToken:c=>`opencx-widget:org-token-${c}:contact-token`,externalContactId:c=>`opencx-widget:org-token-${c}:external-contact-id`},this.setContactToken=async c=>{await this.storage.set(this.KEYS.contactToken(this.config.token),c)},this.getContactToken=async()=>this.storage.get(this.KEYS.contactToken(this.config.token)),this.setExternalContactId=async c=>{await this.storage.set(this.KEYS.externalContactId(this.config.token),c)},this.getExternalContactId=async()=>this.storage.get(this.KEYS.externalContactId(this.config.token)),this.storage=i,this.config=a}}const v=class v{constructor({config:i,storage:a,modes:c,org:d}){if(this.modes=[],this.resetChat=()=>{this.sessionCtx.reset(),this.messageCtx.reset()},!v.pollingIntervalsSeconds)throw Error("Widget polling values are not defined, did you call WidgetCtx.initialize()");this.config=i,this.org=d,this.api=new U({config:i}),this.storageCtx=a?new V({storage:a,config:i}):void 0,this.modes=c,this.contactCtx=new Y({api:this.api,config:this.config,storageCtx:this.storageCtx}),this.sessionCtx=new K({config:this.config,api:this.api,contactCtx:this.contactCtx,sessionsPollingIntervalSeconds:v.pollingIntervalsSeconds.sessions}),this.messageCtx=new W({config:this.config,api:this.api,sessionCtx:this.sessionCtx,contactCtx:this.contactCtx}),this.csatCtx=new $({config:this.config,api:this.api,sessionCtx:this.sessionCtx,messageCtx:this.messageCtx}),this.activeSessionPollingCtx=new j({api:this.api,config:this.config,sessionCtx:this.sessionCtx,messageCtx:this.messageCtx,sessionPollingIntervalSeconds:v.pollingIntervalsSeconds.session}),this.routerCtx=new G({config:this.config,contactCtx:this.contactCtx,sessionCtx:this.sessionCtx,resetChat:this.resetChat})}};v.pollingIntervalsSeconds=null,v.initialize=async({config:i,storage:a})=>{var d,s,e;const c=await new U({config:i}).getExternalWidgetConfig();if(!c.data)throw new Error("Failed to fetch widget config");return v.pollingIntervalsSeconds={session:((d=c.data)==null?void 0:d.sessionPollingIntervalSeconds)||10,sessions:((s=c.data)==null?void 0:s.sessionsPollingIntervalSeconds)||60},new v({config:i,storage:a,modes:((e=c.data)==null?void 0:e.modes)||[],org:{id:c.data.org.id,name:c.data.org.name}})};let P=v;const X={write_a_message_placeholder:"اكتب رسالة...",your_issue_has_been_resolved:"تم حل مشكلتك!",new_conversation:"محادثة جديدة",welcome_screen_title:"مرحبًا بك في دردشة الدعم الخاصة بنا",welcome_screen_description:"نحن هنا للمساعدة! ابدأ محادثة وسنرد عليك في أقرب وقت ممكن.",your_name_placeholder:"اسمك",your_email_placeholder:"عنوان بريدك الإلكتروني",start_chat_button:"تحدث إلى الدعم",start_chat_button_loading:"جاري الاتصال...",i_need_more_help:"أحتاج المزيد من المساعدة",this_was_helpful:"كان هذا مفيدًا",optional:"اختياري",no_conversations_yet:"لا يوجد محادثات",back_to_conversations:"العودة إلى المحادثات",closed_conversations:"المحادثات المغلقة"},J={write_a_message_placeholder:"Nachricht schreiben...",your_issue_has_been_resolved:"Ihr Problem wurde gelöst!",new_conversation:"Neue Konversation",welcome_screen_title:"Willkommen in unserem Support-Chat",welcome_screen_description:"Wir sind hier, um zu helfen! Beginnen Sie ein Gesprách und wir werden so schnell wie mogelijk antworten.",your_name_placeholder:"Ihr Name",your_email_placeholder:"Ihre E-Mail-Adresse",start_chat_button:"Mit dem Support sprechen",start_chat_button_loading:"Verbindung wird hergestellt...",i_need_more_help:"Ich brauche weitere Hilfe",this_was_helpful:"Dies war hilfreich",optional:"Optional",no_conversations_yet:"noch keine Gespräche",back_to_conversations:"Zurück zur Konversationen",closed_conversations:"Geschlossene Konversationen"},Z={write_a_message_placeholder:"Write a message...",your_issue_has_been_resolved:"Your issue has been resolved!",new_conversation:"New conversation",welcome_screen_title:"Welcome to our support chat",welcome_screen_description:"We're here to help! Start a conversation and we'll get back to you as soon as possible.",your_name_placeholder:"Your name",your_email_placeholder:"Your email address",start_chat_button:"Talk to support",start_chat_button_loading:"Connecting...",i_need_more_help:"I need more help",this_was_helpful:"This was helpful",optional:"Optional",no_conversations_yet:"No conversations yet",back_to_conversations:"Back to conversations",closed_conversations:"Closed conversations"},Q={write_a_message_placeholder:"Écrivez un message...",your_issue_has_been_resolved:"Votre problème a été résolu !",new_conversation:"Nouvelle conversation",welcome_screen_title:"Bienvenue dans notre chat de support",welcome_screen_description:"Nous sommes là pour vous aider ! Commencez une conversation et nous vous répondrons dès que possible.",your_name_placeholder:"Votre nom",your_email_placeholder:"Votre adresse e-mail",start_chat_button:"Parler au support",start_chat_button_loading:"Connexion...",i_need_more_help:"Je besoin d'aide plus",this_was_helpful:"C'était utile",optional:"Optionnel",no_conversations_yet:"Aucune conversation pour le moment",back_to_conversations:"Retour aux conversations",closed_conversations:"Conversations fermées"},ee={write_a_message_placeholder:"Schrijf een bericht...",your_issue_has_been_resolved:"Uw probleem is opgelost!",new_conversation:"Nieuw gesprek",welcome_screen_title:"Welkom bij onze supportchat",welcome_screen_description:"We zijn hier om te helpen! Begin een gesprek en we nemen zo snel mogelijk contact met u op.",your_name_placeholder:"Uw naam",your_email_placeholder:"Uw e-mailadres",start_chat_button:"Praat met ondersteuning",start_chat_button_loading:"Verbinding maken...",i_need_more_help:"Ik heb nog meer hulp nodig",this_was_helpful:"Mijn vraag is opgelost",optional:"Optioneel",no_conversations_yet:"Nog geen gesprekken",back_to_conversations:"Terug naar gesprekken",closed_conversations:"Afgesloten gesprekken"},te={write_a_message_placeholder:"Escreva uma mensagem...",your_issue_has_been_resolved:"Seu problema foi resolvido!",new_conversation:"Nova conversa",welcome_screen_title:"Bem-vindo ao nosso chat de suporte",welcome_screen_description:"Estamos aqui para ajudar! Inicie uma conversa e responderemos o mais rápido possível.",your_name_placeholder:"Seu nome",your_email_placeholder:"Seu endereço de email",start_chat_button:"Falar com o suporte",start_chat_button_loading:"Conectando...",i_need_more_help:"preciso de mais ajuda",this_was_helpful:"Isso foi útil",optional:"Opcional",no_conversations_yet:"Nenhuma conversa ainda",back_to_conversations:"Voltar para conversas",closed_conversations:"Conversas fechadas"},se={write_a_message_placeholder:"Escribe un mensaje...",your_issue_has_been_resolved:"¡Tu problema fue resuelto!",new_conversation:"Nueva conversación",welcome_screen_title:"Bienvenido a nuestro chat de soporte",welcome_screen_description:"¡Estamos aquí para ayudarte! Inicia una conversación y responderemos lo antes posible.",your_name_placeholder:"Tu nombre",your_email_placeholder:"Tu correo electrónico",start_chat_button:"Hablar con soporte",start_chat_button_loading:"Conectando...",i_need_more_help:"Necesito más ayuda",this_was_helpful:"Esto fue útil",optional:"Opcional",no_conversations_yet:"Sin conversaciones aún",back_to_conversations:"Volver a conversaciones",closed_conversations:"Conversaciones cerradas"},ie={write_a_message_placeholder:"Bir mesaj yazın...",your_issue_has_been_resolved:"Sorununuz çözüldü!",new_conversation:"Yeni konuşma",welcome_screen_title:"Destek sohbetimize hoş geldiniz",welcome_screen_description:"Yardım etmek için buradayız! Bir konuşma başlatın, en kısa sürede size geri döneceğiz.",your_name_placeholder:"Adınız",your_email_placeholder:"E-posta adresiniz",start_chat_button:"Destekle konuş",start_chat_button_loading:"Bağlanıyor...",i_need_more_help:"Daha fazla yardıma ihtiyacım var",this_was_helpful:"Bu yardımcı oldu",optional:"İsteğe bağlı",no_conversations_yet:"Henüz konuşma yok",back_to_conversations:"Konuşmalara geri dön",closed_conversations:"Kapatılan konuşmalar"},L={en:Z,ar:X,nl:ee,fr:Q,de:J,pt:te,es:se,tr:ie},ne=Object.keys(L);function ae(h){return ne.includes(h)}function oe(h,i,a){var c;return((c=a==null?void 0:a[i])==null?void 0:c[h])||L[i][h]||""}exports.PrimitiveState=y;exports.WidgetCtx=P;exports.getTranslation=oe;exports.isExhaustive=R;exports.isSupportedLanguage=ae;
|
|
4
|
+
${s}`:s})();return{id:x(),type:"USER",content:t,deliveredAt:new Date().toISOString(),attachments:e,timestamp:new Date().toISOString()}},this.toBotMessage=s=>{var e;return s.success&&s.autopilotResponse?{type:"AI",id:s.autopilotResponse.id||x(),timestamp:new Date().toISOString(),component:"bot_message",agent:this.config.bot?{name:this.config.bot.name||"",isAi:!0,avatar:this.config.bot.avatar||"",id:null}:void 0,data:{message:s.autopilotResponse.value.content,action:(e=s.uiResponse)!=null&&e.value.name?{name:s.uiResponse.value.name,data:s.uiResponse.value.request_response}:void 0}}:null},this.toBotErrorMessage=s=>({type:"AI",id:x(),timestamp:new Date().toISOString(),component:"TEXT",data:{message:s,variant:"error",action:void 0}}),this.config=i,this.api=a,this.sessionCtx=c,this.contactCtx=d}}class K{constructor({config:i,contactCtx:a,sessionCtx:c,resetChat:d}){var s;this.registerRoutingListener=()=>{this.contactCtx.state.subscribe(({contact:e})=>{var t;e!=null&&e.token&&this.state.get().screen==="welcome"&&this.state.setPartial({screen:(t=this.config.router)!=null&&t.chatScreenOnly?"chat":"sessions"})}),this.sessionCtx.sessionsState.subscribe(({isInitialFetchLoading:e,data:t})=>{var n,o,r,l;if((n=this.config.router)!=null&&n.chatScreenOnly&&!((o=this.sessionCtx.sessionState.get().session)!=null&&o.id)){const u=(r=t.find(_=>_.isOpened))==null?void 0:r.id;return u?this.toChatScreen(u):void 0}t.length||((l=this.config.router)==null?void 0:l.goToChatIfNoSessions)!==!1&&!e&&this.state.get().screen!=="chat"&&this.toChatScreen()})},this.toSessionsScreen=()=>{this.resetChat(),this.state.setPartial({screen:"sessions"})},this.toChatScreen=e=>{if(this.resetChat(),e){const t=this.sessionCtx.sessionsState.get().data.find(n=>n.id===e);if(!t)return;this.sessionCtx.sessionState.setPartial({session:t})}this.state.setPartial({screen:"chat"})},this.config=i,this.contactCtx=a,this.sessionCtx=c,this.resetChat=d,this.state=new y({screen:this.contactCtx.shouldCollectData()?"welcome":(s=this.config.router)!=null&&s.chatScreenOnly?"chat":"sessions"}),this.registerRoutingListener()}}class V{constructor({storage:i,config:a}){this.KEYS={contactToken:c=>`opencx-widget:org-token-${c}:contact-token`,externalContactId:c=>`opencx-widget:org-token-${c}:external-contact-id`},this.setContactToken=async c=>{await this.storage.set(this.KEYS.contactToken(this.config.token),c)},this.getContactToken=async()=>this.storage.get(this.KEYS.contactToken(this.config.token)),this.setExternalContactId=async c=>{await this.storage.set(this.KEYS.externalContactId(this.config.token),c)},this.getExternalContactId=async()=>this.storage.get(this.KEYS.externalContactId(this.config.token)),this.storage=i,this.config=a}}const S=class S{constructor({config:i,storage:a,modes:c,org:d}){if(this.modes=[],this.resetChat=()=>{this.sessionCtx.reset(),this.messageCtx.reset()},!S.pollingIntervalsSeconds)throw Error("Widget polling values are not defined, did you call WidgetCtx.initialize()");this.config=i,this.org=d,this.api=new U({config:i}),this.storageCtx=a?new V({storage:a,config:i}):void 0,this.modes=c,this.contactCtx=new Y({api:this.api,config:this.config,storageCtx:this.storageCtx}),this.sessionCtx=new W({config:this.config,api:this.api,contactCtx:this.contactCtx,sessionsPollingIntervalSeconds:S.pollingIntervalsSeconds.sessions}),this.messageCtx=new G({config:this.config,api:this.api,sessionCtx:this.sessionCtx,contactCtx:this.contactCtx}),this.csatCtx=new $({config:this.config,api:this.api,sessionCtx:this.sessionCtx,messageCtx:this.messageCtx}),this.activeSessionPollingCtx=new H({api:this.api,config:this.config,sessionCtx:this.sessionCtx,messageCtx:this.messageCtx,sessionPollingIntervalSeconds:S.pollingIntervalsSeconds.session}),this.routerCtx=new K({config:this.config,contactCtx:this.contactCtx,sessionCtx:this.sessionCtx,resetChat:this.resetChat})}};S.pollingIntervalsSeconds=null,S.initialize=async({config:i,storage:a})=>{var d,s,e;const c=await new U({config:i}).getExternalWidgetConfig();if(!c.data)throw new Error("Failed to fetch widget config");return S.pollingIntervalsSeconds={session:((d=c.data)==null?void 0:d.sessionPollingIntervalSeconds)||10,sessions:((s=c.data)==null?void 0:s.sessionsPollingIntervalSeconds)||60},new S({config:i,storage:a,modes:((e=c.data)==null?void 0:e.modes)||[],org:{id:c.data.org.id,name:c.data.org.name}})};let P=S;const J={write_a_message_placeholder:"اكتب رسالة...",your_issue_has_been_resolved:"تم حل مشكلتك!",new_conversation:"محادثة جديدة",welcome_screen_title:"مرحبًا بك في دردشة الدعم الخاصة بنا",welcome_screen_description:"نحن هنا للمساعدة! ابدأ محادثة وسنرد عليك في أقرب وقت ممكن.",your_name_placeholder:"اسمك",your_email_placeholder:"عنوان بريدك الإلكتروني",start_chat_button:"تحدث إلى الدعم",start_chat_button_loading:"جاري الاتصال...",i_need_more_help:"أحتاج المزيد من المساعدة",this_was_helpful:"كان هذا مفيدًا",optional:"اختياري",no_conversations_yet:"لا يوجد محادثات",back_to_conversations:"العودة إلى المحادثات",closed_conversations:"المحادثات المغلقة"},X={write_a_message_placeholder:"Nachricht schreiben...",your_issue_has_been_resolved:"Ihr Problem wurde gelöst!",new_conversation:"Neue Konversation",welcome_screen_title:"Willkommen in unserem Support-Chat",welcome_screen_description:"Wir sind hier, um zu helfen! Beginnen Sie ein Gesprách und wir werden so schnell wie mogelijk antworten.",your_name_placeholder:"Ihr Name",your_email_placeholder:"Ihre E-Mail-Adresse",start_chat_button:"Mit dem Support sprechen",start_chat_button_loading:"Verbindung wird hergestellt...",i_need_more_help:"Ich brauche weitere Hilfe",this_was_helpful:"Dies war hilfreich",optional:"Optional",no_conversations_yet:"noch keine Gespräche",back_to_conversations:"Zurück zur Konversationen",closed_conversations:"Geschlossene Konversationen"},Z={write_a_message_placeholder:"Write a message...",your_issue_has_been_resolved:"Your issue has been resolved!",new_conversation:"New conversation",welcome_screen_title:"Welcome to our support chat",welcome_screen_description:"We're here to help! Start a conversation and we'll get back to you as soon as possible.",your_name_placeholder:"Your name",your_email_placeholder:"Your email address",start_chat_button:"Talk to support",start_chat_button_loading:"Connecting...",i_need_more_help:"I need more help",this_was_helpful:"This was helpful",optional:"Optional",no_conversations_yet:"No conversations yet",back_to_conversations:"Back to conversations",closed_conversations:"Closed conversations"},Q={write_a_message_placeholder:"Escribe un mensaje...",your_issue_has_been_resolved:"¡Tu problema fue resuelto!",new_conversation:"Nueva conversación",welcome_screen_title:"Bienvenido a nuestro chat de soporte",welcome_screen_description:"¡Estamos aquí para ayudarte! Inicia una conversación y responderemos lo antes posible.",your_name_placeholder:"Tu nombre",your_email_placeholder:"Tu correo electrónico",start_chat_button:"Hablar con soporte",start_chat_button_loading:"Conectando...",i_need_more_help:"Necesito más ayuda",this_was_helpful:"Esto fue útil",optional:"Opcional",no_conversations_yet:"Sin conversaciones aún",back_to_conversations:"Volver a conversaciones",closed_conversations:"Conversaciones cerradas"},ee={write_a_message_placeholder:"Écrivez un message...",your_issue_has_been_resolved:"Votre problème a été résolu !",new_conversation:"Nouvelle conversation",welcome_screen_title:"Bienvenue dans notre chat de support",welcome_screen_description:"Nous sommes là pour vous aider ! Commencez une conversation et nous vous répondrons dès que possible.",your_name_placeholder:"Votre nom",your_email_placeholder:"Votre adresse e-mail",start_chat_button:"Parler au support",start_chat_button_loading:"Connexion...",i_need_more_help:"Je besoin d'aide plus",this_was_helpful:"C'était utile",optional:"Optionnel",no_conversations_yet:"Aucune conversation pour le moment",back_to_conversations:"Retour aux conversations",closed_conversations:"Conversations fermées"},te={write_a_message_placeholder:"Schrijf een bericht...",your_issue_has_been_resolved:"Uw probleem is opgelost!",new_conversation:"Nieuw gesprek",welcome_screen_title:"Welkom bij onze supportchat",welcome_screen_description:"We zijn hier om te helpen! Begin een gesprek en we nemen zo snel mogelijk contact met u op.",your_name_placeholder:"Uw naam",your_email_placeholder:"Uw e-mailadres",start_chat_button:"Praat met ondersteuning",start_chat_button_loading:"Verbinding maken...",i_need_more_help:"Ik heb nog meer hulp nodig",this_was_helpful:"Mijn vraag is opgelost",optional:"Optioneel",no_conversations_yet:"Nog geen gesprekken",back_to_conversations:"Terug naar gesprekken",closed_conversations:"Afgesloten gesprekken"},se={write_a_message_placeholder:"Napisz wiadomość...",your_issue_has_been_resolved:"Twój problem został rozwiązany!",new_conversation:"Nowa rozmowa",welcome_screen_title:"Witamy w naszym czacie wsparcia",welcome_screen_description:"Jesteśmy tutaj, aby pomóc! Rozpocznij rozmowę, a odpowiemy jak najszybciej.",your_name_placeholder:"Twoje imię",your_email_placeholder:"Twój adres email",start_chat_button:"Porozmawiaj ze wsparciem",start_chat_button_loading:"Łączenie...",i_need_more_help:"Potrzebuję więcej pomocy",this_was_helpful:"To było pomocne",optional:"Opcjonalne",no_conversations_yet:"Jeszcze brak rozmów",back_to_conversations:"Powrót do rozmów",closed_conversations:"Zamknięte rozmowy"},ie={write_a_message_placeholder:"Escreva uma mensagem...",your_issue_has_been_resolved:"Seu problema foi resolvido!",new_conversation:"Nova conversa",welcome_screen_title:"Bem-vindo ao nosso chat de suporte",welcome_screen_description:"Estamos aqui para ajudar! Inicie uma conversa e responderemos o mais rápido possível.",your_name_placeholder:"Seu nome",your_email_placeholder:"Seu endereço de email",start_chat_button:"Falar com o suporte",start_chat_button_loading:"Conectando...",i_need_more_help:"preciso de mais ajuda",this_was_helpful:"Isso foi útil",optional:"Opcional",no_conversations_yet:"Nenhuma conversa ainda",back_to_conversations:"Voltar para conversas",closed_conversations:"Conversas fechadas"},ne={write_a_message_placeholder:"Bir mesaj yazın...",your_issue_has_been_resolved:"Sorununuz çözüldü!",new_conversation:"Yeni konuşma",welcome_screen_title:"Destek sohbetimize hoş geldiniz",welcome_screen_description:"Yardım etmek için buradayız! Bir konuşma başlatın, en kısa sürede size geri döneceğiz.",your_name_placeholder:"Adınız",your_email_placeholder:"E-posta adresiniz",start_chat_button:"Destekle konuş",start_chat_button_loading:"Bağlanıyor...",i_need_more_help:"Daha fazla yardıma ihtiyacım var",this_was_helpful:"Bu yardımcı oldu",optional:"İsteğe bağlı",no_conversations_yet:"Henüz konuşma yok",back_to_conversations:"Konuşmalara geri dön",closed_conversations:"Kapatılan konuşmalar"},F={en:Z,ar:J,nl:te,fr:ee,de:X,pt:ie,es:Q,tr:ne,pl:se},ae=Object.keys(F);function oe(h){return ae.includes(h)}function re(h,i,a){var c;return((c=a==null?void 0:a[i])==null?void 0:c[h])||F[i][h]||""}exports.PrimitiveState=y;exports.WidgetCtx=P;exports.getTranslation=re;exports.isExhaustive=R;exports.isSupportedLanguage=oe;
|
|
5
5
|
//# sourceMappingURL=index.cjs.map
|