@telia-ace/widget-conversation 1.1.1 → 1.1.2-rc.1

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/agent.d.ts CHANGED
@@ -15,7 +15,7 @@ export declare class Agent {
15
15
  constructor(provider: ConversationProvider, settings: AgentSettings);
16
16
  print: (settings: string | ConversationMessageSettings | ConverstationMessageItem<any> | ConverstationMessageItem<any>[], options?: {
17
17
  key?: string;
18
- }) => ConversationEntry | undefined;
18
+ }, timestamp?: number | null) => ConversationEntry | undefined;
19
19
  typing: () => (() => void) | undefined;
20
20
  update(settings: AgentSettings): void;
21
21
  }
@@ -97,7 +97,7 @@ export declare class ConversationController {
97
97
  getComponentMountedState(): boolean;
98
98
  onUnreadMessage(fn: EventListener): import("@webprovisions/platform").EventSubscriptionCancellation;
99
99
  createEntry(key: string, content: ConversationMessageContent, type: ConversationMessageType, sender?: ConversationMessageSender, timestamp?: number | null): ConversationEntry;
100
- print: (settings: string | ConversationMessageSettings) => ConversationEntry;
100
+ print: (settings: string | ConversationMessageSettings, timestamp?: number | null) => ConversationEntry;
101
101
  update(): void;
102
102
  getMessageStream(): {
103
103
  messages: ConversationMessage[];
package/index.d.ts CHANGED
@@ -8,3 +8,5 @@ export type { ConversationMessageContent, ConversationMessageSender, Converstati
8
8
  export { registerCustomMessageComponent } from './utils/custom-message';
9
9
  export { ConversationPlatform, ConversationEndedBehavior };
10
10
  export type { UnregisterControllerDelegate };
11
+ export { Agent } from './agent';
12
+ export { ConversationProvider } from './conversation-provider';
package/index.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var $=Object.defineProperty;var q=(i,e,t)=>e in i?$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var d=(i,e,t)=>(q(i,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@telia-ace/widget-core"),p=require("@telia-ace/widget-services"),x=require("@telia-ace/widget-utilities"),L=require("@telia-ace/widget-forms"),M=require("@telia-ace/widget-plugins"),N=require("@telia-ace/widget-ui"),z=require("react");class U{constructor(e){d(this,"cache",new Map);d(this,"subscriptions",[]);this.controller=e;const{events:t}=e.container.get("$widget"),s=t.subscribe("data-client:fetched",(r,n)=>{n.type==="contact-method"&&this.cache.set(n.response.id,n.response)});this.subscriptions.push(s)}getConversationLogs(){return this.controller.messages.reduce((t,s)=>{const r=P(s),{key:n,content:a,type:o,sender:c,timestamp:h}=r.content,u=this.parseEntry(a,o,c,h);return u&&t.push(u),t},[])}parseEntry(e,t,s,r){const n=h=>{let u=[],l=[],m;if(Array.isArray(h)){const[g,f]=h;m=f}else m=h;return this.createMessageContent(m).length&&(l=[...l,this.createMessageContent(m)]),u=[...u,...this.createMessageOptions(m)],{messagesAsList:l,options:u}};let a=[],o=[];if(Array.isArray(e.items)){const{items:h}=e;h.forEach(u=>{const l=n(u);a=[...a,...l.options],o=[...o,...l.messagesAsList]})}else{const h=n(e);a=[...a,...h.options],o=[...o,...h.messagesAsList]}return{options:a,message:o.length?o.join(`
2
- `):void 0,source:this.createMessageSource(t),alias:this.createAlias(t,s),timestamp:r}}createMessageSource(e){return e}createAlias(e,t){return e===y.System?"system":(t==null?void 0:t.name)||"Me"}handleContactMethod(e){if(!this.cache.has(e))return;const t=this.cache.get(e);let s="";return s=this.appendText(s,`${t.clientName}:`),s=this.appendText(s,t.title),t.description&&(s=this.appendText(s,t.title)),s}getDetails(e,t=!0){if(!e)return"";const{header:s,title:r,label:n,description:a,text:o,html:c,body:h,contactMethodId:u}=e;let l="";if(u){const m=this.handleContactMethod(u.toString());m&&(l=this.appendText(l,m,t))}return s&&(l=this.appendText(l,s,t)),r&&(l=this.appendText(l,r,t)),a&&(l=this.appendText(l,a,t)),o&&(l=this.appendText(l,o,t)),n&&(l=this.appendText(l,n,t)),c&&(l=this.appendText(l,c,t)),h&&typeof h=="string"&&(l=this.appendText(l,h,t)),l}createMessageContent(e){let t="";return t=this.getDetails(e),t}createMessageOptions(e){let t=[],s=[];return Array.isArray(e==null?void 0:e.actions)?s=e.actions:typeof(e==null?void 0:e.actions)=="object"&&(s=Object.entries(e.actions).map(([r,n])=>({actionKey:r,label:n}))),s.length&&(t=s.map(r=>this.getDetails(r,!1))),t}appendText(e,t,s=!0){return s&&e.length?`${e}
3
- ${t}`:e.length?`${e} ${t}`:t}dispose(){this.subscriptions.forEach(e=>{e()})}}class A{constructor(e,t){d(this,"id");d(this,"name");d(this,"avatar");d(this,"print",(e,t)=>{const s={name:this.name,avatar:this.avatar,id:this.id},r=P(e,t);return this.provider.createEntry(r.key,r.content,y.Agent,s,r.timestamp)});d(this,"typing",()=>this.provider.setTypingState({name:this.name,avatar:this.avatar}));this.provider=e,this.id=t.id||x.uuid(),this.name=t.name,this.avatar=t.avatar}update(e){var r;const{name:t,avatar:s}=e;s===null?this.avatar=void 0:s&&(this.avatar=s),t===null?this.name=void 0:t&&(this.name=t),(r=this.provider.controller)==null||r.events.dispatch("conversation:agent-updated",{agent:this})}}class E{constructor(e,t,s){d(this,"subscriptions",[]);d(this,"options");d(this,"user");this.name=e,this.container=t,this.controller=s,this.user=s==null?void 0:s.user,this.options={silent:!1}}static create(e,t,s){return new E(e,t,s)}createAgent(e={}){var t;if(this.controller){const s=this.controller.getAgentById(e.id),r=s?new A(this,{...s,...e}):new A(this,e);return s||(t=this.controller)==null||t.events.dispatch("conversation:agent-created",{agent:r}),r}}print(e){var t;return(t=this.controller)==null?void 0:t.print(e)}setTypingState(e,t){var s;return(s=this.controller)==null?void 0:s.setTypingState(e,t)}loading(){return this.controller?this.controller.loader():()=>()=>{}}createEntry(e,t,s,r,n){var a;return(a=this.controller)==null?void 0:a.createEntry(e,t,s,r,n)}dispose(){var e;process.env.NODE_ENV!=="production"&&console.log(`conversation-provider: dispose (${this.name})`),(e=this.controller)==null||e.disposeProvider(this),this.controller=null,this.subscriptions.forEach(t=>t())}isRehydrated(){var e;return((e=this.controller)==null?void 0:e.isRehydrated())||Promise.resolve(!1)}getHistory(){var e;return((e=this.controller)==null?void 0:e.getHistory())||[]}complete(){var e;(e=this.controller)==null||e.onCompleteProvider()}setOptions(e={silent:!1}){this.options=e}onUnreadMessage(e){var t;if(this.controller){const s=(t=this.controller)==null?void 0:t.onUnreadMessage(e);return this.subscriptions.push(s),()=>{s()}}}onMounted(e){var t;if(this.controller){const s=(t=this.controller)==null?void 0:t.events.subscribe("conversation:component-mount-changed",e);return this.subscriptions.push(s),e({},this.controller.getComponentMountedState()),()=>{s()}}}}const O=i=>`conversation-${i}`;class K{constructor(){d(this,"_locking",Promise.resolve());d(this,"_locks",0)}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),s=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),s}}class Q{constructor(e,t,s){d(this,"sessionStorageKey");d(this,"locker",new K);d(this,"initialStoredAgents",[]);this.container=e,this.conversation=t,this.enabled=s,this.sessionStorageKey=O(t.id),t.onStarted(async()=>{if(t.messages.length>0)return;const{agents:r}=await this.read(),n=[];r&&r.forEach(o=>{const c=t.providerIndex(o.providerName),h=c>-1?t.registeredProviders[c]:t.createProvider(o.providerName),u=new A(h,{name:o.name,avatar:o.avatar,id:o.id});n.push(u)});const{messages:a}=await this.read();a.forEach(o=>{switch(o.type){case"agent":{const c=n.find(h=>{var u;return h.id===((u=o.sender)==null?void 0:u.id)});c&&c.print(o.content.items||o.content,{key:o.key});return}case"user":{t.user.print(o.content.items||o.content,{key:o.key});return}case"system":default:t.print(o.content.items||o.content)}})}),t.onMessageCreated(async(r,n)=>{this.write(n.message,"messages")}),t.events.subscribe("conversation:agent-created",async(r,n)=>{const a={id:n.agent.id,name:n.agent.name,avatar:n.agent.avatar,providerName:n.agent.provider.name};await this.write(a,"agents")}),t.events.subscribe("conversation:agent-updated",async(r,n)=>{const{agents:a}=await this.read();await this.write([...a.map(o=>o.id===n.agent.id?{...o,name:n.agent.name,avatar:n.agent.avatar}:o)],"agents","update")})}setInitialData(e){this.initialStoredAgents=e.agents}async isRehydrated(){const{messages:e}=await this.read();return e.length>0}getStoredAgent(e){if(this.enabled)return this.initialStoredAgents.find(t=>t.id===e)}async write(e,t,s="add"){if(!this.enabled)return;const r=await this.locker.lock();return p.createStorageWriter(this.container,this.sessionStorageKey,p.StorageCategory.Necessary).then(async n=>{if(s==="add"){const a=await this.read();if(t==="messages"&&a.messages.findIndex(c=>c.key===e.key)>-1){r();return}const o={...a};return t==="messages"?o.messages=[...o.messages,e]:t==="agents"&&(o.agents=[...o.agents,e]),n({...a,...o}).then(()=>{r()})}if(s==="update"&&t==="agents"){const a=await this.read();return n({...a,agents:e}).then(()=>{r()})}return n(e).then(()=>{r()})})}async read(){return p.readStorage(this.container,this.sessionStorageKey).then(e=>e||{messages:[],agents:[]})}}class j{constructor(e){d(this,"print",(e,t)=>{const s=P(e,t);return this.controller.createEntry(s.key,s.content,y.User,void 0,s.timestamp)});this.controller=e}}const k=async(i,e,t)=>{const s=await i.getAsync("conversation"),r=await i.getAsync("components"),n=s.controllers.find(a=>a.conversation.id===e);if(n){const a=[...n.conversation.providers];a.forEach(c=>{n.conversation.setProviderOptions(c,{silent:!0})}),n.conversation.queueProviders(a),n.conversation.setProviders([t]);const o=r.components().ofType("conversation");r.write({key:"setConversationProvider",attributes:{properties:{providers:[t]}},target:o,provider:"localStorage"})}};class H{constructor(e){this.writer=e}update(e){const t=this.getNormalizedSettings(e);this.writer(t)}remove(){this.writer(null)}getNormalizedSettings(e){return typeof e=="string"?{body:e}:e.length>-1&&typeof e=="object"?{items:e}:e}}var y=(i=>(i.User="user",i.Agent="agent",i.System="system",i))(y||{});const P=(i,e)=>{let t,s=(e==null?void 0:e.key)||x.uuid(),r=Date.now();if(Array.isArray(i)&&i.length>-1)typeof i[0]=="string"?t={items:[i]}:t={items:i};else if(typeof i=="string")t={body:i};else if(i=i||{},i.type)t={...i};else{if(t={body:i.body,actions:i.actions,title:i.title},i.key&&(s=i.key),i.timestamp&&(r=i.timestamp),typeof i.form=="function"){const n=L.FormBuilder.create(s);i.form(n);const a=n.get();t.form=a}i.timestamp===null&&(r=null)}return{content:t,key:s,timestamp:r}},W=(i,e)=>{if(!e)return;const t=JSON.stringify(e),s=i.findIndex(r=>t===JSON.stringify(r));if(s>-1)return i.splice(s,1)};class B{constructor(e,t,s){d(this,"formHandlers",{});d(this,"user",new j(this));d(this,"events");d(this,"providers",[]);d(this,"active",!1);d(this,"queuedProviders",[]);d(this,"registeredProviders",[]);d(this,"loaders",0);d(this,"componentMounted",!1);d(this,"store");d(this,"messages",[]);d(this,"typingActors",[]);d(this,"conversationHistory");d(this,"print",e=>{const t=P(e);return this.createEntry(t.key,t.content,"system",void 0,t.timestamp)});this.container=e,this.id=t;const r=e.get("$widget");this.events=r.events.createChild(this),this.store=new Q(e,this,s.rehydrate),this.conversationHistory=new U(this)}setInitialStorage(e){this.store.setInitialData(e)}setProviders(e){const t=[],s=[];this.providers.reduce((r,n)=>(e.indexOf(n)===-1&&r.push(n),r),[]).forEach(r=>{const n=this.providers.indexOf(r);n>-1&&(t.push(r),this.providers.splice(n,1))}),e.forEach(r=>{this.providers.indexOf(r)===-1&&(s.push(r),this.providers.push(r))}),(s.length||t.length)&&this.events.dispatch("conversation:providers-changed",{added:s,removed:t})}createProvider(e){const t=this.providerIndex(e);if(t>-1)return this.registeredProviders[t];const s=E.create(e,this.container,this);return this.registeredProviders.push(s),s}providerIndex(e){return this.registeredProviders.findIndex(t=>t.name===e)}getAgentById(e){if(e)return this.store.getStoredAgent(e)}dispose(){this.conversationHistory.dispose(),this.registeredProviders.forEach(e=>e.dispose()),this.messages=[],this.events.dispatch("conversation:controller-disposed",this),this.active=!1}onDispose(e){return this.events.subscribe("conversation:controller-disposed",e)}onStarted(e){return this.events.subscribe("conversation:started",e)}onMessageCreated(e){return this.events.subscribe("conversation:message-created",e)}isRehydrated(){return this.store.isRehydrated()}disposeProvider(e){const t=this.providerIndex(e.name);t>-1&&this.registeredProviders.splice(t,1),this.events.dispatch("conversation:providers-changed",{removed:[e.name]}),this.registeredProviders.length||this.dispose()}onProvidersChange(e){return this.events.subscribe("conversation:providers-changed",e)}setComponentMountedState(e){this.componentMounted!==e&&(this.componentMounted=e,e&&(this.events.dispatch("conversation:unread-message",!1),this.events.dispatch("conversation:started",!0),this.active=!0),this.events.dispatch("conversation:component-mount-changed",e))}setProviderOptions(e,t){const s=this.providerIndex(e);s>-1&&this.registeredProviders[s].setOptions(t)}changeProvider(e){this.registeredProviders.find(s=>s.name===e)&&k(this.container,this.id,e)}queueProviders(e){this.queuedProviders=e}onCompleteProvider(){const e=this.queuedProviders.pop();e&&k(this.container,this.id,e)}getComponentMountedState(){return this.componentMounted}onUnreadMessage(e){return this.events.subscribe("conversation:unread-message",e)}createEntry(e,t,s,r,n){const a={key:e,content:t,type:s,sender:r||null,timestamp:n||n===null?n:Date.now()};this.messages.push(a),a.type==="agent"&&W(this.typingActors,r);const o=new H(c=>{if(c!==null){const{timestamp:h=void 0,...u}=c;a.content=u,h&&(a.timestamp=h)}else{const h=this.messages.indexOf(a);a.content=null,h>-1&&this.messages.splice(h,1)}this.events.dispatch("conversation:message-updated",{message:a}),this.update()});return this.events.dispatch("conversation:message-created",{message:a}),this.update(),this.componentMounted||this.events.dispatch("conversation:unread-message",!0),o}update(){this.events.dispatch("conversation:updated",{messages:this.messages,loading:this.loaders>0,typingActors:this.typingActors})}getMessageStream(){return{messages:this.messages,loading:this.loaders>0,typingActors:this.typingActors}}setTypingState(e,t){return this.typingActors.indexOf(e)===-1&&(this.typingActors.push(e),this.update()),()=>{W(this.typingActors,e),this.update()}}loader(){this.loaders=this.loaders+1;let e=!1;return this.loaders===1&&this.update(),()=>{e||(e=!0,this.loaders=this.loaders-1,this.loaders===0&&this.update())}}submitForm(e,t){this.formHandlers[e]={...this.formHandlers[e],submit:t}}validateForm(e,t){this.formHandlers[e]={...this.formHandlers[e],validate:t}}getHistory(){return this.conversationHistory.getConversationLogs()}}const F=(i,e)=>{const t=i.split("_contact");return e.widgets.get(t[0])},I=i=>{const e=i.get("$widget"),{name:t,implementation:s}=i.get("$widget"),r=t.indexOf("_contact")>-1?F(t,s):e,{data:n}=i.get("$settings"),{trigger:a}=r.container.get("$settings"),o=`${t.replace("_contact-method","").replace("_contact","")}_contact-method`,c=s.widgets.get(o);return c&&!a?{chatWidget:c,mainWidget:r,data:n}:{mainWidget:r,data:n}},G=i=>{const{chatWidget:e}=I(i);return!!e},R=(i,e,t)=>{const{mainWidget:s,data:r,chatWidget:n}=I(i);return n?n.state==="activated"?n.invoke("open").then(()=>{n.container.getAsync("conversation").then(a=>{a.navigateToConversationIfActive(e.id).then(()=>M.closeAllModals(i))})}):n.activate().then(()=>{const{trigger:a}=n.container.get("$settings");return a.action="hide",n.invoke("setSettings",()=>({data:r,trigger:a,activate:!0})).then(()=>n.container.getAsync("components").then(o=>{const c=o.components().ofType("contact-method");o.write({key:"setContactMethodId",attributes:{properties:{id:e.id,guideId:e.guideId}},target:c,provider:"localStorage"});const h=o.components().ofType("conversation");o.write({key:"setConversationProvider",attributes:{properties:{providers:[e.clientName]}},target:h,provider:"localStorage"})}))}).then(()=>n.invoke("attach",{key:"contact-method",triggerDOMElement:t,withRenderState:"open"})).then(()=>(p.createStorageWriter(n.container,"activeStickyWidget",p.StorageCategory.Necessary,{medium:p.StorageMedium.Local,scope:p.StorageScope.Implementation}).then(a=>a(n.name)),n.container.getAsync("conversation").then(a=>{a.setConversationEndedBehavior(S.Deactivate)}).then(()=>M.closeAllModals(i)).then(()=>!1))):(s.container.getAsync("conversation").then(a=>a.navigateToConversationIfActive(e.id).then(()=>a.setConversationEndedBehavior(S.Navigate))),!n)},J=(i,e,t="conversation")=>{const{mainWidget:s,chatWidget:r}=I(i);return r?r.container.getAsync("router").then(n=>{n.navigate(t,{id:e.id})}):s.container.getAsync("conversation").then(n=>{var a;(a=n.setConversationEndedBehavior(S.Navigate))==null||a.then(()=>{s.container.getAsync("router").then(o=>{s.container.getAsync("components").then(c=>{const h=c.components().ofType("conversation");c.write({key:"setConversationProvider",attributes:{properties:{providers:[e.clientName]}},target:h,provider:"localStorage"})}).then(()=>{o.navigate(t,{id:e.id})})})})})},b="conversations";var S=(i=>(i.Deactivate="deactivate",i.Navigate="navigate",i.None="none",i))(S||{});class w{constructor(e,t){d(this,"events");d(this,"controllers",[]);d(this,"providers",[]);d(this,"disposeProviders",{});d(this,"subscriptions",[]);d(this,"storageWriter",null);d(this,"router",null);d(this,"buttonQuery",null);d(this,"sessionInfo",null);this.container=e,this.components=t;const s=e.get("$widget");this.events=s.events.createChild(this)}initialize(){p.createStorageWriter(this.container,b,p.StorageCategory.Necessary,{medium:p.StorageMedium.Local}).then(e=>this.storageWriter=e),p.readStorage(this.container,b,p.StorageMedium.Local).then(e=>{this.buttonQuery=this.components.components().ofType("conversation-return-button"),e&&(this.sessionInfo=e,e.id&&e.route&&this.writeToComponents({active:!0,alert:{show:!1}}))}),this.container.getAsync("router").then(e=>this.router=e),this.events.subscribe("conversation:ended",(e,t)=>{var s,r,n;switch((s=this.sessionInfo)==null?void 0:s.conversationEndedBehavior){case"deactivate":this.container.get("$widget").deactivate();break;case"navigate":const o=(r=this.router)==null?void 0:r.getInitialRoute();o&&((n=this.router)==null||n.navigate(o.name));break}this.writeToComponents({active:!1}),this.sessionInfo=null,this.storageWriter&&this.storageWriter()})}addSubscription(e){this.subscriptions.push(e)}static getInstance(e,t="conversation"){return x.lock(e)(()=>e.getAsync(t).then(s=>{let r=s;return r||D.ComponentPlatform.getInstance(e).then(n=>(r=new w(e,n),r.initialize(),e.registerAsync(t,()=>r),r))}))}navigateToConversationIfActive(e){return p.readStorage(this.container,b,p.StorageMedium.Local).then(t=>{var s;if(t&&t.id===e&&t.route){const{name:r,params:n}=t.route;(s=this.router)==null||s.navigate(r,n)}})}setConversationEndedBehavior(e){return p.readStorage(this.container,b,p.StorageMedium.Local).then(t=>{let s=t;return s?s.conversationEndedBehavior=e:s={conversationEndedBehavior:e},this.sessionInfo=s,this.storageWriter&&this.storageWriter(this.sessionInfo)||Promise.resolve()})}async createController(e,t){const s=O(e),{agents:r}=await p.readStorage(this.container,s)||{agents:[]},n=this.controllers.findIndex(o=>o.conversation.id===e);let a;return n>-1?a=this.controllers[n].conversation:a=new B(this.container,e,t),a.setInitialStorage({agents:r||[]}),a}registerProvider(e,t){const s={name:e,handler:t};this.providers.push(s),this.controllers.filter(r=>r.conversation.providers.indexOf(e)>-1).forEach(r=>{this.invokeHandler(s,r)})}registerController(e,t){const s=this.controllers.findIndex(n=>n.conversation.id===e.id);let r;if(s<0){r={conversation:e,component:t},this.controllers.push(r);const n=a=>{a&&this.providers.filter(o=>a.indexOf(o.name)>-1).forEach(o=>{this.invokeHandler(o,r)})};return this.subscriptions.push(e.onDispose((a,o)=>{const c=this.controllers.findIndex(h=>h.conversation===o);c>-1&&this.controllers.splice(c,1),this.components.components().ofType("conversation-return-button").select().writeProperties({active:!1}),this.events.dispatch("conversation:ended",{},{bubbles:!0})})),this.subscriptions.push(e.onProvidersChange((a,o)=>{const{added:c,removed:h=[]}=o;h.forEach(u=>{(this.disposeProviders[u]||[]).forEach(l=>{l()})}),n(c)})),this.subscriptions.push(e.onStarted((a,o)=>{var h,u;const c={id:e.id,route:(h=this.router)==null?void 0:h.getRouteData(),conversationEndedBehavior:(u=this.sessionInfo)==null?void 0:u.conversationEndedBehavior};this.sessionInfo=c,this.storageWriter&&this.storageWriter(c),this.writeToComponents({active:o})})),this.subscriptions.push(e.onUnreadMessage((a,o)=>{this.events.dispatch("conversation:unread-message",o),this.writeToComponents({alert:{show:o}})})),n(e.providers),!0}return r=this.controllers[s],!1}writeToComponents(e,t="conversationReturnButtonState"){this.buttonQuery&&this.components.write({key:"conversationReturnButtonState",attributes:{properties:e},target:this.buttonQuery,provider:"localStorage"})}invokeHandler(e,t){const s=e.handler(t.conversation.createProvider(e.name),t.component);s&&(this.disposeProviders[e.name]||(this.disposeProviders[e.name]=[]),this.disposeProviders[e.name].push(s))}getComponentRoute(){return p.readStorage(this.container,b,p.StorageMedium.Local).then(e=>e==null?void 0:e.route)}dispose(){Object.keys(this.disposeProviders).forEach(e=>{this.disposeProviders[e].forEach(t=>{t()})}),this.subscriptions.forEach(e=>{e()}),this.controllers=[],this.providers=[]}static async handleContactMethodClick(e,t,s,r){if(G(t)){e.preventDefault();let n=document.getElementById("humany-dynamic-anchor");n||(n=document.createElement("a"),n.setAttribute("href","#"),n.id="humany-dynamic-anchor",document.body.appendChild(n)),R(t,s,n)}R(t,s)}static async handleContactMethodSubmit(e,t){var s,r;return(r=(s=t==null?void 0:t.body.form.meta)==null?void 0:s.conversation)!=null&&r.id?k(e,t.body.form.meta.conversation.id,t.clientName):J(e,t)}}const V=(i,e)=>i.reduce((t,s,r)=>{var a,o;const n={...s,content:[{...s.content,key:s.key}]};if(t.length>0&&s.type!==y.System){const c=t[t.length-1];if((!e&&e!==0||Math.abs(c.timestamp-s.timestamp)<e)&&((a=c.sender)==null?void 0:a.name)===((o=s.sender)==null?void 0:o.name)&&c.type===s.type)return c.timestamp=s.timestamp,c.content.push({...s.content,key:s.key}),t}return t.push(n),t},[]),Y=i=>Promise.all([w.getInstance(i),i.getAsync("router")]).then(([e,t])=>N.createReactComponent(i,"conversation",Promise.resolve().then(()=>require("./conversation-cba1688c.js")),async s=>{const{rehydrate:r=!1}=s.properties(),a=t.getRouteData().params.id||s.node.name||"component",o=await e.createController(a,{rehydrate:r}),c=e.registerController(o,s),h=3*60*1e3,u=v=>{const{providers:g=[]}=v;if(g){const f=Array.isArray(g)?g:[g];return o.setProviders(f),f}};u(s.properties(u)),o.setComponentMountedState(!0);const l=v=>{const{loading:g,typingActors:f,messages:C}=v;s.writeProperties({loading:g,typingActors:f,messages:V(C,h)})};l(o.getMessageStream()),c&&(s.writeProperties({conversationControllerId:o.id}),s.actions.create("user-submit",(v,g)=>{if(g){const{preventDefault:f,validationPromise:C}=g;if(f){C&&C().then(T=>{T&&o.user.print(T)});return}}o.user.print(v.text)}),s.actions.create("user-typing",(v,g)=>{}),s.actions.create("form",(v,g)=>{}),s.actions.create("action",(v,g)=>{}),s.actions.create("overlay-mounted",(v,g)=>{}),s.actions.create("show-overlay",(v,g)=>{s.writeProperties({overlay:{conversation:!1,secondary:!1}})}),s.actions.create("hide-overlay",(v,g)=>{s.writeProperties({overlay:null})}),s.actions.create("show-overlay-conversation",(v,g)=>{s.writeProperties({overlay:{conversation:!0,secondary:!1}})}),s.actions.create("hide-overlay-conversation",(v,g)=>{s.writeProperties({overlay:{conversation:!1,secondary:!1}})}));const m=o.events.subscribe("conversation:updated",(v,g)=>{l(g)});return()=>{o.setComponentMountedState(!1),m(),o.active||l({messages:[],typingActors:[],loading:!1})}},{reuseController:!0})),X=i=>Promise.all([D.ComponentPlatform.getInstance(i),w.getInstance(i),i.getAsync("router")]).then(([e,t,s])=>N.createReactComponent(i,"conversation-return-button",Promise.resolve().then(()=>require("./return-button-cdc53d1f.js")),r=>{r.actions.create("toggle",(n={})=>{var a;(a=t.getComponentRoute())==null||a.then(o=>{o&&s.navigate(o.name,o.params)})})}));var _=(i=>(i.LinkList="link-list",i.Separator="separator",i.ButtonList="button-list",i.ItemList="item-list",i.Text="text",i.HTML="html",i.VideoRequest="video-request",i))(_||{});const Z=(i,e,t)=>i.getAsync("componentResolver").then(async s=>{(await w.getInstance(i)).addSubscription(s.registerComponent(e,z.lazy(()=>t)))});exports.ConversationComponent=Y;exports.ConversationController=B;exports.ConversationEndedBehavior=S;exports.ConversationEntry=H;exports.ConversationMessageListItemType=_;exports.ConversationMessageType=y;exports.ConversationPlatform=w;exports.ConversationReturnButtonComponent=X;exports.registerCustomMessageComponent=Z;
1
+ "use strict";var $=Object.defineProperty;var q=(o,e,t)=>e in o?$(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var d=(o,e,t)=>(q(o,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@telia-ace/widget-core"),p=require("@telia-ace/widget-services"),E=require("@telia-ace/widget-utilities"),L=require("@telia-ace/widget-forms"),M=require("@telia-ace/widget-plugins"),N=require("@telia-ace/widget-ui"),z=require("react");class U{constructor(e){d(this,"cache",new Map);d(this,"subscriptions",[]);this.controller=e;const{events:t}=e.container.get("$widget"),s=t.subscribe("data-client:fetched",(r,n)=>{n.type==="contact-method"&&this.cache.set(n.response.id,n.response)});this.subscriptions.push(s)}getConversationLogs(){return this.controller.messages.reduce((t,s)=>{const r=k(s),{key:n,content:a,type:i,sender:c,timestamp:h}=r.content,u=this.parseEntry(a,i,c,h);return u&&t.push(u),t},[])}parseEntry(e,t,s,r){const n=h=>{let u=[],l=[],m;if(Array.isArray(h)){const[g,f]=h;m=f}else m=h;return this.createMessageContent(m).length&&(l=[...l,this.createMessageContent(m)]),u=[...u,...this.createMessageOptions(m)],{messagesAsList:l,options:u}};let a=[],i=[];if(Array.isArray(e.items)){const{items:h}=e;h.forEach(u=>{const l=n(u);a=[...a,...l.options],i=[...i,...l.messagesAsList]})}else{const h=n(e);a=[...a,...h.options],i=[...i,...h.messagesAsList]}return{options:a,message:i.length?i.join(`
2
+ `):void 0,source:this.createMessageSource(t),alias:this.createAlias(t,s),timestamp:r}}createMessageSource(e){return e}createAlias(e,t){return e===y.System?"system":(t==null?void 0:t.name)||"Me"}handleContactMethod(e){if(!this.cache.has(e))return;const t=this.cache.get(e);let s="";return s=this.appendText(s,`${t.clientName}:`),s=this.appendText(s,t.title),t.description&&(s=this.appendText(s,t.title)),s}getDetails(e,t=!0){if(!e)return"";const{header:s,title:r,label:n,description:a,text:i,html:c,body:h,contactMethodId:u}=e;let l="";if(u){const m=this.handleContactMethod(u.toString());m&&(l=this.appendText(l,m,t))}return s&&(l=this.appendText(l,s,t)),r&&(l=this.appendText(l,r,t)),a&&(l=this.appendText(l,a,t)),i&&(l=this.appendText(l,i,t)),n&&(l=this.appendText(l,n,t)),c&&(l=this.appendText(l,c,t)),h&&typeof h=="string"&&(l=this.appendText(l,h,t)),l}createMessageContent(e){let t="";return t=this.getDetails(e),t}createMessageOptions(e){let t=[],s=[];return Array.isArray(e==null?void 0:e.actions)?s=e.actions:typeof(e==null?void 0:e.actions)=="object"&&(s=Object.entries(e.actions).map(([r,n])=>({actionKey:r,label:n}))),s.length&&(t=s.map(r=>this.getDetails(r,!1))),t}appendText(e,t,s=!0){return s&&e.length?`${e}
3
+ ${t}`:e.length?`${e} ${t}`:t}dispose(){this.subscriptions.forEach(e=>{e()})}}class P{constructor(e,t){d(this,"id");d(this,"name");d(this,"avatar");d(this,"print",(e,t,s=null)=>{const r={name:this.name,avatar:this.avatar,id:this.id},n=k(e,t);return s=s??n.timestamp,this.provider.createEntry(n.key,n.content,y.Agent,r,s)});d(this,"typing",()=>this.provider.setTypingState({name:this.name,avatar:this.avatar}));this.provider=e,this.id=t.id||E.uuid(),this.name=t.name,this.avatar=t.avatar}update(e){var r;const{name:t,avatar:s}=e;s===null?this.avatar=void 0:s&&(this.avatar=s),t===null?this.name=void 0:t&&(this.name=t),(r=this.provider.controller)==null||r.events.dispatch("conversation:agent-updated",{agent:this})}}class A{constructor(e,t,s){d(this,"subscriptions",[]);d(this,"options");d(this,"user");this.name=e,this.container=t,this.controller=s,this.user=s==null?void 0:s.user,this.options={silent:!1}}static create(e,t,s){return new A(e,t,s)}createAgent(e={}){var t;if(this.controller){const s=this.controller.getAgentById(e.id),r=s?new P(this,{...s,...e}):new P(this,e);return s||(t=this.controller)==null||t.events.dispatch("conversation:agent-created",{agent:r}),r}}print(e){var t;return(t=this.controller)==null?void 0:t.print(e)}setTypingState(e,t){var s;return(s=this.controller)==null?void 0:s.setTypingState(e,t)}loading(){return this.controller?this.controller.loader():()=>()=>{}}createEntry(e,t,s,r,n){var a;return(a=this.controller)==null?void 0:a.createEntry(e,t,s,r,n)}dispose(){var e;process.env.NODE_ENV!=="production"&&console.log(`conversation-provider: dispose (${this.name})`),(e=this.controller)==null||e.disposeProvider(this),this.controller=null,this.subscriptions.forEach(t=>t())}isRehydrated(){var e;return((e=this.controller)==null?void 0:e.isRehydrated())||Promise.resolve(!1)}getHistory(){var e;return((e=this.controller)==null?void 0:e.getHistory())||[]}complete(){var e;(e=this.controller)==null||e.onCompleteProvider()}setOptions(e={silent:!1}){this.options=e}onUnreadMessage(e){var t;if(this.controller){const s=(t=this.controller)==null?void 0:t.onUnreadMessage(e);return this.subscriptions.push(s),()=>{s()}}}onMounted(e){var t;if(this.controller){const s=(t=this.controller)==null?void 0:t.events.subscribe("conversation:component-mount-changed",e);return this.subscriptions.push(s),e({},this.controller.getComponentMountedState()),()=>{s()}}}}const O=o=>`conversation-${o}`;class K{constructor(){d(this,"_locking",Promise.resolve());d(this,"_locks",0)}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),s=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),s}}class Q{constructor(e,t,s){d(this,"sessionStorageKey");d(this,"locker",new K);d(this,"initialStoredAgents",[]);this.container=e,this.conversation=t,this.enabled=s,this.sessionStorageKey=O(t.id),t.onStarted(async()=>{if(t.messages.length>0)return;const{agents:r}=await this.read(),n=[];r&&r.forEach(i=>{const c=t.providerIndex(i.providerName),h=c>-1?t.registeredProviders[c]:t.createProvider(i.providerName),u=new P(h,{name:i.name,avatar:i.avatar,id:i.id});n.push(u)});const{messages:a}=await this.read();a.forEach(i=>{switch(i.type){case"agent":{const c=n.find(h=>{var u;return h.id===((u=i.sender)==null?void 0:u.id)});c&&c.print(i.content.items||i.content,{key:i.key},i.timestamp);return}case"user":{t.user.print(i.content.items||i.content,{key:i.key},i.timestamp);return}case"system":default:t.print(i.content.items||i.content,i.timestamp)}})}),t.onMessageCreated(async(r,n)=>{this.write(n.message,"messages")}),t.events.subscribe("conversation:agent-created",async(r,n)=>{const a={id:n.agent.id,name:n.agent.name,avatar:n.agent.avatar,providerName:n.agent.provider.name};await this.write(a,"agents")}),t.events.subscribe("conversation:agent-updated",async(r,n)=>{const{agents:a}=await this.read();await this.write([...a.map(i=>i.id===n.agent.id?{...i,name:n.agent.name,avatar:n.agent.avatar}:i)],"agents","update")})}setInitialData(e){this.initialStoredAgents=e.agents}async isRehydrated(){const{messages:e}=await this.read();return e.length>0}getStoredAgent(e){if(this.enabled)return this.initialStoredAgents.find(t=>t.id===e)}async write(e,t,s="add"){if(!this.enabled)return;const r=await this.locker.lock();return p.createStorageWriter(this.container,this.sessionStorageKey,p.StorageCategory.Necessary).then(async n=>{if(s==="add"){const a=await this.read();if(t==="messages"&&a.messages.findIndex(c=>c.key===e.key)>-1){r();return}const i={...a};return t==="messages"?i.messages=[...i.messages,e]:t==="agents"&&(i.agents=[...i.agents,e]),n({...a,...i}).then(()=>{r()})}if(s==="update"&&t==="agents"){const a=await this.read();return n({...a,agents:e}).then(()=>{r()})}return n(e).then(()=>{r()})})}async read(){return p.readStorage(this.container,this.sessionStorageKey).then(e=>e||{messages:[],agents:[]})}}class j{constructor(e){d(this,"print",(e,t,s=null)=>{const r=k(e,t);return s=s??r.timestamp,this.controller.createEntry(r.key,r.content,y.User,void 0,s)});this.controller=e}}const x=async(o,e,t)=>{const s=await o.getAsync("conversation"),r=await o.getAsync("components"),n=s.controllers.find(a=>a.conversation.id===e);if(n){const a=[...n.conversation.providers];a.forEach(c=>{n.conversation.setProviderOptions(c,{silent:!0})}),n.conversation.queueProviders(a),n.conversation.setProviders([t]);const i=r.components().ofType("conversation");r.write({key:"setConversationProvider",attributes:{properties:{providers:[t]}},target:i,provider:"localStorage"})}};class H{constructor(e){this.writer=e}update(e){const t=this.getNormalizedSettings(e);this.writer(t)}remove(){this.writer(null)}getNormalizedSettings(e){return typeof e=="string"?{body:e}:e.length>-1&&typeof e=="object"?{items:e}:e}}var y=(o=>(o.User="user",o.Agent="agent",o.System="system",o))(y||{});const k=(o,e)=>{let t,s=(e==null?void 0:e.key)||E.uuid(),r=Date.now();if(Array.isArray(o)&&o.length>-1)typeof o[0]=="string"?t={items:[o]}:t={items:o};else if(typeof o=="string")t={body:o};else if(o=o||{},o.type)t={...o};else{if(t={body:o.body,actions:o.actions,title:o.title},o.key&&(s=o.key),o.timestamp&&(r=o.timestamp),typeof o.form=="function"){const n=L.FormBuilder.create(s);o.form(n);const a=n.get();t.form=a}o.timestamp===null&&(r=null)}return{content:t,key:s,timestamp:r}},W=(o,e)=>{if(!e)return;const t=JSON.stringify(e),s=o.findIndex(r=>t===JSON.stringify(r));if(s>-1)return o.splice(s,1)};class B{constructor(e,t,s){d(this,"formHandlers",{});d(this,"user",new j(this));d(this,"events");d(this,"providers",[]);d(this,"active",!1);d(this,"queuedProviders",[]);d(this,"registeredProviders",[]);d(this,"loaders",0);d(this,"componentMounted",!1);d(this,"store");d(this,"messages",[]);d(this,"typingActors",[]);d(this,"conversationHistory");d(this,"print",(e,t=null)=>{const s=k(e);return t=t??s.timestamp,this.createEntry(s.key,s.content,"system",void 0,t)});this.container=e,this.id=t;const r=e.get("$widget");this.events=r.events.createChild(this),this.store=new Q(e,this,s.rehydrate),this.conversationHistory=new U(this)}setInitialStorage(e){this.store.setInitialData(e)}setProviders(e){const t=[],s=[];this.providers.reduce((r,n)=>(e.indexOf(n)===-1&&r.push(n),r),[]).forEach(r=>{const n=this.providers.indexOf(r);n>-1&&(t.push(r),this.providers.splice(n,1))}),e.forEach(r=>{this.providers.indexOf(r)===-1&&(s.push(r),this.providers.push(r))}),(s.length||t.length)&&this.events.dispatch("conversation:providers-changed",{added:s,removed:t})}createProvider(e){const t=this.providerIndex(e);if(t>-1)return this.registeredProviders[t];const s=A.create(e,this.container,this);return this.registeredProviders.push(s),s}providerIndex(e){return this.registeredProviders.findIndex(t=>t.name===e)}getAgentById(e){if(e)return this.store.getStoredAgent(e)}dispose(){this.conversationHistory.dispose(),this.registeredProviders.forEach(e=>e.dispose()),this.messages=[],this.events.dispatch("conversation:controller-disposed",this),this.active=!1}onDispose(e){return this.events.subscribe("conversation:controller-disposed",e)}onStarted(e){return this.events.subscribe("conversation:started",e)}onMessageCreated(e){return this.events.subscribe("conversation:message-created",e)}isRehydrated(){return this.store.isRehydrated()}disposeProvider(e){const t=this.providerIndex(e.name);t>-1&&this.registeredProviders.splice(t,1),this.events.dispatch("conversation:providers-changed",{removed:[e.name]}),this.registeredProviders.length||this.dispose()}onProvidersChange(e){return this.events.subscribe("conversation:providers-changed",e)}setComponentMountedState(e){this.componentMounted!==e&&(this.componentMounted=e,e&&(this.events.dispatch("conversation:unread-message",!1),this.events.dispatch("conversation:started",!0),this.active=!0),this.events.dispatch("conversation:component-mount-changed",e))}setProviderOptions(e,t){const s=this.providerIndex(e);s>-1&&this.registeredProviders[s].setOptions(t)}changeProvider(e){this.registeredProviders.find(s=>s.name===e)&&x(this.container,this.id,e)}queueProviders(e){this.queuedProviders=e}onCompleteProvider(){const e=this.queuedProviders.pop();e&&x(this.container,this.id,e)}getComponentMountedState(){return this.componentMounted}onUnreadMessage(e){return this.events.subscribe("conversation:unread-message",e)}createEntry(e,t,s,r,n){const a={key:e,content:t,type:s,sender:r||null,timestamp:n||n===null?n:Date.now()};this.messages.push(a),a.type==="agent"&&W(this.typingActors,r);const i=new H(c=>{if(c!==null){const{timestamp:h=void 0,...u}=c;a.content=u,h&&(a.timestamp=h)}else{const h=this.messages.indexOf(a);a.content=null,h>-1&&this.messages.splice(h,1)}this.events.dispatch("conversation:message-updated",{message:a}),this.update()});return this.events.dispatch("conversation:message-created",{message:a}),this.update(),this.componentMounted||this.events.dispatch("conversation:unread-message",!0),i}update(){this.events.dispatch("conversation:updated",{messages:this.messages,loading:this.loaders>0,typingActors:this.typingActors})}getMessageStream(){return{messages:this.messages,loading:this.loaders>0,typingActors:this.typingActors}}setTypingState(e,t){return this.typingActors.indexOf(e)===-1&&(this.typingActors.push(e),this.update()),()=>{W(this.typingActors,e),this.update()}}loader(){this.loaders=this.loaders+1;let e=!1;return this.loaders===1&&this.update(),()=>{e||(e=!0,this.loaders=this.loaders-1,this.loaders===0&&this.update())}}submitForm(e,t){this.formHandlers[e]={...this.formHandlers[e],submit:t}}validateForm(e,t){this.formHandlers[e]={...this.formHandlers[e],validate:t}}getHistory(){return this.conversationHistory.getConversationLogs()}}const F=(o,e)=>{const t=o.split("_contact");return e.widgets.get(t[0])},I=o=>{const e=o.get("$widget"),{name:t,implementation:s}=o.get("$widget"),r=t.indexOf("_contact")>-1?F(t,s):e,{data:n}=o.get("$settings"),{trigger:a}=r.container.get("$settings"),i=`${t.replace("_contact-method","").replace("_contact","")}_contact-method`,c=s.widgets.get(i);return c&&!a?{chatWidget:c,mainWidget:r,data:n}:{mainWidget:r,data:n}},G=o=>{const{chatWidget:e}=I(o);return!!e},R=(o,e,t)=>{const{mainWidget:s,data:r,chatWidget:n}=I(o);return n?n.state==="activated"?n.invoke("open").then(()=>{n.container.getAsync("conversation").then(a=>{a.navigateToConversationIfActive(e.id).then(()=>M.closeAllModals(o))})}):n.activate().then(()=>{const{trigger:a}=n.container.get("$settings");return a.action="hide",n.invoke("setSettings",()=>({data:r,trigger:a,activate:!0})).then(()=>n.container.getAsync("components").then(i=>{const c=i.components().ofType("contact-method");i.write({key:"setContactMethodId",attributes:{properties:{id:e.id,guideId:e.guideId}},target:c,provider:"localStorage"});const h=i.components().ofType("conversation");i.write({key:"setConversationProvider",attributes:{properties:{providers:[e.clientName]}},target:h,provider:"localStorage"})}))}).then(()=>n.invoke("attach",{key:"contact-method",triggerDOMElement:t,withRenderState:"open"})).then(()=>(p.createStorageWriter(n.container,"activeStickyWidget",p.StorageCategory.Necessary,{medium:p.StorageMedium.Local,scope:p.StorageScope.Implementation}).then(a=>a(n.name)),n.container.getAsync("conversation").then(a=>{a.setConversationEndedBehavior(S.Deactivate)}).then(()=>M.closeAllModals(o)).then(()=>!1))):(s.container.getAsync("conversation").then(a=>a.navigateToConversationIfActive(e.id).then(()=>a.setConversationEndedBehavior(S.Navigate))),!n)},J=(o,e,t="conversation")=>{const{mainWidget:s,chatWidget:r}=I(o);return r?r.container.getAsync("router").then(n=>{n.navigate(t,{id:e.id})}):s.container.getAsync("conversation").then(n=>{var a;(a=n.setConversationEndedBehavior(S.Navigate))==null||a.then(()=>{s.container.getAsync("router").then(i=>{s.container.getAsync("components").then(c=>{const h=c.components().ofType("conversation");c.write({key:"setConversationProvider",attributes:{properties:{providers:[e.clientName]}},target:h,provider:"localStorage"})}).then(()=>{i.navigate(t,{id:e.id})})})})})},b="conversations";var S=(o=>(o.Deactivate="deactivate",o.Navigate="navigate",o.None="none",o))(S||{});class w{constructor(e,t){d(this,"events");d(this,"controllers",[]);d(this,"providers",[]);d(this,"disposeProviders",{});d(this,"subscriptions",[]);d(this,"storageWriter",null);d(this,"router",null);d(this,"buttonQuery",null);d(this,"sessionInfo",null);this.container=e,this.components=t;const s=e.get("$widget");this.events=s.events.createChild(this)}initialize(){p.createStorageWriter(this.container,b,p.StorageCategory.Necessary,{medium:p.StorageMedium.Local}).then(e=>this.storageWriter=e),p.readStorage(this.container,b,p.StorageMedium.Local).then(e=>{this.buttonQuery=this.components.components().ofType("conversation-return-button"),e&&(this.sessionInfo=e,e.id&&e.route&&this.writeToComponents({active:!0,alert:{show:!1}}))}),this.container.getAsync("router").then(e=>this.router=e),this.events.subscribe("conversation:ended",(e,t)=>{var s,r,n;switch((s=this.sessionInfo)==null?void 0:s.conversationEndedBehavior){case"deactivate":this.container.get("$widget").deactivate();break;case"navigate":const i=(r=this.router)==null?void 0:r.getInitialRoute();i&&((n=this.router)==null||n.navigate(i.name));break}this.writeToComponents({active:!1}),this.sessionInfo=null,this.storageWriter&&this.storageWriter()})}addSubscription(e){this.subscriptions.push(e)}static getInstance(e,t="conversation"){return E.lock(e)(()=>e.getAsync(t).then(s=>{let r=s;return r||D.ComponentPlatform.getInstance(e).then(n=>(r=new w(e,n),r.initialize(),e.registerAsync(t,()=>r),r))}))}navigateToConversationIfActive(e){return p.readStorage(this.container,b,p.StorageMedium.Local).then(t=>{var s;if(t&&t.id===e&&t.route){const{name:r,params:n}=t.route;(s=this.router)==null||s.navigate(r,n)}})}setConversationEndedBehavior(e){return p.readStorage(this.container,b,p.StorageMedium.Local).then(t=>{let s=t;return s?s.conversationEndedBehavior=e:s={conversationEndedBehavior:e},this.sessionInfo=s,this.storageWriter&&this.storageWriter(this.sessionInfo)||Promise.resolve()})}async createController(e,t){const s=O(e),{agents:r}=await p.readStorage(this.container,s)||{agents:[]},n=this.controllers.findIndex(i=>i.conversation.id===e);let a;return n>-1?a=this.controllers[n].conversation:a=new B(this.container,e,t),a.setInitialStorage({agents:r||[]}),a}registerProvider(e,t){const s={name:e,handler:t};this.providers.push(s),this.controllers.filter(r=>r.conversation.providers.indexOf(e)>-1).forEach(r=>{this.invokeHandler(s,r)})}registerController(e,t){const s=this.controllers.findIndex(n=>n.conversation.id===e.id);let r;if(s<0){r={conversation:e,component:t},this.controllers.push(r);const n=a=>{a&&this.providers.filter(i=>a.indexOf(i.name)>-1).forEach(i=>{this.invokeHandler(i,r)})};return this.subscriptions.push(e.onDispose((a,i)=>{const c=this.controllers.findIndex(h=>h.conversation===i);c>-1&&this.controllers.splice(c,1),this.components.components().ofType("conversation-return-button").select().writeProperties({active:!1}),this.events.dispatch("conversation:ended",{},{bubbles:!0})})),this.subscriptions.push(e.onProvidersChange((a,i)=>{const{added:c,removed:h=[]}=i;h.forEach(u=>{(this.disposeProviders[u]||[]).forEach(l=>{l()})}),n(c)})),this.subscriptions.push(e.onStarted((a,i)=>{var h,u;const c={id:e.id,route:(h=this.router)==null?void 0:h.getRouteData(),conversationEndedBehavior:(u=this.sessionInfo)==null?void 0:u.conversationEndedBehavior};this.sessionInfo=c,this.storageWriter&&this.storageWriter(c),this.writeToComponents({active:i})})),this.subscriptions.push(e.onUnreadMessage((a,i)=>{this.events.dispatch("conversation:unread-message",i),this.writeToComponents({alert:{show:i}})})),n(e.providers),!0}return r=this.controllers[s],!1}writeToComponents(e,t="conversationReturnButtonState"){this.buttonQuery&&this.components.write({key:"conversationReturnButtonState",attributes:{properties:e},target:this.buttonQuery,provider:"localStorage"})}invokeHandler(e,t){const s=e.handler(t.conversation.createProvider(e.name),t.component);s&&(this.disposeProviders[e.name]||(this.disposeProviders[e.name]=[]),this.disposeProviders[e.name].push(s))}getComponentRoute(){return p.readStorage(this.container,b,p.StorageMedium.Local).then(e=>e==null?void 0:e.route)}dispose(){Object.keys(this.disposeProviders).forEach(e=>{this.disposeProviders[e].forEach(t=>{t()})}),this.subscriptions.forEach(e=>{e()}),this.controllers=[],this.providers=[]}static async handleContactMethodClick(e,t,s,r){if(G(t)){e.preventDefault();let n=document.getElementById("humany-dynamic-anchor");n||(n=document.createElement("a"),n.setAttribute("href","#"),n.id="humany-dynamic-anchor",document.body.appendChild(n)),R(t,s,n)}R(t,s)}static async handleContactMethodSubmit(e,t){var s,r;return(r=(s=t==null?void 0:t.body.form.meta)==null?void 0:s.conversation)!=null&&r.id?x(e,t.body.form.meta.conversation.id,t.clientName):J(e,t)}}const V=(o,e)=>o.reduce((t,s,r)=>{var a,i;const n={...s,content:[{...s.content,key:s.key}]};if(t.length>0&&s.type!==y.System){const c=t[t.length-1];if((!e&&e!==0||Math.abs(c.timestamp-s.timestamp)<e)&&((a=c.sender)==null?void 0:a.name)===((i=s.sender)==null?void 0:i.name)&&c.type===s.type)return c.timestamp=s.timestamp,c.content.push({...s.content,key:s.key}),t}return t.push(n),t},[]),Y=o=>Promise.all([w.getInstance(o),o.getAsync("router")]).then(([e,t])=>N.createReactComponent(o,"conversation",Promise.resolve().then(()=>require("./conversation-cba1688c.js")),async s=>{const{rehydrate:r=!1}=s.properties(),a=t.getRouteData().params.id||s.node.name||"component",i=await e.createController(a,{rehydrate:r}),c=e.registerController(i,s),h=3*60*1e3,u=v=>{const{providers:g=[]}=v;if(g){const f=Array.isArray(g)?g:[g];return i.setProviders(f),f}};u(s.properties(u)),i.setComponentMountedState(!0);const l=v=>{const{loading:g,typingActors:f,messages:C}=v;s.writeProperties({loading:g,typingActors:f,messages:V(C,h)})};l(i.getMessageStream()),c&&(s.writeProperties({conversationControllerId:i.id}),s.actions.create("user-submit",(v,g)=>{if(g){const{preventDefault:f,validationPromise:C}=g;if(f){C&&C().then(T=>{T&&i.user.print(T)});return}}i.user.print(v.text)}),s.actions.create("user-typing",(v,g)=>{}),s.actions.create("form",(v,g)=>{}),s.actions.create("action",(v,g)=>{}),s.actions.create("overlay-mounted",(v,g)=>{}),s.actions.create("show-overlay",(v,g)=>{s.writeProperties({overlay:{conversation:!1,secondary:!1}})}),s.actions.create("hide-overlay",(v,g)=>{s.writeProperties({overlay:null})}),s.actions.create("show-overlay-conversation",(v,g)=>{s.writeProperties({overlay:{conversation:!0,secondary:!1}})}),s.actions.create("hide-overlay-conversation",(v,g)=>{s.writeProperties({overlay:{conversation:!1,secondary:!1}})}));const m=i.events.subscribe("conversation:updated",(v,g)=>{l(g)});return()=>{i.setComponentMountedState(!1),m(),i.active||l({messages:[],typingActors:[],loading:!1})}},{reuseController:!0})),X=o=>Promise.all([D.ComponentPlatform.getInstance(o),w.getInstance(o),o.getAsync("router")]).then(([e,t,s])=>N.createReactComponent(o,"conversation-return-button",Promise.resolve().then(()=>require("./return-button-cdc53d1f.js")),r=>{r.actions.create("toggle",(n={})=>{var a;(a=t.getComponentRoute())==null||a.then(i=>{i&&s.navigate(i.name,i.params)})})}));var _=(o=>(o.LinkList="link-list",o.Separator="separator",o.ButtonList="button-list",o.ItemList="item-list",o.Text="text",o.HTML="html",o.VideoRequest="video-request",o))(_||{});const Z=(o,e,t)=>o.getAsync("componentResolver").then(async s=>{(await w.getInstance(o)).addSubscription(s.registerComponent(e,z.lazy(()=>t)))});exports.Agent=P;exports.ConversationComponent=Y;exports.ConversationController=B;exports.ConversationEndedBehavior=S;exports.ConversationEntry=H;exports.ConversationMessageListItemType=_;exports.ConversationMessageType=y;exports.ConversationPlatform=w;exports.ConversationProvider=A;exports.ConversationReturnButtonComponent=X;exports.registerCustomMessageComponent=Z;
package/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  var B = Object.defineProperty;
2
- var L = (n, e, t) => e in n ? B(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
- var d = (n, e, t) => (L(n, typeof e != "symbol" ? e + "" : e, t), t);
2
+ var L = (o, e, t) => e in o ? B(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
+ var d = (o, e, t) => (L(o, typeof e != "symbol" ? e + "" : e, t), t);
4
4
  import { ComponentPlatform as R } from "@telia-ace/widget-core";
5
5
  import { createStorageWriter as E, StorageCategory as I, readStorage as f, StorageMedium as y, StorageScope as z } from "@telia-ace/widget-services";
6
6
  import { uuid as H, lock as K } from "@telia-ace/widget-utilities";
@@ -13,19 +13,19 @@ class q {
13
13
  d(this, "cache", /* @__PURE__ */ new Map());
14
14
  d(this, "subscriptions", []);
15
15
  this.controller = e;
16
- const { events: t } = e.container.get("$widget"), s = t.subscribe("data-client:fetched", (r, i) => {
17
- i.type === "contact-method" && this.cache.set(i.response.id, i.response);
16
+ const { events: t } = e.container.get("$widget"), s = t.subscribe("data-client:fetched", (r, n) => {
17
+ n.type === "contact-method" && this.cache.set(n.response.id, n.response);
18
18
  });
19
19
  this.subscriptions.push(s);
20
20
  }
21
21
  getConversationLogs() {
22
22
  return this.controller.messages.reduce((t, s) => {
23
- const r = C(s), { key: i, content: a, type: o, sender: c, timestamp: h } = r.content, u = this.parseEntry(a, o, c, h);
23
+ const r = C(s), { key: n, content: a, type: i, sender: c, timestamp: h } = r.content, u = this.parseEntry(a, i, c, h);
24
24
  return u && t.push(u), t;
25
25
  }, []);
26
26
  }
27
27
  parseEntry(e, t, s, r) {
28
- const i = (h) => {
28
+ const n = (h) => {
29
29
  let u = [], l = [], v;
30
30
  if (Array.isArray(h)) {
31
31
  const [p, m] = h;
@@ -37,20 +37,20 @@ class q {
37
37
  options: u
38
38
  };
39
39
  };
40
- let a = [], o = [];
40
+ let a = [], i = [];
41
41
  if (Array.isArray(e.items)) {
42
42
  const { items: h } = e;
43
43
  h.forEach((u) => {
44
- const l = i(u);
45
- a = [...a, ...l.options], o = [...o, ...l.messagesAsList];
44
+ const l = n(u);
45
+ a = [...a, ...l.options], i = [...i, ...l.messagesAsList];
46
46
  });
47
47
  } else {
48
- const h = i(e);
49
- a = [...a, ...h.options], o = [...o, ...h.messagesAsList];
48
+ const h = n(e);
49
+ a = [...a, ...h.options], i = [...i, ...h.messagesAsList];
50
50
  }
51
51
  return {
52
52
  options: a,
53
- message: o.length ? o.join(`
53
+ message: i.length ? i.join(`
54
54
  `) : void 0,
55
55
  source: this.createMessageSource(t),
56
56
  alias: this.createAlias(t, s),
@@ -73,13 +73,13 @@ class q {
73
73
  getDetails(e, t = !0) {
74
74
  if (!e)
75
75
  return "";
76
- const { header: s, title: r, label: i, description: a, text: o, html: c, body: h, contactMethodId: u } = e;
76
+ const { header: s, title: r, label: n, description: a, text: i, html: c, body: h, contactMethodId: u } = e;
77
77
  let l = "";
78
78
  if (u) {
79
79
  const v = this.handleContactMethod(u.toString());
80
80
  v && (l = this.appendText(l, v, t));
81
81
  }
82
- return s && (l = this.appendText(l, s, t)), r && (l = this.appendText(l, r, t)), a && (l = this.appendText(l, a, t)), o && (l = this.appendText(l, o, t)), i && (l = this.appendText(l, i, t)), c && (l = this.appendText(l, c, t)), h && typeof h == "string" && (l = this.appendText(l, h, t)), l;
82
+ return s && (l = this.appendText(l, s, t)), r && (l = this.appendText(l, r, t)), a && (l = this.appendText(l, a, t)), i && (l = this.appendText(l, i, t)), n && (l = this.appendText(l, n, t)), c && (l = this.appendText(l, c, t)), h && typeof h == "string" && (l = this.appendText(l, h, t)), l;
83
83
  }
84
84
  createMessageContent(e) {
85
85
  let t = "";
@@ -87,9 +87,9 @@ class q {
87
87
  }
88
88
  createMessageOptions(e) {
89
89
  let t = [], s = [];
90
- return Array.isArray(e == null ? void 0 : e.actions) ? s = e.actions : typeof (e == null ? void 0 : e.actions) == "object" && (s = Object.entries(e.actions).map(([r, i]) => ({
90
+ return Array.isArray(e == null ? void 0 : e.actions) ? s = e.actions : typeof (e == null ? void 0 : e.actions) == "object" && (s = Object.entries(e.actions).map(([r, n]) => ({
91
91
  actionKey: r,
92
- label: i
92
+ label: n
93
93
  }))), s.length && (t = s.map((r) => this.getDetails(r, !1))), t;
94
94
  }
95
95
  appendText(e, t, s = !0) {
@@ -107,21 +107,24 @@ class k {
107
107
  d(this, "id");
108
108
  d(this, "name");
109
109
  d(this, "avatar");
110
- d(this, "print", (e, t) => {
111
- const s = {
110
+ d(this, "print", (e, t, s = null) => {
111
+ const r = {
112
112
  name: this.name,
113
113
  avatar: this.avatar,
114
114
  id: this.id
115
- }, r = C(e, t);
116
- return this.provider.createEntry(
117
- r.key,
118
- r.content,
115
+ }, n = C(e, t);
116
+ return s = s ?? n.timestamp, this.provider.createEntry(
117
+ n.key,
118
+ n.content,
119
119
  w.Agent,
120
- s,
121
- r.timestamp
120
+ r,
121
+ s
122
122
  );
123
123
  });
124
- d(this, "typing", () => this.provider.setTypingState({ name: this.name, avatar: this.avatar }));
124
+ d(this, "typing", () => this.provider.setTypingState({
125
+ name: this.name,
126
+ avatar: this.avatar
127
+ }));
125
128
  this.provider = e, this.id = t.id || H(), this.name = t.name, this.avatar = t.avatar;
126
129
  }
127
130
  update(e) {
@@ -165,9 +168,9 @@ class T {
165
168
  return this.controller ? this.controller.loader() : () => () => {
166
169
  };
167
170
  }
168
- createEntry(e, t, s, r, i) {
171
+ createEntry(e, t, s, r, n) {
169
172
  var a;
170
- return (a = this.controller) == null ? void 0 : a.createEntry(e, t, s, r, i);
173
+ return (a = this.controller) == null ? void 0 : a.createEntry(e, t, s, r, n);
171
174
  }
172
175
  dispose() {
173
176
  var e;
@@ -210,7 +213,7 @@ class T {
210
213
  }
211
214
  }
212
215
  }
213
- const $ = (n) => `conversation-${n}`;
216
+ const $ = (o) => `conversation-${o}`;
214
217
  class j {
215
218
  constructor() {
216
219
  d(this, "_locking", Promise.resolve());
@@ -238,63 +241,74 @@ class F {
238
241
  this.container = e, this.conversation = t, this.enabled = s, this.sessionStorageKey = $(t.id), t.onStarted(async () => {
239
242
  if (t.messages.length > 0)
240
243
  return;
241
- const { agents: r } = await this.read(), i = [];
242
- r && r.forEach((o) => {
243
- const c = t.providerIndex(o.providerName), h = c > -1 ? t.registeredProviders[c] : t.createProvider(o.providerName), u = new k(h, {
244
- name: o.name,
245
- avatar: o.avatar,
246
- id: o.id
244
+ const { agents: r } = await this.read(), n = [];
245
+ r && r.forEach((i) => {
246
+ const c = t.providerIndex(i.providerName), h = c > -1 ? t.registeredProviders[c] : t.createProvider(i.providerName), u = new k(h, {
247
+ name: i.name,
248
+ avatar: i.avatar,
249
+ id: i.id
247
250
  });
248
- i.push(u);
251
+ n.push(u);
249
252
  });
250
253
  const { messages: a } = await this.read();
251
- a.forEach((o) => {
252
- switch (o.type) {
254
+ a.forEach((i) => {
255
+ switch (i.type) {
253
256
  case "agent": {
254
- const c = i.find((h) => {
257
+ const c = n.find((h) => {
255
258
  var u;
256
- return h.id === ((u = o.sender) == null ? void 0 : u.id);
257
- });
258
- c && c.print(o.content.items || o.content, {
259
- key: o.key
259
+ return h.id === ((u = i.sender) == null ? void 0 : u.id);
260
260
  });
261
+ c && c.print(
262
+ i.content.items || i.content,
263
+ {
264
+ key: i.key
265
+ },
266
+ i.timestamp
267
+ );
261
268
  return;
262
269
  }
263
270
  case "user": {
264
- t.user.print(o.content.items || o.content, {
265
- key: o.key
266
- });
271
+ t.user.print(
272
+ i.content.items || i.content,
273
+ {
274
+ key: i.key
275
+ },
276
+ i.timestamp
277
+ );
267
278
  return;
268
279
  }
269
280
  case "system":
270
281
  default:
271
- t.print(o.content.items || o.content);
282
+ t.print(
283
+ i.content.items || i.content,
284
+ i.timestamp
285
+ );
272
286
  }
273
287
  });
274
- }), t.onMessageCreated(async (r, i) => {
275
- this.write(i.message, "messages");
288
+ }), t.onMessageCreated(async (r, n) => {
289
+ this.write(n.message, "messages");
276
290
  }), t.events.subscribe(
277
291
  "conversation:agent-created",
278
- async (r, i) => {
292
+ async (r, n) => {
279
293
  const a = {
280
- id: i.agent.id,
281
- name: i.agent.name,
282
- avatar: i.agent.avatar,
283
- providerName: i.agent.provider.name
294
+ id: n.agent.id,
295
+ name: n.agent.name,
296
+ avatar: n.agent.avatar,
297
+ providerName: n.agent.provider.name
284
298
  };
285
299
  await this.write(a, "agents");
286
300
  }
287
301
  ), t.events.subscribe(
288
302
  "conversation:agent-updated",
289
- async (r, i) => {
303
+ async (r, n) => {
290
304
  const { agents: a } = await this.read();
291
305
  await this.write(
292
306
  [
293
- ...a.map((o) => o.id === i.agent.id ? {
294
- ...o,
295
- name: i.agent.name,
296
- avatar: i.agent.avatar
297
- } : o)
307
+ ...a.map((i) => i.id === n.agent.id ? {
308
+ ...i,
309
+ name: n.agent.name,
310
+ avatar: n.agent.avatar
311
+ } : i)
298
312
  ],
299
313
  "agents",
300
314
  "update"
@@ -321,33 +335,33 @@ class F {
321
335
  this.container,
322
336
  this.sessionStorageKey,
323
337
  I.Necessary
324
- ).then(async (i) => {
338
+ ).then(async (n) => {
325
339
  if (s === "add") {
326
340
  const a = await this.read();
327
341
  if (t === "messages" && a.messages.findIndex((c) => c.key === e.key) > -1) {
328
342
  r();
329
343
  return;
330
344
  }
331
- const o = {
345
+ const i = {
332
346
  ...a
333
347
  };
334
- return t === "messages" ? o.messages = [...o.messages, e] : t === "agents" && (o.agents = [...o.agents, e]), i({
348
+ return t === "messages" ? i.messages = [...i.messages, e] : t === "agents" && (i.agents = [...i.agents, e]), n({
335
349
  ...a,
336
- ...o
350
+ ...i
337
351
  }).then(() => {
338
352
  r();
339
353
  });
340
354
  }
341
355
  if (s === "update" && t === "agents") {
342
356
  const a = await this.read();
343
- return i({
357
+ return n({
344
358
  ...a,
345
359
  agents: e
346
360
  }).then(() => {
347
361
  r();
348
362
  });
349
363
  }
350
- return i(e).then(() => {
364
+ return n(e).then(() => {
351
365
  r();
352
366
  });
353
367
  });
@@ -361,33 +375,33 @@ class F {
361
375
  }
362
376
  class G {
363
377
  constructor(e) {
364
- d(this, "print", (e, t) => {
365
- const s = C(e, t);
366
- return this.controller.createEntry(
367
- s.key,
368
- s.content,
378
+ d(this, "print", (e, t, s = null) => {
379
+ const r = C(e, t);
380
+ return s = s ?? r.timestamp, this.controller.createEntry(
381
+ r.key,
382
+ r.content,
369
383
  w.User,
370
384
  void 0,
371
- s.timestamp
385
+ s
372
386
  );
373
387
  });
374
388
  this.controller = e;
375
389
  }
376
390
  }
377
- const x = async (n, e, t) => {
378
- const s = await n.getAsync("conversation"), r = await n.getAsync("components"), i = s.controllers.find((a) => a.conversation.id === e);
379
- if (i) {
380
- const a = [...i.conversation.providers];
391
+ const x = async (o, e, t) => {
392
+ const s = await o.getAsync("conversation"), r = await o.getAsync("components"), n = s.controllers.find((a) => a.conversation.id === e);
393
+ if (n) {
394
+ const a = [...n.conversation.providers];
381
395
  a.forEach((c) => {
382
- i.conversation.setProviderOptions(c, { silent: !0 });
383
- }), i.conversation.queueProviders(a), i.conversation.setProviders([t]);
384
- const o = r.components().ofType("conversation");
396
+ n.conversation.setProviderOptions(c, { silent: !0 });
397
+ }), n.conversation.queueProviders(a), n.conversation.setProviders([t]);
398
+ const i = r.components().ofType("conversation");
385
399
  r.write({
386
400
  key: "setConversationProvider",
387
401
  attributes: {
388
402
  properties: { providers: [t] }
389
403
  },
390
- target: o,
404
+ target: i,
391
405
  provider: "localStorage"
392
406
  });
393
407
  }
@@ -407,37 +421,37 @@ class J {
407
421
  return typeof e == "string" ? { body: e } : e.length > -1 && typeof e == "object" ? { items: e } : e;
408
422
  }
409
423
  }
410
- var w = /* @__PURE__ */ ((n) => (n.User = "user", n.Agent = "agent", n.System = "system", n))(w || {});
411
- const C = (n, e) => {
424
+ var w = /* @__PURE__ */ ((o) => (o.User = "user", o.Agent = "agent", o.System = "system", o))(w || {});
425
+ const C = (o, e) => {
412
426
  let t, s = (e == null ? void 0 : e.key) || H(), r = Date.now();
413
- if (Array.isArray(n) && n.length > -1)
414
- typeof n[0] == "string" ? t = { items: [n] } : t = { items: n };
415
- else if (typeof n == "string")
416
- t = { body: n };
417
- else if (n = n || {}, n.type)
427
+ if (Array.isArray(o) && o.length > -1)
428
+ typeof o[0] == "string" ? t = { items: [o] } : t = { items: o };
429
+ else if (typeof o == "string")
430
+ t = { body: o };
431
+ else if (o = o || {}, o.type)
418
432
  t = {
419
- ...n
433
+ ...o
420
434
  };
421
435
  else {
422
436
  if (t = {
423
- body: n.body,
424
- actions: n.actions,
425
- title: n.title
426
- }, n.key && (s = n.key), n.timestamp && (r = n.timestamp), typeof n.form == "function") {
427
- const i = Q.create(s);
428
- n.form(i);
429
- const a = i.get();
437
+ body: o.body,
438
+ actions: o.actions,
439
+ title: o.title
440
+ }, o.key && (s = o.key), o.timestamp && (r = o.timestamp), typeof o.form == "function") {
441
+ const n = Q.create(s);
442
+ o.form(n);
443
+ const a = n.get();
430
444
  t.form = a;
431
445
  }
432
- n.timestamp === null && (r = null);
446
+ o.timestamp === null && (r = null);
433
447
  }
434
448
  return { content: t, key: s, timestamp: r };
435
- }, N = (n, e) => {
449
+ }, N = (o, e) => {
436
450
  if (!e)
437
451
  return;
438
- const t = JSON.stringify(e), s = n.findIndex((r) => t === JSON.stringify(r));
452
+ const t = JSON.stringify(e), s = o.findIndex((r) => t === JSON.stringify(r));
439
453
  if (s > -1)
440
- return n.splice(s, 1);
454
+ return o.splice(s, 1);
441
455
  };
442
456
  class V {
443
457
  constructor(e, t, s) {
@@ -457,14 +471,14 @@ class V {
457
471
  d(this, "messages", []);
458
472
  d(this, "typingActors", []);
459
473
  d(this, "conversationHistory");
460
- d(this, "print", (e) => {
461
- const t = C(e);
462
- return this.createEntry(
463
- t.key,
464
- t.content,
474
+ d(this, "print", (e, t = null) => {
475
+ const s = C(e);
476
+ return t = t ?? s.timestamp, this.createEntry(
477
+ s.key,
478
+ s.content,
465
479
  "system",
466
480
  void 0,
467
- t.timestamp
481
+ t
468
482
  );
469
483
  });
470
484
  this.container = e, this.id = t;
@@ -476,9 +490,9 @@ class V {
476
490
  }
477
491
  setProviders(e) {
478
492
  const t = [], s = [];
479
- this.providers.reduce((r, i) => (e.indexOf(i) === -1 && r.push(i), r), []).forEach((r) => {
480
- const i = this.providers.indexOf(r);
481
- i > -1 && (t.push(r), this.providers.splice(i, 1));
493
+ this.providers.reduce((r, n) => (e.indexOf(n) === -1 && r.push(n), r), []).forEach((r) => {
494
+ const n = this.providers.indexOf(r);
495
+ n > -1 && (t.push(r), this.providers.splice(n, 1));
482
496
  }), e.forEach((r) => {
483
497
  this.providers.indexOf(r) === -1 && (s.push(r), this.providers.push(r));
484
498
  }), (s.length || t.length) && this.events.dispatch("conversation:providers-changed", {
@@ -549,16 +563,16 @@ class V {
549
563
  onUnreadMessage(e) {
550
564
  return this.events.subscribe("conversation:unread-message", e);
551
565
  }
552
- createEntry(e, t, s, r, i) {
566
+ createEntry(e, t, s, r, n) {
553
567
  const a = {
554
568
  key: e,
555
569
  content: t,
556
570
  type: s,
557
571
  sender: r || null,
558
- timestamp: i || i === null ? i : Date.now()
572
+ timestamp: n || n === null ? n : Date.now()
559
573
  };
560
574
  this.messages.push(a), a.type === "agent" && N(this.typingActors, r);
561
- const o = new J((c) => {
575
+ const i = new J((c) => {
562
576
  if (c !== null) {
563
577
  const { timestamp: h = void 0, ...u } = c;
564
578
  a.content = u, h && (a.timestamp = h);
@@ -568,7 +582,7 @@ class V {
568
582
  }
569
583
  this.events.dispatch("conversation:message-updated", { message: a }), this.update();
570
584
  });
571
- return this.events.dispatch("conversation:message-created", { message: a }), this.update(), this.componentMounted || this.events.dispatch("conversation:unread-message", !0), o;
585
+ return this.events.dispatch("conversation:message-created", { message: a }), this.update(), this.componentMounted || this.events.dispatch("conversation:unread-message", !0), i;
572
586
  }
573
587
  update() {
574
588
  this.events.dispatch("conversation:updated", {
@@ -609,30 +623,30 @@ class V {
609
623
  return this.conversationHistory.getConversationLogs();
610
624
  }
611
625
  }
612
- const Y = (n, e) => {
613
- const t = n.split("_contact");
626
+ const Y = (o, e) => {
627
+ const t = o.split("_contact");
614
628
  return e.widgets.get(t[0]);
615
- }, W = (n) => {
616
- const e = n.get("$widget"), { name: t, implementation: s } = n.get("$widget"), r = t.indexOf("_contact") > -1 ? Y(t, s) : e, { data: i } = n.get("$settings"), { trigger: a } = r.container.get("$settings"), o = `${t.replace("_contact-method", "").replace("_contact", "")}_contact-method`, c = s.widgets.get(o);
617
- return c && !a ? { chatWidget: c, mainWidget: r, data: i } : { mainWidget: r, data: i };
618
- }, X = (n) => {
619
- const { chatWidget: e } = W(n);
629
+ }, W = (o) => {
630
+ const e = o.get("$widget"), { name: t, implementation: s } = o.get("$widget"), r = t.indexOf("_contact") > -1 ? Y(t, s) : e, { data: n } = o.get("$settings"), { trigger: a } = r.container.get("$settings"), i = `${t.replace("_contact-method", "").replace("_contact", "")}_contact-method`, c = s.widgets.get(i);
631
+ return c && !a ? { chatWidget: c, mainWidget: r, data: n } : { mainWidget: r, data: n };
632
+ }, X = (o) => {
633
+ const { chatWidget: e } = W(o);
620
634
  return !!e;
621
- }, O = (n, e, t) => {
622
- const { mainWidget: s, data: r, chatWidget: i } = W(n);
623
- return i ? i.state === "activated" ? i.invoke("open").then(() => {
624
- i.container.getAsync("conversation").then((a) => {
625
- a.navigateToConversationIfActive(e.id).then(() => M(n));
635
+ }, O = (o, e, t) => {
636
+ const { mainWidget: s, data: r, chatWidget: n } = W(o);
637
+ return n ? n.state === "activated" ? n.invoke("open").then(() => {
638
+ n.container.getAsync("conversation").then((a) => {
639
+ a.navigateToConversationIfActive(e.id).then(() => M(o));
626
640
  });
627
- }) : i.activate().then(() => {
628
- const { trigger: a } = i.container.get("$settings");
629
- return a.action = "hide", i.invoke("setSettings", () => ({
641
+ }) : n.activate().then(() => {
642
+ const { trigger: a } = n.container.get("$settings");
643
+ return a.action = "hide", n.invoke("setSettings", () => ({
630
644
  data: r,
631
645
  trigger: a,
632
646
  activate: !0
633
- })).then(() => i.container.getAsync("components").then((o) => {
634
- const c = o.components().ofType("contact-method");
635
- o.write({
647
+ })).then(() => n.container.getAsync("components").then((i) => {
648
+ const c = i.components().ofType("contact-method");
649
+ i.write({
636
650
  key: "setContactMethodId",
637
651
  attributes: {
638
652
  properties: {
@@ -643,8 +657,8 @@ const Y = (n, e) => {
643
657
  target: c,
644
658
  provider: "localStorage"
645
659
  });
646
- const h = o.components().ofType("conversation");
647
- o.write({
660
+ const h = i.components().ofType("conversation");
661
+ i.write({
648
662
  key: "setConversationProvider",
649
663
  attributes: {
650
664
  properties: { providers: [e.clientName] }
@@ -653,29 +667,29 @@ const Y = (n, e) => {
653
667
  provider: "localStorage"
654
668
  });
655
669
  }));
656
- }).then(() => i.invoke("attach", {
670
+ }).then(() => n.invoke("attach", {
657
671
  key: "contact-method",
658
672
  triggerDOMElement: t,
659
673
  withRenderState: "open"
660
674
  })).then(() => (E(
661
- i.container,
675
+ n.container,
662
676
  "activeStickyWidget",
663
677
  I.Necessary,
664
678
  {
665
679
  medium: y.Local,
666
680
  scope: z.Implementation
667
681
  }
668
- ).then((a) => a(i.name)), i.container.getAsync("conversation").then((a) => {
682
+ ).then((a) => a(n.name)), n.container.getAsync("conversation").then((a) => {
669
683
  a.setConversationEndedBehavior(S.Deactivate);
670
- }).then(() => M(n)).then(() => !1))) : (s.container.getAsync("conversation").then((a) => a.navigateToConversationIfActive(e.id).then(() => a.setConversationEndedBehavior(S.Navigate))), !i);
671
- }, Z = (n, e, t = "conversation") => {
672
- const { mainWidget: s, chatWidget: r } = W(n);
673
- return r ? r.container.getAsync("router").then((i) => {
674
- i.navigate(t, { id: e.id });
675
- }) : s.container.getAsync("conversation").then((i) => {
684
+ }).then(() => M(o)).then(() => !1))) : (s.container.getAsync("conversation").then((a) => a.navigateToConversationIfActive(e.id).then(() => a.setConversationEndedBehavior(S.Navigate))), !n);
685
+ }, Z = (o, e, t = "conversation") => {
686
+ const { mainWidget: s, chatWidget: r } = W(o);
687
+ return r ? r.container.getAsync("router").then((n) => {
688
+ n.navigate(t, { id: e.id });
689
+ }) : s.container.getAsync("conversation").then((n) => {
676
690
  var a;
677
- (a = i.setConversationEndedBehavior(S.Navigate)) == null || a.then(() => {
678
- s.container.getAsync("router").then((o) => {
691
+ (a = n.setConversationEndedBehavior(S.Navigate)) == null || a.then(() => {
692
+ s.container.getAsync("router").then((i) => {
679
693
  s.container.getAsync("components").then((c) => {
680
694
  const h = c.components().ofType("conversation");
681
695
  c.write({
@@ -685,13 +699,13 @@ const Y = (n, e) => {
685
699
  provider: "localStorage"
686
700
  });
687
701
  }).then(() => {
688
- o.navigate(t, { id: e.id });
702
+ i.navigate(t, { id: e.id });
689
703
  });
690
704
  });
691
705
  });
692
706
  });
693
707
  }, b = "conversations";
694
- var S = /* @__PURE__ */ ((n) => (n.Deactivate = "deactivate", n.Navigate = "navigate", n.None = "none", n))(S || {});
708
+ var S = /* @__PURE__ */ ((o) => (o.Deactivate = "deactivate", o.Navigate = "navigate", o.None = "none", o))(S || {});
695
709
  class A {
696
710
  constructor(e, t) {
697
711
  d(this, "events");
@@ -722,14 +736,14 @@ class A {
722
736
  ).then((e) => {
723
737
  this.buttonQuery = this.components.components().ofType("conversation-return-button"), e && (this.sessionInfo = e, e.id && e.route && this.writeToComponents({ active: !0, alert: { show: !1 } }));
724
738
  }), this.container.getAsync("router").then((e) => this.router = e), this.events.subscribe("conversation:ended", (e, t) => {
725
- var s, r, i;
739
+ var s, r, n;
726
740
  switch ((s = this.sessionInfo) == null ? void 0 : s.conversationEndedBehavior) {
727
741
  case "deactivate":
728
742
  this.container.get("$widget").deactivate();
729
743
  break;
730
744
  case "navigate":
731
- const o = (r = this.router) == null ? void 0 : r.getInitialRoute();
732
- o && ((i = this.router) == null || i.navigate(o.name));
745
+ const i = (r = this.router) == null ? void 0 : r.getInitialRoute();
746
+ i && ((n = this.router) == null || n.navigate(i.name));
733
747
  break;
734
748
  }
735
749
  this.writeToComponents({ active: !1 }), this.sessionInfo = null, this.storageWriter && this.storageWriter();
@@ -741,7 +755,7 @@ class A {
741
755
  static getInstance(e, t = "conversation") {
742
756
  return K(e)(() => e.getAsync(t).then((s) => {
743
757
  let r = s;
744
- return r || R.getInstance(e).then((i) => (r = new A(e, i), r.initialize(), e.registerAsync(t, () => r), r));
758
+ return r || R.getInstance(e).then((n) => (r = new A(e, n), r.initialize(), e.registerAsync(t, () => r), r));
745
759
  }));
746
760
  }
747
761
  navigateToConversationIfActive(e) {
@@ -752,8 +766,8 @@ class A {
752
766
  ).then((t) => {
753
767
  var s;
754
768
  if (t && t.id === e && t.route) {
755
- const { name: r, params: i } = t.route;
756
- (s = this.router) == null || s.navigate(r, i);
769
+ const { name: r, params: n } = t.route;
770
+ (s = this.router) == null || s.navigate(r, n);
757
771
  }
758
772
  });
759
773
  }
@@ -768,9 +782,9 @@ class A {
768
782
  });
769
783
  }
770
784
  async createController(e, t) {
771
- const s = $(e), { agents: r } = await f(this.container, s) || { agents: [] }, i = this.controllers.findIndex((o) => o.conversation.id === e);
785
+ const s = $(e), { agents: r } = await f(this.container, s) || { agents: [] }, n = this.controllers.findIndex((i) => i.conversation.id === e);
772
786
  let a;
773
- return i > -1 ? a = this.controllers[i].conversation : a = new V(this.container, e, t), a.setInitialStorage({ agents: r || [] }), a;
787
+ return n > -1 ? a = this.controllers[n].conversation : a = new V(this.container, e, t), a.setInitialStorage({ agents: r || [] }), a;
774
788
  }
775
789
  registerProvider(e, t) {
776
790
  const s = {
@@ -785,52 +799,52 @@ class A {
785
799
  }
786
800
  registerController(e, t) {
787
801
  const s = this.controllers.findIndex(
788
- (i) => i.conversation.id === e.id
802
+ (n) => n.conversation.id === e.id
789
803
  );
790
804
  let r;
791
805
  if (s < 0) {
792
806
  r = { conversation: e, component: t }, this.controllers.push(r);
793
- const i = (a) => {
794
- a && this.providers.filter((o) => a.indexOf(o.name) > -1).forEach((o) => {
795
- this.invokeHandler(o, r);
807
+ const n = (a) => {
808
+ a && this.providers.filter((i) => a.indexOf(i.name) > -1).forEach((i) => {
809
+ this.invokeHandler(i, r);
796
810
  });
797
811
  };
798
812
  return this.subscriptions.push(
799
- e.onDispose((a, o) => {
813
+ e.onDispose((a, i) => {
800
814
  const c = this.controllers.findIndex(
801
- (h) => h.conversation === o
815
+ (h) => h.conversation === i
802
816
  );
803
817
  c > -1 && this.controllers.splice(c, 1), this.components.components().ofType("conversation-return-button").select().writeProperties({ active: !1 }), this.events.dispatch("conversation:ended", {}, { bubbles: !0 });
804
818
  })
805
819
  ), this.subscriptions.push(
806
- e.onProvidersChange((a, o) => {
820
+ e.onProvidersChange((a, i) => {
807
821
  const {
808
822
  added: c,
809
823
  removed: h = []
810
- } = o;
824
+ } = i;
811
825
  h.forEach((u) => {
812
826
  (this.disposeProviders[u] || []).forEach(
813
827
  (l) => {
814
828
  l();
815
829
  }
816
830
  );
817
- }), i(c);
831
+ }), n(c);
818
832
  })
819
833
  ), this.subscriptions.push(
820
- e.onStarted((a, o) => {
834
+ e.onStarted((a, i) => {
821
835
  var h, u;
822
836
  const c = {
823
837
  id: e.id,
824
838
  route: (h = this.router) == null ? void 0 : h.getRouteData(),
825
839
  conversationEndedBehavior: (u = this.sessionInfo) == null ? void 0 : u.conversationEndedBehavior
826
840
  };
827
- this.sessionInfo = c, this.storageWriter && this.storageWriter(c), this.writeToComponents({ active: o });
841
+ this.sessionInfo = c, this.storageWriter && this.storageWriter(c), this.writeToComponents({ active: i });
828
842
  })
829
843
  ), this.subscriptions.push(
830
- e.onUnreadMessage((a, o) => {
831
- this.events.dispatch("conversation:unread-message", o), this.writeToComponents({ alert: { show: o } });
844
+ e.onUnreadMessage((a, i) => {
845
+ this.events.dispatch("conversation:unread-message", i), this.writeToComponents({ alert: { show: i } });
832
846
  })
833
- ), i(e.providers), !0;
847
+ ), n(e.providers), !0;
834
848
  }
835
849
  return r = this.controllers[s], !1;
836
850
  }
@@ -868,8 +882,8 @@ class A {
868
882
  static async handleContactMethodClick(e, t, s, r) {
869
883
  if (X(t)) {
870
884
  e.preventDefault();
871
- let i = document.getElementById("humany-dynamic-anchor");
872
- i || (i = document.createElement("a"), i.setAttribute("href", "#"), i.id = "humany-dynamic-anchor", document.body.appendChild(i)), O(t, s, i);
885
+ let n = document.getElementById("humany-dynamic-anchor");
886
+ n || (n = document.createElement("a"), n.setAttribute("href", "#"), n.id = "humany-dynamic-anchor", document.body.appendChild(n)), O(t, s, n);
873
887
  }
874
888
  O(t, s);
875
889
  }
@@ -882,34 +896,34 @@ class A {
882
896
  ) : Z(e, t);
883
897
  }
884
898
  }
885
- const ee = (n, e) => n.reduce((t, s, r) => {
886
- var a, o;
887
- const i = {
899
+ const ee = (o, e) => o.reduce((t, s, r) => {
900
+ var a, i;
901
+ const n = {
888
902
  ...s,
889
903
  content: [{ ...s.content, key: s.key }]
890
904
  };
891
905
  if (t.length > 0 && s.type !== w.System) {
892
906
  const c = t[t.length - 1];
893
- if ((!e && e !== 0 || Math.abs(c.timestamp - s.timestamp) < e) && ((a = c.sender) == null ? void 0 : a.name) === ((o = s.sender) == null ? void 0 : o.name) && c.type === s.type)
907
+ if ((!e && e !== 0 || Math.abs(c.timestamp - s.timestamp) < e) && ((a = c.sender) == null ? void 0 : a.name) === ((i = s.sender) == null ? void 0 : i.name) && c.type === s.type)
894
908
  return c.timestamp = s.timestamp, c.content.push({ ...s.content, key: s.key }), t;
895
909
  }
896
- return t.push(i), t;
897
- }, []), he = (n) => Promise.all([
898
- A.getInstance(n),
899
- n.getAsync("router")
910
+ return t.push(n), t;
911
+ }, []), he = (o) => Promise.all([
912
+ A.getInstance(o),
913
+ o.getAsync("router")
900
914
  ]).then(([e, t]) => _(
901
- n,
915
+ o,
902
916
  "conversation",
903
917
  import("./conversation-b5103766.mjs"),
904
918
  async (s) => {
905
- const { rehydrate: r = !1 } = s.properties(), a = t.getRouteData().params.id || s.node.name || "component", o = await e.createController(a, { rehydrate: r }), c = e.registerController(o, s), h = 3 * 60 * 1e3, u = (g) => {
919
+ const { rehydrate: r = !1 } = s.properties(), a = t.getRouteData().params.id || s.node.name || "component", i = await e.createController(a, { rehydrate: r }), c = e.registerController(i, s), h = 3 * 60 * 1e3, u = (g) => {
906
920
  const { providers: p = [] } = g;
907
921
  if (p) {
908
922
  const m = Array.isArray(p) ? p : [p];
909
- return o.setProviders(m), m;
923
+ return i.setProviders(m), m;
910
924
  }
911
925
  };
912
- u(s.properties(u)), o.setComponentMountedState(!0);
926
+ u(s.properties(u)), i.setComponentMountedState(!0);
913
927
  const l = (g) => {
914
928
  const { loading: p, typingActors: m, messages: P } = g;
915
929
  s.writeProperties({
@@ -918,17 +932,17 @@ const ee = (n, e) => n.reduce((t, s, r) => {
918
932
  messages: ee(P, h)
919
933
  });
920
934
  };
921
- l(o.getMessageStream()), c && (s.writeProperties({ conversationControllerId: o.id }), s.actions.create("user-submit", (g, p) => {
935
+ l(i.getMessageStream()), c && (s.writeProperties({ conversationControllerId: i.id }), s.actions.create("user-submit", (g, p) => {
922
936
  if (p) {
923
937
  const { preventDefault: m, validationPromise: P } = p;
924
938
  if (m) {
925
939
  P && P().then((D) => {
926
- D && o.user.print(D);
940
+ D && i.user.print(D);
927
941
  });
928
942
  return;
929
943
  }
930
944
  }
931
- o.user.print(g.text);
945
+ i.user.print(g.text);
932
946
  }), s.actions.create("user-typing", (g, p) => {
933
947
  }), s.actions.create("form", (g, p) => {
934
948
  }), s.actions.create("action", (g, p) => {
@@ -950,39 +964,39 @@ const ee = (n, e) => n.reduce((t, s, r) => {
950
964
  overlay: { conversation: !1, secondary: !1 }
951
965
  });
952
966
  }));
953
- const v = o.events.subscribe(
967
+ const v = i.events.subscribe(
954
968
  "conversation:updated",
955
969
  (g, p) => {
956
970
  l(p);
957
971
  }
958
972
  );
959
973
  return () => {
960
- o.setComponentMountedState(!1), v(), o.active || l({ messages: [], typingActors: [], loading: !1 });
974
+ i.setComponentMountedState(!1), v(), i.active || l({ messages: [], typingActors: [], loading: !1 });
961
975
  };
962
976
  },
963
977
  { reuseController: !0 }
964
- )), le = (n) => Promise.all([
965
- R.getInstance(n),
966
- A.getInstance(n),
967
- n.getAsync("router")
978
+ )), le = (o) => Promise.all([
979
+ R.getInstance(o),
980
+ A.getInstance(o),
981
+ o.getAsync("router")
968
982
  ]).then(
969
983
  ([e, t, s]) => _(
970
- n,
984
+ o,
971
985
  "conversation-return-button",
972
986
  import("./return-button-70a640cb.mjs"),
973
987
  (r) => {
974
- r.actions.create("toggle", (i = {}) => {
988
+ r.actions.create("toggle", (n = {}) => {
975
989
  var a;
976
- (a = t.getComponentRoute()) == null || a.then((o) => {
977
- o && s.navigate(o.name, o.params);
990
+ (a = t.getComponentRoute()) == null || a.then((i) => {
991
+ i && s.navigate(i.name, i.params);
978
992
  });
979
993
  });
980
994
  }
981
995
  )
982
996
  );
983
- var te = /* @__PURE__ */ ((n) => (n.LinkList = "link-list", n.Separator = "separator", n.ButtonList = "button-list", n.ItemList = "item-list", n.Text = "text", n.HTML = "html", n.VideoRequest = "video-request", n))(te || {});
984
- const ue = (n, e, t) => n.getAsync("componentResolver").then(async (s) => {
985
- (await A.getInstance(n)).addSubscription(
997
+ var te = /* @__PURE__ */ ((o) => (o.LinkList = "link-list", o.Separator = "separator", o.ButtonList = "button-list", o.ItemList = "item-list", o.Text = "text", o.HTML = "html", o.VideoRequest = "video-request", o))(te || {});
998
+ const ue = (o, e, t) => o.getAsync("componentResolver").then(async (s) => {
999
+ (await A.getInstance(o)).addSubscription(
986
1000
  s.registerComponent(
987
1001
  e,
988
1002
  U(() => t)
@@ -990,6 +1004,7 @@ const ue = (n, e, t) => n.getAsync("componentResolver").then(async (s) => {
990
1004
  );
991
1005
  });
992
1006
  export {
1007
+ k as Agent,
993
1008
  he as ConversationComponent,
994
1009
  V as ConversationController,
995
1010
  S as ConversationEndedBehavior,
@@ -997,6 +1012,7 @@ export {
997
1012
  te as ConversationMessageListItemType,
998
1013
  w as ConversationMessageType,
999
1014
  A as ConversationPlatform,
1015
+ T as ConversationProvider,
1000
1016
  le as ConversationReturnButtonComponent,
1001
1017
  ue as registerCustomMessageComponent
1002
1018
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telia-ace/widget-conversation",
3
- "version": "1.1.1",
3
+ "version": "1.1.2-rc.1",
4
4
  "main": "./index.js",
5
5
  "types": "./index.d.ts",
6
6
  "exports": {
@@ -10,13 +10,13 @@
10
10
  }
11
11
  },
12
12
  "dependencies": {
13
- "@telia-ace/widget-core": "^1.1.1",
14
- "@telia-ace/widget-forms": "^1.1.1",
15
- "@telia-ace/widget-plugins": "^1.1.1",
16
- "@telia-ace/widget-routing": "^1.1.1",
17
- "@telia-ace/widget-services": "^1.1.1",
18
- "@telia-ace/widget-ui": "^1.1.1",
19
- "@telia-ace/widget-utilities": "^1.1.1",
13
+ "@telia-ace/widget-core": "^1.1.2-rc.1",
14
+ "@telia-ace/widget-forms": "^1.1.2-rc.1",
15
+ "@telia-ace/widget-plugins": "^1.1.2-rc.1",
16
+ "@telia-ace/widget-routing": "^1.1.2-rc.1",
17
+ "@telia-ace/widget-services": "^1.1.2-rc.1",
18
+ "@telia-ace/widget-ui": "^1.1.2-rc.1",
19
+ "@telia-ace/widget-utilities": "^1.1.2-rc.1",
20
20
  "@webprovisions/platform": "^1.1.4"
21
21
  },
22
22
  "peerDependencies": {
package/user.d.ts CHANGED
@@ -5,5 +5,5 @@ export declare class User {
5
5
  constructor(controller: ConversationController);
6
6
  print: (settings: string | ConversationMessageSettings, options?: {
7
7
  key?: string;
8
- }) => ConversationEntry;
8
+ }, timestamp?: number | null) => ConversationEntry;
9
9
  }