@telia-ace/conversational-hub-bot-provider 1.3.59 → 1.3.60-rc.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.
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("react/jsx-runtime"),R=require("@emotion/styled"),F=require("@telia-ace/knowledge-data-client"),$=require("@telia-ace/knowledge-widget-adapters"),v=require("@telia-ace/knowledge-widget-ui"),z=require("@telia-ace/widget-forms"),O=require("@telia-ace/widget-utilities"),l=require("react"),x=require("./index-CqXeCBbx.js"),U=({contactMethodId:s,guideId:n,groupId:b,className:T})=>{var h,q,k,S,j;const[e,u]=l.useState(),c=v.useContainer(),A=v.useDispatch(),f=l.useRef(!0),y=v.useConversation();l.useEffect(()=>{const{events:t}=c.get("$widget"),m=t.subscribe("conversational-hub-provider:form-submitted",async(i,o)=>{var D;if(((D=o.form.meta)==null?void 0:D.groupId)!==b||o.id!==(e==null?void 0:e.id))return;y&&(o.form.meta||(o.form.meta={}),o.form.meta.conversation=y);const p=await c.getAsync("contactMethods"),r={...e,body:{...e.body,form:o.form}},{errors:d,valid:g,errorTypes:_}=await p.validate(r);if(!g){const E=new z.FormBuilder(e.body.form);u(void 0),E.setValidationErrors(d),r.body={...r.body,form:E.get()},u({...r});return}const B=await p.submit(r);r.confirmation=B,u(r)}),a=t.subscribe("conversational-hub-provider:evaluate",async(i,o)=>{if(String(o.id)!==String(s))return;const r=await(await c.getAsync("contactMethods")).evaluate(e);let d={...e,body:{...e.body,form:r}};const g=x.updateForm(d,{submit:"Submit",errors:{},meta:{groupId:b}});d={...d,body:g},u(d)});return()=>{m(),a()}},[c,e,u,y]);const C=(t,m,a=null)=>{if(t["ui:component"]&&t["ui:component"]==="Date")return Object.assign(t,{"ui:bot":!0,"ui:entrance":m}),t;for(const i in t)if(typeof t[i]=="object"&&t[i]!==null){const o=C(t[i],m,t);if(o!==void 0)return o}},w=l.useCallback(async t=>{const a=await(await F.DataClient.getInstance(c)).fetch(F.DataType.ContactMethod,{contactMethodId:t,guideId:n},{noCache:!0,isBot:!0}),i=x.updateForm(a,{submit:"Submit",errors:{},meta:{groupId:b}});if(a.body=i,a.body.guideId=n,!f.current)return null;u(a)},[f]);return l.useEffect(()=>(w(s),()=>{f.current=!1}),[s,w]),e?(e.clientName==="ace.callback"&&((h=e.body)!=null&&h.entrance)&&C(e,(q=e.body)==null?void 0:q.entrance),N.jsx(W,{...e,body:{...e.body,form:e.body.form?{...e.body.form,data:(k=e.body.form)==null?void 0:k.data,layout:{...e.body.form.layout},meta:(S=e.body.form)==null?void 0:S.meta,schema:(j=e.body.form)==null?void 0:j.schema}:void 0,guideId:e.body.guideId},inline:!0,expanded:!0,dispatch:A,className:O.appendClassNames("humany-bot-contact-method",T)})):null},W=R($.ContactMethod)`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("react/jsx-runtime"),R=require("@emotion/styled"),F=require("@telia-ace/knowledge-data-client"),$=require("@telia-ace/knowledge-widget-adapters"),v=require("@telia-ace/knowledge-widget-ui"),z=require("@telia-ace/widget-forms"),O=require("@telia-ace/widget-utilities"),l=require("react"),x=require("./index-BVRRx5B7.js"),U=({contactMethodId:s,guideId:n,groupId:b,className:T})=>{var h,q,k,S,j;const[e,u]=l.useState(),c=v.useContainer(),A=v.useDispatch(),f=l.useRef(!0),y=v.useConversation();l.useEffect(()=>{const{events:t}=c.get("$widget"),m=t.subscribe("conversational-hub-provider:form-submitted",async(i,o)=>{var D;if(((D=o.form.meta)==null?void 0:D.groupId)!==b||o.id!==(e==null?void 0:e.id))return;y&&(o.form.meta||(o.form.meta={}),o.form.meta.conversation=y);const p=await c.getAsync("contactMethods"),r={...e,body:{...e.body,form:o.form}},{errors:d,valid:g,errorTypes:_}=await p.validate(r);if(!g){const E=new z.FormBuilder(e.body.form);u(void 0),E.setValidationErrors(d),r.body={...r.body,form:E.get()},u({...r});return}const B=await p.submit(r);r.confirmation=B,u(r)}),a=t.subscribe("conversational-hub-provider:evaluate",async(i,o)=>{if(String(o.id)!==String(s))return;const r=await(await c.getAsync("contactMethods")).evaluate(e);let d={...e,body:{...e.body,form:r}};const g=x.updateForm(d,{submit:"Submit",errors:{},meta:{groupId:b}});d={...d,body:g},u(d)});return()=>{m(),a()}},[c,e,u,y]);const C=(t,m,a=null)=>{if(t["ui:component"]&&t["ui:component"]==="Date")return Object.assign(t,{"ui:bot":!0,"ui:entrance":m}),t;for(const i in t)if(typeof t[i]=="object"&&t[i]!==null){const o=C(t[i],m,t);if(o!==void 0)return o}},w=l.useCallback(async t=>{const a=await(await F.DataClient.getInstance(c)).fetch(F.DataType.ContactMethod,{contactMethodId:t,guideId:n},{noCache:!0,isBot:!0}),i=x.updateForm(a,{submit:"Submit",errors:{},meta:{groupId:b}});if(a.body=i,a.body.guideId=n,!f.current)return null;u(a)},[f]);return l.useEffect(()=>(w(s),()=>{f.current=!1}),[s,w]),e?(e.clientName==="ace.callback"&&((h=e.body)!=null&&h.entrance)&&C(e,(q=e.body)==null?void 0:q.entrance),N.jsx(W,{...e,body:{...e.body,form:e.body.form?{...e.body.form,data:(k=e.body.form)==null?void 0:k.data,layout:{...e.body.form.layout},meta:(S=e.body.form)==null?void 0:S.meta,schema:(j=e.body.form)==null?void 0:j.schema}:void 0,guideId:e.body.guideId},inline:!0,expanded:!0,dispatch:A,className:O.appendClassNames("humany-bot-contact-method",T)})):null},W=R($.ContactMethod)`
2
2
  padding: ${s=>{var n;return(n=s.theme.sizes)==null?void 0:n.normal}} ${s=>{var n;return(n=s.theme.sizes)==null?void 0:n.medium}};
