@iai-lib/any-chat-widget 0.1.0-alpha.41 → 0.1.0-alpha.42
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.
|
@@ -4541,7 +4541,7 @@ Zn([
|
|
|
4541
4541
|
Nt = Zn([
|
|
4542
4542
|
qe("iai-chat-popup")
|
|
4543
4543
|
], Nt);
|
|
4544
|
-
const Os = "https://api
|
|
4544
|
+
const Os = "https://api.ai.inhabit.services";
|
|
4545
4545
|
async function $l(s, e = {}) {
|
|
4546
4546
|
const t = await fetch(`${Os}/threads`, {
|
|
4547
4547
|
method: "POST",
|
|
@@ -8265,8 +8265,8 @@ var xs;
|
|
|
8265
8265
|
})(s.ConversationStatus || (s.ConversationStatus = {}));
|
|
8266
8266
|
})(xs || (xs = {}));
|
|
8267
8267
|
const Hc = xs.AcknowledgeType, Uc = "Anyone Home", Bc = "IB Chat Leasing - Development";
|
|
8268
|
-
let Wc = "https://five9.ah.inhabit.
|
|
8269
|
-
const Vc = "https://five9.ah.inhabit.
|
|
8268
|
+
let Wc = "https://five9.ah.inhabit.service";
|
|
8269
|
+
const Vc = "https://five9.ah.inhabit.service".replace("http", "ws").replace(/\/$/, "");
|
|
8270
8270
|
var Be, xt;
|
|
8271
8271
|
const mn = class mn {
|
|
8272
8272
|
constructor() {
|
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
/>
|
|
158
158
|
</div>
|
|
159
159
|
</div>
|
|
160
|
-
`}toggleChat(){this.isOpen=!this.isOpen,this.onResizeHandler()}};Nt.styles=[Be],Rn([ne({type:Object})],Nt.prototype,"options",2),Rn([wt()],Nt.prototype,"isOpen",2),Rn([ns("iai-chat")],Nt.prototype,"chatWindow",2),Rn([ei.debounce(250)],Nt.prototype,"onResizeHandler",2),Nt=Rn([He("iai-chat-popup")],Nt);const _s="https://api-dev.ai.inhabit.work";async function wl(s,e={}){const t=await fetch(`${_s}/threads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({assistantId:s,params:e})});if(!t.ok)throw new Error(`Failed to create thread: ${t.statusText} (${t.status})`);return t.json()}async function _l(s,e="No reason provided"){const t=await fetch(`${_s}/threads/${s}/end`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e})});if(!t.ok)throw new Error(`Failed to end thread: ${t.statusText} (${t.status})`)}async function xl(s,e){const t=await fetch(`${_s}/threads/${s}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:e})});if(!t.ok)throw new Error(`Failed to send message: ${t.statusText} (${t.status})`);return t.json()}async function kl(s,e,t,n=!1){const i=await fetch(`${_s}/threads/${s}/functions/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:t,rerunLLM:n})});if(!i.ok)throw new Error(`Failed to respond to function call: ${i.statusText} (${i.status})`);return i.json()}function $l(s){return{all:s=s||new Map,on:function(e,t){var n=s.get(e);n?n.push(t):s.set(e,[t])},off:function(e,t){var n=s.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var n=s.get(e);n&&n.slice().map(function(i){i(t)}),(n=s.get("*"))&&n.slice().map(function(i){i(e,t)})}}}class Al{constructor(e,t={}){if(this._assistantId="",this._conversationDetails=null,this._messages=[],this.isTyping=!1,this.inputDisabled=!1,this.chatEndingWarningSent=!1,this.chatEnded=!1,this.onStorageEvent=n=>{var i;const[r,a,o]=((i=n.key)==null?void 0:i.split("-"))||[];if(!(r!=="iaiChat"||a!==this.options.historyKey))switch(o){case"messageHistory":this.onMessageHistoryStorageEvent(n);break;case"conversation":this.setConversationDetails(JSON.parse(n.newValue||"null"),!0);break;case"lastActivity":this.keepAlive(JSON.parse(n.newValue||"null"),!0);break;case"chatEndingWarningSent":this.setChatEndingWarningSent(JSON.parse(n.newValue||"false"),!0);break;case"chatEnded":this.setChatEnded(JSON.parse(n.newValue||"false"),!0);break;case"typing":this.setTyping(JSON.parse(n.newValue||"false"),!0);break;case"inputDisabled":this.setInputDisabled(JSON.parse(n.newValue||"false"),!0);break}},this._assistantId=e,this.options={params:{},simulateDelays:!1,resetEndedChatOnLoad:!1,historyKey:"main",...t},this._emitter=$l(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),t.events&&Object.entries(t.events).forEach(([n,i])=>{this._emitter.on(n,i)}),t.historyKey){this._messages=this.storageGet("messageHistory",[]);const n=this.storageGet("conversation");n&&this.setConversationDetails(n,!0);const i=this.storageGet("chatEndingWarningSent");i&&this.setChatEndingWarningSent(i,!0);const r=this.storageGet("chatEnded");r&&this.setChatEnded(r,!0);const a=this.storageGet("typing");a&&this.setTyping(a,!0);const o=this.storageGet("inputDisabled");o&&this.setInputDisabled(o,!0);const l=this.storageGet("lastActivity");l&&setTimeout(()=>this.keepAlive(l,!0),0),setTimeout(()=>{this.chatEnded&&this.options.resetEndedChatOnLoad&&this.reset()},0),window.addEventListener("storage",this.onStorageEvent)}}onMessageHistoryStorageEvent(e){if(!e.newValue){this.reset();return}const t=JSON.parse(e.newValue),n=this._messages.map(r=>r.id),i=t.map(r=>r.id);this._messages.forEach(r=>{i.includes(r.id)||this._emitter.emit("messageRemoved",r.id)}),t.forEach(r=>{n.includes(r.id)||this._emitter.emit("message",r)}),this._messages=t}async endChat(e,t=!0){!this.threadId||this.chatEnded||(t&&(this._emitter.emit("chatEnded"),this.setChatEnded(!0)),this.stopInactivityTimers(),await _l(this.threadId,e))}reset(e){this.endChat(e,!1).then(()=>{}),this._messages=[],this.setConversationDetails(null),this.setTyping(!1),this.setInputDisabled(!1),this.setChatEnded(!1),this.stopInactivityTimers(),this.storageRemoveAll(),this._emitter.emit("reset")}destroy(){this._emitter.all.clear(),window.removeEventListener("storage",this.onStorageEvent),this.stopInactivityTimers(),this._emitter.emit("destroy")}stopInactivityTimers(){this._inactivityTimeout&&(clearTimeout(this._inactivityTimeout),this._inactivityTimeout=null),this._inactivityWarningTimeout&&(clearTimeout(this._inactivityWarningTimeout),this._inactivityWarningTimeout=null)}keepAlive(e=Date.now(),t=!1){if(this.stopInactivityTimers(),this.chatEnded||!e)return;const{timeUntilChatEnds:n,timeUntilWarnAboutChatEnding:i}=this;if(!n)return;t||this.storageSet("lastActivity",e);const r=Date.now()-e;r>n?(this.chatEnded||this._emitter.emit("chatEnded"),this.setChatEnded(!0)):r>i?(this.sendChatEndingWarning(),this._inactivityTimeout=setTimeout(()=>{this.chatEnded||this._emitter.emit("chatEnded"),this.setChatEnded(!0)},n-r)):(this.setChatEndingWarningSent(!1),this._inactivityWarningTimeout=setTimeout(()=>this.sendChatEndingWarning(),i-r),this._inactivityTimeout=setTimeout(()=>{this.chatEnded||this._emitter.emit("chatEnded"),this.setChatEnded(!0)},n-r))}async startChat(){if(this.chatStarted)return;const{id:e,inactivityWaitTime:t,inactivityWarningTime:n}=await wl(this.assistantId,this.params);if(!e)throw new Error("Could not start chat");this.setConversationDetails({threadId:e,inactivityWaitTime:t,inactivityWarningTime:n})}addMessage(e){const t={...e,id:e.id||Math.random().toString(36).substring(7)};return this._messages.push(t),this.storageSet("messageHistory",this._messages),this._emitter.emit("message",t),t}removeMessage(e){this._messages=this._messages.filter(t=>t.id!==e),this.storageSet("messageHistory",this._messages),this._emitter.emit("messageRemoved",e)}async respondToFunctionCall(e,t,n){if(!this.threadId)throw new Error("Thread not started");try{this.simulateDelay(1800).then(()=>this.setTyping(!0));const i=this.simulateDelay(2e3);this.keepAlive(),await this.insertMessagesWithSimulatedDelays(Promise.all([kl(this.threadId,e,t,n),i]).then(([r])=>r))}catch(i){this.addMessage({role:"assistant",content:"There was an unexpected error. Please try again later."}),this.setTyping(!1),console.error("Error sending message:",i)}}async sendUserMessage(e){try{this.addMessage({role:"user",content:e}),this.simulateDelay(1800).then(()=>this.setTyping(!0));let t=this.simulateDelay(4800);if(!this.chatStarted){const{initialReplyMessage:r}=this.options;r&&(this.simulateDelay(3800).then(()=>{this.addMessage({role:"assistant",content:r}),this.setTyping(!1)}),this.simulateDelay(6200).then(()=>this.setTyping(!0)),t=this.simulateDelay(8200)),await this.startChat()}this.keepAlive();const{messages:n,functions:i}=await this.insertMessagesWithSimulatedDelays(Promise.all([xl(this.threadId,e),t]).then(([r])=>r));return{messages:n,functions:i}}catch(t){this.addMessage({role:"assistant",content:"There was an unexpected error. Please try again later."}),this.setTyping(!1),console.error("Error sending message:",t)}}setTyping(e,t=!1){this.isTyping=e,this._emitter.emit("typing",e),t||this.storageSet("typing",e)}setConversationDetails(e,t=!1){this._conversationDetails=e,t||this.storageSet("conversation",e)}setInputDisabled(e,t=!1){this.inputDisabled=e,this._emitter.emit("inputDisabled",e),t||this.storageSet("inputDisabled",e)}setChatEnded(e,t=!1){this.chatEnded=e,t||this.storageSet("chatEnded",e)}setChatEndingWarningSent(e,t=!1){this.chatEndingWarningSent=e,t||this.storageSet("chatEndingWarningSent",e)}sendChatEndingWarning(){this.chatEndingWarningSent||(this._emitter.emit("inactivityWarning"),this.setChatEndingWarningSent(!0))}async insertMessagesWithSimulatedDelays(e){const t=await e,{messages:n,functions:i}=t;return await Promise.all(n.map(async(r,a)=>(await this.simulateDelay(1e3*a),this.addMessage(r)))),this.setTyping(!1),i.forEach(r=>this._emitter.emit("functionCall",r)),{messages:n,functions:i}}simulateDelay(e){return this.options.simulateDelays?new Promise(t=>{setTimeout(t,e)}):Promise.resolve()}get assistantId(){return this._assistantId}get params(){return this.options.params}get threadId(){var e;return(e=this._conversationDetails)==null?void 0:e.threadId}get timeUntilChatEnds(){const{inactivityWaitTime:e}=this._conversationDetails||{};return e?e*60*1e3:null}get timeUntilWarnAboutChatEnding(){const{inactivityWaitTime:e=0,inactivityWarningTime:t=0}=this._conversationDetails||{};return(e-t)*60*1e3}get messages(){return this._messages}get chatStarted(){return!!this.threadId}storageSet(e,t){this.options.historyKey&&localStorage.setItem(`iaiChat-${this.options.historyKey}-${e}`,JSON.stringify(t))}storageGet(e,t=null){if(!this.options.historyKey)return null;const n=localStorage.getItem(`iaiChat-${this.options.historyKey}-${e}`);return n?JSON.parse(n):t}storageRemove(e){localStorage.removeItem(`iaiChat-${this.options.historyKey}-${e}`)}storageRemoveAll(){this.options.historyKey&&Object.keys(localStorage).forEach(e=>{e.startsWith(`iaiChat-${this.options.historyKey}-`)&&localStorage.removeItem(e)})}}var Kr={exports:{}};(function(s,e){(function(t,n){s.exports=n()})($o,function(){var t=1e3,n=6e4,i=36e5,r="millisecond",a="second",o="minute",l="hour",d="day",u="week",h="month",c="quarter",f="year",A="date",V="Invalid Date",ae=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,ze=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,nn={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(M){var w=["th","st","nd","rd"],m=M%100;return"["+M+(w[(m-20)%10]||w[m]||w[0])+"]"}},lt=function(M,w,m){var $=String(M);return!$||$.length>=w?M:""+Array(w+1-$.length).join(m)+M},sn={s:lt,z:function(M){var w=-M.utcOffset(),m=Math.abs(w),$=Math.floor(m/60),v=m%60;return(w<=0?"+":"-")+lt($,2,"0")+":"+lt(v,2,"0")},m:function M(w,m){if(w.date()<m.date())return-M(m,w);var $=12*(m.year()-w.year())+(m.month()-w.month()),v=w.clone().add($,h),R=m-v<0,S=w.clone().add($+(R?-1:1),h);return+(-($+(m-v)/(R?v-S:S-v))||0)},a:function(M){return M<0?Math.ceil(M)||0:Math.floor(M)},p:function(M){return{M:h,y:f,w:u,d,D:A,h:l,m:o,s:a,ms:r,Q:c}[M]||String(M||"").toLowerCase().replace(/s$/,"")},u:function(M){return M===void 0}},Te="en",z={};z[Te]=nn;var Fn="$isDayjsObject",be=function(M){return M instanceof Dt||!(!M||!M[Fn])},ct=function M(w,m,$){var v;if(!w)return Te;if(typeof w=="string"){var R=w.toLowerCase();z[R]&&(v=R),m&&(z[R]=m,v=R);var S=w.split("-");if(!v&&S.length>1)return M(S[0])}else{var K=w.name;z[K]=w,v=K}return!$&&v&&(Te=v),v||!$&&Te},oe=function(M,w){if(be(M))return M.clone();var m=typeof w=="object"?w:{};return m.date=M,m.args=arguments,new Dt(m)},W=sn;W.l=ct,W.i=be,W.w=function(M,w){return oe(M,{locale:w.$L,utc:w.$u,x:w.$x,$offset:w.$offset})};var Dt=function(){function M(m){this.$L=ct(m.locale,null,!0),this.parse(m),this.$x=this.$x||m.x||{},this[Fn]=!0}var w=M.prototype;return w.parse=function(m){this.$d=function($){var v=$.date,R=$.utc;if(v===null)return new Date(NaN);if(W.u(v))return new Date;if(v instanceof Date)return new Date(v);if(typeof v=="string"&&!/Z$/i.test(v)){var S=v.match(ae);if(S){var K=S[2]-1||0,te=(S[7]||"0").substring(0,3);return R?new Date(Date.UTC(S[1],K,S[3]||1,S[4]||0,S[5]||0,S[6]||0,te)):new Date(S[1],K,S[3]||1,S[4]||0,S[5]||0,S[6]||0,te)}}return new Date(v)}(m),this.init()},w.init=function(){var m=this.$d;this.$y=m.getFullYear(),this.$M=m.getMonth(),this.$D=m.getDate(),this.$W=m.getDay(),this.$H=m.getHours(),this.$m=m.getMinutes(),this.$s=m.getSeconds(),this.$ms=m.getMilliseconds()},w.$utils=function(){return W},w.isValid=function(){return this.$d.toString()!==V},w.isSame=function(m,$){var v=oe(m);return this.startOf($)<=v&&v<=this.endOf($)},w.isAfter=function(m,$){return oe(m)<this.startOf($)},w.isBefore=function(m,$){return this.endOf($)<oe(m)},w.$g=function(m,$,v){return W.u(m)?this[$]:this.set(v,m)},w.unix=function(){return Math.floor(this.valueOf()/1e3)},w.valueOf=function(){return this.$d.getTime()},w.startOf=function(m,$){var v=this,R=!!W.u($)||$,S=W.p(m),K=function(De,pe){var Le=W.w(v.$u?Date.UTC(v.$y,pe,De):new Date(v.$y,pe,De),v);return R?Le:Le.endOf(d)},te=function(De,pe){return W.w(v.toDate()[De].apply(v.toDate("s"),(R?[0,0,0,0]:[23,59,59,999]).slice(pe)),v)},se=this.$W,le=this.$M,me=this.$D,dt="set"+(this.$u?"UTC":"");switch(S){case f:return R?K(1,0):K(31,11);case h:return R?K(1,le):K(0,le+1);case u:var qe=this.$locale().weekStart||0,Lt=(se<qe?se+7:se)-qe;return K(R?me-Lt:me+(6-Lt),le);case d:case A:return te(dt+"Hours",0);case l:return te(dt+"Minutes",1);case o:return te(dt+"Seconds",2);case a:return te(dt+"Milliseconds",3);default:return this.clone()}},w.endOf=function(m){return this.startOf(m,!1)},w.$set=function(m,$){var v,R=W.p(m),S="set"+(this.$u?"UTC":""),K=(v={},v[d]=S+"Date",v[A]=S+"Date",v[h]=S+"Month",v[f]=S+"FullYear",v[l]=S+"Hours",v[o]=S+"Minutes",v[a]=S+"Seconds",v[r]=S+"Milliseconds",v)[R],te=R===d?this.$D+($-this.$W):$;if(R===h||R===f){var se=this.clone().set(A,1);se.$d[K](te),se.init(),this.$d=se.set(A,Math.min(this.$D,se.daysInMonth())).$d}else K&&this.$d[K](te);return this.init(),this},w.set=function(m,$){return this.clone().$set(m,$)},w.get=function(m){return this[W.p(m)]()},w.add=function(m,$){var v,R=this;m=Number(m);var S=W.p($),K=function(le){var me=oe(R);return W.w(me.date(me.date()+Math.round(le*m)),R)};if(S===h)return this.set(h,this.$M+m);if(S===f)return this.set(f,this.$y+m);if(S===d)return K(1);if(S===u)return K(7);var te=(v={},v[o]=n,v[l]=i,v[a]=t,v)[S]||1,se=this.$d.getTime()+m*te;return W.w(se,this)},w.subtract=function(m,$){return this.add(-1*m,$)},w.format=function(m){var $=this,v=this.$locale();if(!this.isValid())return v.invalidDate||V;var R=m||"YYYY-MM-DDTHH:mm:ssZ",S=W.z(this),K=this.$H,te=this.$m,se=this.$M,le=v.weekdays,me=v.months,dt=v.meridiem,qe=function(pe,Le,Je,an){return pe&&(pe[Le]||pe($,R))||Je[Le].slice(0,an)},Lt=function(pe){return W.s(K%12||12,pe,"0")},De=dt||function(pe,Le,Je){var an=pe<12?"AM":"PM";return Je?an.toLowerCase():an};return R.replace(ze,function(pe,Le){return Le||function(Je){switch(Je){case"YY":return String($.$y).slice(-2);case"YYYY":return W.s($.$y,4,"0");case"M":return se+1;case"MM":return W.s(se+1,2,"0");case"MMM":return qe(v.monthsShort,se,me,3);case"MMMM":return qe(me,se);case"D":return $.$D;case"DD":return W.s($.$D,2,"0");case"d":return String($.$W);case"dd":return qe(v.weekdaysMin,$.$W,le,2);case"ddd":return qe(v.weekdaysShort,$.$W,le,3);case"dddd":return le[$.$W];case"H":return String(K);case"HH":return W.s(K,2,"0");case"h":return Lt(1);case"hh":return Lt(2);case"a":return De(K,te,!0);case"A":return De(K,te,!1);case"m":return String(te);case"mm":return W.s(te,2,"0");case"s":return String($.$s);case"ss":return W.s($.$s,2,"0");case"SSS":return W.s($.$ms,3,"0");case"Z":return S}return null}(pe)||S.replace(":","")})},w.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},w.diff=function(m,$,v){var R,S=this,K=W.p($),te=oe(m),se=(te.utcOffset()-this.utcOffset())*n,le=this-te,me=function(){return W.m(S,te)};switch(K){case f:R=me()/12;break;case h:R=me();break;case c:R=me()/3;break;case u:R=(le-se)/6048e5;break;case d:R=(le-se)/864e5;break;case l:R=le/i;break;case o:R=le/n;break;case a:R=le/t;break;default:R=le}return v?R:W.a(R)},w.daysInMonth=function(){return this.endOf(h).$D},w.$locale=function(){return z[this.$L]},w.locale=function(m,$){if(!m)return this.$L;var v=this.clone(),R=ct(m,$,!0);return R&&(v.$L=R),v},w.clone=function(){return W.w(this.$d,this)},w.toDate=function(){return new Date(this.valueOf())},w.toJSON=function(){return this.isValid()?this.toISOString():null},w.toISOString=function(){return this.$d.toISOString()},w.toString=function(){return this.$d.toUTCString()},M}(),rn=Dt.prototype;return oe.prototype=rn,[["$ms",r],["$s",a],["$m",o],["$H",l],["$W",d],["$M",h],["$y",f],["$D",A]].forEach(function(M){rn[M[1]]=function(w){return this.$g(w,M[0],M[1])}}),oe.extend=function(M,w){return M.$i||(M(w,Dt,oe),M.$i=!0),oe},oe.locale=ct,oe.isDayjs=be,oe.unix=function(M){return oe(1e3*M)},oe.en=z[Te],oe.Ls=z,oe.p={},oe})})(Kr);var Tl=Kr.exports;const qr=jr(Tl);/**
|
|
160
|
+
`}toggleChat(){this.isOpen=!this.isOpen,this.onResizeHandler()}};Nt.styles=[Be],Rn([ne({type:Object})],Nt.prototype,"options",2),Rn([wt()],Nt.prototype,"isOpen",2),Rn([ns("iai-chat")],Nt.prototype,"chatWindow",2),Rn([ei.debounce(250)],Nt.prototype,"onResizeHandler",2),Nt=Rn([He("iai-chat-popup")],Nt);const _s="https://api.ai.inhabit.services";async function wl(s,e={}){const t=await fetch(`${_s}/threads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({assistantId:s,params:e})});if(!t.ok)throw new Error(`Failed to create thread: ${t.statusText} (${t.status})`);return t.json()}async function _l(s,e="No reason provided"){const t=await fetch(`${_s}/threads/${s}/end`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:e})});if(!t.ok)throw new Error(`Failed to end thread: ${t.statusText} (${t.status})`)}async function xl(s,e){const t=await fetch(`${_s}/threads/${s}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:e})});if(!t.ok)throw new Error(`Failed to send message: ${t.statusText} (${t.status})`);return t.json()}async function kl(s,e,t,n=!1){const i=await fetch(`${_s}/threads/${s}/functions/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:t,rerunLLM:n})});if(!i.ok)throw new Error(`Failed to respond to function call: ${i.statusText} (${i.status})`);return i.json()}function $l(s){return{all:s=s||new Map,on:function(e,t){var n=s.get(e);n?n.push(t):s.set(e,[t])},off:function(e,t){var n=s.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var n=s.get(e);n&&n.slice().map(function(i){i(t)}),(n=s.get("*"))&&n.slice().map(function(i){i(e,t)})}}}class Al{constructor(e,t={}){if(this._assistantId="",this._conversationDetails=null,this._messages=[],this.isTyping=!1,this.inputDisabled=!1,this.chatEndingWarningSent=!1,this.chatEnded=!1,this.onStorageEvent=n=>{var i;const[r,a,o]=((i=n.key)==null?void 0:i.split("-"))||[];if(!(r!=="iaiChat"||a!==this.options.historyKey))switch(o){case"messageHistory":this.onMessageHistoryStorageEvent(n);break;case"conversation":this.setConversationDetails(JSON.parse(n.newValue||"null"),!0);break;case"lastActivity":this.keepAlive(JSON.parse(n.newValue||"null"),!0);break;case"chatEndingWarningSent":this.setChatEndingWarningSent(JSON.parse(n.newValue||"false"),!0);break;case"chatEnded":this.setChatEnded(JSON.parse(n.newValue||"false"),!0);break;case"typing":this.setTyping(JSON.parse(n.newValue||"false"),!0);break;case"inputDisabled":this.setInputDisabled(JSON.parse(n.newValue||"false"),!0);break}},this._assistantId=e,this.options={params:{},simulateDelays:!1,resetEndedChatOnLoad:!1,historyKey:"main",...t},this._emitter=$l(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),t.events&&Object.entries(t.events).forEach(([n,i])=>{this._emitter.on(n,i)}),t.historyKey){this._messages=this.storageGet("messageHistory",[]);const n=this.storageGet("conversation");n&&this.setConversationDetails(n,!0);const i=this.storageGet("chatEndingWarningSent");i&&this.setChatEndingWarningSent(i,!0);const r=this.storageGet("chatEnded");r&&this.setChatEnded(r,!0);const a=this.storageGet("typing");a&&this.setTyping(a,!0);const o=this.storageGet("inputDisabled");o&&this.setInputDisabled(o,!0);const l=this.storageGet("lastActivity");l&&setTimeout(()=>this.keepAlive(l,!0),0),setTimeout(()=>{this.chatEnded&&this.options.resetEndedChatOnLoad&&this.reset()},0),window.addEventListener("storage",this.onStorageEvent)}}onMessageHistoryStorageEvent(e){if(!e.newValue){this.reset();return}const t=JSON.parse(e.newValue),n=this._messages.map(r=>r.id),i=t.map(r=>r.id);this._messages.forEach(r=>{i.includes(r.id)||this._emitter.emit("messageRemoved",r.id)}),t.forEach(r=>{n.includes(r.id)||this._emitter.emit("message",r)}),this._messages=t}async endChat(e,t=!0){!this.threadId||this.chatEnded||(t&&(this._emitter.emit("chatEnded"),this.setChatEnded(!0)),this.stopInactivityTimers(),await _l(this.threadId,e))}reset(e){this.endChat(e,!1).then(()=>{}),this._messages=[],this.setConversationDetails(null),this.setTyping(!1),this.setInputDisabled(!1),this.setChatEnded(!1),this.stopInactivityTimers(),this.storageRemoveAll(),this._emitter.emit("reset")}destroy(){this._emitter.all.clear(),window.removeEventListener("storage",this.onStorageEvent),this.stopInactivityTimers(),this._emitter.emit("destroy")}stopInactivityTimers(){this._inactivityTimeout&&(clearTimeout(this._inactivityTimeout),this._inactivityTimeout=null),this._inactivityWarningTimeout&&(clearTimeout(this._inactivityWarningTimeout),this._inactivityWarningTimeout=null)}keepAlive(e=Date.now(),t=!1){if(this.stopInactivityTimers(),this.chatEnded||!e)return;const{timeUntilChatEnds:n,timeUntilWarnAboutChatEnding:i}=this;if(!n)return;t||this.storageSet("lastActivity",e);const r=Date.now()-e;r>n?(this.chatEnded||this._emitter.emit("chatEnded"),this.setChatEnded(!0)):r>i?(this.sendChatEndingWarning(),this._inactivityTimeout=setTimeout(()=>{this.chatEnded||this._emitter.emit("chatEnded"),this.setChatEnded(!0)},n-r)):(this.setChatEndingWarningSent(!1),this._inactivityWarningTimeout=setTimeout(()=>this.sendChatEndingWarning(),i-r),this._inactivityTimeout=setTimeout(()=>{this.chatEnded||this._emitter.emit("chatEnded"),this.setChatEnded(!0)},n-r))}async startChat(){if(this.chatStarted)return;const{id:e,inactivityWaitTime:t,inactivityWarningTime:n}=await wl(this.assistantId,this.params);if(!e)throw new Error("Could not start chat");this.setConversationDetails({threadId:e,inactivityWaitTime:t,inactivityWarningTime:n})}addMessage(e){const t={...e,id:e.id||Math.random().toString(36).substring(7)};return this._messages.push(t),this.storageSet("messageHistory",this._messages),this._emitter.emit("message",t),t}removeMessage(e){this._messages=this._messages.filter(t=>t.id!==e),this.storageSet("messageHistory",this._messages),this._emitter.emit("messageRemoved",e)}async respondToFunctionCall(e,t,n){if(!this.threadId)throw new Error("Thread not started");try{this.simulateDelay(1800).then(()=>this.setTyping(!0));const i=this.simulateDelay(2e3);this.keepAlive(),await this.insertMessagesWithSimulatedDelays(Promise.all([kl(this.threadId,e,t,n),i]).then(([r])=>r))}catch(i){this.addMessage({role:"assistant",content:"There was an unexpected error. Please try again later."}),this.setTyping(!1),console.error("Error sending message:",i)}}async sendUserMessage(e){try{this.addMessage({role:"user",content:e}),this.simulateDelay(1800).then(()=>this.setTyping(!0));let t=this.simulateDelay(4800);if(!this.chatStarted){const{initialReplyMessage:r}=this.options;r&&(this.simulateDelay(3800).then(()=>{this.addMessage({role:"assistant",content:r}),this.setTyping(!1)}),this.simulateDelay(6200).then(()=>this.setTyping(!0)),t=this.simulateDelay(8200)),await this.startChat()}this.keepAlive();const{messages:n,functions:i}=await this.insertMessagesWithSimulatedDelays(Promise.all([xl(this.threadId,e),t]).then(([r])=>r));return{messages:n,functions:i}}catch(t){this.addMessage({role:"assistant",content:"There was an unexpected error. Please try again later."}),this.setTyping(!1),console.error("Error sending message:",t)}}setTyping(e,t=!1){this.isTyping=e,this._emitter.emit("typing",e),t||this.storageSet("typing",e)}setConversationDetails(e,t=!1){this._conversationDetails=e,t||this.storageSet("conversation",e)}setInputDisabled(e,t=!1){this.inputDisabled=e,this._emitter.emit("inputDisabled",e),t||this.storageSet("inputDisabled",e)}setChatEnded(e,t=!1){this.chatEnded=e,t||this.storageSet("chatEnded",e)}setChatEndingWarningSent(e,t=!1){this.chatEndingWarningSent=e,t||this.storageSet("chatEndingWarningSent",e)}sendChatEndingWarning(){this.chatEndingWarningSent||(this._emitter.emit("inactivityWarning"),this.setChatEndingWarningSent(!0))}async insertMessagesWithSimulatedDelays(e){const t=await e,{messages:n,functions:i}=t;return await Promise.all(n.map(async(r,a)=>(await this.simulateDelay(1e3*a),this.addMessage(r)))),this.setTyping(!1),i.forEach(r=>this._emitter.emit("functionCall",r)),{messages:n,functions:i}}simulateDelay(e){return this.options.simulateDelays?new Promise(t=>{setTimeout(t,e)}):Promise.resolve()}get assistantId(){return this._assistantId}get params(){return this.options.params}get threadId(){var e;return(e=this._conversationDetails)==null?void 0:e.threadId}get timeUntilChatEnds(){const{inactivityWaitTime:e}=this._conversationDetails||{};return e?e*60*1e3:null}get timeUntilWarnAboutChatEnding(){const{inactivityWaitTime:e=0,inactivityWarningTime:t=0}=this._conversationDetails||{};return(e-t)*60*1e3}get messages(){return this._messages}get chatStarted(){return!!this.threadId}storageSet(e,t){this.options.historyKey&&localStorage.setItem(`iaiChat-${this.options.historyKey}-${e}`,JSON.stringify(t))}storageGet(e,t=null){if(!this.options.historyKey)return null;const n=localStorage.getItem(`iaiChat-${this.options.historyKey}-${e}`);return n?JSON.parse(n):t}storageRemove(e){localStorage.removeItem(`iaiChat-${this.options.historyKey}-${e}`)}storageRemoveAll(){this.options.historyKey&&Object.keys(localStorage).forEach(e=>{e.startsWith(`iaiChat-${this.options.historyKey}-`)&&localStorage.removeItem(e)})}}var Kr={exports:{}};(function(s,e){(function(t,n){s.exports=n()})($o,function(){var t=1e3,n=6e4,i=36e5,r="millisecond",a="second",o="minute",l="hour",d="day",u="week",h="month",c="quarter",f="year",A="date",V="Invalid Date",ae=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,ze=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,nn={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(M){var w=["th","st","nd","rd"],m=M%100;return"["+M+(w[(m-20)%10]||w[m]||w[0])+"]"}},lt=function(M,w,m){var $=String(M);return!$||$.length>=w?M:""+Array(w+1-$.length).join(m)+M},sn={s:lt,z:function(M){var w=-M.utcOffset(),m=Math.abs(w),$=Math.floor(m/60),v=m%60;return(w<=0?"+":"-")+lt($,2,"0")+":"+lt(v,2,"0")},m:function M(w,m){if(w.date()<m.date())return-M(m,w);var $=12*(m.year()-w.year())+(m.month()-w.month()),v=w.clone().add($,h),R=m-v<0,S=w.clone().add($+(R?-1:1),h);return+(-($+(m-v)/(R?v-S:S-v))||0)},a:function(M){return M<0?Math.ceil(M)||0:Math.floor(M)},p:function(M){return{M:h,y:f,w:u,d,D:A,h:l,m:o,s:a,ms:r,Q:c}[M]||String(M||"").toLowerCase().replace(/s$/,"")},u:function(M){return M===void 0}},Te="en",z={};z[Te]=nn;var Fn="$isDayjsObject",be=function(M){return M instanceof Dt||!(!M||!M[Fn])},ct=function M(w,m,$){var v;if(!w)return Te;if(typeof w=="string"){var R=w.toLowerCase();z[R]&&(v=R),m&&(z[R]=m,v=R);var S=w.split("-");if(!v&&S.length>1)return M(S[0])}else{var K=w.name;z[K]=w,v=K}return!$&&v&&(Te=v),v||!$&&Te},oe=function(M,w){if(be(M))return M.clone();var m=typeof w=="object"?w:{};return m.date=M,m.args=arguments,new Dt(m)},W=sn;W.l=ct,W.i=be,W.w=function(M,w){return oe(M,{locale:w.$L,utc:w.$u,x:w.$x,$offset:w.$offset})};var Dt=function(){function M(m){this.$L=ct(m.locale,null,!0),this.parse(m),this.$x=this.$x||m.x||{},this[Fn]=!0}var w=M.prototype;return w.parse=function(m){this.$d=function($){var v=$.date,R=$.utc;if(v===null)return new Date(NaN);if(W.u(v))return new Date;if(v instanceof Date)return new Date(v);if(typeof v=="string"&&!/Z$/i.test(v)){var S=v.match(ae);if(S){var K=S[2]-1||0,te=(S[7]||"0").substring(0,3);return R?new Date(Date.UTC(S[1],K,S[3]||1,S[4]||0,S[5]||0,S[6]||0,te)):new Date(S[1],K,S[3]||1,S[4]||0,S[5]||0,S[6]||0,te)}}return new Date(v)}(m),this.init()},w.init=function(){var m=this.$d;this.$y=m.getFullYear(),this.$M=m.getMonth(),this.$D=m.getDate(),this.$W=m.getDay(),this.$H=m.getHours(),this.$m=m.getMinutes(),this.$s=m.getSeconds(),this.$ms=m.getMilliseconds()},w.$utils=function(){return W},w.isValid=function(){return this.$d.toString()!==V},w.isSame=function(m,$){var v=oe(m);return this.startOf($)<=v&&v<=this.endOf($)},w.isAfter=function(m,$){return oe(m)<this.startOf($)},w.isBefore=function(m,$){return this.endOf($)<oe(m)},w.$g=function(m,$,v){return W.u(m)?this[$]:this.set(v,m)},w.unix=function(){return Math.floor(this.valueOf()/1e3)},w.valueOf=function(){return this.$d.getTime()},w.startOf=function(m,$){var v=this,R=!!W.u($)||$,S=W.p(m),K=function(De,pe){var Le=W.w(v.$u?Date.UTC(v.$y,pe,De):new Date(v.$y,pe,De),v);return R?Le:Le.endOf(d)},te=function(De,pe){return W.w(v.toDate()[De].apply(v.toDate("s"),(R?[0,0,0,0]:[23,59,59,999]).slice(pe)),v)},se=this.$W,le=this.$M,me=this.$D,dt="set"+(this.$u?"UTC":"");switch(S){case f:return R?K(1,0):K(31,11);case h:return R?K(1,le):K(0,le+1);case u:var qe=this.$locale().weekStart||0,Lt=(se<qe?se+7:se)-qe;return K(R?me-Lt:me+(6-Lt),le);case d:case A:return te(dt+"Hours",0);case l:return te(dt+"Minutes",1);case o:return te(dt+"Seconds",2);case a:return te(dt+"Milliseconds",3);default:return this.clone()}},w.endOf=function(m){return this.startOf(m,!1)},w.$set=function(m,$){var v,R=W.p(m),S="set"+(this.$u?"UTC":""),K=(v={},v[d]=S+"Date",v[A]=S+"Date",v[h]=S+"Month",v[f]=S+"FullYear",v[l]=S+"Hours",v[o]=S+"Minutes",v[a]=S+"Seconds",v[r]=S+"Milliseconds",v)[R],te=R===d?this.$D+($-this.$W):$;if(R===h||R===f){var se=this.clone().set(A,1);se.$d[K](te),se.init(),this.$d=se.set(A,Math.min(this.$D,se.daysInMonth())).$d}else K&&this.$d[K](te);return this.init(),this},w.set=function(m,$){return this.clone().$set(m,$)},w.get=function(m){return this[W.p(m)]()},w.add=function(m,$){var v,R=this;m=Number(m);var S=W.p($),K=function(le){var me=oe(R);return W.w(me.date(me.date()+Math.round(le*m)),R)};if(S===h)return this.set(h,this.$M+m);if(S===f)return this.set(f,this.$y+m);if(S===d)return K(1);if(S===u)return K(7);var te=(v={},v[o]=n,v[l]=i,v[a]=t,v)[S]||1,se=this.$d.getTime()+m*te;return W.w(se,this)},w.subtract=function(m,$){return this.add(-1*m,$)},w.format=function(m){var $=this,v=this.$locale();if(!this.isValid())return v.invalidDate||V;var R=m||"YYYY-MM-DDTHH:mm:ssZ",S=W.z(this),K=this.$H,te=this.$m,se=this.$M,le=v.weekdays,me=v.months,dt=v.meridiem,qe=function(pe,Le,Je,an){return pe&&(pe[Le]||pe($,R))||Je[Le].slice(0,an)},Lt=function(pe){return W.s(K%12||12,pe,"0")},De=dt||function(pe,Le,Je){var an=pe<12?"AM":"PM";return Je?an.toLowerCase():an};return R.replace(ze,function(pe,Le){return Le||function(Je){switch(Je){case"YY":return String($.$y).slice(-2);case"YYYY":return W.s($.$y,4,"0");case"M":return se+1;case"MM":return W.s(se+1,2,"0");case"MMM":return qe(v.monthsShort,se,me,3);case"MMMM":return qe(me,se);case"D":return $.$D;case"DD":return W.s($.$D,2,"0");case"d":return String($.$W);case"dd":return qe(v.weekdaysMin,$.$W,le,2);case"ddd":return qe(v.weekdaysShort,$.$W,le,3);case"dddd":return le[$.$W];case"H":return String(K);case"HH":return W.s(K,2,"0");case"h":return Lt(1);case"hh":return Lt(2);case"a":return De(K,te,!0);case"A":return De(K,te,!1);case"m":return String(te);case"mm":return W.s(te,2,"0");case"s":return String($.$s);case"ss":return W.s($.$s,2,"0");case"SSS":return W.s($.$ms,3,"0");case"Z":return S}return null}(pe)||S.replace(":","")})},w.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},w.diff=function(m,$,v){var R,S=this,K=W.p($),te=oe(m),se=(te.utcOffset()-this.utcOffset())*n,le=this-te,me=function(){return W.m(S,te)};switch(K){case f:R=me()/12;break;case h:R=me();break;case c:R=me()/3;break;case u:R=(le-se)/6048e5;break;case d:R=(le-se)/864e5;break;case l:R=le/i;break;case o:R=le/n;break;case a:R=le/t;break;default:R=le}return v?R:W.a(R)},w.daysInMonth=function(){return this.endOf(h).$D},w.$locale=function(){return z[this.$L]},w.locale=function(m,$){if(!m)return this.$L;var v=this.clone(),R=ct(m,$,!0);return R&&(v.$L=R),v},w.clone=function(){return W.w(this.$d,this)},w.toDate=function(){return new Date(this.valueOf())},w.toJSON=function(){return this.isValid()?this.toISOString():null},w.toISOString=function(){return this.$d.toISOString()},w.toString=function(){return this.$d.toUTCString()},M}(),rn=Dt.prototype;return oe.prototype=rn,[["$ms",r],["$s",a],["$m",o],["$H",l],["$W",d],["$M",h],["$y",f],["$D",A]].forEach(function(M){rn[M[1]]=function(w){return this.$g(w,M[0],M[1])}}),oe.extend=function(M,w){return M.$i||(M(w,Dt,oe),M.$i=!0),oe},oe.locale=ct,oe.isDayjs=be,oe.unix=function(M){return oe(1e3*M)},oe.en=z[Te],oe.Ls=z,oe.p={},oe})})(Kr);var Tl=Kr.exports;const qr=jr(Tl);/**
|
|
161
161
|
* @license
|
|
162
162
|
* Copyright 2021 Google LLC
|
|
163
163
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -516,7 +516,7 @@ Please report this to https://github.com/markedjs/marked.`,s){const n="<p>An err
|
|
|
516
516
|
</div>
|
|
517
517
|
`)}
|
|
518
518
|
</iai-chat-carousel>
|
|
519
|
-
`}function Pc(s){return async function({id:t,params:n,chatWindow:i}){i.setInputDisabled(!0);const r={...n.guestCardId&&{guestCardId:n.guestCardId},...n.customerFirstName&&{firstName:n.customerFirstName},...n.customerLastName&&{lastName:n.customerLastName},...n.customerEmail&&{email:n.customerEmail},...n.customerPhoneNumber&&{phone:n.customerPhoneNumber},...n.desiredMoveInDate&&{moveInDate:n.desiredMoveInDate}},a=document.createElement("iai-chat-iframe-modal");a.title="Schedule a Tour",a.src=`${s}?${new URLSearchParams(r).toString()}`,a.showHeader=!1;const o=()=>{a.remove(),window.removeEventListener("beforeunload",u),i.setInputDisabled(!1)},l=async({detail:h})=>{if(h.type!=="tourScheduled")return;const{tourType:c,tourDate:f,tourTime:A,guestCardId:V}=h;o(),i.addMessage({role:"system",content:"Your tour has been scheduled!"}),await i.sendFunctionCallResponse(t,{status:"scheduled",tourType:c,tourDate:f,tourTime:A,guestCardId:V},!0)},d=async()=>{o(),i.addMessage({role:"system",content:"Tour Scheduler Closed"}),await i.sendFunctionCallResponse(t,{status:"canceled"},!0)},u=async()=>{o(),i.addMessage({role:"system",content:"Tour Scheduler Closed"})};a.addEventListener("message-received",l),a.addEventListener("close",d),window.addEventListener("beforeunload",u),document.body.appendChild(a),i.addMessage({role:"system",content:"Tour Scheduler Opened"})}}function ba(s){return{all:s=s||new Map,on:function(e,t){var n=s.get(e);n?n.push(t):s.set(e,[t])},off:function(e,t){var n=s.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var n=s.get(e);n&&n.slice().map(function(i){i(t)}),(n=s.get("*"))&&n.slice().map(function(i){i(e,t)})}}}class jc{constructor(e){this.chatWsUrl=e,this._emitter=ba(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),this.reconnectCodes=new Set([1006]),this.reconnectAttempts=0,this.maxReconnectAttempts=10}connect(){const e=new WebSocket(this.chatWsUrl);e.onopen=async()=>{this.reconnectAttempts=0,e.send(JSON.stringify({type:"ready"}))},e.onmessage=t=>{const n=JSON.parse(t.data);this._emitter.emit(n.type,n.data)},e.onclose=t=>{console.log("Disconnected: ",t.code,t.reason||"No reason provided"),this._emitter.emit("disconnected",t),this.reconnectCodes.has(t.code)&&this.reconnectAttempts<this.maxReconnectAttempts&&(console.log("Reconnecting..."),this._emitter.emit("reconnecting"),this.reconnectAttempts++,setTimeout(()=>this.connect(),this.reconnectAttempts*1e3))},e.onerror=t=>{console.log("Error:",t),this._emitter.emit("error",t)},this.ws=e}reconnect(){this.reconnectAttempts=0,this.connect()}disconnect(){var e;(e=this.ws)==null||e.close()}destroy(){this.disconnect(),this._emitter.all.clear()}}var Ms;(s=>{(e=>{e.TEXT="TEXT"})(s.MessageType||(s.MessageType={})),(e=>{e.DELIVERED="DELIVERED",e.READ="READ",e.FAILED="FAILED"})(s.AcknowledgeType||(s.AcknowledgeType={})),(e=>{e.GENERIC="GENERIC",e.SMS="SMS",e.RCS="RCS",e.FACEBOOK="FACEBOOK",e.TWITTER="TWITTER",e.WHATSAPP="WHATSAPP",e.WECHAT="WECHAT",e.QQMOBILE="QQMOBILE",e.APPLE_BUSINESS_CHAT="APPLE_BUSINESS_CHAT",e.SKYPE="SKYPE",e.SNAPCHAT="SNAPCHAT",e.VIBER="VIBER",e.LINE="LINE",e.TELEGRAM="TELEGRAM",e.KAKAO="KAKAO"})(s.ContentType||(s.ContentType={})),(e=>{e.SYSTEM="SYSTEM",e.USER="USER"})(s.ConversationEventOrigin||(s.ConversationEventOrigin={})),(e=>{e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.TERMINATED="TERMINATED"})(s.ConversationStatus||(s.ConversationStatus={}))})(Ms||(Ms={}));const zc=Ms.AcknowledgeType,Dc="Anyone Home",Lc="IB Chat Leasing - Development";let Zc="https://five9.ah.inhabit.
|
|
519
|
+
`}function Pc(s){return async function({id:t,params:n,chatWindow:i}){i.setInputDisabled(!0);const r={...n.guestCardId&&{guestCardId:n.guestCardId},...n.customerFirstName&&{firstName:n.customerFirstName},...n.customerLastName&&{lastName:n.customerLastName},...n.customerEmail&&{email:n.customerEmail},...n.customerPhoneNumber&&{phone:n.customerPhoneNumber},...n.desiredMoveInDate&&{moveInDate:n.desiredMoveInDate}},a=document.createElement("iai-chat-iframe-modal");a.title="Schedule a Tour",a.src=`${s}?${new URLSearchParams(r).toString()}`,a.showHeader=!1;const o=()=>{a.remove(),window.removeEventListener("beforeunload",u),i.setInputDisabled(!1)},l=async({detail:h})=>{if(h.type!=="tourScheduled")return;const{tourType:c,tourDate:f,tourTime:A,guestCardId:V}=h;o(),i.addMessage({role:"system",content:"Your tour has been scheduled!"}),await i.sendFunctionCallResponse(t,{status:"scheduled",tourType:c,tourDate:f,tourTime:A,guestCardId:V},!0)},d=async()=>{o(),i.addMessage({role:"system",content:"Tour Scheduler Closed"}),await i.sendFunctionCallResponse(t,{status:"canceled"},!0)},u=async()=>{o(),i.addMessage({role:"system",content:"Tour Scheduler Closed"})};a.addEventListener("message-received",l),a.addEventListener("close",d),window.addEventListener("beforeunload",u),document.body.appendChild(a),i.addMessage({role:"system",content:"Tour Scheduler Opened"})}}function ba(s){return{all:s=s||new Map,on:function(e,t){var n=s.get(e);n?n.push(t):s.set(e,[t])},off:function(e,t){var n=s.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var n=s.get(e);n&&n.slice().map(function(i){i(t)}),(n=s.get("*"))&&n.slice().map(function(i){i(e,t)})}}}class jc{constructor(e){this.chatWsUrl=e,this._emitter=ba(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),this.reconnectCodes=new Set([1006]),this.reconnectAttempts=0,this.maxReconnectAttempts=10}connect(){const e=new WebSocket(this.chatWsUrl);e.onopen=async()=>{this.reconnectAttempts=0,e.send(JSON.stringify({type:"ready"}))},e.onmessage=t=>{const n=JSON.parse(t.data);this._emitter.emit(n.type,n.data)},e.onclose=t=>{console.log("Disconnected: ",t.code,t.reason||"No reason provided"),this._emitter.emit("disconnected",t),this.reconnectCodes.has(t.code)&&this.reconnectAttempts<this.maxReconnectAttempts&&(console.log("Reconnecting..."),this._emitter.emit("reconnecting"),this.reconnectAttempts++,setTimeout(()=>this.connect(),this.reconnectAttempts*1e3))},e.onerror=t=>{console.log("Error:",t),this._emitter.emit("error",t)},this.ws=e}reconnect(){this.reconnectAttempts=0,this.connect()}disconnect(){var e;(e=this.ws)==null||e.close()}destroy(){this.disconnect(),this._emitter.all.clear()}}var Ms;(s=>{(e=>{e.TEXT="TEXT"})(s.MessageType||(s.MessageType={})),(e=>{e.DELIVERED="DELIVERED",e.READ="READ",e.FAILED="FAILED"})(s.AcknowledgeType||(s.AcknowledgeType={})),(e=>{e.GENERIC="GENERIC",e.SMS="SMS",e.RCS="RCS",e.FACEBOOK="FACEBOOK",e.TWITTER="TWITTER",e.WHATSAPP="WHATSAPP",e.WECHAT="WECHAT",e.QQMOBILE="QQMOBILE",e.APPLE_BUSINESS_CHAT="APPLE_BUSINESS_CHAT",e.SKYPE="SKYPE",e.SNAPCHAT="SNAPCHAT",e.VIBER="VIBER",e.LINE="LINE",e.TELEGRAM="TELEGRAM",e.KAKAO="KAKAO"})(s.ContentType||(s.ContentType={})),(e=>{e.SYSTEM="SYSTEM",e.USER="USER"})(s.ConversationEventOrigin||(s.ConversationEventOrigin={})),(e=>{e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.TERMINATED="TERMINATED"})(s.ConversationStatus||(s.ConversationStatus={}))})(Ms||(Ms={}));const zc=Ms.AcknowledgeType,Dc="Anyone Home",Lc="IB Chat Leasing - Development";let Zc="https://five9.ah.inhabit.service";const Hc="https://five9.ah.inhabit.service".replace("http","ws").replace(/\/$/,""),Vn=class Vn{constructor(){Ei(this,Ke,void 0);Ei(this,zt,void 0);this._emitter=ba(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),ut(this,Ke,null),ut(this,zt,null),this.conversationStarted=!1}serialize(){return JSON.stringify({sessionToken:this.sessionToken,conversationId:this.conversationId,conversationStarted:this.conversationStarted})}static deserialize(e){const t=JSON.parse(e),n=new Vn;return t.sessionToken&&n.setSession(t.sessionToken),t.conversationId&&n.setConversationId(t.conversationId),n.conversationStarted=t.conversationStarted||!1,n}static generateBaseUrl(e){return`https://${e}/appsvcs/rs/svc`}async createSession(){const e=await fetch(`${Vn.generateBaseUrl("app-scl.five9.com")}/auth/anon?cookieless=true`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({tenantName:Dc})});return ut(this,Ke,await e.json()),Ps(this,Ke)}setSession(e){ut(this,Ke,e)}setConversationId(e){ut(this,zt,e),this.five9WebSocket&&(this.five9WebSocket.destroy(),this.five9WebSocket=void 0,e&&this.connectToWebSocket())}connect(){if(!this.sessionToken)throw new Error("Session not created");if(!this.conversationId)throw new Error("Conversation not started");this.connectToWebSocket()}connectToWebSocket(){if(!this.conversationId)throw new Error("Conversation not started");this.five9WebSocket&&this.five9WebSocket.destroy();const e=new jc(`${Hc}/conversations/${this.conversationId}/ws`);e.on("*",(t,n)=>{this._emitter.emit(t,n)}),e.on("conversationCreated",t=>{this.conversationStarted=!0,console.log("Conversation Created:",t)}),e.on("conversationAccepted",t=>{console.log("Conversation Accepted:",t)}),e.on("agentJoined",t=>{console.log("Agent Joined:",t)}),e.on("agentTransferredConversation",t=>{console.log("Agent Transferred Conversation:",t)}),e.on("conversationTransferredToGroup",t=>{console.log("Conversation Transferred To Group:",t)}),e.on("agentLeftConversation",t=>{console.log("Agent Left Conversation:",t)}),e.on("agentTyping",t=>{console.log("Agent Typing:",t)}),e.on("message",async t=>{console.log("Message:",t),await this.acknowledgeMessage({messages:[{messageId:t.messageId,type:zc.READ}]})}),e.on("conversationTerminated",t=>{console.log("Conversation Terminated:",t)}),e.on("error",t=>{console.log("Error:",t)}),this.five9WebSocket=e,e.connect()}async authenticatedFetch(e,t={}){const{sessionToken:n}=this;if(!n)throw new Error("Session not found");e=e.startsWith("/")?e:`/${e}`;const i=n.metadata.dataCenters[0].apiUrls[0].host,r=await fetch(`${Vn.generateBaseUrl(i)}${e}`,{...t,headers:{...t.headers,"Content-Type":"application/json",Accept:"application/json",Authorization:n.tokenId,farmId:n.context.farmId}});return r.status===204?null:r.json()}async getMetadata(){if(!this.sessionToken)throw new Error("Session not created");return this.authenticatedFetch("/auth/metadata",{method:"GET"})}async createConversation(e){if(!this.sessionToken)throw new Error("Session not created");const t=e.contact||{};Object.keys(t).forEach(r=>{const a=r;t[a]||delete t[a]});const n={...e,campaignName:Lc,tenantId:this.tenantId,callbackUrl:Zc};console.log("body",n);const i=await this.authenticatedFetch("/conversations",{method:"POST",body:JSON.stringify(n)});return this.setConversationId(i.id),i}async sendMessage(e){const{conversationId:t,conversationStarted:n}=this;if(!t||!n)throw new Error("Conversation not started");const i={messageType:Ms.MessageType.TEXT,message:e};await this.authenticatedFetch(`/conversations/${t}/messages`,{method:"POST",body:JSON.stringify(i)})}async sendTyping(){const{conversationId:e}=this;if(!e)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${e}/messages/typing`,{method:"PUT"})}async acknowledgeMessage(e){const{conversationId:t}=this;if(!t)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${t}/messages/acknowledge`,{method:"PUT",body:JSON.stringify(e)})}async terminateConversation(){const{conversationId:e}=this;if(!e)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${e}/terminate`,{method:"POST"}),this.destroy()}destroy(){this.five9WebSocket&&this.five9WebSocket.destroy(),ut(this,Ke,null),ut(this,zt,null)}get sessionToken(){return Ps(this,Ke)}get conversationId(){return Ps(this,zt)}get dataCenter(){var e;return(e=this.sessionToken)==null?void 0:e.metadata.dataCenters[0]}get apiUrl(){var e;return(e=this.dataCenter)==null?void 0:e.apiUrls[0].host}get tenantId(){var e;return(e=this.sessionToken)==null?void 0:e.orgId}get tokenId(){var e;return(e=this.sessionToken)==null?void 0:e.tokenId}get farmId(){var e;return(e=this.sessionToken)==null?void 0:e.context.farmId}};Ke=new WeakMap,zt=new WeakMap;let Ns=Vn;function Wn(s){return`any-${s||"main"}-chatSession`}async function Uc({id:s,params:e,chatWindow:t,html:n}){t=t;const i=async()=>{t.removeMessage("transferMessageId"),await t.sendFunctionCallResponse(s,{transfer:"Declined"},!0),t.setInputDisabled(!1)},r=async()=>{t.setInputDisabled(!0),t.removeMessage("transferMessageId"),t.addMessage({role:"system",content:"Please wait while we connect you to a live agent"}),await t.chatManager.endChat("Transferred to live agent",!1);const a=new Ns;await a.createSession();const{summary:o,subject:l,guestCardId:d,...u}=e;await a.createConversation({contact:u,attributes:{...d&&{"Chat.gc_id":d},Question:l,"AI Summary":o}}),localStorage.setItem(Wn(t.cleanOptions.config.historyKey),a.serialize()),wa(t,a)};t.addMessage({id:"transferMessageId",role:"system",contentHtmlTemplate:n`
|
|
520
520
|
<style>
|
|
521
521
|
.btn {
|
|
522
522
|
background-color: var(--iai-chat-i-message-user-bg);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iai-lib/any-chat-widget",
|
|
3
3
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
4
|
-
"version": "0.1.0-alpha.
|
|
4
|
+
"version": "0.1.0-alpha.42",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"vite-plugin-static-copy": "^1.0.1"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@iai-lib/chat-widget": "^1.0.0-alpha.
|
|
37
|
+
"@iai-lib/chat-widget": "^1.0.0-alpha.42",
|
|
38
38
|
"mitt": "^3.0.1"
|
|
39
39
|
},
|
|
40
|
-
"gitHead": "
|
|
40
|
+
"gitHead": "6881dc15598470142a799f766b0cc1f9a641e39a"
|
|
41
41
|
}
|