@prodantix/sdk 0.7.0-beta.437 → 0.7.0-beta.438
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat.cjs +9 -5
- package/dist/chat.d.cts +3 -3
- package/dist/chat.d.ts +3 -3
- package/dist/chat.js +9 -5
- package/dist/{config-6ulvfBFp.d.ts → config-C9Njc6-j.d.ts} +1 -0
- package/dist/{config-g14Jiv1t.d.cts → config-CpfUyEw8.d.cts} +1 -0
- package/dist/messenger.cjs +1 -1
- package/dist/messenger.d.cts +1 -1
- package/dist/messenger.d.ts +1 -1
- package/dist/messenger.iife.js +9 -5
- package/dist/messenger.js +1 -1
- package/package.json +1 -1
package/dist/chat.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
'use strict';var J=Object.defineProperty;var V=(n,e,t)=>e in n?J(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var l=(n,e,t)=>V(n,typeof e!="symbol"?e+"":e,t);var A=class extends Error{constructor(t,r,i){super(r,i);l(this,"code");this.code=t,this.name="ProdantixError";}},P=class extends A{constructor(e){super("config",e),this.name="ConfigError";}};var v=class extends A{constructor(t,r,i){super("transport",t,i);l(this,"status");this.status=r,this.name="TransportError";}};function $(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function M(n){return n.replace(/\/+$/,"")}var O="X-Prodantix-Conversation-Token",F="prodantix.chat.handle";function X(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var T=class{constructor(e){this.options=e;l(this,"fetchImpl");l(this,"fileFetchImpl");l(this,"host");l(this,"storage");l(this,"handle");l(this,"identity",null);this.fetchImpl=$(e.fetchImpl),this.fileFetchImpl=e.fileFetchImpl??((t,r)=>fetch(t,r)),this.host=M(e.host),this.storage=e.storage??X(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(F,JSON.stringify(this.handle)),true)}async send(e,t,r){if(!await this.ensureThread())return null;let i=this.handle;return i?(await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async helpCentre(e,t){let r=Object.entries({...t,...this.options.locale?{lang:this.options.locale}:{}}).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return this.request("GET",`/v1/messenger/articles${e}${r?`?${r}`:""}`)}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(F);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(F),null}async fileRequest(e,t,r,i,a){let o={authorization:`Bearer ${this.options.apiKey}`,[O]:r};a&&(o["content-type"]=a.type||"application/octet-stream");try{let s=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:o,method:e});if(s.ok)return await i(s);this.options.onError?.(new v(`prodantix chat ${t}: ${s.status}`,s.status));}catch(s){this.options.onError?.(s);}return null}async request(e,t,r={}){let i=this.fetchImpl;if(!i)return this.options.onError?.(new v("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[O]=r.token);try{let o=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),s=await o.text();return o.ok?s?JSON.parse(s):{}:(this.options.onError?.(new v(`prodantix chat ${t}: ${o.status}`,o.status)),null)}catch(o){return this.options.onError?.(o),null}}};var Z={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function N(n,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=Z[t.find(s=>s.type==="weekday")?.value??""];if(!r)return false;let i=t.find(s=>s.type==="hour")?.value??"",a=t.find(s=>s.type==="minute")?.value??"",o=`${i}:${a}`;return n.windows.some(s=>s.days.includes(r)&&s.open<=o&&o<s.close)}var f={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},Q=["quiet","standard"],ee=["round","square"],te=["rounded","tailed"],ne=["filled","outlined"],re=["circle","pill","squircle"],ie=["filled","outlined"],ae=["avatar","glyph","team_faces"],oe=["large","medium","small"],se=["above","hidden","inline"],le=["beside_name","none","under_turn"],ce=["time","time_and_latency"],x=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,U=(n,e)=>typeof n=="boolean"?n:e,de={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},pe={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},he={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ue={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},me={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function L(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:de[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:pe[i],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:he[o],h=typeof e.skin=="string"?e.skin:void 0,u=h===void 0?void 0:ue[h],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,d=c===void 0?void 0:me[c],p={bubbleFill:x(e.bubbleFill,ne,d?.[1]??f.bubbleFill),bubbleShape:x(e.bubbleShape,te,d?.[0]??f.bubbleShape),composerShape:x(e.composerShape,ee,u?.[1]??f.composerShape),dayDividers:U(e.dayDividers,s?.[0]??f.dayDividers),launcherContent:x(e.launcherContent,ae,r?.[2]??f.launcherContent),launcherFill:x(e.launcherFill,ie,r?.[1]??f.launcherFill),launcherShape:x(e.launcherShape,re,r?.[0]??f.launcherShape),launcherSize:x(e.launcherSize,oe,r?.[3]??f.launcherSize),nameAvatar:U(e.nameAvatar,a?.[1]??f.nameAvatar),namePlacement:x(e.namePlacement,se,a?.[0]??f.namePlacement),skin:x(e.skin,Q,u?.[0]??f.skin),stampContent:x(e.stampContent,ce,s?.[2]??f.stampContent),stampPlacement:x(e.stampPlacement,le,s?.[1]??f.stampPlacement)};return p.stampPlacement==="beside_name"&&p.namePlacement==="hidden"&&(p.stampPlacement="under_turn"),p}function K(n){let e=n.split(/\s+/).filter(r=>r.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var ge="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",fe={large:66,medium:56,small:46},be={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},ye={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},xe={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},ve=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",Se={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ke={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},Ce={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Ee={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function z(n,e,t,r){return `.launcher{--fab-size:${fe[r]}px;${be[n]}${ye[e]}}${xe[t]}${ve}${Se[n]}${ke[e]}${Ce[n]}${Ee[n]}`}function B(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${ge}"/></svg>`,i.append(...a.childNodes,I()),i}return n==="avatar"?(i.append(D(t[0],e,r),I()),i):(i.append(H(t,e,r),I()),i)}function H(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(D(i,e,t));return r}function D(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n?.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function I(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Te={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},E={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...f},Le={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},we={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Ae={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Pe={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ne={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},_e=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Fe='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Ie={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},He=".lat{font-size:11px;opacity:.7;margin-left:6px}",G=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
'use strict';var J=Object.defineProperty;var V=(n,e,t)=>e in n?J(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var l=(n,e,t)=>V(n,typeof e!="symbol"?e+"":e,t);var A=class extends Error{constructor(t,r,i){super(r,i);l(this,"code");this.code=t,this.name="ProdantixError";}},P=class extends A{constructor(e){super("config",e),this.name="ConfigError";}};var v=class extends A{constructor(t,r,i){super("transport",t,i);l(this,"status");this.status=r,this.name="TransportError";}};function $(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function M(n){return n.replace(/\/+$/,"")}var O="X-Prodantix-Conversation-Token",F="prodantix.chat.handle";function X(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var T=class{constructor(e){this.options=e;l(this,"fetchImpl");l(this,"fileFetchImpl");l(this,"host");l(this,"storage");l(this,"handle");l(this,"identity",null);this.fetchImpl=$(e.fetchImpl),this.fileFetchImpl=e.fileFetchImpl??((t,r)=>fetch(t,r)),this.host=M(e.host),this.storage=e.storage??X(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(F,JSON.stringify(this.handle)),true)}async send(e,t,r){if(!await this.ensureThread())return null;let i=this.handle;return i?(await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async helpCentre(e,t){let r=Object.entries({...t,...this.options.locale?{lang:this.options.locale}:{}}).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return this.request("GET",`/v1/messenger/articles${e}${r?`?${r}`:""}`)}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(F);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(F),null}async fileRequest(e,t,r,i,a){let o={authorization:`Bearer ${this.options.apiKey}`,[O]:r};a&&(o["content-type"]=a.type||"application/octet-stream");try{let s=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:o,method:e});if(s.ok)return await i(s);this.options.onError?.(new v(`prodantix chat ${t}: ${s.status}`,s.status));}catch(s){this.options.onError?.(s);}return null}async request(e,t,r={}){let i=this.fetchImpl;if(!i)return this.options.onError?.(new v("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[O]=r.token);try{let o=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),s=await o.text();return o.ok?s?JSON.parse(s):{}:(this.options.onError?.(new v(`prodantix chat ${t}: ${o.status}`,o.status)),null)}catch(o){return this.options.onError?.(o),null}}};var Z={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function N(n,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=Z[t.find(s=>s.type==="weekday")?.value??""];if(!r)return false;let i=t.find(s=>s.type==="hour")?.value??"",a=t.find(s=>s.type==="minute")?.value??"",o=`${i}:${a}`;return n.windows.some(s=>s.days.includes(r)&&s.open<=o&&o<s.close)}var f={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},Q=["quiet","standard"],ee=["round","square"],te=["rounded","tailed"],ne=["filled","outlined"],re=["circle","pill","squircle"],ie=["filled","outlined"],ae=["avatar","glyph","team_faces"],oe=["large","medium","small"],se=["above","hidden","inline"],le=["beside_name","none","under_turn"],ce=["time","time_and_latency"],y=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,U=(n,e)=>typeof n=="boolean"?n:e,de={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},pe={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},he={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ue={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},me={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function w(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:de[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:pe[i],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:he[o],h=typeof e.skin=="string"?e.skin:void 0,u=h===void 0?void 0:ue[h],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,d=c===void 0?void 0:me[c],p={bubbleFill:y(e.bubbleFill,ne,d?.[1]??f.bubbleFill),bubbleShape:y(e.bubbleShape,te,d?.[0]??f.bubbleShape),composerShape:y(e.composerShape,ee,u?.[1]??f.composerShape),dayDividers:U(e.dayDividers,s?.[0]??f.dayDividers),launcherContent:y(e.launcherContent,ae,r?.[2]??f.launcherContent),launcherFill:y(e.launcherFill,ie,r?.[1]??f.launcherFill),launcherShape:y(e.launcherShape,re,r?.[0]??f.launcherShape),launcherSize:y(e.launcherSize,oe,r?.[3]??f.launcherSize),nameAvatar:U(e.nameAvatar,a?.[1]??f.nameAvatar),namePlacement:y(e.namePlacement,se,a?.[0]??f.namePlacement),skin:y(e.skin,Q,u?.[0]??f.skin),stampContent:y(e.stampContent,ce,s?.[2]??f.stampContent),stampPlacement:y(e.stampPlacement,le,s?.[1]??f.stampPlacement)};return p.stampPlacement==="beside_name"&&p.namePlacement==="hidden"&&(p.stampPlacement="under_turn"),p}function K(n){let e=n.split(/\s+/).filter(r=>r.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var ge="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",fe={large:66,medium:56,small:46},be={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},xe={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},ye={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},ve=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",Se={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ke={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},Ce={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Ee={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function z(n,e,t,r){return `.launcher{--fab-size:${fe[r]}px;${be[n]}${xe[e]}}${ye[t]}${ve}${Se[n]}${ke[e]}${Ce[n]}${Ee[n]}`}function B(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${ge}"/></svg>`,i.append(...a.childNodes,I()),i}return n==="avatar"?(i.append(D(t[0],e,r),I()),i):(i.append(H(t,e,r),I()),i)}function H(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(D(i,e,t));return r}function D(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n?.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function I(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Te={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},E={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...f};function we(n,e){let t=document.createElement("a");t.className="powered",t.href="https://prodantix.com",t.target="_blank",t.rel="noopener";let r=document.createElement("img");return r.src=e,r.alt="",r.width=12,r.height=12,t.append(r,n),t}var Le={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Ae={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Pe={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Ne={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},_e={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Fe=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Ie='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',He={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Re=".lat{font-size:11px;opacity:.7;margin-left:6px}",G=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
-
--online: oklch(72% 0.13 163.23);`;function
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function $e(n){return n==="light"?"":n==="dark"?`:host { ${G} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
5
5
|
${G}
|
|
6
6
|
}
|
|
7
|
-
}`}var
|
|
7
|
+
}`}var Me=/https?:\/\/[^\s<>"]+/g,Oe=/[.,;:!?)]$/,Ue=n=>{let e=n;for(;Oe.test(e);){let t=e.split("(").length-1,r=e.split(")").length-1;if(e.endsWith(")")&&t>=r)break;e=e.slice(0,-1);}return e};function Ke(n,e){let t=0;for(let r of e.matchAll(Me)){let i=r.index??0,a=Ue(r[0]);i>t&&n.append(e.slice(t,i));let o=document.createElement("a");o.href=a,o.target="_blank",o.rel="noopener noreferrer",o.textContent=a,n.append(o),t=i+a.length;}t<e.length&&n.append(e.slice(t));}var ze=["P","BR","STRONG","EM","A","UL","OL","LI"],Be=n=>typeof n=="object"&&n!==null&&"html"in n&&typeof n.html=="string"&&"text"in n&&typeof n.text=="string",De=(n,e)=>e.name==="class"||e.name==="data-block-type"?true:n!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),Ge=n=>[...n.querySelectorAll("*")].every(e=>ze.includes(e.tagName)&&[...e.attributes].every(t=>De(e.tagName,t)));function q(n,e="system"){let t=w(n),r=n.launcherPosition==="bottom_left"?"left":"right",i=n.accentColor;return `${`
|
|
8
8
|
:host {
|
|
9
9
|
all: initial; z-index: 2147483000; --a: ${i};
|
|
10
10
|
--paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
--online: oklch(53.8% 0.1274 163.23);
|
|
13
13
|
color-scheme: ${e==="system"?"light dark":e};
|
|
14
14
|
}
|
|
15
|
-
${
|
|
15
|
+
${$e(e)}
|
|
16
16
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
17
17
|
.launcher {
|
|
18
18
|
z-index: 2147483000; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
|
|
@@ -98,10 +98,14 @@ ${Re(e)}
|
|
|
98
98
|
.composer button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
|
|
99
99
|
.composer button .sendglyph { display: none; width: 17px; height: 17px; }
|
|
100
100
|
.composer button:focus-visible { outline: 2px solid #0b0e14; }
|
|
101
|
+
.powered { display: flex; align-items: center; justify-content: center; gap: 4px; height: 24px; font-size: 11px; font-weight: 500; color: var(--ink-3); text-decoration: none; }
|
|
102
|
+
.powered:hover { color: var(--ink-2); }
|
|
103
|
+
.powered:focus-visible { outline: 2px solid var(--ink); outline-offset: -2px; }
|
|
104
|
+
.powered img { width: 12px; height: 12px; }
|
|
101
105
|
@media (prefers-reduced-motion: no-preference) {
|
|
102
106
|
.panel { animation: rise 180ms ease-out; }
|
|
103
107
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
104
108
|
}
|
|
105
109
|
.scrim,.grip{display:none}@media (max-width:770px){.panel{inset:auto 0 0;width:100%;max-width:none;height:86dvh;max-height:86dvh}:host .panel{border-bottom-left-radius:0;border-bottom-right-radius:0}.scrim{display:block;position:fixed;inset:0;z-index:2147483000;background:rgb(15 23 42/.24)}.grip{display:block;position:absolute;top:7px;left:calc(50% - 17px);width:34px;height:4px;border-radius:2px;background:currentColor;opacity:.45}.panel:not([data-dragging]){transition:translate .2s}.composer{padding-bottom:max(12px,env(safe-area-inset-bottom))}}
|
|
106
|
-
`}${we[t.composerShape]}${Le[t.skin]}${z(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ae[t.bubbleShape]}${Pe[t.bubbleFill]}${Ne[t.namePlacement]}${t.nameAvatar?_e:""}${t.dayDividers?Fe:""}${Ie[t.stampPlacement]}${t.stampContent==="time_and_latency"?He:""}`}var Ge=["end_user","agent","ai"];function qe(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var je='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',w=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;l(this,"root");l(this,"strings");l(this,"settings");l(this,"appearance");l(this,"launcher");l(this,"badge");l(this,"panel",null);l(this,"scrim",null);l(this,"lastFocused",null);l(this,"unread",0);l(this,"pendingTurns",0);l(this,"openNow");l(this,"styles");l(this,"scheme");l(this,"picked",null);l(this,"objectUrls",[]);l(this,"helpLoader");l(this,"kit",null);l(this,"kitLoad",null);l(this,"filesLoader");l(this,"filesKit",null);l(this,"filesLoad",null);this.strings={...Te,...r},this.appearance={...E,...i},this.settings=L({...E,...i}),this.root=e.attachShadow({mode:a.shadowMode??"closed"}),this.openNow=N(this.appearance.availability,new Date),this.scheme=a.scheme,this.helpLoader=a.help,this.filesLoader=a.files,this.styles=Je(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(B(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...E,...e},this.settings=L(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){this.styles(`${q(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(this.appearance.attachments?.enabled===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):(this.kitLoad??(this.kitLoad=this.helpLoader().then(e=>(this.kit=e,this.paint(),e))),this.kitLoad)}loadFiles(){return this.filesLoader?(this.filesLoad??(this.filesLoad=this.filesLoader().then(e=>(this.filesKit=e,this.paint(),e))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("span");r.className="grip",r.setAttribute("aria-hidden","true"),t.append(r);let i=this.appearance.team??[];i.length>0&&t.append(H(i,this.strings,y=>this.client.avatarUrl(y)));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let s=document.createElement("p");s.className="status";let h=document.createElement("span");h.className="live",h.setAttribute("aria-hidden","true"),s.append(h,this.strings.replyTime),a.append(o,s);let u=document.createElement("button");u.className="close",u.type="button",u.setAttribute("aria-label",this.strings.closeLabel),u.innerHTML=je,u.addEventListener("click",()=>this.close()),t.append(a,u);let c=document.createElement("div");c.className="log",c.setAttribute("role","log"),c.setAttribute("aria-live","polite"),c.setAttribute("aria-label",this.strings.title);let d=document.createElement("form");d.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let C=document.createElement("span");C.className="sendtext",C.textContent=this.strings.sendLabel,m.append(C),d.append(p,m),d.addEventListener("submit",y=>{y.preventDefault(),this.submit(p,c);}),e.append(t,c,d),e.addEventListener("keydown",y=>this.onKeydown(y,e,u));let S=document.createElement("div");S.className="scrim",S.addEventListener("click",()=>this.close()),this.root.append(S,e),this.panel=e,this.scrim=S,We(e,()=>this.close()),p.focus();let k=this.appearance.attachments,[g]=await Promise.all([this.client.load(),this.loadKit(),k?.enabled&&this.client.upload?this.loadFiles():null]);if(g?.turns.some(y=>y.attachments?.length)&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&k?.enabled&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:y=>{this.picked=y;},objectUrl:y=>this.objectUrl(y),removeFileLabel:this.strings.removeFileLabel,root:this.root},d,p,c,k);let b=this.helpHost();b?.placement==="tab"&&b.host.source.collections&&b.host.source.collectionArticles&&b.kit.helpTab(b.host),b?.placement==="while_typing"&&b.kit.whileTyping(b.host,p,d),g&&g.turns.length>0?this.renderThread(c,g):this.renderFirstRun(c,p),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,r.append(i);let a=this.helpHost();if(a?.placement==="first_view")a.kit.firstView(a.host,r);else {let s=document.createElement("p");s.textContent=this.strings.emptyBody,r.append(s);}this.appearance.starterPrompts.filter(ze).forEach((s,h)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${h}`;let d=document.createElement("template");d.innerHTML=s.html,De(d.content)?c.append(d.content):c.textContent=s.text;for(let m of c.querySelectorAll("a"))m.target="_blank",m.rel="noopener noreferrer";let p=document.createElement("button");p.className="promptpress",p.type="button",p.setAttribute("aria-labelledby",c.id),p.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),u.append(c,p),r.append(u);}),e.replaceChildren(r);}helpHost(){let e=this.appearance.help,{kit:t,panel:r}=this,i=e&&t&&r?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:r,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.scrim?.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel&&e.attachments?.length&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let a=r?await this.client.upload?.(r):void 0,o=a===null?null:await this.client.send(t,qe(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),o){i.dataset.turnId=o.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),(t.querySelector(".body")??t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){e.querySelector(".empty")?.remove();let i=Ge.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${i}`,o.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let d=document.createElement("span");if(d.className=i==="ai"?"av bot":"av",d.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),d.append(p);}else {d.textContent=i==="ai"?this.strings.aiLabel:K(this.agentName(t));let p=i==="agent"?this.appearance.team?.find(m=>m.name===t.authorName)?.tone:void 0;p&&(d.style.background=p);}o.append(d);}let h=document.createElement("div");if(h.className="body",i==="end_user"){let d=this.filesKit,p=m=>this.objectUrl(m);r&&d?.drawFile(h,r.name,r.type,r.size,Promise.resolve(r),p);for(let m of t.attachments??[])d?.drawFile(h,m.name,m.contentType,m.bytes,this.client.file?.(m.url)??Promise.resolve(null),p);}let u=i!=="end_user"&&a.namePlacement!=="hidden",c=document.createElement("div");if(i==="ai"?Ue(c,t.body):c.textContent=t.body,u||i==="ai"&&a.namePlacement==="hidden"){let d=document.createElement("div");d.className=i==="ai"?"author ai":"author",d.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&d.append(this.stamp(t)),a.namePlacement==="inline"?(d.classList.add("below"),h.append(c,d)):h.append(d,c);}else t.body&&h.append(c);return a.stampPlacement==="under_turn"&&h.append(this.stamp(t)),o.append(h),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(h=>!h.closest("[hidden]")&&!h.hidden);if(i.length===0)return;let a=i[0],o=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},Ye="(max-width: 770px)";function We(n,e){let t=null;n.addEventListener("pointerdown",i=>{if(t||i.button!==0||!globalThis.matchMedia?.(Ye).matches)return;let a=i.target;if(!a?.closest("a, button, input, textarea, iframe")){for(;a&&a!==n;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},n.setPointerCapture?.(i.pointerId),n.dataset.dragging="";}}),n.addEventListener("pointermove",i=>{if(t?.id!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),n.style.translate=`0 ${t.offset}px`;});let r=i=>{let a=t;if(a?.id!==i.pointerId)return;t=null,delete n.dataset.dragging;let o=a.offset>Math.min(72,n.getBoundingClientRect().height*.4),s=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;o||s?e():n.style.translate="";};n.addEventListener("pointerup",r),n.addEventListener("pointercancel",r);}var Je=n=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in n&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return n.adoptedStyleSheets=[t],r=>t.replaceSync(r)}let e=document.createElement("style");return n.append(e),t=>{e.textContent=t;}};function j(n){return `40${JSON.stringify(n)}`}function Y(){return "3"}function W(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=R(t);return {kind:"open",pingInterval:typeof o?.pingInterval=="number"?o.pingInterval:25e3,pingTimeout:typeof o?.pingTimeout=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=R(i);return {kind:"connectError",message:typeof o?.message=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let a=R(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function R(n){try{return JSON.parse(n)}catch{return null}}var Ve="/socket.io/?EIO=4&transport=websocket",_=class{constructor(e){this.options=e;l(this,"socket",null);l(this,"heartbeat",null);l(this,"ready",false);l(this,"closed",false);l(this,"heartbeatWindow",45e3);l(this,"factory");l(this,"setTimer");l(this,"clearTimer");this.factory=e.socketFactory??Xe,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ve}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=W(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(j(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(Y());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let r=t.payload?.turn;r&&this.options.onTurn(r);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Xe(n){let e=globalThis.WebSocket;if(!e)throw new v("no WebSocket");return new e(n)}var Ze=6e4;function Tt(n){let e=globalThis.document;if(!e)throw new P("prodantix chat requires a document; mount it in the browser");let t=n.mountPoint??e.createElement("div");n.mountPoint||e.body.append(t);let r=new T(n),i=new w(t,r,n.strings,n.appearance,{files:n.files,help:n.help}),a=n.appearance?.availability??E.availability,o,s=()=>{i.setOpenNow(N(a,new Date)),o=setTimeout(s,Ze);};s();let h=new Set,u,c=null,d=n.pollIntervalMs??15e3,p=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),i.onIncomingTurn(g));},m=async()=>{if(!r.hasThread)return;let g=await r.load();if(g){for(let b of g.turns)p(b);h=new Set(g.turns.map(b=>b.id));}},C=()=>{u||d<=0||(u=setInterval(()=>void m(),d));},S=()=>{u&&clearInterval(u),u=void 0;},k=()=>{if(c||!n.socketHost)return;let g=r.socketAuth;g&&(c=new _({auth:g,host:n.socketHost,onClosed:b=>{c=null,C(),b&&k();},onReady:S,onTurn:p,socketFactory:n.socketFactory}),c.open());};return C(),k(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(o),c?.close(),c=null,i.close(),t.remove();},identify:g=>r.identify(g),open:()=>{i.open().then(k);}}}exports.ChatClient=T;exports.ChatPanel=w;exports.DEFAULT_APPEARANCE=E;exports.DEFAULT_APPEARANCE_SETTINGS=f;exports.mountChat=Tt;exports.panelStyles=q;exports.resolveAppearance=L;//# sourceMappingURL=chat.cjs.map
|
|
110
|
+
`}${Ae[t.composerShape]}${Le[t.skin]}${z(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Pe[t.bubbleShape]}${Ne[t.bubbleFill]}${_e[t.namePlacement]}${t.nameAvatar?Fe:""}${t.dayDividers?Ie:""}${He[t.stampPlacement]}${t.stampContent==="time_and_latency"?Re:""}`}var qe=["end_user","agent","ai"];function je(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var Ye='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',L=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;l(this,"root");l(this,"strings");l(this,"settings");l(this,"appearance");l(this,"launcher");l(this,"badge");l(this,"panel",null);l(this,"scrim",null);l(this,"lastFocused",null);l(this,"unread",0);l(this,"pendingTurns",0);l(this,"openNow");l(this,"styles");l(this,"scheme");l(this,"picked",null);l(this,"objectUrls",[]);l(this,"helpLoader");l(this,"kit",null);l(this,"kitLoad",null);l(this,"filesLoader");l(this,"filesKit",null);l(this,"filesLoad",null);this.strings={...Te,...r},this.appearance={...E,...i},this.settings=w({...E,...i}),this.root=e.attachShadow({mode:a.shadowMode??"closed"}),this.openNow=N(this.appearance.availability,new Date),this.scheme=a.scheme,this.helpLoader=a.help,this.filesLoader=a.files,this.styles=Ve(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(B(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...E,...e},this.settings=w(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){this.styles(`${q(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(this.appearance.attachments?.enabled===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):(this.kitLoad??(this.kitLoad=this.helpLoader().then(e=>(this.kit=e,this.paint(),e))),this.kitLoad)}loadFiles(){return this.filesLoader?(this.filesLoad??(this.filesLoad=this.filesLoader().then(e=>(this.filesKit=e,this.paint(),e))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("span");r.className="grip",r.setAttribute("aria-hidden","true"),t.append(r);let i=this.appearance.team??[];i.length>0&&t.append(H(i,this.strings,x=>this.client.avatarUrl(x)));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let s=document.createElement("p");s.className="status";let h=document.createElement("span");h.className="live",h.setAttribute("aria-hidden","true"),s.append(h,this.strings.replyTime),a.append(o,s);let u=document.createElement("button");u.className="close",u.type="button",u.setAttribute("aria-label",this.strings.closeLabel),u.innerHTML=Ye,u.addEventListener("click",()=>this.close()),t.append(a,u);let c=document.createElement("div");c.className="log",c.setAttribute("role","log"),c.setAttribute("aria-live","polite"),c.setAttribute("aria-label",this.strings.title);let d=document.createElement("form");d.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let C=document.createElement("span");C.className="sendtext",C.textContent=this.strings.sendLabel,m.append(C),d.append(p,m),d.addEventListener("submit",x=>{x.preventDefault(),this.submit(p,c);}),e.append(t,c,d),this.appearance.poweredBy&&e.append(we(this.appearance.poweredBy,this.client.avatarUrl("/messenger-mark.png"))),e.addEventListener("keydown",x=>this.onKeydown(x,e,u));let S=document.createElement("div");S.className="scrim",S.addEventListener("click",()=>this.close()),this.root.append(S,e),this.panel=e,this.scrim=S,Je(e,()=>this.close()),p.focus();let k=this.appearance.attachments,[g]=await Promise.all([this.client.load(),this.loadKit(),k?.enabled&&this.client.upload?this.loadFiles():null]);if(g?.turns.some(x=>x.attachments?.length)&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&k?.enabled&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:x=>{this.picked=x;},objectUrl:x=>this.objectUrl(x),removeFileLabel:this.strings.removeFileLabel,root:this.root},d,p,c,k);let b=this.helpHost();b?.placement==="tab"&&b.host.source.collections&&b.host.source.collectionArticles&&b.kit.helpTab(b.host),b?.placement==="while_typing"&&b.kit.whileTyping(b.host,p,d),g&&g.turns.length>0?this.renderThread(c,g):this.renderFirstRun(c,p),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,r.append(i);let a=this.helpHost();if(a?.placement==="first_view")a.kit.firstView(a.host,r);else {let s=document.createElement("p");s.textContent=this.strings.emptyBody,r.append(s);}this.appearance.starterPrompts.filter(Be).forEach((s,h)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${h}`;let d=document.createElement("template");d.innerHTML=s.html,Ge(d.content)?c.append(d.content):c.textContent=s.text;for(let m of c.querySelectorAll("a"))m.target="_blank",m.rel="noopener noreferrer";let p=document.createElement("button");p.className="promptpress",p.type="button",p.setAttribute("aria-labelledby",c.id),p.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),u.append(c,p),r.append(u);}),e.replaceChildren(r);}helpHost(){let e=this.appearance.help,{kit:t,panel:r}=this,i=e&&t&&r?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:r,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.scrim?.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel&&e.attachments?.length&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let a=r?await this.client.upload?.(r):void 0,o=a===null?null:await this.client.send(t,je(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),o){i.dataset.turnId=o.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),(t.querySelector(".body")??t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){e.querySelector(".empty")?.remove();let i=qe.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${i}`,o.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let d=document.createElement("span");if(d.className=i==="ai"?"av bot":"av",d.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),d.append(p);}else {d.textContent=i==="ai"?this.strings.aiLabel:K(this.agentName(t));let p=i==="agent"?this.appearance.team?.find(m=>m.name===t.authorName)?.tone:void 0;p&&(d.style.background=p);}o.append(d);}let h=document.createElement("div");if(h.className="body",i==="end_user"){let d=this.filesKit,p=m=>this.objectUrl(m);r&&d?.drawFile(h,r.name,r.type,r.size,Promise.resolve(r),p);for(let m of t.attachments??[])d?.drawFile(h,m.name,m.contentType,m.bytes,this.client.file?.(m.url)??Promise.resolve(null),p);}let u=i!=="end_user"&&a.namePlacement!=="hidden",c=document.createElement("div");if(i==="ai"?Ke(c,t.body):c.textContent=t.body,u||i==="ai"&&a.namePlacement==="hidden"){let d=document.createElement("div");d.className=i==="ai"?"author ai":"author",d.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&d.append(this.stamp(t)),a.namePlacement==="inline"?(d.classList.add("below"),h.append(c,d)):h.append(d,c);}else t.body&&h.append(c);return a.stampPlacement==="under_turn"&&h.append(this.stamp(t)),o.append(h),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(h=>!h.closest("[hidden]")&&!h.hidden);if(i.length===0)return;let a=i[0],o=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},We="(max-width: 770px)";function Je(n,e){let t=null;n.addEventListener("pointerdown",i=>{if(t||i.button!==0||!globalThis.matchMedia?.(We).matches)return;let a=i.target;if(!a?.closest("a, button, input, textarea, iframe")){for(;a&&a!==n;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},n.setPointerCapture?.(i.pointerId),n.dataset.dragging="";}}),n.addEventListener("pointermove",i=>{if(t?.id!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),n.style.translate=`0 ${t.offset}px`;});let r=i=>{let a=t;if(a?.id!==i.pointerId)return;t=null,delete n.dataset.dragging;let o=a.offset>Math.min(72,n.getBoundingClientRect().height*.4),s=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;o||s?e():n.style.translate="";};n.addEventListener("pointerup",r),n.addEventListener("pointercancel",r);}var Ve=n=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in n&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return n.adoptedStyleSheets=[t],r=>t.replaceSync(r)}let e=document.createElement("style");return n.append(e),t=>{e.textContent=t;}};function j(n){return `40${JSON.stringify(n)}`}function Y(){return "3"}function W(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=R(t);return {kind:"open",pingInterval:typeof o?.pingInterval=="number"?o.pingInterval:25e3,pingTimeout:typeof o?.pingTimeout=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=R(i);return {kind:"connectError",message:typeof o?.message=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let a=R(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function R(n){try{return JSON.parse(n)}catch{return null}}var Xe="/socket.io/?EIO=4&transport=websocket",_=class{constructor(e){this.options=e;l(this,"socket",null);l(this,"heartbeat",null);l(this,"ready",false);l(this,"closed",false);l(this,"heartbeatWindow",45e3);l(this,"factory");l(this,"setTimer");l(this,"clearTimer");this.factory=e.socketFactory??Ze,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Xe}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=W(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(j(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(Y());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let r=t.payload?.turn;r&&this.options.onTurn(r);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ze(n){let e=globalThis.WebSocket;if(!e)throw new v("no WebSocket");return new e(n)}var Qe=6e4;function wt(n){let e=globalThis.document;if(!e)throw new P("prodantix chat requires a document; mount it in the browser");let t=n.mountPoint??e.createElement("div");n.mountPoint||e.body.append(t);let r=new T(n),i=new L(t,r,n.strings,n.appearance,{files:n.files,help:n.help}),a=n.appearance?.availability??E.availability,o,s=()=>{i.setOpenNow(N(a,new Date)),o=setTimeout(s,Qe);};s();let h=new Set,u,c=null,d=n.pollIntervalMs??15e3,p=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),i.onIncomingTurn(g));},m=async()=>{if(!r.hasThread)return;let g=await r.load();if(g){for(let b of g.turns)p(b);h=new Set(g.turns.map(b=>b.id));}},C=()=>{u||d<=0||(u=setInterval(()=>void m(),d));},S=()=>{u&&clearInterval(u),u=void 0;},k=()=>{if(c||!n.socketHost)return;let g=r.socketAuth;g&&(c=new _({auth:g,host:n.socketHost,onClosed:b=>{c=null,C(),b&&k();},onReady:S,onTurn:p,socketFactory:n.socketFactory}),c.open());};return C(),k(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(o),c?.close(),c=null,i.close(),t.remove();},identify:g=>r.identify(g),open:()=>{i.open().then(k);}}}exports.ChatClient=T;exports.ChatPanel=L;exports.DEFAULT_APPEARANCE=E;exports.DEFAULT_APPEARANCE_SETTINGS=f;exports.mountChat=wt;exports.panelStyles=q;exports.resolveAppearance=w;//# sourceMappingURL=chat.cjs.map
|
|
107
111
|
//# sourceMappingURL=chat.cjs.map
|
package/dist/chat.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as ArticleHit, a as ArticleCollection, H as HelpWords, M as MessengerAttachments, b as AppearanceSettings, C as ChatThread, P as PageContext, c as ChatTurn, d as ChatUpload, e as MessengerConfig, f as ChatIdentity, g as ChatClientOptions } from './config-
|
|
2
|
-
export { B as BubbleFill, h as BubbleShape, i as ChatAttachment, j as ChatClient, k as ChatStorage, l as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, m as FileResponseLike, L as LauncherContent, n as LauncherFill, o as LauncherShape, p as LauncherSize, q as MessengerSkin, N as NamePlacement, S as StampContent, r as StampPlacement, s as resolveAppearance } from './config-
|
|
1
|
+
import { A as ArticleHit, a as ArticleCollection, H as HelpWords, M as MessengerAttachments, b as AppearanceSettings, C as ChatThread, P as PageContext, c as ChatTurn, d as ChatUpload, e as MessengerConfig, f as ChatIdentity, g as ChatClientOptions } from './config-CpfUyEw8.cjs';
|
|
2
|
+
export { B as BubbleFill, h as BubbleShape, i as ChatAttachment, j as ChatClient, k as ChatStorage, l as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, m as FileResponseLike, L as LauncherContent, n as LauncherFill, o as LauncherShape, p as LauncherSize, q as MessengerSkin, N as NamePlacement, S as StampContent, r as StampPlacement, s as resolveAppearance } from './config-CpfUyEw8.cjs';
|
|
3
3
|
import { S as SocketFactory } from './types-Q2VNlJbG.cjs';
|
|
4
4
|
import './http-BCh716Vs.cjs';
|
|
5
5
|
|
|
@@ -119,7 +119,7 @@ interface ChatStrings {
|
|
|
119
119
|
removeFileLabel: string;
|
|
120
120
|
fileRefusal: (size: string, limit: string) => string;
|
|
121
121
|
}
|
|
122
|
-
type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'attachments' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'help' | 'starterPrompts' | 'team'> & AppearanceSettings;
|
|
122
|
+
type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'attachments' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'help' | 'poweredBy' | 'starterPrompts' | 'team'> & AppearanceSettings;
|
|
123
123
|
declare const DEFAULT_APPEARANCE: MessengerAppearance;
|
|
124
124
|
interface ChatSource {
|
|
125
125
|
avatarUrl(url: string): string;
|
package/dist/chat.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as ArticleHit, a as ArticleCollection, H as HelpWords, M as MessengerAttachments, b as AppearanceSettings, C as ChatThread, P as PageContext, c as ChatTurn, d as ChatUpload, e as MessengerConfig, f as ChatIdentity, g as ChatClientOptions } from './config-
|
|
2
|
-
export { B as BubbleFill, h as BubbleShape, i as ChatAttachment, j as ChatClient, k as ChatStorage, l as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, m as FileResponseLike, L as LauncherContent, n as LauncherFill, o as LauncherShape, p as LauncherSize, q as MessengerSkin, N as NamePlacement, S as StampContent, r as StampPlacement, s as resolveAppearance } from './config-
|
|
1
|
+
import { A as ArticleHit, a as ArticleCollection, H as HelpWords, M as MessengerAttachments, b as AppearanceSettings, C as ChatThread, P as PageContext, c as ChatTurn, d as ChatUpload, e as MessengerConfig, f as ChatIdentity, g as ChatClientOptions } from './config-C9Njc6-j.js';
|
|
2
|
+
export { B as BubbleFill, h as BubbleShape, i as ChatAttachment, j as ChatClient, k as ChatStorage, l as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, m as FileResponseLike, L as LauncherContent, n as LauncherFill, o as LauncherShape, p as LauncherSize, q as MessengerSkin, N as NamePlacement, S as StampContent, r as StampPlacement, s as resolveAppearance } from './config-C9Njc6-j.js';
|
|
3
3
|
import { S as SocketFactory } from './types-Q2VNlJbG.js';
|
|
4
4
|
import './http-BCh716Vs.js';
|
|
5
5
|
|
|
@@ -119,7 +119,7 @@ interface ChatStrings {
|
|
|
119
119
|
removeFileLabel: string;
|
|
120
120
|
fileRefusal: (size: string, limit: string) => string;
|
|
121
121
|
}
|
|
122
|
-
type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'attachments' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'help' | 'starterPrompts' | 'team'> & AppearanceSettings;
|
|
122
|
+
type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'attachments' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'help' | 'poweredBy' | 'starterPrompts' | 'team'> & AppearanceSettings;
|
|
123
123
|
declare const DEFAULT_APPEARANCE: MessengerAppearance;
|
|
124
124
|
interface ChatSource {
|
|
125
125
|
avatarUrl(url: string): string;
|
package/dist/chat.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {c,a as a$1,b as b$1}from'./chunk-V77KYPOF.js';import {e,h,d,b}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var z="X-Prodantix-Conversation-Token",F="prodantix.chat.handle";function Y(){let r=globalThis.localStorage;if(r)return {get:e=>r.getItem(e),remove:e=>r.removeItem(e),set:(e,t)=>r.setItem(e,t)}}var w=class{constructor(e$1){this.options=e$1;a(this,"fetchImpl");a(this,"fileFetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=e(e$1.fetchImpl),this.fileFetchImpl=e$1.fileFetchImpl??((t,n)=>fetch(t,n)),this.host=h(e$1.host),this.storage=e$1.storage??Y(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(F,JSON.stringify(this.handle)),true)}async send(e,t,n){if(!await this.ensureThread())return null;let i=this.handle;return i?(await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:n,body:e,pageContext:t},token:i.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async n=>JSON.parse(await n.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,n=>n.blob()):null}async helpCentre(e,t){let n=Object.entries({...t,...this.options.locale?{lang:this.options.locale}:{}}).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return this.request("GET",`/v1/messenger/articles${e}${n?`?${n}`:""}`)}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(F);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(F),null}async fileRequest(e,t,n,i,a){let s={authorization:`Bearer ${this.options.apiKey}`,[z]:n};a&&(s["content-type"]=a.type||"application/octet-stream");try{let o=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:s,method:e});if(o.ok)return await i(o);this.options.onError?.(new d(`prodantix chat ${t}: ${o.status}`,o.status));}catch(o){this.options.onError?.(o);}return null}async request(e,t,n={}){let i=this.fetchImpl;if(!i)return this.options.onError?.(new d("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(a[z]=n.token);try{let s=await i(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:a,method:e}),o=await s.text();return s.ok?o?JSON.parse(o):{}:(this.options.onError?.(new d(`prodantix chat ${t}: ${s.status}`,s.status)),null)}catch(s){return this.options.onError?.(s),null}}};var W={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function A(r,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:r.timezone,weekday:"short"}).formatToParts(e),n=W[t.find(o=>o.type==="weekday")?.value??""];if(!n)return false;let i=t.find(o=>o.type==="hour")?.value??"",a=t.find(o=>o.type==="minute")?.value??"",s=`${i}:${a}`;return r.windows.some(o=>o.days.includes(n)&&o.open<=s&&s<o.close)}var f={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},J=["quiet","standard"],X=["round","square"],V=["rounded","tailed"],Z=["filled","outlined"],Q=["circle","pill","squircle"],ee=["filled","outlined"],te=["avatar","glyph","team_faces"],ne=["large","medium","small"],re=["above","hidden","inline"],ie=["beside_name","none","under_turn"],ae=["time","time_and_latency"],x=(r,e,t)=>typeof r=="string"&&e.includes(r)?r:t,B=(r,e)=>typeof r=="boolean"?r:e,oe={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},se={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},le={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ce={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},de={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function T(r){let e=typeof r=="object"&&r!==null?r:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:oe[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:se[i],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,o=s===void 0?void 0:le[s],h=typeof e.skin=="string"?e.skin:void 0,u=h===void 0?void 0:ce[h],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,d=c===void 0?void 0:de[c],p={bubbleFill:x(e.bubbleFill,Z,d?.[1]??f.bubbleFill),bubbleShape:x(e.bubbleShape,V,d?.[0]??f.bubbleShape),composerShape:x(e.composerShape,X,u?.[1]??f.composerShape),dayDividers:B(e.dayDividers,o?.[0]??f.dayDividers),launcherContent:x(e.launcherContent,te,n?.[2]??f.launcherContent),launcherFill:x(e.launcherFill,ee,n?.[1]??f.launcherFill),launcherShape:x(e.launcherShape,Q,n?.[0]??f.launcherShape),launcherSize:x(e.launcherSize,ne,n?.[3]??f.launcherSize),nameAvatar:B(e.nameAvatar,a?.[1]??f.nameAvatar),namePlacement:x(e.namePlacement,re,a?.[0]??f.namePlacement),skin:x(e.skin,J,u?.[0]??f.skin),stampContent:x(e.stampContent,ae,o?.[2]??f.stampContent),stampPlacement:x(e.stampPlacement,ie,o?.[1]??f.stampPlacement)};return p.stampPlacement==="beside_name"&&p.namePlacement==="hidden"&&(p.stampPlacement="under_turn"),p}function O(r){let e=r.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var pe="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",he={large:66,medium:56,small:46},ue={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},me={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},ge={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},fe=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",be={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ye={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},xe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ve={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function K(r,e,t,n){return `.launcher{--fab-size:${he[n]}px;${ue[r]}${me[e]}}${ge[t]}${fe}${be[r]}${ye[e]}${xe[r]}${ve[r]}`}function D(r,e,t,n=i=>i){let i=document.createDocumentFragment();if(r==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${pe}"/></svg>`,i.append(...a.childNodes,_()),i}return r==="avatar"?(i.append(q(t[0],e,n),_()),i):(i.append(H(t,e,n),_()),i)}function H(r,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let i of r.slice(0,2))n.append(q(i,e,t));return n}function q(r,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),r&&(n.style.background=r.tone),r?.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(r.avatarUrl),n.append(i),n}return n.textContent=r?r.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function _(){let r=document.createElement("span");return r.className="live",r.setAttribute("aria-hidden","true"),r}var Se={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(r,e)=>`That file is ${r}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:r=>{let e=new Date(r);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:r=>`${r} unread`},L={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...f},ke={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Ce={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Le={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},we={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Te={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Ee=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Ae='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Pe={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Fe=".lat{font-size:11px;opacity:.7;margin-left:6px}",j=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
import {c,a as a$1,b as b$1}from'./chunk-V77KYPOF.js';import {e,h,d,b}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var z="X-Prodantix-Conversation-Token",F="prodantix.chat.handle";function Y(){let r=globalThis.localStorage;if(r)return {get:e=>r.getItem(e),remove:e=>r.removeItem(e),set:(e,t)=>r.setItem(e,t)}}var L=class{constructor(e$1){this.options=e$1;a(this,"fetchImpl");a(this,"fileFetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=e(e$1.fetchImpl),this.fileFetchImpl=e$1.fileFetchImpl??((t,n)=>fetch(t,n)),this.host=h(e$1.host),this.storage=e$1.storage??Y(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(F,JSON.stringify(this.handle)),true)}async send(e,t,n){if(!await this.ensureThread())return null;let i=this.handle;return i?(await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:n,body:e,pageContext:t},token:i.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async n=>JSON.parse(await n.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,n=>n.blob()):null}async helpCentre(e,t){let n=Object.entries({...t,...this.options.locale?{lang:this.options.locale}:{}}).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return this.request("GET",`/v1/messenger/articles${e}${n?`?${n}`:""}`)}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(F);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(F),null}async fileRequest(e,t,n,i,a){let s={authorization:`Bearer ${this.options.apiKey}`,[z]:n};a&&(s["content-type"]=a.type||"application/octet-stream");try{let o=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:s,method:e});if(o.ok)return await i(o);this.options.onError?.(new d(`prodantix chat ${t}: ${o.status}`,o.status));}catch(o){this.options.onError?.(o);}return null}async request(e,t,n={}){let i=this.fetchImpl;if(!i)return this.options.onError?.(new d("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(a[z]=n.token);try{let s=await i(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:a,method:e}),o=await s.text();return s.ok?o?JSON.parse(o):{}:(this.options.onError?.(new d(`prodantix chat ${t}: ${s.status}`,s.status)),null)}catch(s){return this.options.onError?.(s),null}}};var W={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function A(r,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:r.timezone,weekday:"short"}).formatToParts(e),n=W[t.find(o=>o.type==="weekday")?.value??""];if(!n)return false;let i=t.find(o=>o.type==="hour")?.value??"",a=t.find(o=>o.type==="minute")?.value??"",s=`${i}:${a}`;return r.windows.some(o=>o.days.includes(n)&&o.open<=s&&s<o.close)}var f={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},J=["quiet","standard"],X=["round","square"],V=["rounded","tailed"],Z=["filled","outlined"],Q=["circle","pill","squircle"],ee=["filled","outlined"],te=["avatar","glyph","team_faces"],ne=["large","medium","small"],re=["above","hidden","inline"],ie=["beside_name","none","under_turn"],ae=["time","time_and_latency"],x=(r,e,t)=>typeof r=="string"&&e.includes(r)?r:t,B=(r,e)=>typeof r=="boolean"?r:e,oe={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},se={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},le={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ce={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},de={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function T(r){let e=typeof r=="object"&&r!==null?r:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:oe[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:se[i],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,o=s===void 0?void 0:le[s],h=typeof e.skin=="string"?e.skin:void 0,u=h===void 0?void 0:ce[h],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,d=c===void 0?void 0:de[c],p={bubbleFill:x(e.bubbleFill,Z,d?.[1]??f.bubbleFill),bubbleShape:x(e.bubbleShape,V,d?.[0]??f.bubbleShape),composerShape:x(e.composerShape,X,u?.[1]??f.composerShape),dayDividers:B(e.dayDividers,o?.[0]??f.dayDividers),launcherContent:x(e.launcherContent,te,n?.[2]??f.launcherContent),launcherFill:x(e.launcherFill,ee,n?.[1]??f.launcherFill),launcherShape:x(e.launcherShape,Q,n?.[0]??f.launcherShape),launcherSize:x(e.launcherSize,ne,n?.[3]??f.launcherSize),nameAvatar:B(e.nameAvatar,a?.[1]??f.nameAvatar),namePlacement:x(e.namePlacement,re,a?.[0]??f.namePlacement),skin:x(e.skin,J,u?.[0]??f.skin),stampContent:x(e.stampContent,ae,o?.[2]??f.stampContent),stampPlacement:x(e.stampPlacement,ie,o?.[1]??f.stampPlacement)};return p.stampPlacement==="beside_name"&&p.namePlacement==="hidden"&&(p.stampPlacement="under_turn"),p}function O(r){let e=r.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var pe="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",he={large:66,medium:56,small:46},ue={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},me={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},ge={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},fe=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",be={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ye={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},xe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ve={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function K(r,e,t,n){return `.launcher{--fab-size:${he[n]}px;${ue[r]}${me[e]}}${ge[t]}${fe}${be[r]}${ye[e]}${xe[r]}${ve[r]}`}function D(r,e,t,n=i=>i){let i=document.createDocumentFragment();if(r==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${pe}"/></svg>`,i.append(...a.childNodes,_()),i}return r==="avatar"?(i.append(q(t[0],e,n),_()),i):(i.append(H(t,e,n),_()),i)}function H(r,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let i of r.slice(0,2))n.append(q(i,e,t));return n}function q(r,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),r&&(n.style.background=r.tone),r?.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(r.avatarUrl),n.append(i),n}return n.textContent=r?r.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function _(){let r=document.createElement("span");return r.className="live",r.setAttribute("aria-hidden","true"),r}var Se={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(r,e)=>`That file is ${r}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:r=>{let e=new Date(r);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:r=>`${r} unread`},w={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...f};function ke(r,e){let t=document.createElement("a");t.className="powered",t.href="https://prodantix.com",t.target="_blank",t.rel="noopener";let n=document.createElement("img");return n.src=e,n.alt="",n.width=12,n.height=12,t.append(n,r),t}var Ce={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},we={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Le={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Te={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ee={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Ae=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Pe='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Fe={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},_e=".lat{font-size:11px;opacity:.7;margin-left:6px}",j=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
-
--online: oklch(72% 0.13 163.23);`;function
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function He(r){return r==="light"?"":r==="dark"?`:host { ${j} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
5
5
|
${j}
|
|
6
6
|
}
|
|
7
|
-
}`}var
|
|
7
|
+
}`}var Ne=/https?:\/\/[^\s<>"]+/g,Re=/[.,;:!?)]$/,Ie=r=>{let e=r;for(;Re.test(e);){let t=e.split("(").length-1,n=e.split(")").length-1;if(e.endsWith(")")&&t>=n)break;e=e.slice(0,-1);}return e};function $e(r,e){let t=0;for(let n of e.matchAll(Ne)){let i=n.index??0,a=Ie(n[0]);i>t&&r.append(e.slice(t,i));let s=document.createElement("a");s.href=a,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,r.append(s),t=i+a.length;}t<e.length&&r.append(e.slice(t));}var Me=["P","BR","STRONG","EM","A","UL","OL","LI"],Ue=r=>typeof r=="object"&&r!==null&&"html"in r&&typeof r.html=="string"&&"text"in r&&typeof r.text=="string",ze=(r,e)=>e.name==="class"||e.name==="data-block-type"?true:r!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),Be=r=>[...r.querySelectorAll("*")].every(e=>Me.includes(e.tagName)&&[...e.attributes].every(t=>ze(e.tagName,t)));function G(r,e="system"){let t=T(r),n=r.launcherPosition==="bottom_left"?"left":"right",i=r.accentColor;return `${`
|
|
8
8
|
:host {
|
|
9
9
|
all: initial; z-index: 2147483000; --a: ${i};
|
|
10
10
|
--paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
|
|
@@ -12,7 +12,7 @@ import {c,a as a$1,b as b$1}from'./chunk-V77KYPOF.js';import {e,h,d,b}from'./chu
|
|
|
12
12
|
--online: oklch(53.8% 0.1274 163.23);
|
|
13
13
|
color-scheme: ${e==="system"?"light dark":e};
|
|
14
14
|
}
|
|
15
|
-
${
|
|
15
|
+
${He(e)}
|
|
16
16
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
17
17
|
.launcher {
|
|
18
18
|
z-index: 2147483000; position: fixed; ${n}: ${r.launcherOffsetX}px; bottom: ${r.launcherOffsetY}px; width: 56px; height: 56px;
|
|
@@ -98,10 +98,14 @@ ${_e(e)}
|
|
|
98
98
|
.composer button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
|
|
99
99
|
.composer button .sendglyph { display: none; width: 17px; height: 17px; }
|
|
100
100
|
.composer button:focus-visible { outline: 2px solid #0b0e14; }
|
|
101
|
+
.powered { display: flex; align-items: center; justify-content: center; gap: 4px; height: 24px; font-size: 11px; font-weight: 500; color: var(--ink-3); text-decoration: none; }
|
|
102
|
+
.powered:hover { color: var(--ink-2); }
|
|
103
|
+
.powered:focus-visible { outline: 2px solid var(--ink); outline-offset: -2px; }
|
|
104
|
+
.powered img { width: 12px; height: 12px; }
|
|
101
105
|
@media (prefers-reduced-motion: no-preference) {
|
|
102
106
|
.panel { animation: rise 180ms ease-out; }
|
|
103
107
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
104
108
|
}
|
|
105
109
|
.scrim,.grip{display:none}@media (max-width:770px){.panel{inset:auto 0 0;width:100%;max-width:none;height:86dvh;max-height:86dvh}:host .panel{border-bottom-left-radius:0;border-bottom-right-radius:0}.scrim{display:block;position:fixed;inset:0;z-index:2147483000;background:rgb(15 23 42/.24)}.grip{display:block;position:absolute;top:7px;left:calc(50% - 17px);width:34px;height:4px;border-radius:2px;background:currentColor;opacity:.45}.panel:not([data-dragging]){transition:translate .2s}.composer{padding-bottom:max(12px,env(safe-area-inset-bottom))}}
|
|
106
|
-
`}${Ce[t.composerShape]}${ke[t.skin]}${K(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Le[t.bubbleShape]}${we[t.bubbleFill]}${Te[t.namePlacement]}${t.nameAvatar?Ee:""}${t.dayDividers?Ae:""}${Pe[t.stampPlacement]}${t.stampContent==="time_and_latency"?Fe:""}`}var Be=["end_user","agent","ai"];function Oe(){let r=globalThis.location;if(r)return {host:r.host,path:r.pathname,title:document.title}}var Ke='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',E=class{constructor(e,t,n={},i={},a$1={}){this.host=e;this.client=t;a(this,"root");a(this,"strings");a(this,"settings");a(this,"appearance");a(this,"launcher");a(this,"badge");a(this,"panel",null);a(this,"scrim",null);a(this,"lastFocused",null);a(this,"unread",0);a(this,"pendingTurns",0);a(this,"openNow");a(this,"styles");a(this,"scheme");a(this,"picked",null);a(this,"objectUrls",[]);a(this,"helpLoader");a(this,"kit",null);a(this,"kitLoad",null);a(this,"filesLoader");a(this,"filesKit",null);a(this,"filesLoad",null);this.strings={...Se,...n},this.appearance={...L,...i},this.settings=T({...L,...i}),this.root=e.attachShadow({mode:a$1.shadowMode??"closed"}),this.openNow=A(this.appearance.availability,new Date),this.scheme=a$1.scheme,this.helpLoader=a$1.help,this.filesLoader=a$1.files,this.styles=je(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(D(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...L,...e},this.settings=T(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){this.styles(`${G(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(this.appearance.attachments?.enabled===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):(this.kitLoad??(this.kitLoad=this.helpLoader().then(e=>(this.kit=e,this.paint(),e))),this.kitLoad)}loadFiles(){return this.filesLoader?(this.filesLoad??(this.filesLoad=this.filesLoader().then(e=>(this.filesKit=e,this.paint(),e))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=document.createElement("span");n.className="grip",n.setAttribute("aria-hidden","true"),t.append(n);let i=this.appearance.team??[];i.length>0&&t.append(H(i,this.strings,y=>this.client.avatarUrl(y)));let a=document.createElement("div");a.className="headmain";let s=document.createElement("h2");s.textContent=this.strings.title;let o=document.createElement("p");o.className="status";let h=document.createElement("span");h.className="live",h.setAttribute("aria-hidden","true"),o.append(h,this.strings.replyTime),a.append(s,o);let u=document.createElement("button");u.className="close",u.type="button",u.setAttribute("aria-label",this.strings.closeLabel),u.innerHTML=Ke,u.addEventListener("click",()=>this.close()),t.append(a,u);let c=document.createElement("div");c.className="log",c.setAttribute("role","log"),c.setAttribute("aria-live","polite"),c.setAttribute("aria-label",this.strings.title);let d=document.createElement("form");d.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let k=document.createElement("span");k.className="sendtext",k.textContent=this.strings.sendLabel,m.append(k),d.append(p,m),d.addEventListener("submit",y=>{y.preventDefault(),this.submit(p,c);}),e.append(t,c,d),e.addEventListener("keydown",y=>this.onKeydown(y,e,u));let v=document.createElement("div");v.className="scrim",v.addEventListener("click",()=>this.close()),this.root.append(v,e),this.panel=e,this.scrim=v,qe(e,()=>this.close()),p.focus();let S=this.appearance.attachments,[g]=await Promise.all([this.client.load(),this.loadKit(),S?.enabled&&this.client.upload?this.loadFiles():null]);if(g?.turns.some(y=>y.attachments?.length)&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&S?.enabled&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:y=>{this.picked=y;},objectUrl:y=>this.objectUrl(y),removeFileLabel:this.strings.removeFileLabel,root:this.root},d,p,c,S);let b=this.helpHost();b?.placement==="tab"&&b.host.source.collections&&b.host.source.collectionArticles&&b.kit.helpTab(b.host),b?.placement==="while_typing"&&b.kit.whileTyping(b.host,p,d),g&&g.turns.length>0?this.renderThread(c,g):this.renderFirstRun(c,p),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,n.append(i);let a=this.helpHost();if(a?.placement==="first_view")a.kit.firstView(a.host,n);else {let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(o);}this.appearance.starterPrompts.filter(Me).forEach((o,h)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${h}`;let d=document.createElement("template");d.innerHTML=o.html,ze(d.content)?c.append(d.content):c.textContent=o.text;for(let m of c.querySelectorAll("a"))m.target="_blank",m.rel="noopener noreferrer";let p=document.createElement("button");p.className="promptpress",p.type="button",p.setAttribute("aria-labelledby",c.id),p.addEventListener("click",()=>{t.value=o.text,this.submit(t,e);}),u.append(c,p),n.append(u);}),e.replaceChildren(n);}helpHost(){let e=this.appearance.help,{kit:t,panel:n}=this,i=e&&t&&n?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:n,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let n=document.createElement("span");n.className="awayglyph",n.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(n,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.scrim?.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel&&e.attachments?.length&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim(),i=this.picked;if(!(!n&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,n,i);}}async sendBody(e,t,n=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},n);i.setAttribute("data-pending","");let a=n?await this.client.upload?.(n):void 0,s=a===null?null:await this.client.send(t,Oe(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),s){i.dataset.turnId=s.id;return}this.markFailed(e,i,t,n);}markFailed(e,t,n,i){t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,n,i);}),(t.querySelector(".body")??t).append(a);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t,n=null){e.querySelector(".empty")?.remove();let i=Be.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,s=document.createElement("div");if(s.className=`turn ${i}`,s.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let d=document.createElement("span");if(d.className=i==="ai"?"av bot":"av",d.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),d.append(p);}else {d.textContent=i==="ai"?this.strings.aiLabel:O(this.agentName(t));let p=i==="agent"?this.appearance.team?.find(m=>m.name===t.authorName)?.tone:void 0;p&&(d.style.background=p);}s.append(d);}let h=document.createElement("div");if(h.className="body",i==="end_user"){let d=this.filesKit,p=m=>this.objectUrl(m);n&&d?.drawFile(h,n.name,n.type,n.size,Promise.resolve(n),p);for(let m of t.attachments??[])d?.drawFile(h,m.name,m.contentType,m.bytes,this.client.file?.(m.url)??Promise.resolve(null),p);}let u=i!=="end_user"&&a.namePlacement!=="hidden",c=document.createElement("div");if(i==="ai"?Ie(c,t.body):c.textContent=t.body,u||i==="ai"&&a.namePlacement==="hidden"){let d=document.createElement("div");d.className=i==="ai"?"author ai":"author",d.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&d.append(this.stamp(t)),a.namePlacement==="inline"?(d.classList.add("below"),h.append(c,d)):h.append(d,c);}else t.body&&h.append(c);return a.stampPlacement==="under_turn"&&h.append(this.stamp(t)),s.append(h),e.append(s),e.scrollTop=e.scrollHeight,s}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(h=>!h.closest("[hidden]")&&!h.hidden);if(i.length===0)return;let a=i[0],s=i[i.length-1],o=this.root.activeElement;e.shiftKey&&o===a?(e.preventDefault(),s.focus()):!e.shiftKey&&o===s?(e.preventDefault(),a.focus()):o===null&&(e.preventDefault(),n.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},De="(max-width: 770px)";function qe(r,e){let t=null;r.addEventListener("pointerdown",i=>{if(t||i.button!==0||!globalThis.matchMedia?.(De).matches)return;let a=i.target;if(!a?.closest("a, button, input, textarea, iframe")){for(;a&&a!==r;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},r.setPointerCapture?.(i.pointerId),r.dataset.dragging="";}}),r.addEventListener("pointermove",i=>{if(t?.id!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),r.style.translate=`0 ${t.offset}px`;});let n=i=>{let a=t;if(a?.id!==i.pointerId)return;t=null,delete r.dataset.dragging;let s=a.offset>Math.min(72,r.getBoundingClientRect().height*.4),o=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;s||o?e():r.style.translate="";};r.addEventListener("pointerup",n),r.addEventListener("pointercancel",n);}var je=r=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in r&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return r.adoptedStyleSheets=[t],n=>t.replaceSync(n)}let e=document.createElement("style");return r.append(e),t=>{e.textContent=t;}};var Ge="/socket.io/?EIO=4&transport=websocket",P=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??Ye,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ge}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$1(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$1());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ye(r){let e=globalThis.WebSocket;if(!e)throw new d("no WebSocket");return new e(r)}var We=6e4;function ft(r){let e=globalThis.document;if(!e)throw new b("prodantix chat requires a document; mount it in the browser");let t=r.mountPoint??e.createElement("div");r.mountPoint||e.body.append(t);let n=new w(r),i=new E(t,n,r.strings,r.appearance,{files:r.files,help:r.help}),a=r.appearance?.availability??L.availability,s,o=()=>{i.setOpenNow(A(a,new Date)),s=setTimeout(o,We);};o();let h=new Set,u,c=null,d=r.pollIntervalMs??15e3,p=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),i.onIncomingTurn(g));},m=async()=>{if(!n.hasThread)return;let g=await n.load();if(g){for(let b of g.turns)p(b);h=new Set(g.turns.map(b=>b.id));}},k=()=>{u||d<=0||(u=setInterval(()=>void m(),d));},v=()=>{u&&clearInterval(u),u=void 0;},S=()=>{if(c||!r.socketHost)return;let g=n.socketAuth;g&&(c=new P({auth:g,host:r.socketHost,onClosed:b=>{c=null,k(),b&&S();},onReady:v,onTurn:p,socketFactory:r.socketFactory}),c.open());};return k(),S(),{close:()=>i.close(),destroy:()=>{v(),clearTimeout(s),c?.close(),c=null,i.close(),t.remove();},identify:g=>n.identify(g),open:()=>{i.open().then(S);}}}export{w as ChatClient,E as ChatPanel,L as DEFAULT_APPEARANCE,f as DEFAULT_APPEARANCE_SETTINGS,ft as mountChat,G as panelStyles,T as resolveAppearance};//# sourceMappingURL=chat.js.map
|
|
110
|
+
`}${we[t.composerShape]}${Ce[t.skin]}${K(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Le[t.bubbleShape]}${Te[t.bubbleFill]}${Ee[t.namePlacement]}${t.nameAvatar?Ae:""}${t.dayDividers?Pe:""}${Fe[t.stampPlacement]}${t.stampContent==="time_and_latency"?_e:""}`}var Oe=["end_user","agent","ai"];function Ke(){let r=globalThis.location;if(r)return {host:r.host,path:r.pathname,title:document.title}}var De='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',E=class{constructor(e,t,n={},i={},a$1={}){this.host=e;this.client=t;a(this,"root");a(this,"strings");a(this,"settings");a(this,"appearance");a(this,"launcher");a(this,"badge");a(this,"panel",null);a(this,"scrim",null);a(this,"lastFocused",null);a(this,"unread",0);a(this,"pendingTurns",0);a(this,"openNow");a(this,"styles");a(this,"scheme");a(this,"picked",null);a(this,"objectUrls",[]);a(this,"helpLoader");a(this,"kit",null);a(this,"kitLoad",null);a(this,"filesLoader");a(this,"filesKit",null);a(this,"filesLoad",null);this.strings={...Se,...n},this.appearance={...w,...i},this.settings=T({...w,...i}),this.root=e.attachShadow({mode:a$1.shadowMode??"closed"}),this.openNow=A(this.appearance.availability,new Date),this.scheme=a$1.scheme,this.helpLoader=a$1.help,this.filesLoader=a$1.files,this.styles=Ge(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(D(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...w,...e},this.settings=T(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){this.styles(`${G(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(this.appearance.attachments?.enabled===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):(this.kitLoad??(this.kitLoad=this.helpLoader().then(e=>(this.kit=e,this.paint(),e))),this.kitLoad)}loadFiles(){return this.filesLoader?(this.filesLoad??(this.filesLoad=this.filesLoader().then(e=>(this.filesKit=e,this.paint(),e))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=document.createElement("span");n.className="grip",n.setAttribute("aria-hidden","true"),t.append(n);let i=this.appearance.team??[];i.length>0&&t.append(H(i,this.strings,y=>this.client.avatarUrl(y)));let a=document.createElement("div");a.className="headmain";let s=document.createElement("h2");s.textContent=this.strings.title;let o=document.createElement("p");o.className="status";let h=document.createElement("span");h.className="live",h.setAttribute("aria-hidden","true"),o.append(h,this.strings.replyTime),a.append(s,o);let u=document.createElement("button");u.className="close",u.type="button",u.setAttribute("aria-label",this.strings.closeLabel),u.innerHTML=De,u.addEventListener("click",()=>this.close()),t.append(a,u);let c=document.createElement("div");c.className="log",c.setAttribute("role","log"),c.setAttribute("aria-live","polite"),c.setAttribute("aria-label",this.strings.title);let d=document.createElement("form");d.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let k=document.createElement("span");k.className="sendtext",k.textContent=this.strings.sendLabel,m.append(k),d.append(p,m),d.addEventListener("submit",y=>{y.preventDefault(),this.submit(p,c);}),e.append(t,c,d),this.appearance.poweredBy&&e.append(ke(this.appearance.poweredBy,this.client.avatarUrl("/messenger-mark.png"))),e.addEventListener("keydown",y=>this.onKeydown(y,e,u));let v=document.createElement("div");v.className="scrim",v.addEventListener("click",()=>this.close()),this.root.append(v,e),this.panel=e,this.scrim=v,je(e,()=>this.close()),p.focus();let S=this.appearance.attachments,[g]=await Promise.all([this.client.load(),this.loadKit(),S?.enabled&&this.client.upload?this.loadFiles():null]);if(g?.turns.some(y=>y.attachments?.length)&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&S?.enabled&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:y=>{this.picked=y;},objectUrl:y=>this.objectUrl(y),removeFileLabel:this.strings.removeFileLabel,root:this.root},d,p,c,S);let b=this.helpHost();b?.placement==="tab"&&b.host.source.collections&&b.host.source.collectionArticles&&b.kit.helpTab(b.host),b?.placement==="while_typing"&&b.kit.whileTyping(b.host,p,d),g&&g.turns.length>0?this.renderThread(c,g):this.renderFirstRun(c,p),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,n.append(i);let a=this.helpHost();if(a?.placement==="first_view")a.kit.firstView(a.host,n);else {let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(o);}this.appearance.starterPrompts.filter(Ue).forEach((o,h)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${h}`;let d=document.createElement("template");d.innerHTML=o.html,Be(d.content)?c.append(d.content):c.textContent=o.text;for(let m of c.querySelectorAll("a"))m.target="_blank",m.rel="noopener noreferrer";let p=document.createElement("button");p.className="promptpress",p.type="button",p.setAttribute("aria-labelledby",c.id),p.addEventListener("click",()=>{t.value=o.text,this.submit(t,e);}),u.append(c,p),n.append(u);}),e.replaceChildren(n);}helpHost(){let e=this.appearance.help,{kit:t,panel:n}=this,i=e&&t&&n?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:n,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let n=document.createElement("span");n.className="awayglyph",n.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(n,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.scrim?.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel&&e.attachments?.length&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim(),i=this.picked;if(!(!n&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,n,i);}}async sendBody(e,t,n=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},n);i.setAttribute("data-pending","");let a=n?await this.client.upload?.(n):void 0,s=a===null?null:await this.client.send(t,Ke(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),s){i.dataset.turnId=s.id;return}this.markFailed(e,i,t,n);}markFailed(e,t,n,i){t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,n,i);}),(t.querySelector(".body")??t).append(a);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t,n=null){e.querySelector(".empty")?.remove();let i=Oe.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,s=document.createElement("div");if(s.className=`turn ${i}`,s.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let d=document.createElement("span");if(d.className=i==="ai"?"av bot":"av",d.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),d.append(p);}else {d.textContent=i==="ai"?this.strings.aiLabel:O(this.agentName(t));let p=i==="agent"?this.appearance.team?.find(m=>m.name===t.authorName)?.tone:void 0;p&&(d.style.background=p);}s.append(d);}let h=document.createElement("div");if(h.className="body",i==="end_user"){let d=this.filesKit,p=m=>this.objectUrl(m);n&&d?.drawFile(h,n.name,n.type,n.size,Promise.resolve(n),p);for(let m of t.attachments??[])d?.drawFile(h,m.name,m.contentType,m.bytes,this.client.file?.(m.url)??Promise.resolve(null),p);}let u=i!=="end_user"&&a.namePlacement!=="hidden",c=document.createElement("div");if(i==="ai"?$e(c,t.body):c.textContent=t.body,u||i==="ai"&&a.namePlacement==="hidden"){let d=document.createElement("div");d.className=i==="ai"?"author ai":"author",d.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&d.append(this.stamp(t)),a.namePlacement==="inline"?(d.classList.add("below"),h.append(c,d)):h.append(d,c);}else t.body&&h.append(c);return a.stampPlacement==="under_turn"&&h.append(this.stamp(t)),s.append(h),e.append(s),e.scrollTop=e.scrollHeight,s}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(h=>!h.closest("[hidden]")&&!h.hidden);if(i.length===0)return;let a=i[0],s=i[i.length-1],o=this.root.activeElement;e.shiftKey&&o===a?(e.preventDefault(),s.focus()):!e.shiftKey&&o===s?(e.preventDefault(),a.focus()):o===null&&(e.preventDefault(),n.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},qe="(max-width: 770px)";function je(r,e){let t=null;r.addEventListener("pointerdown",i=>{if(t||i.button!==0||!globalThis.matchMedia?.(qe).matches)return;let a=i.target;if(!a?.closest("a, button, input, textarea, iframe")){for(;a&&a!==r;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},r.setPointerCapture?.(i.pointerId),r.dataset.dragging="";}}),r.addEventListener("pointermove",i=>{if(t?.id!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),r.style.translate=`0 ${t.offset}px`;});let n=i=>{let a=t;if(a?.id!==i.pointerId)return;t=null,delete r.dataset.dragging;let s=a.offset>Math.min(72,r.getBoundingClientRect().height*.4),o=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;s||o?e():r.style.translate="";};r.addEventListener("pointerup",n),r.addEventListener("pointercancel",n);}var Ge=r=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in r&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return r.adoptedStyleSheets=[t],n=>t.replaceSync(n)}let e=document.createElement("style");return r.append(e),t=>{e.textContent=t;}};var Ye="/socket.io/?EIO=4&transport=websocket",P=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??We,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ye}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$1(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$1());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function We(r){let e=globalThis.WebSocket;if(!e)throw new d("no WebSocket");return new e(r)}var Je=6e4;function bt(r){let e=globalThis.document;if(!e)throw new b("prodantix chat requires a document; mount it in the browser");let t=r.mountPoint??e.createElement("div");r.mountPoint||e.body.append(t);let n=new L(r),i=new E(t,n,r.strings,r.appearance,{files:r.files,help:r.help}),a=r.appearance?.availability??w.availability,s,o=()=>{i.setOpenNow(A(a,new Date)),s=setTimeout(o,Je);};o();let h=new Set,u,c=null,d=r.pollIntervalMs??15e3,p=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),i.onIncomingTurn(g));},m=async()=>{if(!n.hasThread)return;let g=await n.load();if(g){for(let b of g.turns)p(b);h=new Set(g.turns.map(b=>b.id));}},k=()=>{u||d<=0||(u=setInterval(()=>void m(),d));},v=()=>{u&&clearInterval(u),u=void 0;},S=()=>{if(c||!r.socketHost)return;let g=n.socketAuth;g&&(c=new P({auth:g,host:r.socketHost,onClosed:b=>{c=null,k(),b&&S();},onReady:v,onTurn:p,socketFactory:r.socketFactory}),c.open());};return k(),S(),{close:()=>i.close(),destroy:()=>{v(),clearTimeout(s),c?.close(),c=null,i.close(),t.remove();},identify:g=>n.identify(g),open:()=>{i.open().then(S);}}}export{L as ChatClient,E as ChatPanel,w as DEFAULT_APPEARANCE,f as DEFAULT_APPEARANCE_SETTINGS,bt as mountChat,G as panelStyles,T as resolveAppearance};//# sourceMappingURL=chat.js.map
|
|
107
111
|
//# sourceMappingURL=chat.js.map
|
package/dist/messenger.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var d=Object.defineProperty;var f=(e,t,r)=>t in e?d(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var c=(e,t,r)=>f(e,typeof t!="symbol"?t+"":t,r);var l=class extends Error{constructor(r,n,o){super(n,o);c(this,"code");this.code=r,this.name="ProdantixError";}};var i=class extends l{constructor(r,n,o){super("transport",r,o);c(this,"status");this.status=n,this.name="TransportError";}};function g(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function p(e){return e.replace(/\/+$/,"")}var h="prodantix.messenger.config",E=e=>{let t=e.navigator?.languages;return Array.isArray(t)&&t.length>0?t.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},u=(e,t)=>`${h}:${e}:${t??""}`;function k(e,t,r){let n=e?.get(u(t,r));if(!n)return null;try{let o=JSON.parse(n);return o?.apiKey===t?o.config:null}catch{return null}}async function v(e){let t=g(e.fetchImpl);if(!t)return e.onError?.(new i("no fetch available for the prodantix messenger")),null;let r=p(e.host),n=u(e.apiKey,e.locale),o=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let s=await t(`${r}/v1/messenger/config${o}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!s.ok)return e.onError?.(new i(`prodantix messenger config: ${s.status}`,s.status)),null;let a=JSON.parse(await s.text());return a.enabled?(e.storage?.set(n,JSON.stringify({apiKey:e.apiKey,config:a})),a):(e.storage?.remove(n),a)}catch(s){return e.onError?.(s),null}}exports.MESSENGER_CACHE_KEY=h;exports.cacheKeyFor=u;exports.cachedMessengerConfig=k;exports.fetchMessengerConfig=v;exports.localeCandidates=E;//# sourceMappingURL=messenger.cjs.map
|
|
2
2
|
//# sourceMappingURL=messenger.cjs.map
|
package/dist/messenger.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { H as HelpWords, t as MESSENGER_CACHE_KEY, M as MessengerAttachments, e as MessengerConfig, u as MessengerConfigOptions, v as MessengerHelp, w as StarterPrompt, x as cacheKeyFor, y as cachedMessengerConfig, z as fetchMessengerConfig, E as localeCandidates } from './config-
|
|
1
|
+
export { H as HelpWords, t as MESSENGER_CACHE_KEY, M as MessengerAttachments, e as MessengerConfig, u as MessengerConfigOptions, v as MessengerHelp, w as StarterPrompt, x as cacheKeyFor, y as cachedMessengerConfig, z as fetchMessengerConfig, E as localeCandidates } from './config-CpfUyEw8.cjs';
|
|
2
2
|
import './http-BCh716Vs.cjs';
|
package/dist/messenger.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { H as HelpWords, t as MESSENGER_CACHE_KEY, M as MessengerAttachments, e as MessengerConfig, u as MessengerConfigOptions, v as MessengerHelp, w as StarterPrompt, x as cacheKeyFor, y as cachedMessengerConfig, z as fetchMessengerConfig, E as localeCandidates } from './config-
|
|
1
|
+
export { H as HelpWords, t as MESSENGER_CACHE_KEY, M as MessengerAttachments, e as MessengerConfig, u as MessengerConfigOptions, v as MessengerHelp, w as StarterPrompt, x as cacheKeyFor, y as cachedMessengerConfig, z as fetchMessengerConfig, E as localeCandidates } from './config-C9Njc6-j.js';
|
|
2
2
|
import './http-BCh716Vs.js';
|
package/dist/messenger.iife.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(){'use strict';var ce=Object.defineProperty;var de=(n,e,t)=>e in n?ce(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var h=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var P=class extends Error{constructor(t,r,i){super(r,i);h(this,"code");this.code=t,this.name="ProdantixError";}},N=class extends P{constructor(e){super("config",e),this.name="ConfigError";}};var E=class extends P{constructor(t,r,i){super("transport",t,i);h(this,"status");this.status=r,this.name="TransportError";}};function _(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function F(n){return n.replace(/\/+$/,"")}var q="X-Prodantix-Conversation-Token",O="prodantix.chat.handle";function pe(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var H=class{constructor(e){this.options=e;h(this,"fetchImpl");h(this,"fileFetchImpl");h(this,"host");h(this,"storage");h(this,"handle");h(this,"identity",null);var t,r;this.fetchImpl=_(e.fetchImpl),this.fileFetchImpl=(t=e.fileFetchImpl)!=null?t:((i,a)=>fetch(i,a)),this.host=F(e.host),this.storage=(r=e.storage)!=null?r:pe(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,i,a;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(a=this.storage)==null||a.set(O,JSON.stringify(this.handle)),true)}async send(e,t,r){var o;if(!await this.ensureThread())return null;let i=this.handle;if(!i)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token});return (o=a==null?void 0:a.turn)!=null?o:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async helpCentre(e,t){let r=Object.entries({...t,...this.options.locale?{lang:this.options.locale}:{}}).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return this.request("GET",`/v1/messenger/articles${e}${r?`?${r}`:""}`)}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r,i,a;let e=(t=this.storage)==null?void 0:t.get(O);if(!e)return null;try{let o=JSON.parse(e);if(typeof o.conversationId=="string"&&typeof o.token=="string")return {conversationId:o.conversationId,token:o.token}}catch(o){(i=(r=this.options).onError)==null||i.call(r,o);}return (a=this.storage)==null||a.remove(O),null}async fileRequest(e,t,r,i,a){var s,p,d,l;let o={authorization:`Bearer ${this.options.apiKey}`,[q]:r};a&&(o["content-type"]=a.type||"application/octet-stream");try{let c=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:o,method:e});if(c.ok)return await i(c);(p=(s=this.options).onError)==null||p.call(s,new E(`prodantix chat ${t}: ${c.status}`,c.status));}catch(c){(l=(d=this.options).onError)==null||l.call(d,c);}return null}async request(e,t,r={}){var o,s,p,d,l,c;let i=this.fetchImpl;if(!i)return (s=(o=this.options).onError)==null||s.call(o,new E("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[q]=r.token);try{let m=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),g=await m.text();return m.ok?g?JSON.parse(g):{}:((d=(p=this.options).onError)==null||d.call(p,new E(`prodantix chat ${t}: ${m.status}`,m.status)),null)}catch(m){return (c=(l=this.options).onError)==null||c.call(l,m),null}}};var ue={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function I(n,e){var s,p,d,l,c,m;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=ue[(p=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?p:""];if(!r)return false;let i=(l=(d=t.find(g=>g.type==="hour"))==null?void 0:d.value)!=null?l:"",a=(m=(c=t.find(g=>g.type==="minute"))==null?void 0:c.value)!=null?m:"",o=`${i}:${a}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=o&&o<g.close)}var k={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},he=["quiet","standard"],me=["round","square"],ge=["rounded","tailed"],fe=["filled","outlined"],be=["circle","pill","squircle"],ye=["filled","outlined"],xe=["avatar","glyph","team_faces"],ve=["large","medium","small"],Se=["above","hidden","inline"],Ce=["beside_name","none","under_turn"],ke=["time","time_and_latency"],T=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,j=(n,e)=>typeof n=="boolean"?n:e,Ee={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},Te={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},we={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},Ae={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Le={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function M(n){var g,C,S,f,y,u,v,b,x,w,B,D,G;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:Ee[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:Te[i],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:we[o],p=typeof e.skin=="string"?e.skin:void 0,d=p===void 0?void 0:Ae[p],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=l===void 0?void 0:Le[l],m={bubbleFill:T(e.bubbleFill,fe,(g=c==null?void 0:c[1])!=null?g:k.bubbleFill),bubbleShape:T(e.bubbleShape,ge,(C=c==null?void 0:c[0])!=null?C:k.bubbleShape),composerShape:T(e.composerShape,me,(S=d==null?void 0:d[1])!=null?S:k.composerShape),dayDividers:j(e.dayDividers,(f=s==null?void 0:s[0])!=null?f:k.dayDividers),launcherContent:T(e.launcherContent,xe,(y=r==null?void 0:r[2])!=null?y:k.launcherContent),launcherFill:T(e.launcherFill,ye,(u=r==null?void 0:r[1])!=null?u:k.launcherFill),launcherShape:T(e.launcherShape,be,(v=r==null?void 0:r[0])!=null?v:k.launcherShape),launcherSize:T(e.launcherSize,ve,(b=r==null?void 0:r[3])!=null?b:k.launcherSize),nameAvatar:j(e.nameAvatar,(x=a==null?void 0:a[1])!=null?x:k.nameAvatar),namePlacement:T(e.namePlacement,Se,(w=a==null?void 0:a[0])!=null?w:k.namePlacement),skin:T(e.skin,he,(B=d==null?void 0:d[0])!=null?B:k.skin),stampContent:T(e.stampContent,ke,(D=s==null?void 0:s[2])!=null?D:k.stampContent),stampPlacement:T(e.stampPlacement,Ce,(G=s==null?void 0:s[1])!=null?G:k.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function W(n){var r,i,a,o;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(i=e[1])==null?void 0:i.slice(0,1)}`:(o=(a=e[0])==null?void 0:a.slice(0,2))!=null?o:"").toUpperCase()}var Pe="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",Ne={large:66,medium:56,small:46},_e={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},Fe={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},He={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},Ie=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",Me={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Re={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},$e={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Oe={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function Y(n,e,t,r){return `.launcher{--fab-size:${Ne[r]}px;${_e[n]}${Fe[e]}}${He[t]}${Ie}${Me[n]}${Re[e]}${$e[n]}${Oe[n]}`}function J(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${Pe}"/></svg>`,i.append(...a.childNodes,K()),i}return n==="avatar"?(i.append(X(t[0],e,r),K()),i):(i.append(U(t,e,r),K()),i)}function U(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(X(i,e,t));return r}function X(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function K(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Ke={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},L={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...k},Ue={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},ze={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Be={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},De={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ge={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},qe=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",je='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',We={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Ye=".lat{font-size:11px;opacity:.7;margin-left:6px}",V=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
(function(){'use strict';var ce=Object.defineProperty;var de=(n,e,t)=>e in n?ce(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var h=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var P=class extends Error{constructor(t,r,i){super(r,i);h(this,"code");this.code=t,this.name="ProdantixError";}},N=class extends P{constructor(e){super("config",e),this.name="ConfigError";}};var E=class extends P{constructor(t,r,i){super("transport",t,i);h(this,"status");this.status=r,this.name="TransportError";}};function _(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function F(n){return n.replace(/\/+$/,"")}var q="X-Prodantix-Conversation-Token",O="prodantix.chat.handle";function pe(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var H=class{constructor(e){this.options=e;h(this,"fetchImpl");h(this,"fileFetchImpl");h(this,"host");h(this,"storage");h(this,"handle");h(this,"identity",null);var t,r;this.fetchImpl=_(e.fetchImpl),this.fileFetchImpl=(t=e.fileFetchImpl)!=null?t:((i,a)=>fetch(i,a)),this.host=F(e.host),this.storage=(r=e.storage)!=null?r:pe(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,i,a;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(a=this.storage)==null||a.set(O,JSON.stringify(this.handle)),true)}async send(e,t,r){var o;if(!await this.ensureThread())return null;let i=this.handle;if(!i)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token});return (o=a==null?void 0:a.turn)!=null?o:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async helpCentre(e,t){let r=Object.entries({...t,...this.options.locale?{lang:this.options.locale}:{}}).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return this.request("GET",`/v1/messenger/articles${e}${r?`?${r}`:""}`)}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r,i,a;let e=(t=this.storage)==null?void 0:t.get(O);if(!e)return null;try{let o=JSON.parse(e);if(typeof o.conversationId=="string"&&typeof o.token=="string")return {conversationId:o.conversationId,token:o.token}}catch(o){(i=(r=this.options).onError)==null||i.call(r,o);}return (a=this.storage)==null||a.remove(O),null}async fileRequest(e,t,r,i,a){var s,p,d,l;let o={authorization:`Bearer ${this.options.apiKey}`,[q]:r};a&&(o["content-type"]=a.type||"application/octet-stream");try{let c=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:o,method:e});if(c.ok)return await i(c);(p=(s=this.options).onError)==null||p.call(s,new E(`prodantix chat ${t}: ${c.status}`,c.status));}catch(c){(l=(d=this.options).onError)==null||l.call(d,c);}return null}async request(e,t,r={}){var o,s,p,d,l,c;let i=this.fetchImpl;if(!i)return (s=(o=this.options).onError)==null||s.call(o,new E("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[q]=r.token);try{let m=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),g=await m.text();return m.ok?g?JSON.parse(g):{}:((d=(p=this.options).onError)==null||d.call(p,new E(`prodantix chat ${t}: ${m.status}`,m.status)),null)}catch(m){return (c=(l=this.options).onError)==null||c.call(l,m),null}}};var ue={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function I(n,e){var s,p,d,l,c,m;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=ue[(p=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?p:""];if(!r)return false;let i=(l=(d=t.find(g=>g.type==="hour"))==null?void 0:d.value)!=null?l:"",a=(m=(c=t.find(g=>g.type==="minute"))==null?void 0:c.value)!=null?m:"",o=`${i}:${a}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=o&&o<g.close)}var C={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},he=["quiet","standard"],me=["round","square"],ge=["rounded","tailed"],fe=["filled","outlined"],be=["circle","pill","squircle"],xe=["filled","outlined"],ye=["avatar","glyph","team_faces"],ve=["large","medium","small"],Se=["above","hidden","inline"],ke=["beside_name","none","under_turn"],Ce=["time","time_and_latency"],w=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,j=(n,e)=>typeof n=="boolean"?n:e,Ee={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},we={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Te={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},Ae={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Le={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function M(n){var g,k,S,f,x,u,v,b,y,T,B,D,G;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:Ee[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:we[i],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:Te[o],p=typeof e.skin=="string"?e.skin:void 0,d=p===void 0?void 0:Ae[p],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=l===void 0?void 0:Le[l],m={bubbleFill:w(e.bubbleFill,fe,(g=c==null?void 0:c[1])!=null?g:C.bubbleFill),bubbleShape:w(e.bubbleShape,ge,(k=c==null?void 0:c[0])!=null?k:C.bubbleShape),composerShape:w(e.composerShape,me,(S=d==null?void 0:d[1])!=null?S:C.composerShape),dayDividers:j(e.dayDividers,(f=s==null?void 0:s[0])!=null?f:C.dayDividers),launcherContent:w(e.launcherContent,ye,(x=r==null?void 0:r[2])!=null?x:C.launcherContent),launcherFill:w(e.launcherFill,xe,(u=r==null?void 0:r[1])!=null?u:C.launcherFill),launcherShape:w(e.launcherShape,be,(v=r==null?void 0:r[0])!=null?v:C.launcherShape),launcherSize:w(e.launcherSize,ve,(b=r==null?void 0:r[3])!=null?b:C.launcherSize),nameAvatar:j(e.nameAvatar,(y=a==null?void 0:a[1])!=null?y:C.nameAvatar),namePlacement:w(e.namePlacement,Se,(T=a==null?void 0:a[0])!=null?T:C.namePlacement),skin:w(e.skin,he,(B=d==null?void 0:d[0])!=null?B:C.skin),stampContent:w(e.stampContent,Ce,(D=s==null?void 0:s[2])!=null?D:C.stampContent),stampPlacement:w(e.stampPlacement,ke,(G=s==null?void 0:s[1])!=null?G:C.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function W(n){var r,i,a,o;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(i=e[1])==null?void 0:i.slice(0,1)}`:(o=(a=e[0])==null?void 0:a.slice(0,2))!=null?o:"").toUpperCase()}var Pe="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",Ne={large:66,medium:56,small:46},_e={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},Fe={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},He={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},Ie=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",Me={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Re={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},$e={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Oe={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function Y(n,e,t,r){return `.launcher{--fab-size:${Ne[r]}px;${_e[n]}${Fe[e]}}${He[t]}${Ie}${Me[n]}${Re[e]}${$e[n]}${Oe[n]}`}function J(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${Pe}"/></svg>`,i.append(...a.childNodes,K()),i}return n==="avatar"?(i.append(X(t[0],e,r),K()),i):(i.append(U(t,e,r),K()),i)}function U(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(X(i,e,t));return r}function X(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function K(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Ke={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},L={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...C};function Ue(n,e){let t=document.createElement("a");t.className="powered",t.href="https://prodantix.com",t.target="_blank",t.rel="noopener";let r=document.createElement("img");return r.src=e,r.alt="",r.width=12,r.height=12,t.append(r,n),t}var ze={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Be={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},De={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Ge={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},qe={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},je=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",We='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Ye={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Je=".lat{font-size:11px;opacity:.7;margin-left:6px}",V=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
-
--online: oklch(72% 0.13 163.23);`;function
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function Xe(n){return n==="light"?"":n==="dark"?`:host { ${V} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
5
5
|
${V}
|
|
6
6
|
}
|
|
7
|
-
}`}var
|
|
7
|
+
}`}var Ve=/https?:\/\/[^\s<>"]+/g,Qe=/[.,;:!?)]$/,Ze=n=>{let e=n;for(;Qe.test(e);){let t=e.split("(").length-1,r=e.split(")").length-1;if(e.endsWith(")")&&t>=r)break;e=e.slice(0,-1);}return e};function et(n,e){var r;let t=0;for(let i of e.matchAll(Ve)){let a=(r=i.index)!=null?r:0,o=Ze(i[0]);a>t&&n.append(e.slice(t,a));let s=document.createElement("a");s.href=o,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o,n.append(s),t=a+o.length;}t<e.length&&n.append(e.slice(t));}var tt=["P","BR","STRONG","EM","A","UL","OL","LI"],nt=n=>typeof n=="object"&&n!==null&&"html"in n&&typeof n.html=="string"&&"text"in n&&typeof n.text=="string",rt=(n,e)=>e.name==="class"||e.name==="data-block-type"?true:n!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),it=n=>[...n.querySelectorAll("*")].every(e=>tt.includes(e.tagName)&&[...e.attributes].every(t=>rt(e.tagName,t)));function at(n,e="system"){let t=M(n),r=n.launcherPosition==="bottom_left"?"left":"right",i=n.accentColor;return `${`
|
|
8
8
|
:host {
|
|
9
9
|
all: initial; z-index: 2147483000; --a: ${i};
|
|
10
10
|
--paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
--online: oklch(53.8% 0.1274 163.23);
|
|
13
13
|
color-scheme: ${e==="system"?"light dark":e};
|
|
14
14
|
}
|
|
15
|
-
${
|
|
15
|
+
${Xe(e)}
|
|
16
16
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
17
17
|
.launcher {
|
|
18
18
|
z-index: 2147483000; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
|
|
@@ -98,10 +98,14 @@ ${Je(e)}
|
|
|
98
98
|
.composer button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
|
|
99
99
|
.composer button .sendglyph { display: none; width: 17px; height: 17px; }
|
|
100
100
|
.composer button:focus-visible { outline: 2px solid #0b0e14; }
|
|
101
|
+
.powered { display: flex; align-items: center; justify-content: center; gap: 4px; height: 24px; font-size: 11px; font-weight: 500; color: var(--ink-3); text-decoration: none; }
|
|
102
|
+
.powered:hover { color: var(--ink-2); }
|
|
103
|
+
.powered:focus-visible { outline: 2px solid var(--ink); outline-offset: -2px; }
|
|
104
|
+
.powered img { width: 12px; height: 12px; }
|
|
101
105
|
@media (prefers-reduced-motion: no-preference) {
|
|
102
106
|
.panel { animation: rise 180ms ease-out; }
|
|
103
107
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
104
108
|
}
|
|
105
109
|
.scrim,.grip{display:none}@media (max-width:770px){.panel{inset:auto 0 0;width:100%;max-width:none;height:86dvh;max-height:86dvh}:host .panel{border-bottom-left-radius:0;border-bottom-right-radius:0}.scrim{display:block;position:fixed;inset:0;z-index:2147483000;background:rgb(15 23 42/.24)}.grip{display:block;position:absolute;top:7px;left:calc(50% - 17px);width:34px;height:4px;border-radius:2px;background:currentColor;opacity:.45}.panel:not([data-dragging]){transition:translate .2s}.composer{padding-bottom:max(12px,env(safe-area-inset-bottom))}}
|
|
106
|
-
`}${ze[t.composerShape]}${Ue[t.skin]}${Y(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Be[t.bubbleShape]}${De[t.bubbleFill]}${Ge[t.namePlacement]}${t.nameAvatar?qe:""}${t.dayDividers?je:""}${We[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ye:""}`}var at=["end_user","agent","ai"];function ot(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var st='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',R=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;h(this,"root");h(this,"strings");h(this,"settings");h(this,"appearance");h(this,"launcher");h(this,"badge");h(this,"panel",null);h(this,"scrim",null);h(this,"lastFocused",null);h(this,"unread",0);h(this,"pendingTurns",0);h(this,"openNow");h(this,"styles");h(this,"scheme");h(this,"picked",null);h(this,"objectUrls",[]);h(this,"helpLoader");h(this,"kit",null);h(this,"kitLoad",null);h(this,"filesLoader");h(this,"filesKit",null);h(this,"filesLoad",null);var o;this.strings={...Ke,...r},this.appearance={...L,...i},this.settings=M({...L,...i}),this.root=e.attachShadow({mode:(o=a.shadowMode)!=null?o:"closed"}),this.openNow=I(this.appearance.availability,new Date),this.scheme=a.scheme,this.helpLoader=a.help,this.filesLoader=a.files,this.styles=dt(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(J(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...L,...e},this.settings=M(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){var e;this.styles(`${it(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(((e=this.appearance.attachments)==null?void 0:e.enabled)===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):((this.kitLoad)!=null||(this.kitLoad=this.helpLoader().then(t=>(this.kit=t,this.paint(),t))),this.kitLoad)}loadFiles(){return this.filesLoader?((this.filesLoad)!=null||(this.filesLoad=this.filesLoader().then(t=>(this.filesKit=t,this.paint(),t))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var v;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("span");r.className="grip",r.setAttribute("aria-hidden","true"),t.append(r);let i=(v=this.appearance.team)!=null?v:[];i.length>0&&t.append(U(i,this.strings,b=>this.client.avatarUrl(b)));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let s=document.createElement("p");s.className="status";let p=document.createElement("span");p.className="live",p.setAttribute("aria-hidden","true"),s.append(p,this.strings.replyTime),a.append(o,s);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=st,d.addEventListener("click",()=>this.close()),t.append(a,d);let l=document.createElement("div");l.className="log",l.setAttribute("role","log"),l.setAttribute("aria-live","polite"),l.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let m=document.createElement("input");m.type="text",m.setAttribute("aria-label",this.strings.inputPlaceholder),m.placeholder=this.strings.inputPlaceholder;let g=document.createElement("button");g.type="submit",g.setAttribute("aria-label",this.strings.sendLabel),g.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let C=document.createElement("span");C.className="sendtext",C.textContent=this.strings.sendLabel,g.append(C),c.append(m,g),c.addEventListener("submit",b=>{b.preventDefault(),this.submit(m,l);}),e.append(t,l,c),e.addEventListener("keydown",b=>this.onKeydown(b,e,d));let S=document.createElement("div");S.className="scrim",S.addEventListener("click",()=>this.close()),this.root.append(S,e),this.panel=e,this.scrim=S,ct(e,()=>this.close()),m.focus();let f=this.appearance.attachments,[y]=await Promise.all([this.client.load(),this.loadKit(),f!=null&&f.enabled&&this.client.upload?this.loadFiles():null]);if(y!=null&&y.turns.some(b=>{var x;return (x=b.attachments)==null?void 0:x.length})&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&(f!=null&&f.enabled)&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:b=>{this.picked=b;},objectUrl:b=>this.objectUrl(b),removeFileLabel:this.strings.removeFileLabel,root:this.root},c,m,l,f);let u=this.helpHost();(u==null?void 0:u.placement)==="tab"&&u.host.source.collections&&u.host.source.collectionArticles&&u.kit.helpTab(u.host),(u==null?void 0:u.placement)==="while_typing"&&u.kit.whileTyping(u.host,m,c),y&&y.turns.length>0?this.renderThread(l,y):this.renderFirstRun(l,m),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,r.append(i);let a=this.helpHost();if((a==null?void 0:a.placement)==="first_view")a.kit.firstView(a.host,r);else {let s=document.createElement("p");s.textContent=this.strings.emptyBody,r.append(s);}this.appearance.starterPrompts.filter(tt).forEach((s,p)=>{let d=document.createElement("div");d.className="prompt";let l=document.createElement("div");l.className="promptwords",l.id=`prompt-${p}`;let c=document.createElement("template");c.innerHTML=s.html,rt(c.content)?l.append(c.content):l.textContent=s.text;for(let g of l.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let m=document.createElement("button");m.className="promptpress",m.type="button",m.setAttribute("aria-labelledby",l.id),m.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),d.append(l,m),r.append(d);}),e.replaceChildren(r);}helpHost(){let e=this.appearance.help,{kit:t,panel:r}=this,i=e&&t&&r?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:r,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){var e;if(this.panel){this.panel.remove(),(e=this.scrim)==null||e.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let t of this.objectUrls)URL.revokeObjectURL(t);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){var t;if(this.panel&&((t=e.attachments)!=null&&t.length)&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){var s,p,d;(s=e.querySelector(".empty"))==null||s.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let a=r?await((d=(p=this.client).upload)==null?void 0:d.call(p,r)):void 0,o=a===null?null:await this.client.send(t,ot(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),o){i.dataset.turnId=o.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){var o;t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),((o=t.querySelector(".body"))!=null?o:t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){var c,m,g,C,S,f,y;(c=e.querySelector(".empty"))==null||c.remove();let i=at.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${i}`,o.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let u=document.createElement("span");if(u.className=i==="ai"?"av bot":"av",u.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let v=document.createElement("img");v.alt="",v.src=this.client.avatarUrl(t.authorAvatarUrl),u.append(v);}else {u.textContent=i==="ai"?this.strings.aiLabel:W(this.agentName(t));let v=i==="agent"?(g=(m=this.appearance.team)==null?void 0:m.find(b=>b.name===t.authorName))==null?void 0:g.tone:void 0;v&&(u.style.background=v);}o.append(u);}let p=document.createElement("div");if(p.className="body",i==="end_user"){let u=this.filesKit,v=b=>this.objectUrl(b);r&&(u==null||u.drawFile(p,r.name,r.type,r.size,Promise.resolve(r),v));for(let b of (C=t.attachments)!=null?C:[])u==null||u.drawFile(p,b.name,b.contentType,b.bytes,(y=(f=(S=this.client).file)==null?void 0:f.call(S,b.url))!=null?y:Promise.resolve(null),v);}let d=i!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(i==="ai"?Ze(l,t.body):l.textContent=t.body,d||i==="ai"&&a.namePlacement==="hidden"){let u=document.createElement("div");u.className=i==="ai"?"author ai":"author",u.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&u.append(this.stamp(t)),a.namePlacement==="inline"?(u.classList.add("below"),p.append(l,u)):p.append(u,l);}else t.body&&p.append(l);return a.stampPlacement==="under_turn"&&p.append(this.stamp(t)),o.append(p),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(p=>!p.closest("[hidden]")&&!p.hidden);if(i.length===0)return;let a=i[0],o=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},lt="(max-width: 770px)";function ct(n,e){let t=null;n.addEventListener("pointerdown",i=>{var o,s;if(t||i.button!==0||!((o=globalThis.matchMedia)!=null&&o.call(globalThis,lt).matches))return;let a=i.target;if(!(a!=null&&a.closest("a, button, input, textarea, iframe"))){for(;a&&a!==n;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},(s=n.setPointerCapture)==null||s.call(n,i.pointerId),n.dataset.dragging="";}}),n.addEventListener("pointermove",i=>{if((t==null?void 0:t.id)!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),n.style.translate=`0 ${t.offset}px`;});let r=i=>{let a=t;if((a==null?void 0:a.id)!==i.pointerId)return;t=null,delete n.dataset.dragging;let o=a.offset>Math.min(72,n.getBoundingClientRect().height*.4),s=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;o||s?e():n.style.translate="";};n.addEventListener("pointerup",r),n.addEventListener("pointercancel",r);}var dt=n=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in n&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return n.adoptedStyleSheets=[t],r=>t.replaceSync(r)}let e=document.createElement("style");return n.append(e),t=>{e.textContent=t;}};function Q(n){return `40${JSON.stringify(n)}`}function Z(){return "3"}function ee(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=z(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=z(i);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let a=z(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function z(n){try{return JSON.parse(n)}catch(e){return null}}var pt="/socket.io/?EIO=4&transport=websocket",$=class{constructor(e){this.options=e;h(this,"socket",null);h(this,"heartbeat",null);h(this,"ready",false);h(this,"closed",false);h(this,"heartbeatWindow",45e3);h(this,"factory");h(this,"setTimer");h(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ut,this.setTimer=(r=e.setTimer)!=null?r:((a,o)=>setTimeout(a,o)),this.clearTimer=(i=e.clearTimer)!=null?i:(a=>clearTimeout(a));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${pt}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,a,o;let t=ee(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(Q(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(Z());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(a=this.socket)==null||a.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ut(n){let e=globalThis.WebSocket;if(!e)throw new E("no WebSocket");return new e(n)}var ht=6e4;function te(n){var y,u,v,b;let e=globalThis.document;if(!e)throw new N("prodantix chat requires a document; mount it in the browser");let t=(y=n.mountPoint)!=null?y:e.createElement("div");n.mountPoint||e.body.append(t);let r=new H(n),i=new R(t,r,n.strings,n.appearance,{files:n.files,help:n.help}),a=(v=(u=n.appearance)==null?void 0:u.availability)!=null?v:L.availability,o,s=()=>{i.setOpenNow(I(a,new Date)),o=setTimeout(s,ht);};s();let p=new Set,d,l=null,c=(b=n.pollIntervalMs)!=null?b:15e3,m=x=>{p.has(x.id)||x.authorKind==="end_user"||(p.add(x.id),i.onIncomingTurn(x));},g=async()=>{if(!r.hasThread)return;let x=await r.load();if(x){for(let w of x.turns)m(w);p=new Set(x.turns.map(w=>w.id));}},C=()=>{d||c<=0||(d=setInterval(()=>void g(),c));},S=()=>{d&&clearInterval(d),d=void 0;},f=()=>{if(l||!n.socketHost)return;let x=r.socketAuth;x&&(l=new $({auth:x,host:n.socketHost,onClosed:w=>{l=null,C(),w&&f();},onReady:S,onTurn:m,socketFactory:n.socketFactory}),l.open());};return C(),f(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(o),l==null||l.close(),l=null,i.close(),t.remove();},identify:x=>r.identify(x),open:()=>{i.open().then(f);}}}var mt="prodantix.messenger.config",ne=n=>{var t,r,i,a;let e=(t=n.navigator)==null?void 0:t.languages;return Array.isArray(e)&&e.length>0?e.join(","):((r=n.navigator)==null?void 0:r.language)||((a=(i=n.document)==null?void 0:i.documentElement)==null?void 0:a.lang)||void 0},re=(n,e)=>`${mt}:${n}:${e!=null?e:""}`;function ie(n,e,t){let r=n==null?void 0:n.get(re(e,t));if(!r)return null;try{let i=JSON.parse(r);return (i==null?void 0:i.apiKey)===e?i.config:null}catch(i){return null}}async function ae(n){var a,o,s,p,d;let e=_(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new E("no fetch available for the prodantix messenger")),null;let t=F(n.host),r=re(n.apiKey,n.locale),i=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let l=await e(`${t}/v1/messenger/config${i}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!l.ok)return (o=n.onError)==null||o.call(n,new E(`prodantix messenger config: ${l.status}`,l.status)),null;let c=JSON.parse(await l.text());return c.enabled?((p=n.storage)==null||p.set(r,JSON.stringify({apiKey:n.apiKey,config:c})),c):((s=n.storage)==null||s.remove(r),c)}catch(l){return (d=n.onError)==null||d.call(n,l),null}}var gt=["close","identify","open","shutdown","toggle"],A="[prodantix/messenger]";function ft(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!gt.includes(r)||e(r,...i);}}function bt(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}function se(n,e,t,r,i){return new Promise(a=>{let o=n.document.createElement("script");o.src=e,o.onload=()=>{var p;let s=(p=r())!=null?p:null;s||i(`${A} the ${t} script registered nothing.`),a(s);},o.onerror=()=>{i(`${A} the ${t} script could not load from ${new URL(e).origin}.`),a(null);},n.document.head.append(o);})}var yt=(n,e,t)=>se(n,`${e}/messenger-help.js`,"help centre",()=>n.prodantixMessengerHelp,t),xt=(n,e,t)=>se(n,`${e}/messenger-files.js`,"files",()=>n.prodantixMessengerFiles,t);async function le(n,e={}){var g,C,S;let t=(g=e.warn)!=null?g:(f=>console.warn(f)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${A} no project key on the install snippet; nothing will load.`),null;let a=bt((C=e.scriptSrc)!=null?C:vt(n));if(!a)return t(`${A} could not tell which host served this script; nothing will load.`),null;let o=St(n),s=ne(n),p=ie(o,i,s),d=await ae({apiKey:i,host:a,locale:s,onError:f=>t(`${A} settings could not be read: ${String(f)}`),storage:o}),l=d!=null?d:p;if(!l)return t(`${A} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let c=te({apiKey:i,appearance:l,distinctId:kt(n,o),files:()=>xt(n,a,t),help:l.help?()=>yt(n,a,t):void 0,host:a,locale:s,socketHost:l.socketUrl||void 0}),m=(f,...y)=>{if((f==="open"||f==="toggle")&&c.open(),f==="close"&&c.close(),f==="shutdown"&&c.destroy(),f==="identify"){let u=Ct(y[0]);if(!u){console.error(`${A} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}c.identify(u);}};return ft((S=r==null?void 0:r.q)!=null?S:[],m),n.prodantix=Object.assign((f,...y)=>m(f,...y),{k:i,q:[]}),c}function vt(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function St(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function Ct(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var oe="prodantix.messenger.anon";function kt(n,e){var i,a,o;let t=e==null?void 0:e.get(oe);if(t)return t;let r=`anon_${(o=(a=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:a.call(i))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(oe,r),r}le(window);})();//# sourceMappingURL=messenger.iife.js.map
|
|
110
|
+
`}${Be[t.composerShape]}${ze[t.skin]}${Y(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${De[t.bubbleShape]}${Ge[t.bubbleFill]}${qe[t.namePlacement]}${t.nameAvatar?je:""}${t.dayDividers?We:""}${Ye[t.stampPlacement]}${t.stampContent==="time_and_latency"?Je:""}`}var ot=["end_user","agent","ai"];function st(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var lt='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',R=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;h(this,"root");h(this,"strings");h(this,"settings");h(this,"appearance");h(this,"launcher");h(this,"badge");h(this,"panel",null);h(this,"scrim",null);h(this,"lastFocused",null);h(this,"unread",0);h(this,"pendingTurns",0);h(this,"openNow");h(this,"styles");h(this,"scheme");h(this,"picked",null);h(this,"objectUrls",[]);h(this,"helpLoader");h(this,"kit",null);h(this,"kitLoad",null);h(this,"filesLoader");h(this,"filesKit",null);h(this,"filesLoad",null);var o;this.strings={...Ke,...r},this.appearance={...L,...i},this.settings=M({...L,...i}),this.root=e.attachShadow({mode:(o=a.shadowMode)!=null?o:"closed"}),this.openNow=I(this.appearance.availability,new Date),this.scheme=a.scheme,this.helpLoader=a.help,this.filesLoader=a.files,this.styles=pt(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(J(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...L,...e},this.settings=M(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){var e;this.styles(`${at(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(((e=this.appearance.attachments)==null?void 0:e.enabled)===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):((this.kitLoad)!=null||(this.kitLoad=this.helpLoader().then(t=>(this.kit=t,this.paint(),t))),this.kitLoad)}loadFiles(){return this.filesLoader?((this.filesLoad)!=null||(this.filesLoad=this.filesLoader().then(t=>(this.filesKit=t,this.paint(),t))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var v;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("span");r.className="grip",r.setAttribute("aria-hidden","true"),t.append(r);let i=(v=this.appearance.team)!=null?v:[];i.length>0&&t.append(U(i,this.strings,b=>this.client.avatarUrl(b)));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let s=document.createElement("p");s.className="status";let p=document.createElement("span");p.className="live",p.setAttribute("aria-hidden","true"),s.append(p,this.strings.replyTime),a.append(o,s);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=lt,d.addEventListener("click",()=>this.close()),t.append(a,d);let l=document.createElement("div");l.className="log",l.setAttribute("role","log"),l.setAttribute("aria-live","polite"),l.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let m=document.createElement("input");m.type="text",m.setAttribute("aria-label",this.strings.inputPlaceholder),m.placeholder=this.strings.inputPlaceholder;let g=document.createElement("button");g.type="submit",g.setAttribute("aria-label",this.strings.sendLabel),g.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let k=document.createElement("span");k.className="sendtext",k.textContent=this.strings.sendLabel,g.append(k),c.append(m,g),c.addEventListener("submit",b=>{b.preventDefault(),this.submit(m,l);}),e.append(t,l,c),this.appearance.poweredBy&&e.append(Ue(this.appearance.poweredBy,this.client.avatarUrl("/messenger-mark.png"))),e.addEventListener("keydown",b=>this.onKeydown(b,e,d));let S=document.createElement("div");S.className="scrim",S.addEventListener("click",()=>this.close()),this.root.append(S,e),this.panel=e,this.scrim=S,dt(e,()=>this.close()),m.focus();let f=this.appearance.attachments,[x]=await Promise.all([this.client.load(),this.loadKit(),f!=null&&f.enabled&&this.client.upload?this.loadFiles():null]);if(x!=null&&x.turns.some(b=>{var y;return (y=b.attachments)==null?void 0:y.length})&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&(f!=null&&f.enabled)&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:b=>{this.picked=b;},objectUrl:b=>this.objectUrl(b),removeFileLabel:this.strings.removeFileLabel,root:this.root},c,m,l,f);let u=this.helpHost();(u==null?void 0:u.placement)==="tab"&&u.host.source.collections&&u.host.source.collectionArticles&&u.kit.helpTab(u.host),(u==null?void 0:u.placement)==="while_typing"&&u.kit.whileTyping(u.host,m,c),x&&x.turns.length>0?this.renderThread(l,x):this.renderFirstRun(l,m),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,r.append(i);let a=this.helpHost();if((a==null?void 0:a.placement)==="first_view")a.kit.firstView(a.host,r);else {let s=document.createElement("p");s.textContent=this.strings.emptyBody,r.append(s);}this.appearance.starterPrompts.filter(nt).forEach((s,p)=>{let d=document.createElement("div");d.className="prompt";let l=document.createElement("div");l.className="promptwords",l.id=`prompt-${p}`;let c=document.createElement("template");c.innerHTML=s.html,it(c.content)?l.append(c.content):l.textContent=s.text;for(let g of l.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let m=document.createElement("button");m.className="promptpress",m.type="button",m.setAttribute("aria-labelledby",l.id),m.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),d.append(l,m),r.append(d);}),e.replaceChildren(r);}helpHost(){let e=this.appearance.help,{kit:t,panel:r}=this,i=e&&t&&r?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:r,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){var e;if(this.panel){this.panel.remove(),(e=this.scrim)==null||e.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let t of this.objectUrls)URL.revokeObjectURL(t);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){var t;if(this.panel&&((t=e.attachments)!=null&&t.length)&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){var s,p,d;(s=e.querySelector(".empty"))==null||s.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let a=r?await((d=(p=this.client).upload)==null?void 0:d.call(p,r)):void 0,o=a===null?null:await this.client.send(t,st(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),o){i.dataset.turnId=o.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){var o;t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),((o=t.querySelector(".body"))!=null?o:t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){var c,m,g,k,S,f,x;(c=e.querySelector(".empty"))==null||c.remove();let i=ot.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${i}`,o.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let u=document.createElement("span");if(u.className=i==="ai"?"av bot":"av",u.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let v=document.createElement("img");v.alt="",v.src=this.client.avatarUrl(t.authorAvatarUrl),u.append(v);}else {u.textContent=i==="ai"?this.strings.aiLabel:W(this.agentName(t));let v=i==="agent"?(g=(m=this.appearance.team)==null?void 0:m.find(b=>b.name===t.authorName))==null?void 0:g.tone:void 0;v&&(u.style.background=v);}o.append(u);}let p=document.createElement("div");if(p.className="body",i==="end_user"){let u=this.filesKit,v=b=>this.objectUrl(b);r&&(u==null||u.drawFile(p,r.name,r.type,r.size,Promise.resolve(r),v));for(let b of (k=t.attachments)!=null?k:[])u==null||u.drawFile(p,b.name,b.contentType,b.bytes,(x=(f=(S=this.client).file)==null?void 0:f.call(S,b.url))!=null?x:Promise.resolve(null),v);}let d=i!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(i==="ai"?et(l,t.body):l.textContent=t.body,d||i==="ai"&&a.namePlacement==="hidden"){let u=document.createElement("div");u.className=i==="ai"?"author ai":"author",u.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&u.append(this.stamp(t)),a.namePlacement==="inline"?(u.classList.add("below"),p.append(l,u)):p.append(u,l);}else t.body&&p.append(l);return a.stampPlacement==="under_turn"&&p.append(this.stamp(t)),o.append(p),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(p=>!p.closest("[hidden]")&&!p.hidden);if(i.length===0)return;let a=i[0],o=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},ct="(max-width: 770px)";function dt(n,e){let t=null;n.addEventListener("pointerdown",i=>{var o,s;if(t||i.button!==0||!((o=globalThis.matchMedia)!=null&&o.call(globalThis,ct).matches))return;let a=i.target;if(!(a!=null&&a.closest("a, button, input, textarea, iframe"))){for(;a&&a!==n;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},(s=n.setPointerCapture)==null||s.call(n,i.pointerId),n.dataset.dragging="";}}),n.addEventListener("pointermove",i=>{if((t==null?void 0:t.id)!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),n.style.translate=`0 ${t.offset}px`;});let r=i=>{let a=t;if((a==null?void 0:a.id)!==i.pointerId)return;t=null,delete n.dataset.dragging;let o=a.offset>Math.min(72,n.getBoundingClientRect().height*.4),s=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;o||s?e():n.style.translate="";};n.addEventListener("pointerup",r),n.addEventListener("pointercancel",r);}var pt=n=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in n&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return n.adoptedStyleSheets=[t],r=>t.replaceSync(r)}let e=document.createElement("style");return n.append(e),t=>{e.textContent=t;}};function Q(n){return `40${JSON.stringify(n)}`}function Z(){return "3"}function ee(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=z(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=z(i);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let a=z(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function z(n){try{return JSON.parse(n)}catch(e){return null}}var ut="/socket.io/?EIO=4&transport=websocket",$=class{constructor(e){this.options=e;h(this,"socket",null);h(this,"heartbeat",null);h(this,"ready",false);h(this,"closed",false);h(this,"heartbeatWindow",45e3);h(this,"factory");h(this,"setTimer");h(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ht,this.setTimer=(r=e.setTimer)!=null?r:((a,o)=>setTimeout(a,o)),this.clearTimer=(i=e.clearTimer)!=null?i:(a=>clearTimeout(a));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${ut}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,a,o;let t=ee(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(Q(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(Z());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(a=this.socket)==null||a.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ht(n){let e=globalThis.WebSocket;if(!e)throw new E("no WebSocket");return new e(n)}var mt=6e4;function te(n){var x,u,v,b;let e=globalThis.document;if(!e)throw new N("prodantix chat requires a document; mount it in the browser");let t=(x=n.mountPoint)!=null?x:e.createElement("div");n.mountPoint||e.body.append(t);let r=new H(n),i=new R(t,r,n.strings,n.appearance,{files:n.files,help:n.help}),a=(v=(u=n.appearance)==null?void 0:u.availability)!=null?v:L.availability,o,s=()=>{i.setOpenNow(I(a,new Date)),o=setTimeout(s,mt);};s();let p=new Set,d,l=null,c=(b=n.pollIntervalMs)!=null?b:15e3,m=y=>{p.has(y.id)||y.authorKind==="end_user"||(p.add(y.id),i.onIncomingTurn(y));},g=async()=>{if(!r.hasThread)return;let y=await r.load();if(y){for(let T of y.turns)m(T);p=new Set(y.turns.map(T=>T.id));}},k=()=>{d||c<=0||(d=setInterval(()=>void g(),c));},S=()=>{d&&clearInterval(d),d=void 0;},f=()=>{if(l||!n.socketHost)return;let y=r.socketAuth;y&&(l=new $({auth:y,host:n.socketHost,onClosed:T=>{l=null,k(),T&&f();},onReady:S,onTurn:m,socketFactory:n.socketFactory}),l.open());};return k(),f(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(o),l==null||l.close(),l=null,i.close(),t.remove();},identify:y=>r.identify(y),open:()=>{i.open().then(f);}}}var gt="prodantix.messenger.config",ne=n=>{var t,r,i,a;let e=(t=n.navigator)==null?void 0:t.languages;return Array.isArray(e)&&e.length>0?e.join(","):((r=n.navigator)==null?void 0:r.language)||((a=(i=n.document)==null?void 0:i.documentElement)==null?void 0:a.lang)||void 0},re=(n,e)=>`${gt}:${n}:${e!=null?e:""}`;function ie(n,e,t){let r=n==null?void 0:n.get(re(e,t));if(!r)return null;try{let i=JSON.parse(r);return (i==null?void 0:i.apiKey)===e?i.config:null}catch(i){return null}}async function ae(n){var a,o,s,p,d;let e=_(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new E("no fetch available for the prodantix messenger")),null;let t=F(n.host),r=re(n.apiKey,n.locale),i=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let l=await e(`${t}/v1/messenger/config${i}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!l.ok)return (o=n.onError)==null||o.call(n,new E(`prodantix messenger config: ${l.status}`,l.status)),null;let c=JSON.parse(await l.text());return c.enabled?((p=n.storage)==null||p.set(r,JSON.stringify({apiKey:n.apiKey,config:c})),c):((s=n.storage)==null||s.remove(r),c)}catch(l){return (d=n.onError)==null||d.call(n,l),null}}var ft=["close","identify","open","shutdown","toggle"],A="[prodantix/messenger]";function bt(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!ft.includes(r)||e(r,...i);}}function xt(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}function se(n,e,t,r,i){return new Promise(a=>{let o=n.document.createElement("script");o.src=e,o.onload=()=>{var p;let s=(p=r())!=null?p:null;s||i(`${A} the ${t} script registered nothing.`),a(s);},o.onerror=()=>{i(`${A} the ${t} script could not load from ${new URL(e).origin}.`),a(null);},n.document.head.append(o);})}var yt=(n,e,t)=>se(n,`${e}/messenger-help.js`,"help centre",()=>n.prodantixMessengerHelp,t),vt=(n,e,t)=>se(n,`${e}/messenger-files.js`,"files",()=>n.prodantixMessengerFiles,t);async function le(n,e={}){var g,k,S;let t=(g=e.warn)!=null?g:(f=>console.warn(f)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${A} no project key on the install snippet; nothing will load.`),null;let a=xt((k=e.scriptSrc)!=null?k:St(n));if(!a)return t(`${A} could not tell which host served this script; nothing will load.`),null;let o=kt(n),s=ne(n),p=ie(o,i,s),d=await ae({apiKey:i,host:a,locale:s,onError:f=>t(`${A} settings could not be read: ${String(f)}`),storage:o}),l=d!=null?d:p;if(!l)return t(`${A} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let c=te({apiKey:i,appearance:l,distinctId:Et(n,o),files:()=>vt(n,a,t),help:l.help?()=>yt(n,a,t):void 0,host:a,locale:s,socketHost:l.socketUrl||void 0}),m=(f,...x)=>{if((f==="open"||f==="toggle")&&c.open(),f==="close"&&c.close(),f==="shutdown"&&c.destroy(),f==="identify"){let u=Ct(x[0]);if(!u){console.error(`${A} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}c.identify(u);}};return bt((S=r==null?void 0:r.q)!=null?S:[],m),n.prodantix=Object.assign((f,...x)=>m(f,...x),{k:i,q:[]}),c}function St(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function kt(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function Ct(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var oe="prodantix.messenger.anon";function Et(n,e){var i,a,o;let t=e==null?void 0:e.get(oe);if(t)return t;let r=`anon_${(o=(a=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:a.call(i))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(oe,r),r}le(window);})();//# sourceMappingURL=messenger.iife.js.map
|
|
107
111
|
//# sourceMappingURL=messenger.iife.js.map
|
package/dist/messenger.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {e,d as d$1,h}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var f="prodantix.messenger.config",m=e=>{let
|
|
1
|
+
import {e,d as d$1,h}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var f="prodantix.messenger.config",m=e=>{let r=e.navigator?.languages;return Array.isArray(r)&&r.length>0?r.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},l=(e,r)=>`${f}:${e}:${r??""}`;function u(e,r,i){let n=e?.get(l(r,i));if(!n)return null;try{let a=JSON.parse(n);return a?.apiKey===r?a.config:null}catch{return null}}async function d(e$1){let r=e(e$1.fetchImpl);if(!r)return e$1.onError?.(new d$1("no fetch available for the prodantix messenger")),null;let i=h(e$1.host),n=l(e$1.apiKey,e$1.locale),a=e$1.locale?`?locale=${encodeURIComponent(e$1.locale)}`:"";try{let t=await r(`${i}/v1/messenger/config${a}`,{headers:{authorization:`Bearer ${e$1.apiKey}`},method:"GET"});if(!t.ok)return e$1.onError?.(new d$1(`prodantix messenger config: ${t.status}`,t.status)),null;let s=JSON.parse(await t.text());return s.enabled?(e$1.storage?.set(n,JSON.stringify({apiKey:e$1.apiKey,config:s})),s):(e$1.storage?.remove(n),s)}catch(t){return e$1.onError?.(t),null}}export{f as MESSENGER_CACHE_KEY,l as cacheKeyFor,u as cachedMessengerConfig,d as fetchMessengerConfig,m as localeCandidates};//# sourceMappingURL=messenger.js.map
|
|
2
2
|
//# sourceMappingURL=messenger.js.map
|
package/package.json
CHANGED