3
3
  `;exports.default=U;
@@ -6,7 +6,7 @@ import { useContainer as _, useDispatch as G, useConversation as I } from "@teli
6
6
  import { FormBuilder as M } from "@telia-ace/widget-forms";
7
7
  import { appendClassNames as O } from "@telia-ace/widget-utilities";
8
8
  import { useState as V, useRef as q, useEffect as $, useCallback as H } from "react";
9
- import { u as j } from "./index-DlrDioqz.mjs";
9
+ import { u as j } from "./index-YseNYD9Z.mjs";
10
10
  const et = ({
11
11
  contactMethodId: a,
12
12
  guideId: n,
@@ -3,7 +3,7 @@ import l from "@emotion/styled";
3
3
  import { ContactList as M, ContactMethod as b } from "@telia-ace/knowledge-widget-adapters";
4
4
  import { useDispatch as $, useContainer as k } from "@telia-ace/knowledge-widget-ui";
5
5
  import { useState as f, useEffect as E } from "react";
6
- import S from "./contact-method-B38jdJFB.mjs";
6
+ import S from "./contact-method-DJLku_0u.mjs";
7
7
  const P = ({ actions: t, entryId: e, groupId: y }) => {
8
8
  const g = $(), d = k(), [m, x] = f([]), [c, C] = f([]);
9
9
  return E(() => {
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),u=require("@emotion/styled"),y=require("@telia-ace/knowledge-widget-adapters"),g=require("@telia-ace/knowledge-widget-ui"),l=require("react"),k=require("./contact-method-BVsnE2Mg.js"),j=({actions:e,entryId:t,groupId:x})=>{const C=g.useDispatch(),d=g.useContainer(),[h,M]=l.useState([]),[c,b]=l.useState([]);return l.useEffect(()=>{d.getAsync("contactMethods").then(n=>{if(!n)return;const r=e.map(async i=>{var m;if(!((m=i.data)!=null&&m.clientName))return null;const s=await n.handleAdapters(i.data);return{...s,...i.data,description:i.data.description?i.data.description:s.description,onClick:(p,o)=>{if(typeof s.onClick=="function"&&s.onClick(p,o),!p.defaultPrevented)if(o.inline&&!o.expanded)b([...c,o.id]);else{const{events:f}=d.get("$widget");f.dispatch("conversational-hub-provider:open-contact-method",{entryId:t,contactMethod:o,actionKey:i.actionKey}),f.dispatch("tracking:contact-method-list-item-clicked",o)}}}});Promise.all(r).then(i=>{M(i.filter(s=>!!s))})})},[e,d,t,c]),h.length?a.jsx(S,{className:"humany-bot-contact-list",contactMethods:h,dispatch:C,itemRenderer:(n,r)=>(c.includes(n.id)||n.expanded)&&n.inline||n.clientName==="custom.link"?a.jsx(q,{contactMethodId:n.id,groupId:x,guideId:n.body.guideId}):a.jsx($,{...n,...r})}):null},S=u(y.ContactList)`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),u=require("@emotion/styled"),y=require("@telia-ace/knowledge-widget-adapters"),g=require("@telia-ace/knowledge-widget-ui"),l=require("react"),k=require("./contact-method-DGL-OlIC.js"),j=({actions:e,entryId:t,groupId:x})=>{const C=g.useDispatch(),d=g.useContainer(),[h,M]=l.useState([]),[c,b]=l.useState([]);return l.useEffect(()=>{d.getAsync("contactMethods").then(n=>{if(!n)return;const r=e.map(async i=>{var m;if(!((m=i.data)!=null&&m.clientName))return null;const s=await n.handleAdapters(i.data);return{...s,...i.data,description:i.data.description?i.data.description:s.description,onClick:(p,o)=>{if(typeof s.onClick=="function"&&s.onClick(p,o),!p.defaultPrevented)if(o.inline&&!o.expanded)b([...c,o.id]);else{const{events:f}=d.get("$widget");f.dispatch("conversational-hub-provider:open-contact-method",{entryId:t,contactMethod:o,actionKey:i.actionKey}),f.dispatch("tracking:contact-method-list-item-clicked",o)}}}});Promise.all(r).then(i=>{M(i.filter(s=>!!s))})})},[e,d,t,c]),h.length?a.jsx(S,{className:"humany-bot-contact-list",contactMethods:h,dispatch:C,itemRenderer:(n,r)=>(c.includes(n.id)||n.expanded)&&n.inline||n.clientName==="custom.link"?a.jsx(q,{contactMethodId:n.id,groupId:x,guideId:n.body.guideId}):a.jsx($,{...n,...r})}):null},S=u(y.ContactList)`
2
2
  > ul > li {
3
3
  a {
4
4
  display: flex;
@@ -1,4 +1,3 @@
1
1
  import { Container } from '@webprovisions/platform';
2
2
  import { MessageGroup, ServerEntry } from './types';
3
-
4
3
  export declare const processEntries: (container: Container, entries: ServerEntry[], prevGroup?: MessageGroup) => Promise<MessageGroup[]>;
package/http-client.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { Container, EventManager } from '@webprovisions/platform';
2
2
  import { default as Store } from './store';
3
3
  import { MessageGroup } from './types';
4
-
5
4
  declare class HttpClient {
6
5
  private endpoint;
7
6
  private events;
@@ -0,0 +1,5 @@
1
+ "use strict";var ft=Object.defineProperty;var bt=(t,n,o)=>n in t?ft(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o;var L=(t,n,o)=>bt(t,typeof n!="symbol"?n+"":n,o);const P=require("@telia-ace/widget-conversation"),R=require("@telia-ace/widget-services"),A=require("@telia-ace/widget-utilities"),D=require("@telia-ace/widget-forms"),yt=require("@webprovisions/platform");class vt{constructor(n){L(this,"container");L(this,"enabled",!0);L(this,"botProviderGlobalStateKey","bot-provider-global-state");L(this,"botProviderLocalStateKey","bot-provider-local-state");L(this,"botProviderEntriesKey","bot-provider-entries");L(this,"botProviderMetaStateKey","bot-provider-conversation-meta");this.container=n}getKey(n){let o;switch(n){case"localState":o=this.botProviderLocalStateKey;break;case"globalState":o=this.botProviderGlobalStateKey;break;case"entries":o=this.botProviderEntriesKey;break;case"meta":o=this.botProviderMetaStateKey;break}return o}async read(n){const o=this.getKey(n);if(!(!this.enabled||!o))return R.readStorage(this.container,o)}async write(n,o){const e=this.getKey(o);if(!this.enabled||!e)return;(await R.createStorageWriter(this.container,e,R.StorageCategory.Necessary))(n)}}var M=(t=>(t.ContactMethod="ace-conversational-hub-contact-method",t.ContactList="ace-conversational-hub-contact-list",t))(M||{});const St=t=>{if(t){const{type:n,content:o}=t;if(n&&o)return{type:n,content:o}}},wt=({isUser:t,items:n=[],meta:o={}})=>{const e=A.uuid();return{id:e,isUser:t,items:n.map(f=>({id:f.id||A.uuid(),isUser:t,groupId:e,message:f.message||[]})),meta:o}},$t=({id:t,title:n,defaultIcon:o,exits:[e],exitType:i,confirmationText:f,expandFormAutomatically:c,form:v,description:d},s={})=>{const{adapter:a}=e||{},{clientName:h="",settings:S={},customClientName:b=""}=a,{validation:m}=s,g={id:t.toString(),title:n,description:d,symbol:St(o),clientName:h==="custom.adapter"?b:h,expanded:!0,inline:!0,body:{}};if(h.indexOf("phone")>-1||h.indexOf("freetext")>-1){const{displayTextBeforeClick:y,textBeforeClick:x}=S;y==="true"&&(g.expanded=!1,g.title=x),h.indexOf("phone.text")>-1?g.body.phoneNumber=S.phoneNumber:g.body.freetext=S.freetext}return(h.indexOf("chat.popup")>-1||h.indexOf("link")>-1||h==="custom.adapter"&&i==="custom")&&(g.body=S,g.body.confirmationFallback=f),h.indexOf("ace")>-1&&(g.body=S),v&&v.hasValueComponents&&(m?g.body.form=D.FormBuilder.fromLegacyForm(t.toString(),v,m).get():g.body.form=D.FormBuilder.fromLegacyForm(t.toString(),v).get(),c||(g.expanded=g.inline=!1),g.body=ct(g,{submit:"Submit"})),s.guideId&&(g.body.guideId=s.guideId),g},Ct=t=>{const{localState:n}=t;return t.tags.includes("category")&&t.tags.includes("contact")?P.ConversationMessageListItemType.ItemList:t.tags.includes("suggestion")?P.ConversationMessageListItemType.LinkList:(n==null?void 0:n.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"?M.ContactList:P.ConversationMessageListItemType.ButtonList},ct=(t,{submit:n,errors:o,meta:e})=>{var i;if((i=t==null?void 0:t.body)!=null&&i.form){const{body:f}=t,c=new D.FormBuilder(f.form);return f.form.layout.submit||c.createComponent(D.submitButton(n,"submit")),o&&c.setValidationErrors(o),e&&c.setMeta(e),{...f,form:c.get()}}return(t==null?void 0:t.body)||{}},It=async(t,n,o)=>{(await(await t.getAsync("dataClient")).getClient()).parameters.set(n,o)},N=({messageId:t,message:n,group:o})=>({id:t,message:n,groupId:o.id,isUser:o.isUser}),Et=async(t,n,o)=>{const e=(s,a,h,S={actions:[],entryId:a.id,groupId:h})=>{const b=[];return S.actions=a.content.items.map(m=>{var y;const g={label:m.title,actionKey:m.actionKey,symbol:m.symbol?m.symbol:void 0,description:m.description||void 0};if(m.data){const x=a.actions[m.actionKey];s===M.ContactList?(b.push(m.data.id),g.data=$t(m.data,{guideId:(y=x==null?void 0:x.guideId)==null?void 0:y.toString()})):g.data=m.data}return g}),s===M.ContactList&&(S.contactMethodIds=b),S},i=async(s,a,h=[],S)=>{var m,g;const b=A.uuid();switch(s.type!=="List"&&s.tags.includes("guide")&&((g=(m=s.content.hints)==null?void 0:m[0])!=null&&g.id)&&await It(t,"LastGuideId",s.content.hints[0].id),s.type){case"List":{if(!s.content)return[];const{items:y,html:x}=s.content,T=[];let E={actions:[],entryId:s.id,groupId:a.id};if((y==null?void 0:y.length)>0){const O=Ct(s);if(E=e(O,s,a.id,E),h.length){const k=h.find(K=>K.tags.includes("paging"));k!=null&&k.content&&(a.meta.paging={actions:k.actions,items:k.content.items,localState:k.localState},k.content.items.forEach(K=>{E.actions.push({label:K.title,actionKey:K.actionKey,data:{groupId:S?S.id:a.id}})}))}T.unshift(N({messageId:b,message:[O,E],group:a}))}return x&&T.unshift(N({messageId:b,message:[P.ConversationMessageListItemType.HTML,{body:x}],group:a})),T}case"Text":{const y=[];if(y.push(N({messageId:b,message:[P.ConversationMessageListItemType.HTML,{body:s.content.html}],group:a})),h.length){const x=h.find(E=>{var O;return E.type==="List"&&((O=E.localState)==null?void 0:O.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"}),T=h.find(E=>E.tags.includes("contact")&&E.type==="Contact");if(T&&y.push(N({messageId:b,message:[M.ContactMethod,{contactMethodId:T.content.id,groupId:a.id,guideId:T.content.guideId}],group:a})),x){const E=e(M.ContactList,x,a.id);y.push(N({messageId:b,message:[P.ConversationMessageListItemType.Separator,void 0],group:a})),y.push(N({messageId:b,message:[M.ContactList,E],group:a}))}}return y}case"Contact":return[N({messageId:b,message:[M.ContactMethod,{contactMethodId:s.content.id,groupId:a.id,guideId:s.content.guideId}],group:a})];case"Error":return[N({messageId:b,message:[P.ConversationMessageListItemType.HTML,{body:s.content.message||"Something went wrong."}],group:a})];default:return[]}},f=new Map([["Text",1],["List",2],["Contact",3]]),c=[],v=n.sort((s,a)=>{const S=f.get(s.type)||20,b=f.get(a.type)||20;return S-b}).filter(s=>!s.relation).reduce((s,a)=>s.concat(a),[]),d=s=>typeof s.actions.selector<"u";for(const s of v){const a=n.filter(b=>b.relation===s.id&&!d(b)),h=wt({isUser:!1});(await i(s,h,a,o)).forEach(b=>{h.items.push(b)}),h.items.length&&c.push(h)}return c};class Lt{constructor(n,o,e,i){L(this,"endpoint");L(this,"events");L(this,"store");L(this,"container");L(this,"globalState");L(this,"localState");L(this,"clientId");L(this,"entries");this.endpoint=n,this.events=o,this.store=e,this.container=i,this.clientId=A.uuid(),this.entries=[]}async fetchGuide(n){const o={command:{guide:{id:n}},globalState:this.globalState,clientId:this.clientId};return await this.postEnvelope(o)}async postEnvelope(n,o){try{const e=await fetch(this.endpoint,this.getHttpOptions(n));if(!e.ok)throw e;const i=await e.json();return this.handleResponse(i,o)}catch(e){process.env.NODE_ENV!=="production"&&console.warn("Something went wrong when posting the envelope.");let i="Something went wrong";return(e.message==="Failed to fetch"||e.message==="NetworkError when attempting to fetch resource.")&&(i="Lost connection... Please try again."),this.events.dispatch("tracking:http-client-error",{message:i,error:e}),this.handleResponse({entries:[{id:A.uuid(),type:"Error",timestamp:new Date().toISOString(),content:{message:i},actions:{},tags:[]}]})}}async handleResponse(n,o){this.entries=this.entries.concat(n.entries),this.store.write(this.entries,"entries");const e=n.entries.find(f=>f.type==="Widget");return e&&this.events.dispatch("provider:widget-entry",e.content),n.globalState&&(this.globalState=n.globalState,this.store.write(n.globalState,"globalState")),this.localState=n.entries.reduce((f,c)=>c.localState?c.localState:f,void 0),this.store.write(this.localState,"localState"),await Et(this.container,n.entries,o)}getHttpOptions(n){const o={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};return n.funnel=this.container.get("$widget").name,n.localState=n.localState||this.localState,Object.assign({},o,{body:JSON.stringify(n),credentials:"same-origin"})}}const lt=/^(?:https?:|mailto:|tel:)/i,ot=["_blank","_self","_parent","_top"],xt=/\uE000(\d+)\uE001/g,st="",kt=/[\uE000-\uE002]/g,q="A-Za-z0-9_\\u00C0-\\u024F",dt=/^ {0,3}(`{3,}|~{3,})/,gt=/^ {0,3}(#{1,6})[ \t]+(.*?)(?:[ \t]+#+)?[ \t]*$/,z=/^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/,F=/^ {0,3}&gt; ?/,U=/^( *)([-*+]|\d{1,9}[.)])(?:[ \t]+(.*))?$/,_t=/^ *\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/,V=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),it=(t,n)=>{const o=new RegExp(`(?:^|\\s)${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+))`,"i").exec(t);return o?o[1]??o[2]??o[3]:void 0},G=t=>t.length-t.trimStart().length,rt=t=>/\d/.test(t),at=t=>t.replace(/\*\*\*(?=\S)(.*?\S)\*\*\*/g,"<strong><em>$1</em></strong>").replace(/\*\*(?=\S)(.*?\S)\*\*/g,"<strong>$1</strong>").replace(new RegExp(`(^|[^${q}])__(?=\\S)(.*?\\S)__(?![${q}])`,"g"),"$1<strong>$2</strong>").replace(/~~(?=\S)(.*?\S)~~/g,"<del>$1</del>").replace(/\*(?=\S)(.*?\S)\*/g,"<em>$1</em>").replace(new RegExp(`(^|[^${q}])_(?=\\S)(.*?\\S)_(?![${q}])`,"g"),"$1<em>$2</em>"),J=(t,n)=>at(t.replace(/(`+)(.+?)\1(?!`)/g,(o,e,i)=>n.store(`<code>${i.trim()}</code>`)).replace(/\\([\\`*_{}[\]()#+\-.!|~])/g,(o,e)=>n.store(e)).replace(/&lt;((?:https?:|mailto:)\S+?)&gt;/gi,(o,e)=>n.link(e,e)).replace(/!?\[([^\]\n]+)\]\(\s*([^\s)]+)(?:\s+&quot;.*?&quot;)?\s*\)/g,(o,e,i)=>lt.test(i)?n.link(i,at(e)):e)),ut=(t,n)=>t[n].includes("|")&&n+1<t.length&&t[n+1].includes("|")&&_t.test(t[n+1]),ht=(t,n)=>dt.test(t[n])||gt.test(t[n])||z.test(t[n])||F.test(t[n])||U.test(t[n])||ut(t,n),W=t=>t.replace(/\\\|/g,st).trim().replace(/^\||\|$/g,"").split("|").map(n=>n.split(st).join("\\|").trim()),Tt=(t,n,o)=>{const e=W(t[n]),i=W(t[n+1]).map(s=>s.startsWith(":")&&s.endsWith(":")?"center":s.endsWith(":")?"right":s.startsWith(":")?"left":""),f=(s,a)=>`<tr>${e.map((h,S)=>{const b=i[S]?` style="text-align: ${i[S]}"`:"";return`<${a}${b}>${J(s[S]??"",o)}</${a}>`}).join("")}</tr>`,c=[];let v=n+2;for(;v<t.length&&t[v].trim()&&t[v].includes("|");)c.push(f(W(t[v]),"td")),v++;const d=c.length?`<tbody>${c.join("")}</tbody>`:"";return[`<table><thead>${f(e,"th")}</thead>${d}</table>`,v]},Mt=(t,n,o)=>{const e=U.exec(t[n]),i=e[1].length,f=rt(e[2]),c=[];let v=0;const d=m=>{const g=U.exec(m);return g&&g[1].length<=i+1&&rt(g[2])===f&&!z.test(m)?g:null};let s=n;for(;s<t.length;){const m=t[s],g=d(m);if(g){const y=g[3]??"";v=y?m.length-y.length:g[1].length+g[2].length+1,c.push([y])}else if(m.trim())if(G(m)>i+1)c[c.length-1].push(m.slice(Math.min(G(m),v)));else{if(ht(t,s))break;c[c.length-1].push(m.trimStart())}else{let y=s+1;for(;y<t.length&&!t[y].trim();)y++;if(y>=t.length||G(t[y])<=i+1&&!d(t[y]))break;c[c.length-1].push("")}s++}const a=f?"ol":"ul",h=parseInt(e[2],10),S=f&&h!==1?` start="${h}"`:"",b=c.map(m=>`<li>${Q(m,o).replace(/^<p>([\s\S]*?)<\/p>/,"$1")}</li>`).join("");return[`<${a}${S}>${b}</${a}>`,s]},Q=(t,n)=>{const o=[];let e=0;for(;e<t.length;){const i=t[e];if(!i.trim()){e++;continue}const f=dt.exec(i);if(f){const d=[];for(e++;e<t.length&&!t[e].trimStart().startsWith(f[1]);)d.push(t[e]),e++;e++,o.push(`<pre><code>${d.join(`
2
+ `)}</code></pre>`);continue}const c=gt.exec(i);if(c){const d=Math.min(c[1].length+2,6);o.push(`<h${d}>${J(c[2],n)}</h${d}>`),e++;continue}if(z.test(i)){o.push("<hr>"),e++;continue}if(F.test(i)){const d=[];for(;e<t.length&&F.test(t[e]);)d.push(t[e].replace(F,"")),e++;o.push(`<blockquote>${Q(d,n)}</blockquote>`);continue}if(ut(t,e)){const[d,s]=Tt(t,e,n);o.push(d),e=s;continue}if(U.test(i)){const[d,s]=Mt(t,e,n);o.push(d),e=s;continue}const v=[i.trim()];for(e++;e<t.length&&t[e].trim()&&!ht(t,e);)v.push(t[e].trim()),e++;o.push(`<p>${J(v.join(`
3
+ `),n).replace(/\n/g,"<br>")}</p>`)}return o.join("")},Pt=(t,n={})=>{const o=n.linkTarget&&ot.includes(n.linkTarget)?n.linkTarget:"_blank",e=[],i={store:d=>`${e.push(d)-1}`,link:(d,s,a=o)=>i.store(`<a href="${d}" target="${a}" rel="noopener noreferrer">${s}</a>`)},f=t.replace(kt,"").replace(/\r\n?/g,`
4
+ `).replace(/<a\s([^>]*)>([\s\S]*?)<\/a\s*>/gi,(d,s,a)=>{var m;const h=(m=it(s,"href"))==null?void 0:m.trim().replace(/&amp;/g,"&"),S=it(s,"target"),b=V(a);return!h||!lt.test(h)?i.store(b):i.link(V(h),b,S&&ot.includes(S)?S:o)}),c=V(f).split(`
5
+ `).map(d=>d.replace(/^\t+/,s=>" ".repeat(s.length)));let v=Q(c,i);for(;v.includes("");)v=v.replace(xt,(d,s)=>e[+s]);return v},Ot="@telia-ace/conversational-hub-bot-provider",At="0.0.16",H={name:Ot,version:At},Nt=async t=>{var Z,X,Y,tt,et;const n="chub-plugin",o=t.get("$widget"),e=(et=(tt=(Y=(X=(Z=o==null?void 0:o.container)==null?void 0:Z.get("$settings"))==null?void 0:X.components)==null?void 0:Y.conversation)==null?void 0:tt.properties)==null?void 0:et.conversationalHubPluginSettings;let i,f,c,v=(e==null?void 0:e.connectionAttempts)??5,d,s,a;A.Logger.info((H==null?void 0:H.name)+" version: "+(H==null?void 0:H.version)),P.registerCustomMessageComponent(t,M.ContactMethod,Promise.resolve().then(()=>require("./contact-method-DGL-OlIC.js"))),P.registerCustomMessageComponent(t,M.ContactList,Promise.resolve().then(()=>require("./contact-method-list-Czl8gqcV.js")));const h=await R.createStorageWriter(t,"conversational-hub-session",R.StorageCategory.Necessary),S=(u,l)=>{const{knowledgeBotEndpoint:r}=l.properties();if(r)return`${r}/conversations`;const{data:p}=u.get("$settings");if(!p||!p.projection)throw new Error("Missing Knowledge Bot endpoint");return`${p.projection}/conversations`},b=u=>{var l;if(u.target instanceof HTMLButtonElement){const r=u.target;if((l=r.getAttribute("class"))!=null&&l.includes("dialog-option-cx")){const p=r.getAttribute("value");O(p),i.user.print(p.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}}};(await P.ConversationPlatform.getInstance(t)).registerProvider(n,(u,l)=>{i=u,f=i.controller,c=i.createAgent({name:e==null?void 0:e.botName,avatar:e==null?void 0:e.avatar}),a=S(t,l);const{events:r}=t.get("$widget"),p=new vt(t);s=new Lt(a,r,p,t),T();const[w]=t.get("widgetDOMElements");w.querySelectorAll(".humany-bot-contact-method").forEach(C=>{var $;($=C.closest(".humany-conversation-entry"))==null||$.remove()}),w.removeEventListener("click",b),w.addEventListener("click",b);const I=()=>f.providers.includes(n);l.actions.create("submit",C=>{const{events:$}=t.get("$widget");$.dispatch("conversational-hub-provider:form-submitted",C)}),l.actions.create("evaluate",C=>{const{events:$}=t.get("$widget");$.dispatch("conversational-hub-provider:evaluate",C)}),l.actions.watch("conversation.action",(C,$)=>(I()&&E(C),$(C))),l.actions.watch("conversation.user-submit",(C,$)=>{if(!I())return $(C);O(C.text),i.user.print(C.text.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}),o.events.subscribe("conversational-hub-provider:fetch-guide",async(C,$)=>{if(!($!=null&&$.guideId))return;const B=await s.fetchGuide(parseInt($.guideId));B&&g(B)})});async function g(u){u.forEach(l=>{const r=l.items.map(p=>p.message);l.writer=c.print(r)})}const y=sessionStorage.getItem(`humany_${x(o.implementation.tenant+o.implementation.name+o.name)}`);function x(u){let l=0;if(u.length===0)return l.toString();for(let r=0;r<u.length;r++){const p=u.charCodeAt(r);l=(l<<5)-l+p,l=l&l}return l.toString()}async function T(u=!0){const l=await R.readStorage(t,"conversational-hub-session"),r=t.get("dialogflowSettings");if(r!=null&&r.silentStart)delete r.silentStart,o.events.dispatch("conversational-hub-provider:started",{});else if(l!=null&&l.sessionId&&u)d=l==null?void 0:l.sessionId;else if(e!=null&&e.welcomeMessage){if(!(y!=null&&y.length?JSON.parse(y):{})["conversation-conversation"]){const w=e.welcomeMessage.replaceAll("$lt;","<").replaceAll("$gt;",">");c.print(w)}}else{const p={extension:e.extension};r!=null&&r.initCommand&&(p.input={type:"event",language:e.language,content:{name:r.initCommand,parameters:r.initParameters||{}}}),await k(e.baseUrl+"/initialize",JSON.stringify(p),u)}}async function E(u){await k(`${e.baseUrl}/input/${d}`,`{"type":"button_click","language":"${e.language}","content":{"button_text":"${u.label}","value":"${u.actionKey}"}}`)}async function O(u){const l={text:u};if(!d){const r={extension:e.extension},p=t.get("dialogflowSettings");p!=null&&p.initCommand&&(r.input={type:"event",language:e.language,content:{name:p.initCommand,parameters:p.initParameters||{}}}),await k(e.baseUrl+"/initialize",JSON.stringify(r),!1)}await k(`${e.baseUrl}/input/${d}`,`{"type":"text","language":"${e.language}","content":${JSON.stringify(l)}}`)}async function k(u,l,r=!0){var C,$,B,nt;const p=i.loading();let w,I;try{w=await fetch(u,{method:"POST",body:l}),I=await(w==null?void 0:w.json())}catch(j){j instanceof SyntaxError?A.Logger.error("Incorrect JSON format.",j):A.Logger.error("Network error: check connection or baseUrl.",j),p(),c.print(e.errorMessage||"An error occurred");return}if(!(w!=null&&w.ok)){if(A.Logger.error(`HTTP ${w==null?void 0:w.status}.`,JSON.stringify(I)),p(),!!((C=I==null?void 0:I.errors)!=null&&C.filter(_=>_.code==="1003").length)&&v>0){v--,await new Promise(pt=>setTimeout(pt,500)),await T(!1);const _=JSON.parse(l);($=_==null?void 0:_.content)!=null&&$.text?await O(_.content.text):(B=_==null?void 0:_.content)!=null&&B.action&&await E((nt=_==null?void 0:_.content)==null?void 0:nt.action)}else c.print(e.errorMessage||"An error occurred");return}p(),v=(e==null?void 0:e.connectionAttempts)??5,I!=null&&I.action_payload&&K(I.action_payload),d=I==null?void 0:I.session_id,h({sessionId:d}),r&&mt(I)}async function K(u){var w;const l=(w=u==null?void 0:u.transfer_parameters)==null?void 0:w.contactGuide,r=i.loading(),p=await s.fetchGuide(parseInt(l));r(),p&&g(p)}function mt(u){var l;u==null||u.agent_response.forEach(r=>{c.print(e!=null&&e.markdown&&r.type==="text"?Pt(r.payload.text,{linkTarget:e==null?void 0:e.linkTarget}):r.payload.text)}),(l=u==null?void 0:u.prompt)!=null&&l.items&&c.print(["button-list",{actions:u.prompt.items.map(r=>{let p;return r.type==="button"&&(p={actionKey:r.value,label:r.text}),r.type==="link"&&(p={actionKey:r.value,label:r.text,data:{href:r.url,target:(e==null?void 0:e.linkTarget)??"_blank"}}),p})}])}},Kt=yt.createConfigurationApi(t=>{t.createCommand("dialogflow",n=>o=>{const e={initCommand:o.initCommand};o.initParameters&&(e.initParameters=o.initParameters),o.silentStart&&(e.silentStart=o.silentStart),n.container.register("dialogflowSettings",e)})});exports.ConversationalHubPlugin=Nt;exports.dialogflowConfigurationApi=Kt;exports.updateForm=ct;
@@ -1,6 +1,6 @@
1
1
  var St = Object.defineProperty;
2
2
  var vt = (t, n, o) => n in t ? St(t, n, { enumerable: !0, configurable: !0, writable: !0, value: o }) : t[n] = o;
3
- var O = (t, n, o) => vt(t, typeof n != "symbol" ? n + "" : n, o);
3
+ var x = (t, n, o) => vt(t, typeof n != "symbol" ? n + "" : n, o);
4
4
  import { ConversationMessageListItemType as M, registerCustomMessageComponent as ot, ConversationPlatform as wt } from "@telia-ace/widget-conversation";
5
5
  import { readStorage as lt, createStorageWriter as dt, StorageCategory as ut } from "@telia-ace/widget-services";
6
6
  import { uuid as H, Logger as B } from "@telia-ace/widget-utilities";
@@ -8,12 +8,13 @@ import { FormBuilder as W, submitButton as $t } from "@telia-ace/widget-forms";
8
8
  import { createConfigurationApi as Et } from "@webprovisions/platform";
9
9
  class Ct {
10
10
  constructor(n) {
11
- O(this, "enabled", !0);
11
+ x(this, "container");
12
+ x(this, "enabled", !0);
12
13
  // set whether or not to store data
13
- O(this, "botProviderGlobalStateKey", "bot-provider-global-state");
14
- O(this, "botProviderLocalStateKey", "bot-provider-local-state");
15
- O(this, "botProviderEntriesKey", "bot-provider-entries");
16
- O(this, "botProviderMetaStateKey", "bot-provider-conversation-meta");
14
+ x(this, "botProviderGlobalStateKey", "bot-provider-global-state");
15
+ x(this, "botProviderLocalStateKey", "bot-provider-local-state");
16
+ x(this, "botProviderEntriesKey", "bot-provider-entries");
17
+ x(this, "botProviderMetaStateKey", "bot-provider-conversation-meta");
17
18
  this.container = n;
18
19
  }
19
20
  getKey(n) {
@@ -89,7 +90,7 @@ const It = (t) => {
89
90
  clientName: h = "",
90
91
  settings: v = {},
91
92
  customClientName: b = ""
92
- } = r, { validation: m } = i, u = {
93
+ } = r, { validation: p } = i, u = {
93
94
  id: t.toString(),
94
95
  title: n,
95
96
  description: d,
@@ -100,13 +101,13 @@ const It = (t) => {
100
101
  body: {}
101
102
  };
102
103
  if (h.indexOf("phone") > -1 || h.indexOf("freetext") > -1) {
103
- const { displayTextBeforeClick: y, textBeforeClick: x } = v;
104
- y === "true" && (u.expanded = !1, u.title = x), h.indexOf("phone.text") > -1 ? u.body.phoneNumber = v.phoneNumber : u.body.freetext = v.freetext;
104
+ const { displayTextBeforeClick: y, textBeforeClick: L } = v;
105
+ y === "true" && (u.expanded = !1, u.title = L), h.indexOf("phone.text") > -1 ? u.body.phoneNumber = v.phoneNumber : u.body.freetext = v.freetext;
105
106
  }
106
- return (h.indexOf("chat.popup") > -1 || h.indexOf("link") > -1 || h === "custom.adapter" && s === "custom") && (u.body = v, u.body.confirmationFallback = f), h.indexOf("ace") > -1 && (u.body = v), S && S.hasValueComponents && (m ? u.body.form = W.fromLegacyForm(
107
+ return (h.indexOf("chat.popup") > -1 || h.indexOf("link") > -1 || h === "custom.adapter" && s === "custom") && (u.body = v, u.body.confirmationFallback = f), h.indexOf("ace") > -1 && (u.body = v), S && S.hasValueComponents && (p ? u.body.form = W.fromLegacyForm(
107
108
  t.toString(),
108
109
  S,
109
- m
110
+ p
110
111
  ).get() : u.body.form = W.fromLegacyForm(
111
112
  t.toString(),
112
113
  S
@@ -146,33 +147,33 @@ const It = (t) => {
146
147
  groupId: h
147
148
  }) => {
148
149
  const b = [];
149
- return v.actions = r.content.items.map((m) => {
150
+ return v.actions = r.content.items.map((p) => {
150
151
  var y;
151
152
  const u = {
152
- label: m.title,
153
- actionKey: m.actionKey,
154
- symbol: m.symbol ? m.symbol : void 0,
155
- description: m.description || void 0
153
+ label: p.title,
154
+ actionKey: p.actionKey,
155
+ symbol: p.symbol ? p.symbol : void 0,
156
+ description: p.description || void 0
156
157
  };
157
- if (m.data) {
158
- const x = r.actions[m.actionKey];
159
- i === T.ContactList ? (b.push(m.data.id), u.data = Lt(m.data, {
160
- guideId: (y = x == null ? void 0 : x.guideId) == null ? void 0 : y.toString()
161
- })) : u.data = m.data;
158
+ if (p.data) {
159
+ const L = r.actions[p.actionKey];
160
+ i === T.ContactList ? (b.push(p.data.id), u.data = Lt(p.data, {
161
+ guideId: (y = L == null ? void 0 : L.guideId) == null ? void 0 : y.toString()
162
+ })) : u.data = p.data;
162
163
  }
163
164
  return u;
164
165
  }), i === T.ContactList && (v.contactMethodIds = b), v;
165
166
  }, s = async (i, r, h = [], v) => {
166
- var m, u;
167
+ var p, u;
167
168
  const b = H();
168
- switch (i.type !== "List" && i.tags.includes("guide") && ((u = (m = i.content.hints) == null ? void 0 : m[0]) != null && u.id) && await Ot(
169
+ switch (i.type !== "List" && i.tags.includes("guide") && ((u = (p = i.content.hints) == null ? void 0 : p[0]) != null && u.id) && await Ot(
169
170
  t,
170
171
  "LastGuideId",
171
172
  i.content.hints[0].id
172
173
  ), i.type) {
173
174
  case "List": {
174
175
  if (!i.content) return [];
175
- const { items: y, html: x } = i.content, _ = [];
176
+ const { items: y, html: L } = i.content, O = [];
176
177
  let I = {
177
178
  actions: [],
178
179
  entryId: i.id,
@@ -186,14 +187,14 @@ const It = (t) => {
186
187
  r.id,
187
188
  I
188
189
  ), h.length) {
189
- const L = h.find(
190
+ const k = h.find(
190
191
  (N) => N.tags.includes("paging")
191
192
  );
192
- L != null && L.content && (r.meta.paging = {
193
- actions: L.actions,
194
- items: L.content.items,
195
- localState: L.localState
196
- }, L.content.items.forEach((N) => {
193
+ k != null && k.content && (r.meta.paging = {
194
+ actions: k.actions,
195
+ items: k.content.items,
196
+ localState: k.localState
197
+ }, k.content.items.forEach((N) => {
197
198
  I.actions.push({
198
199
  label: N.title,
199
200
  actionKey: N.actionKey,
@@ -203,7 +204,7 @@ const It = (t) => {
203
204
  });
204
205
  }));
205
206
  }
206
- _.unshift(
207
+ O.unshift(
207
208
  A({
208
209
  messageId: b,
209
210
  message: [P, I],
@@ -211,13 +212,13 @@ const It = (t) => {
211
212
  })
212
213
  );
213
214
  }
214
- return x && _.unshift(
215
+ return L && O.unshift(
215
216
  A({
216
217
  messageId: b,
217
- message: [M.HTML, { body: x }],
218
+ message: [M.HTML, { body: L }],
218
219
  group: r
219
220
  })
220
- ), _;
221
+ ), O;
221
222
  }
222
223
  case "Text": {
223
224
  const y = [];
@@ -231,31 +232,31 @@ const It = (t) => {
231
232
  group: r
232
233
  })
233
234
  ), h.length) {
234
- const x = h.find(
235
+ const L = h.find(
235
236
  (I) => {
236
237
  var P;
237
238
  return I.type === "List" && ((P = I.localState) == null ? void 0 : P.$type) === "Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching";
238
239
  }
239
- ), _ = h.find(
240
+ ), O = h.find(
240
241
  (I) => I.tags.includes("contact") && I.type === "Contact"
241
242
  );
242
- if (_ && y.push(
243
+ if (O && y.push(
243
244
  A({
244
245
  messageId: b,
245
246
  message: [
246
247
  T.ContactMethod,
247
248
  {
248
- contactMethodId: _.content.id,
249
+ contactMethodId: O.content.id,
249
250
  groupId: r.id,
250
- guideId: _.content.guideId
251
+ guideId: O.content.guideId
251
252
  }
252
253
  ],
253
254
  group: r
254
255
  })
255
- ), x) {
256
+ ), L) {
256
257
  const I = e(
257
258
  T.ContactList,
258
- x,
259
+ L,
259
260
  r.id
260
261
  );
261
262
  y.push(
@@ -329,10 +330,14 @@ const It = (t) => {
329
330
  };
330
331
  class Pt {
331
332
  constructor(n, o, e, s) {
332
- O(this, "globalState");
333
- O(this, "localState");
334
- O(this, "clientId");
335
- O(this, "entries");
333
+ x(this, "endpoint");
334
+ x(this, "events");
335
+ x(this, "store");
336
+ x(this, "container");
337
+ x(this, "globalState");
338
+ x(this, "localState");
339
+ x(this, "clientId");
340
+ x(this, "entries");
336
341
  this.endpoint = n, this.events = o, this.store = e, this.container = s, this.clientId = H(), this.entries = [];
337
342
  }
338
343
  async fetchGuide(n) {
@@ -398,7 +403,7 @@ class Pt {
398
403
  });
399
404
  }
400
405
  }
401
- const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_top"], At = /\uE000(\d+)\uE001/g, st = "", Mt = /[\uE000-\uE002]/g, D = "A-Za-z0-9_\\u00C0-\\u024F", ht = /^ {0,3}(`{3,}|~{3,})/, mt = /^ {0,3}(#{1,6})[ \t]+(.*?)(?:[ \t]+#+)?[ \t]*$/, z = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/, V = /^ {0,3}&gt; ?/, G = /^( *)([-*+]|\d{1,9}[.)])(?:[ \t]+(.*))?$/, Nt = /^ *\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/, U = (t) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"), at = (t, n) => {
406
+ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_top"], At = /\uE000(\d+)\uE001/g, st = "", Mt = /[\uE000-\uE002]/g, D = "A-Za-z0-9_\\u00C0-\\u024F", ht = /^ {0,3}(`{3,}|~{3,})/, pt = /^ {0,3}(#{1,6})[ \t]+(.*?)(?:[ \t]+#+)?[ \t]*$/, z = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/, V = /^ {0,3}&gt; ?/, G = /^( *)([-*+]|\d{1,9}[.)])(?:[ \t]+(.*))?$/, Nt = /^ *\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/, U = (t) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"), at = (t, n) => {
402
407
  const o = new RegExp(
403
408
  `(?:^|\\s)${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+))`,
404
409
  "i"
@@ -424,7 +429,7 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
424
429
  /!?\[([^\]\n]+)\]\(\s*([^\s)]+)(?:\s+&quot;.*?&quot;)?\s*\)/g,
425
430
  (o, e, s) => gt.test(s) ? n.link(s, ct(e)) : e
426
431
  )
427
- ), pt = (t, n) => t[n].includes("|") && n + 1 < t.length && t[n + 1].includes("|") && Nt.test(t[n + 1]), ft = (t, n) => ht.test(t[n]) || mt.test(t[n]) || z.test(t[n]) || V.test(t[n]) || G.test(t[n]) || pt(t, n), J = (t) => t.replace(/\\\|/g, st).trim().replace(/^\||\|$/g, "").split("|").map((n) => n.split(st).join("\\|").trim()), Kt = (t, n, o) => {
432
+ ), mt = (t, n) => t[n].includes("|") && n + 1 < t.length && t[n + 1].includes("|") && Nt.test(t[n + 1]), ft = (t, n) => ht.test(t[n]) || pt.test(t[n]) || z.test(t[n]) || V.test(t[n]) || G.test(t[n]) || mt(t, n), J = (t) => t.replace(/\\\|/g, st).trim().replace(/^\||\|$/g, "").split("|").map((n) => n.split(st).join("\\|").trim()), Kt = (t, n, o) => {
428
433
  const e = J(t[n]), s = J(t[n + 1]).map((i) => i.startsWith(":") && i.endsWith(":") ? "center" : i.endsWith(":") ? "right" : i.startsWith(":") ? "left" : ""), f = (i, r) => `<tr>${e.map((h, v) => {
429
434
  const b = s[v] ? ` style="text-align: ${s[v]}"` : "";
430
435
  return `<${r}${b}>${q(i[v] ?? "", o)}</${r}>`;
@@ -440,25 +445,25 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
440
445
  }, Rt = (t, n, o) => {
441
446
  const e = G.exec(t[n]), s = e[1].length, f = rt(e[2]), c = [];
442
447
  let S = 0;
443
- const d = (m) => {
444
- const u = G.exec(m);
445
- return u && u[1].length <= s + 1 && rt(u[2]) === f && !z.test(m) ? u : null;
448
+ const d = (p) => {
449
+ const u = G.exec(p);
450
+ return u && u[1].length <= s + 1 && rt(u[2]) === f && !z.test(p) ? u : null;
446
451
  };
447
452
  let i = n;
448
453
  for (; i < t.length; ) {
449
- const m = t[i], u = d(m);
454
+ const p = t[i], u = d(p);
450
455
  if (u) {
451
456
  const y = u[3] ?? "";
452
- S = y ? m.length - y.length : u[1].length + u[2].length + 1, c.push([y]);
453
- } else if (m.trim())
454
- if (F(m) > s + 1)
457
+ S = y ? p.length - y.length : u[1].length + u[2].length + 1, c.push([y]);
458
+ } else if (p.trim())
459
+ if (F(p) > s + 1)
455
460
  c[c.length - 1].push(
456
- m.slice(Math.min(F(m), S))
461
+ p.slice(Math.min(F(p), S))
457
462
  );
458
463
  else {
459
464
  if (ft(t, i))
460
465
  break;
461
- c[c.length - 1].push(m.trimStart());
466
+ c[c.length - 1].push(p.trimStart());
462
467
  }
463
468
  else {
464
469
  let y = i + 1;
@@ -470,7 +475,7 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
470
475
  i++;
471
476
  }
472
477
  const r = f ? "ol" : "ul", h = parseInt(e[2], 10), v = f && h !== 1 ? ` start="${h}"` : "", b = c.map(
473
- (m) => `<li>${Q(m, o).replace(
478
+ (p) => `<li>${Q(p, o).replace(
474
479
  /^<p>([\s\S]*?)<\/p>/,
475
480
  "$1"
476
481
  )}</li>`
@@ -494,7 +499,7 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
494
499
  `)}</code></pre>`);
495
500
  continue;
496
501
  }
497
- const c = mt.exec(s);
502
+ const c = pt.exec(s);
498
503
  if (c) {
499
504
  const d = Math.min(c[1].length + 2, 6);
500
505
  o.push(`<h${d}>${q(c[2], n)}</h${d}>`), e++;
@@ -511,7 +516,7 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
511
516
  o.push(`<blockquote>${Q(d, n)}</blockquote>`);
512
517
  continue;
513
518
  }
514
- if (pt(t, e)) {
519
+ if (mt(t, e)) {
515
520
  const [d, i] = Kt(t, e, n);
516
521
  o.push(d), e = i;
517
522
  continue;
@@ -540,8 +545,8 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
540
545
  `).replace(
541
546
  /<a\s([^>]*)>([\s\S]*?)<\/a\s*>/gi,
542
547
  (d, i, r) => {
543
- var m;
544
- const h = (m = at(i, "href")) == null ? void 0 : m.trim().replace(/&amp;/g, "&"), v = at(i, "target"), b = U(r);
548
+ var p;
549
+ const h = (p = at(i, "href")) == null ? void 0 : p.trim().replace(/&amp;/g, "&"), v = at(i, "target"), b = U(r);
545
550
  return !h || !gt.test(h) ? s.store(b) : s.link(
546
551
  U(h),
547
552
  b,
@@ -564,11 +569,11 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
564
569
  B.info((K == null ? void 0 : K.name) + " version: " + (K == null ? void 0 : K.version)), ot(
565
570
  t,
566
571
  T.ContactMethod,
567
- import("./contact-method-B38jdJFB.mjs")
572
+ import("./contact-method-DJLku_0u.mjs")
568
573
  ), ot(
569
574
  t,
570
575
  T.ContactList,
571
- import("./contact-method-list-hOqDT0Ae.mjs")
576
+ import("./contact-method-list-Bm-7fTSA.mjs")
572
577
  );
573
578
  const h = await dt(
574
579
  t,
@@ -578,18 +583,18 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
578
583
  const { knowledgeBotEndpoint: a } = l.properties();
579
584
  if (a)
580
585
  return `${a}/conversations`;
581
- const { data: p } = g.get("$settings");
582
- if (!p || !p.projection)
586
+ const { data: m } = g.get("$settings");
587
+ if (!m || !m.projection)
583
588
  throw new Error("Missing Knowledge Bot endpoint");
584
- return `${p.projection}/conversations`;
589
+ return `${m.projection}/conversations`;
585
590
  }, b = (g) => {
586
591
  var l;
587
592
  if (g.target instanceof HTMLButtonElement) {
588
593
  const a = g.target;
589
594
  if ((l = a.getAttribute("class")) != null && l.includes("dialog-option-cx")) {
590
- const p = a.getAttribute("value");
591
- P(p), s.user.print(
592
- p.replace(/</g, "&lt;").replace(/>/g, "&gt;")
595
+ const m = a.getAttribute("value");
596
+ P(m), s.user.print(
597
+ m.replace(/</g, "&lt;").replace(/>/g, "&gt;")
593
598
  );
594
599
  }
595
600
  }
@@ -601,8 +606,8 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
601
606
  name: e == null ? void 0 : e.botName,
602
607
  avatar: e == null ? void 0 : e.avatar
603
608
  }), r = v(t, l);
604
- const { events: a } = t.get("$widget"), p = new Ct(t);
605
- i = new Pt(r, a, p, t), _();
609
+ const { events: a } = t.get("$widget"), m = new Ct(t);
610
+ i = new Pt(r, a, m, t), O();
606
611
  const [w] = t.get("widgetDOMElements");
607
612
  w.querySelectorAll(".humany-bot-contact-method").forEach((E) => {
608
613
  var $;
@@ -631,26 +636,26 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
631
636
  });
632
637
  async function u(g) {
633
638
  g.forEach((l) => {
634
- const a = l.items.map((p) => p.message);
639
+ const a = l.items.map((m) => m.message);
635
640
  l.writer = c.print(a);
636
641
  });
637
642
  }
638
643
  const y = sessionStorage.getItem(
639
- `humany_${x(
644
+ `humany_${L(
640
645
  o.implementation.tenant + o.implementation.name + o.name
641
646
  )}`
642
647
  );
643
- function x(g) {
648
+ function L(g) {
644
649
  let l = 0;
645
650
  if (g.length === 0)
646
651
  return l.toString();
647
652
  for (let a = 0; a < g.length; a++) {
648
- const p = g.charCodeAt(a);
649
- l = (l << 5) - l + p, l = l & l;
653
+ const m = g.charCodeAt(a);
654
+ l = (l << 5) - l + m, l = l & l;
650
655
  }
651
656
  return l.toString();
652
657
  }
653
- async function _(g = !0) {
658
+ async function O(g = !0) {
654
659
  const l = await lt(
655
660
  t,
656
661
  "conversational-hub-session"
@@ -665,25 +670,25 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
665
670
  c.print(w);
666
671
  }
667
672
  } else {
668
- const p = {
673
+ const m = {
669
674
  extension: e.extension
670
675
  };
671
- a != null && a.initCommand && (p.input = {
676
+ a != null && a.initCommand && (m.input = {
672
677
  type: "event",
673
678
  language: e.language,
674
679
  content: {
675
680
  name: a.initCommand,
676
681
  parameters: a.initParameters || {}
677
682
  }
678
- }), await L(
683
+ }), await k(
679
684
  e.baseUrl + "/initialize",
680
- JSON.stringify(p),
685
+ JSON.stringify(m),
681
686
  g
682
687
  );
683
688
  }
684
689
  }
685
690
  async function I(g) {
686
- await L(
691
+ await k(
687
692
  `${e.baseUrl}/input/${d}`,
688
693
  `{"type":"button_click","language":"${e.language}","content":{"button_text":"${g.label}","value":"${g.actionKey}"}}`
689
694
  );
@@ -693,28 +698,28 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
693
698
  if (!d) {
694
699
  const a = {
695
700
  extension: e.extension
696
- }, p = t.get("dialogflowSettings");
697
- p != null && p.initCommand && (a.input = {
701
+ }, m = t.get("dialogflowSettings");
702
+ m != null && m.initCommand && (a.input = {
698
703
  type: "event",
699
704
  language: e.language,
700
705
  content: {
701
- name: p.initCommand,
702
- parameters: p.initParameters || {}
706
+ name: m.initCommand,
707
+ parameters: m.initParameters || {}
703
708
  }
704
- }), await L(
709
+ }), await k(
705
710
  e.baseUrl + "/initialize",
706
711
  JSON.stringify(a),
707
712
  !1
708
713
  );
709
714
  }
710
- await L(
715
+ await k(
711
716
  `${e.baseUrl}/input/${d}`,
712
717
  `{"type":"text","language":"${e.language}","content":${JSON.stringify(l)}}`
713
718
  );
714
719
  }
715
- async function L(g, l, a = !0) {
720
+ async function k(g, l, a = !0) {
716
721
  var E, $, R, nt;
717
- const p = s.loading();
722
+ const m = s.loading();
718
723
  let w, C;
719
724
  try {
720
725
  w = await fetch(g, {
@@ -722,26 +727,26 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
722
727
  body: l
723
728
  }), C = await (w == null ? void 0 : w.json());
724
729
  } catch (j) {
725
- j instanceof SyntaxError ? B.error("Incorrect JSON format.", j) : B.error("Network error: check connection or baseUrl.", j), p(), c.print(e.errorMessage || "An error occurred");
730
+ j instanceof SyntaxError ? B.error("Incorrect JSON format.", j) : B.error("Network error: check connection or baseUrl.", j), m(), c.print(e.errorMessage || "An error occurred");
726
731
  return;
727
732
  }
728
733
  if (!(w != null && w.ok)) {
729
- if (B.error(`HTTP ${w == null ? void 0 : w.status}.`, JSON.stringify(C)), p(), !!((E = C == null ? void 0 : C.errors) != null && E.filter(
730
- (k) => k.code === "1003"
734
+ if (B.error(`HTTP ${w == null ? void 0 : w.status}.`, JSON.stringify(C)), m(), !!((E = C == null ? void 0 : C.errors) != null && E.filter(
735
+ (_) => _.code === "1003"
731
736
  ).length) && S > 0) {
732
- S--, await new Promise((yt) => setTimeout(yt, 500)), await _(!1);
733
- const k = JSON.parse(l);
734
- ($ = k == null ? void 0 : k.content) != null && $.text ? await P(k.content.text) : (R = k == null ? void 0 : k.content) != null && R.action && await I((nt = k == null ? void 0 : k.content) == null ? void 0 : nt.action);
737
+ S--, await new Promise((yt) => setTimeout(yt, 500)), await O(!1);
738
+ const _ = JSON.parse(l);
739
+ ($ = _ == null ? void 0 : _.content) != null && $.text ? await P(_.content.text) : (R = _ == null ? void 0 : _.content) != null && R.action && await I((nt = _ == null ? void 0 : _.content) == null ? void 0 : nt.action);
735
740
  } else
736
741
  c.print(e.errorMessage || "An error occurred");
737
742
  return;
738
743
  }
739
- p(), S = (e == null ? void 0 : e.connectionAttempts) ?? 5, C != null && C.action_payload && N(C.action_payload), d = C == null ? void 0 : C.session_id, h({ sessionId: d }), a && bt(C);
744
+ m(), S = (e == null ? void 0 : e.connectionAttempts) ?? 5, C != null && C.action_payload && N(C.action_payload), d = C == null ? void 0 : C.session_id, h({ sessionId: d }), a && bt(C);
740
745
  }
741
746
  async function N(g) {
742
747
  var w;
743
- const l = (w = g == null ? void 0 : g.transfer_parameters) == null ? void 0 : w.contactGuide, a = s.loading(), p = await i.fetchGuide(parseInt(l));
744
- a(), p && u(p);
748
+ const l = (w = g == null ? void 0 : g.transfer_parameters) == null ? void 0 : w.contactGuide, a = s.loading(), m = await i.fetchGuide(parseInt(l));
749
+ a(), m && u(m);
745
750
  }
746
751
  function bt(g) {
747
752
  var l;
@@ -755,15 +760,15 @@ const gt = /^(?:https?:|mailto:|tel:)/i, it = ["_blank", "_self", "_parent", "_t
755
760
  "button-list",
756
761
  {
757
762
  actions: g.prompt.items.map((a) => {
758
- let p;
759
- return a.type === "button" && (p = { actionKey: a.value, label: a.text }), a.type === "link" && (p = {
763
+ let m;
764
+ return a.type === "button" && (m = { actionKey: a.value, label: a.text }), a.type === "link" && (m = {
760
765
  actionKey: a.value,
761
766
  label: a.text,
762
767
  data: {
763
768
  href: a.url,
764
769
  target: (e == null ? void 0 : e.linkTarget) ?? "_blank"
765
770
  }
766
- }), p;
771
+ }), m;
767
772
  })
768
773
  }
769
774
  ]);
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./index-CqXeCBbx.js");exports.ConversationalHubPlugin=i.ConversationalHubPlugin;exports.dialogflowConfigurationApi=i.dialogflowConfigurationApi;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./index-BVRRx5B7.js");exports.ConversationalHubPlugin=i.ConversationalHubPlugin;exports.dialogflowConfigurationApi=i.dialogflowConfigurationApi;
package/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { C as i, d as n } from "./index-DlrDioqz.mjs";
1
+ import { C as i, d as n } from "./index-YseNYD9Z.mjs";
2
2
  export {
3
3
  i as ConversationalHubPlugin,
4
4
  n as dialogflowConfigurationApi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telia-ace/conversational-hub-bot-provider",
3
- "version": "1.3.59",
3
+ "version": "1.3.60-rc.0",
4
4
  "main": "./index.js",
5
5
  "types": "./index.d.ts",
6
6
  "exports": {
@@ -10,15 +10,15 @@
10
10
  }
11
11
  },
12
12
  "dependencies": {
13
- "@telia-ace/knowledge-data-client": "^1.3.59",
14
- "@telia-ace/knowledge-widget-adapters": "^1.3.59",
15
- "@telia-ace/knowledge-widget-core": "^1.3.59",
16
- "@telia-ace/knowledge-widget-ui": "^1.3.59",
17
- "@telia-ace/widget-conversation": "^1.3.59",
18
- "@telia-ace/widget-core": "^1.3.59",
19
- "@telia-ace/widget-forms": "^1.3.59",
20
- "@telia-ace/widget-services": "^1.3.59",
21
- "@telia-ace/widget-utilities": "^1.3.59",
13
+ "@telia-ace/knowledge-data-client": "^1.3.60-rc.0",
14
+ "@telia-ace/knowledge-widget-adapters": "^1.3.60-rc.0",
15
+ "@telia-ace/knowledge-widget-core": "^1.3.60-rc.0",
16
+ "@telia-ace/knowledge-widget-ui": "^1.3.60-rc.0",
17
+ "@telia-ace/widget-conversation": "^1.3.60-rc.0",
18
+ "@telia-ace/widget-core": "^1.3.60-rc.0",
19
+ "@telia-ace/widget-forms": "^1.3.60-rc.0",
20
+ "@telia-ace/widget-services": "^1.3.60-rc.0",
21
+ "@telia-ace/widget-utilities": "^1.3.60-rc.0",
22
22
  "@webprovisions/platform": "^1.1.4"
23
23
  },
24
24
  "peerDependencies": {
package/plugin.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { Container } from '@webprovisions/platform';
2
-
3
2
  /**
4
3
  * Plugin for communicating with Webconnector API 1.0 in Conversational Hub.
5
4
  */
package/store.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Container } from '@webprovisions/platform';
2
2
  import { GlobalState, LooseObject, ServerEntry } from './types';
3
-
4
3
  type MetaData = {
5
4
  agent: {
6
5
  name: string;
package/types.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { ConversationMessageListItemType } from '../../../conversation/src/index.ts';
2
-
1
+ import { ConversationMessageListItemType } from '@telia-ace/widget-conversation';
3
2
  export type AgentResponse = {
4
3
  language: string;
5
4
  type: string;
@@ -1,6 +1,5 @@
1
1
  import { default as React } from 'react';
2
2
  import { ActionItem } from '../types';
3
-
4
3
  type Props = {
5
4
  actions: ActionItem[];
6
5
  contactMethodIds?: string[];
@@ -1,5 +1,4 @@
1
1
  import { default as React } from 'react';
2
-
3
2
  type Props = {
4
3
  contactMethodId: string;
5
4
  groupId: string;
package/utils.d.ts CHANGED
@@ -1,9 +1,8 @@
1
- import { ContactMethodType } from '../../../knowledge/adapters/src/index.ts';
2
- import { ConversationMessageListItemType } from '../../../conversation/src/index.ts';
1
+ import { ContactMethodType } from '@telia-ace/knowledge-widget-adapters';
2
+ import { ConversationMessageListItemType } from '@telia-ace/widget-conversation';
3
3
  import { Container } from '@webprovisions/platform';
4
- import { ComponentNodeController } from '../../../core/src/index.ts';
4
+ import { ComponentNodeController } from '@telia-ace/widget-core';
5
5
  import { CustomMessageTypes, MessageGroup, MessageGroupItem, ServerEntry } from './types';
6
-
7
6
  export declare const createGroup: ({ isUser, items, meta, }: {
8
7
  isUser: boolean;
9
8
  items?: Partial<MessageGroupItem>[];
package/index-CqXeCBbx.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";var ft=Object.defineProperty;var bt=(t,n,o)=>n in t?ft(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o;var T=(t,n,o)=>bt(t,typeof n!="symbol"?n+"":n,o);const P=require("@telia-ace/widget-conversation"),R=require("@telia-ace/widget-services"),A=require("@telia-ace/widget-utilities"),D=require("@telia-ace/widget-forms"),yt=require("@webprovisions/platform");class vt{constructor(n){T(this,"enabled",!0);T(this,"botProviderGlobalStateKey","bot-provider-global-state");T(this,"botProviderLocalStateKey","bot-provider-local-state");T(this,"botProviderEntriesKey","bot-provider-entries");T(this,"botProviderMetaStateKey","bot-provider-conversation-meta");this.container=n}getKey(n){let o;switch(n){case"localState":o=this.botProviderLocalStateKey;break;case"globalState":o=this.botProviderGlobalStateKey;break;case"entries":o=this.botProviderEntriesKey;break;case"meta":o=this.botProviderMetaStateKey;break}return o}async read(n){const o=this.getKey(n);if(!(!this.enabled||!o))return R.readStorage(this.container,o)}async write(n,o){const e=this.getKey(o);if(!this.enabled||!e)return;(await R.createStorageWriter(this.container,e,R.StorageCategory.Necessary))(n)}}var M=(t=>(t.ContactMethod="ace-conversational-hub-contact-method",t.ContactList="ace-conversational-hub-contact-list",t))(M||{});const St=t=>{if(t){const{type:n,content:o}=t;if(n&&o)return{type:n,content:o}}},wt=({isUser:t,items:n=[],meta:o={}})=>{const e=A.uuid();return{id:e,isUser:t,items:n.map(f=>({id:f.id||A.uuid(),isUser:t,groupId:e,message:f.message||[]})),meta:o}},$t=({id:t,title:n,defaultIcon:o,exits:[e],exitType:i,confirmationText:f,expandFormAutomatically:c,form:v,description:d},s={})=>{const{adapter:a}=e||{},{clientName:h="",settings:S={},customClientName:b=""}=a,{validation:m}=s,g={id:t.toString(),title:n,description:d,symbol:St(o),clientName:h==="custom.adapter"?b:h,expanded:!0,inline:!0,body:{}};if(h.indexOf("phone")>-1||h.indexOf("freetext")>-1){const{displayTextBeforeClick:y,textBeforeClick:L}=S;y==="true"&&(g.expanded=!1,g.title=L),h.indexOf("phone.text")>-1?g.body.phoneNumber=S.phoneNumber:g.body.freetext=S.freetext}return(h.indexOf("chat.popup")>-1||h.indexOf("link")>-1||h==="custom.adapter"&&i==="custom")&&(g.body=S,g.body.confirmationFallback=f),h.indexOf("ace")>-1&&(g.body=S),v&&v.hasValueComponents&&(m?g.body.form=D.FormBuilder.fromLegacyForm(t.toString(),v,m).get():g.body.form=D.FormBuilder.fromLegacyForm(t.toString(),v).get(),c||(g.expanded=g.inline=!1),g.body=ct(g,{submit:"Submit"})),s.guideId&&(g.body.guideId=s.guideId),g},Ct=t=>{const{localState:n}=t;return t.tags.includes("category")&&t.tags.includes("contact")?P.ConversationMessageListItemType.ItemList:t.tags.includes("suggestion")?P.ConversationMessageListItemType.LinkList:(n==null?void 0:n.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"?M.ContactList:P.ConversationMessageListItemType.ButtonList},ct=(t,{submit:n,errors:o,meta:e})=>{var i;if((i=t==null?void 0:t.body)!=null&&i.form){const{body:f}=t,c=new D.FormBuilder(f.form);return f.form.layout.submit||c.createComponent(D.submitButton(n,"submit")),o&&c.setValidationErrors(o),e&&c.setMeta(e),{...f,form:c.get()}}return(t==null?void 0:t.body)||{}},It=async(t,n,o)=>{(await(await t.getAsync("dataClient")).getClient()).parameters.set(n,o)},N=({messageId:t,message:n,group:o})=>({id:t,message:n,groupId:o.id,isUser:o.isUser}),Et=async(t,n,o)=>{const e=(s,a,h,S={actions:[],entryId:a.id,groupId:h})=>{const b=[];return S.actions=a.content.items.map(m=>{var y;const g={label:m.title,actionKey:m.actionKey,symbol:m.symbol?m.symbol:void 0,description:m.description||void 0};if(m.data){const L=a.actions[m.actionKey];s===M.ContactList?(b.push(m.data.id),g.data=$t(m.data,{guideId:(y=L==null?void 0:L.guideId)==null?void 0:y.toString()})):g.data=m.data}return g}),s===M.ContactList&&(S.contactMethodIds=b),S},i=async(s,a,h=[],S)=>{var m,g;const b=A.uuid();switch(s.type!=="List"&&s.tags.includes("guide")&&((g=(m=s.content.hints)==null?void 0:m[0])!=null&&g.id)&&await It(t,"LastGuideId",s.content.hints[0].id),s.type){case"List":{if(!s.content)return[];const{items:y,html:L}=s.content,_=[];let E={actions:[],entryId:s.id,groupId:a.id};if((y==null?void 0:y.length)>0){const O=Ct(s);if(E=e(O,s,a.id,E),h.length){const x=h.find(K=>K.tags.includes("paging"));x!=null&&x.content&&(a.meta.paging={actions:x.actions,items:x.content.items,localState:x.localState},x.content.items.forEach(K=>{E.actions.push({label:K.title,actionKey:K.actionKey,data:{groupId:S?S.id:a.id}})}))}_.unshift(N({messageId:b,message:[O,E],group:a}))}return L&&_.unshift(N({messageId:b,message:[P.ConversationMessageListItemType.HTML,{body:L}],group:a})),_}case"Text":{const y=[];if(y.push(N({messageId:b,message:[P.ConversationMessageListItemType.HTML,{body:s.content.html}],group:a})),h.length){const L=h.find(E=>{var O;return E.type==="List"&&((O=E.localState)==null?void 0:O.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"}),_=h.find(E=>E.tags.includes("contact")&&E.type==="Contact");if(_&&y.push(N({messageId:b,message:[M.ContactMethod,{contactMethodId:_.content.id,groupId:a.id,guideId:_.content.guideId}],group:a})),L){const E=e(M.ContactList,L,a.id);y.push(N({messageId:b,message:[P.ConversationMessageListItemType.Separator,void 0],group:a})),y.push(N({messageId:b,message:[M.ContactList,E],group:a}))}}return y}case"Contact":return[N({messageId:b,message:[M.ContactMethod,{contactMethodId:s.content.id,groupId:a.id,guideId:s.content.guideId}],group:a})];case"Error":return[N({messageId:b,message:[P.ConversationMessageListItemType.HTML,{body:s.content.message||"Something went wrong."}],group:a})];default:return[]}},f=new Map([["Text",1],["List",2],["Contact",3]]),c=[],v=n.sort((s,a)=>{const S=f.get(s.type)||20,b=f.get(a.type)||20;return S-b}).filter(s=>!s.relation).reduce((s,a)=>s.concat(a),[]),d=s=>typeof s.actions.selector<"u";for(const s of v){const a=n.filter(b=>b.relation===s.id&&!d(b)),h=wt({isUser:!1});(await i(s,h,a,o)).forEach(b=>{h.items.push(b)}),h.items.length&&c.push(h)}return c};class Lt{constructor(n,o,e,i){T(this,"globalState");T(this,"localState");T(this,"clientId");T(this,"entries");this.endpoint=n,this.events=o,this.store=e,this.container=i,this.clientId=A.uuid(),this.entries=[]}async fetchGuide(n){const o={command:{guide:{id:n}},globalState:this.globalState,clientId:this.clientId};return await this.postEnvelope(o)}async postEnvelope(n,o){try{const e=await fetch(this.endpoint,this.getHttpOptions(n));if(!e.ok)throw e;const i=await e.json();return this.handleResponse(i,o)}catch(e){process.env.NODE_ENV!=="production"&&console.warn("Something went wrong when posting the envelope.");let i="Something went wrong";return(e.message==="Failed to fetch"||e.message==="NetworkError when attempting to fetch resource.")&&(i="Lost connection... Please try again."),this.events.dispatch("tracking:http-client-error",{message:i,error:e}),this.handleResponse({entries:[{id:A.uuid(),type:"Error",timestamp:new Date().toISOString(),content:{message:i},actions:{},tags:[]}]})}}async handleResponse(n,o){this.entries=this.entries.concat(n.entries),this.store.write(this.entries,"entries");const e=n.entries.find(f=>f.type==="Widget");return e&&this.events.dispatch("provider:widget-entry",e.content),n.globalState&&(this.globalState=n.globalState,this.store.write(n.globalState,"globalState")),this.localState=n.entries.reduce((f,c)=>c.localState?c.localState:f,void 0),this.store.write(this.localState,"localState"),await Et(this.container,n.entries,o)}getHttpOptions(n){const o={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};return n.funnel=this.container.get("$widget").name,n.localState=n.localState||this.localState,Object.assign({},o,{body:JSON.stringify(n),credentials:"same-origin"})}}const lt=/^(?:https?:|mailto:|tel:)/i,ot=["_blank","_self","_parent","_top"],xt=/\uE000(\d+)\uE001/g,st="",kt=/[\uE000-\uE002]/g,q="A-Za-z0-9_\\u00C0-\\u024F",dt=/^ {0,3}(`{3,}|~{3,})/,gt=/^ {0,3}(#{1,6})[ \t]+(.*?)(?:[ \t]+#+)?[ \t]*$/,z=/^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/,F=/^ {0,3}&gt; ?/,U=/^( *)([-*+]|\d{1,9}[.)])(?:[ \t]+(.*))?$/,_t=/^ *\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/,V=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),it=(t,n)=>{const o=new RegExp(`(?:^|\\s)${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+))`,"i").exec(t);return o?o[1]??o[2]??o[3]:void 0},G=t=>t.length-t.trimStart().length,rt=t=>/\d/.test(t),at=t=>t.replace(/\*\*\*(?=\S)(.*?\S)\*\*\*/g,"<strong><em>$1</em></strong>").replace(/\*\*(?=\S)(.*?\S)\*\*/g,"<strong>$1</strong>").replace(new RegExp(`(^|[^${q}])__(?=\\S)(.*?\\S)__(?![${q}])`,"g"),"$1<strong>$2</strong>").replace(/~~(?=\S)(.*?\S)~~/g,"<del>$1</del>").replace(/\*(?=\S)(.*?\S)\*/g,"<em>$1</em>").replace(new RegExp(`(^|[^${q}])_(?=\\S)(.*?\\S)_(?![${q}])`,"g"),"$1<em>$2</em>"),J=(t,n)=>at(t.replace(/(`+)(.+?)\1(?!`)/g,(o,e,i)=>n.store(`<code>${i.trim()}</code>`)).replace(/\\([\\`*_{}[\]()#+\-.!|~])/g,(o,e)=>n.store(e)).replace(/&lt;((?:https?:|mailto:)\S+?)&gt;/gi,(o,e)=>n.link(e,e)).replace(/!?\[([^\]\n]+)\]\(\s*([^\s)]+)(?:\s+&quot;.*?&quot;)?\s*\)/g,(o,e,i)=>lt.test(i)?n.link(i,at(e)):e)),ut=(t,n)=>t[n].includes("|")&&n+1<t.length&&t[n+1].includes("|")&&_t.test(t[n+1]),ht=(t,n)=>dt.test(t[n])||gt.test(t[n])||z.test(t[n])||F.test(t[n])||U.test(t[n])||ut(t,n),W=t=>t.replace(/\\\|/g,st).trim().replace(/^\||\|$/g,"").split("|").map(n=>n.split(st).join("\\|").trim()),Tt=(t,n,o)=>{const e=W(t[n]),i=W(t[n+1]).map(s=>s.startsWith(":")&&s.endsWith(":")?"center":s.endsWith(":")?"right":s.startsWith(":")?"left":""),f=(s,a)=>`<tr>${e.map((h,S)=>{const b=i[S]?` style="text-align: ${i[S]}"`:"";return`<${a}${b}>${J(s[S]??"",o)}</${a}>`}).join("")}</tr>`,c=[];let v=n+2;for(;v<t.length&&t[v].trim()&&t[v].includes("|");)c.push(f(W(t[v]),"td")),v++;const d=c.length?`<tbody>${c.join("")}</tbody>`:"";return[`<table><thead>${f(e,"th")}</thead>${d}</table>`,v]},Mt=(t,n,o)=>{const e=U.exec(t[n]),i=e[1].length,f=rt(e[2]),c=[];let v=0;const d=m=>{const g=U.exec(m);return g&&g[1].length<=i+1&&rt(g[2])===f&&!z.test(m)?g:null};let s=n;for(;s<t.length;){const m=t[s],g=d(m);if(g){const y=g[3]??"";v=y?m.length-y.length:g[1].length+g[2].length+1,c.push([y])}else if(m.trim())if(G(m)>i+1)c[c.length-1].push(m.slice(Math.min(G(m),v)));else{if(ht(t,s))break;c[c.length-1].push(m.trimStart())}else{let y=s+1;for(;y<t.length&&!t[y].trim();)y++;if(y>=t.length||G(t[y])<=i+1&&!d(t[y]))break;c[c.length-1].push("")}s++}const a=f?"ol":"ul",h=parseInt(e[2],10),S=f&&h!==1?` start="${h}"`:"",b=c.map(m=>`<li>${Q(m,o).replace(/^<p>([\s\S]*?)<\/p>/,"$1")}</li>`).join("");return[`<${a}${S}>${b}</${a}>`,s]},Q=(t,n)=>{const o=[];let e=0;for(;e<t.length;){const i=t[e];if(!i.trim()){e++;continue}const f=dt.exec(i);if(f){const d=[];for(e++;e<t.length&&!t[e].trimStart().startsWith(f[1]);)d.push(t[e]),e++;e++,o.push(`<pre><code>${d.join(`
2
- `)}</code></pre>`);continue}const c=gt.exec(i);if(c){const d=Math.min(c[1].length+2,6);o.push(`<h${d}>${J(c[2],n)}</h${d}>`),e++;continue}if(z.test(i)){o.push("<hr>"),e++;continue}if(F.test(i)){const d=[];for(;e<t.length&&F.test(t[e]);)d.push(t[e].replace(F,"")),e++;o.push(`<blockquote>${Q(d,n)}</blockquote>`);continue}if(ut(t,e)){const[d,s]=Tt(t,e,n);o.push(d),e=s;continue}if(U.test(i)){const[d,s]=Mt(t,e,n);o.push(d),e=s;continue}const v=[i.trim()];for(e++;e<t.length&&t[e].trim()&&!ht(t,e);)v.push(t[e].trim()),e++;o.push(`<p>${J(v.join(`
3
- `),n).replace(/\n/g,"<br>")}</p>`)}return o.join("")},Pt=(t,n={})=>{const o=n.linkTarget&&ot.includes(n.linkTarget)?n.linkTarget:"_blank",e=[],i={store:d=>`${e.push(d)-1}`,link:(d,s,a=o)=>i.store(`<a href="${d}" target="${a}" rel="noopener noreferrer">${s}</a>`)},f=t.replace(kt,"").replace(/\r\n?/g,`
4
- `).replace(/<a\s([^>]*)>([\s\S]*?)<\/a\s*>/gi,(d,s,a)=>{var m;const h=(m=it(s,"href"))==null?void 0:m.trim().replace(/&amp;/g,"&"),S=it(s,"target"),b=V(a);return!h||!lt.test(h)?i.store(b):i.link(V(h),b,S&&ot.includes(S)?S:o)}),c=V(f).split(`
5
- `).map(d=>d.replace(/^\t+/,s=>" ".repeat(s.length)));let v=Q(c,i);for(;v.includes("");)v=v.replace(xt,(d,s)=>e[+s]);return v},Ot="@telia-ace/conversational-hub-bot-provider",At="0.0.16",H={name:Ot,version:At},Nt=async t=>{var Z,X,Y,tt,et;const n="chub-plugin",o=t.get("$widget"),e=(et=(tt=(Y=(X=(Z=o==null?void 0:o.container)==null?void 0:Z.get("$settings"))==null?void 0:X.components)==null?void 0:Y.conversation)==null?void 0:tt.properties)==null?void 0:et.conversationalHubPluginSettings;let i,f,c,v=(e==null?void 0:e.connectionAttempts)??5,d,s,a;A.Logger.info((H==null?void 0:H.name)+" version: "+(H==null?void 0:H.version)),P.registerCustomMessageComponent(t,M.ContactMethod,Promise.resolve().then(()=>require("./contact-method-BVsnE2Mg.js"))),P.registerCustomMessageComponent(t,M.ContactList,Promise.resolve().then(()=>require("./contact-method-list-DFpz_Bo3.js")));const h=await R.createStorageWriter(t,"conversational-hub-session",R.StorageCategory.Necessary),S=(u,l)=>{const{knowledgeBotEndpoint:r}=l.properties();if(r)return`${r}/conversations`;const{data:p}=u.get("$settings");if(!p||!p.projection)throw new Error("Missing Knowledge Bot endpoint");return`${p.projection}/conversations`},b=u=>{var l;if(u.target instanceof HTMLButtonElement){const r=u.target;if((l=r.getAttribute("class"))!=null&&l.includes("dialog-option-cx")){const p=r.getAttribute("value");O(p),i.user.print(p.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}}};(await P.ConversationPlatform.getInstance(t)).registerProvider(n,(u,l)=>{i=u,f=i.controller,c=i.createAgent({name:e==null?void 0:e.botName,avatar:e==null?void 0:e.avatar}),a=S(t,l);const{events:r}=t.get("$widget"),p=new vt(t);s=new Lt(a,r,p,t),_();const[w]=t.get("widgetDOMElements");w.querySelectorAll(".humany-bot-contact-method").forEach(C=>{var $;($=C.closest(".humany-conversation-entry"))==null||$.remove()}),w.removeEventListener("click",b),w.addEventListener("click",b);const I=()=>f.providers.includes(n);l.actions.create("submit",C=>{const{events:$}=t.get("$widget");$.dispatch("conversational-hub-provider:form-submitted",C)}),l.actions.create("evaluate",C=>{const{events:$}=t.get("$widget");$.dispatch("conversational-hub-provider:evaluate",C)}),l.actions.watch("conversation.action",(C,$)=>(I()&&E(C),$(C))),l.actions.watch("conversation.user-submit",(C,$)=>{if(!I())return $(C);O(C.text),i.user.print(C.text.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}),o.events.subscribe("conversational-hub-provider:fetch-guide",async(C,$)=>{if(!($!=null&&$.guideId))return;const B=await s.fetchGuide(parseInt($.guideId));B&&g(B)})});async function g(u){u.forEach(l=>{const r=l.items.map(p=>p.message);l.writer=c.print(r)})}const y=sessionStorage.getItem(`humany_${L(o.implementation.tenant+o.implementation.name+o.name)}`);function L(u){let l=0;if(u.length===0)return l.toString();for(let r=0;r<u.length;r++){const p=u.charCodeAt(r);l=(l<<5)-l+p,l=l&l}return l.toString()}async function _(u=!0){const l=await R.readStorage(t,"conversational-hub-session"),r=t.get("dialogflowSettings");if(r!=null&&r.silentStart)delete r.silentStart,o.events.dispatch("conversational-hub-provider:started",{});else if(l!=null&&l.sessionId&&u)d=l==null?void 0:l.sessionId;else if(e!=null&&e.welcomeMessage){if(!(y!=null&&y.length?JSON.parse(y):{})["conversation-conversation"]){const w=e.welcomeMessage.replaceAll("$lt;","<").replaceAll("$gt;",">");c.print(w)}}else{const p={extension:e.extension};r!=null&&r.initCommand&&(p.input={type:"event",language:e.language,content:{name:r.initCommand,parameters:r.initParameters||{}}}),await x(e.baseUrl+"/initialize",JSON.stringify(p),u)}}async function E(u){await x(`${e.baseUrl}/input/${d}`,`{"type":"button_click","language":"${e.language}","content":{"button_text":"${u.label}","value":"${u.actionKey}"}}`)}async function O(u){const l={text:u};if(!d){const r={extension:e.extension},p=t.get("dialogflowSettings");p!=null&&p.initCommand&&(r.input={type:"event",language:e.language,content:{name:p.initCommand,parameters:p.initParameters||{}}}),await x(e.baseUrl+"/initialize",JSON.stringify(r),!1)}await x(`${e.baseUrl}/input/${d}`,`{"type":"text","language":"${e.language}","content":${JSON.stringify(l)}}`)}async function x(u,l,r=!0){var C,$,B,nt;const p=i.loading();let w,I;try{w=await fetch(u,{method:"POST",body:l}),I=await(w==null?void 0:w.json())}catch(j){j instanceof SyntaxError?A.Logger.error("Incorrect JSON format.",j):A.Logger.error("Network error: check connection or baseUrl.",j),p(),c.print(e.errorMessage||"An error occurred");return}if(!(w!=null&&w.ok)){if(A.Logger.error(`HTTP ${w==null?void 0:w.status}.`,JSON.stringify(I)),p(),!!((C=I==null?void 0:I.errors)!=null&&C.filter(k=>k.code==="1003").length)&&v>0){v--,await new Promise(pt=>setTimeout(pt,500)),await _(!1);const k=JSON.parse(l);($=k==null?void 0:k.content)!=null&&$.text?await O(k.content.text):(B=k==null?void 0:k.content)!=null&&B.action&&await E((nt=k==null?void 0:k.content)==null?void 0:nt.action)}else c.print(e.errorMessage||"An error occurred");return}p(),v=(e==null?void 0:e.connectionAttempts)??5,I!=null&&I.action_payload&&K(I.action_payload),d=I==null?void 0:I.session_id,h({sessionId:d}),r&&mt(I)}async function K(u){var w;const l=(w=u==null?void 0:u.transfer_parameters)==null?void 0:w.contactGuide,r=i.loading(),p=await s.fetchGuide(parseInt(l));r(),p&&g(p)}function mt(u){var l;u==null||u.agent_response.forEach(r=>{c.print(e!=null&&e.markdown&&r.type==="text"?Pt(r.payload.text,{linkTarget:e==null?void 0:e.linkTarget}):r.payload.text)}),(l=u==null?void 0:u.prompt)!=null&&l.items&&c.print(["button-list",{actions:u.prompt.items.map(r=>{let p;return r.type==="button"&&(p={actionKey:r.value,label:r.text}),r.type==="link"&&(p={actionKey:r.value,label:r.text,data:{href:r.url,target:(e==null?void 0:e.linkTarget)??"_blank"}}),p})}])}},Kt=yt.createConfigurationApi(t=>{t.createCommand("dialogflow",n=>o=>{const e={initCommand:o.initCommand};o.initParameters&&(e.initParameters=o.initParameters),o.silentStart&&(e.silentStart=o.silentStart),n.container.register("dialogflowSettings",e)})});exports.ConversationalHubPlugin=Nt;exports.dialogflowConfigurationApi=Kt;exports.updateForm=ct;