@prodantix/sdk 0.2.0-beta.358 → 0.2.0-beta.371
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 +6 -5
- package/dist/chat.d.cts +5 -3
- package/dist/chat.d.ts +5 -3
- package/dist/chat.js +6 -5
- package/dist/chunk-ESOQKMEE.js +2 -0
- package/dist/{config-CWmtX8Gl.d.cts → config-BD9kg-c4.d.cts} +19 -5
- package/dist/{config-DDlHv52p.d.ts → config-BR_iYD-k.d.ts} +19 -5
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +28 -1
- package/dist/index.d.ts +28 -1
- package/dist/index.js +1 -1
- package/dist/messenger.d.cts +1 -1
- package/dist/messenger.d.ts +1 -1
- package/dist/messenger.iife.js +6 -5
- package/dist/node.cjs +1 -1
- package/dist/node.js +1 -1
- package/dist/web.cjs +1 -1
- package/dist/web.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5CBVQAZ2.js +0 -2
package/dist/chat.cjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
'use strict';var $=Object.defineProperty;var z=(n,e,t)=>e in n?$(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var l=(n,e,t)=>z(n,typeof e!="symbol"?e+"":e,t);function A(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function w(n){return n.replace(/\/+$/,"")}var D="X-Prodantix-Conversation-Token",C="prodantix.chat.handle";function K(){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 b=class{constructor(e){this.options=e;l(this,"fetchImpl");l(this,"host");l(this,"storage");l(this,"handle");l(this,"identity",null);this.fetchImpl=A(e.fetchImpl),this.host=w(e.host),this.storage=e.storage??K(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}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(C,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let r=this.handle;return r?(await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{body:e,pageContext:t},token:r.token}))?.turn??null:null}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(C);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{}return this.storage?.remove(C),null}async request(e,t,r={}){let a=this.fetchImpl;if(!a)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let s={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(s[D]=r.token);try{let o=await a(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:s,method:e}),i=await o.text();return o.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${o.status}`)),null)}catch(o){return this.options.onError?.(o),null}}};var p={bubbleStyle:"tailed",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"concierge",stampContent:"time",stampPlacement:"none"},G=["concierge","console","quiet"],U=["hairline","outlined","rounded","tailed"],B=["circle","pill","squircle"],q=["filled","outlined"],Y=["avatar","glyph","team_faces"],j=["large","medium","small"],W=["above","hidden","inline"],J=["beside_name","none","under_turn"],X=["time","time_and_latency"],m=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,L=(n,e)=>typeof n=="boolean"?n:e,V={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"]},Z={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Q={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"]};function y(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:V[t],a=typeof e.namePlacement=="string"?e.namePlacement:void 0,s=a===void 0?void 0:Z[a],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=o===void 0?void 0:Q[o],c={bubbleStyle:m(e.bubbleStyle,U,p.bubbleStyle),dayDividers:L(e.dayDividers,i?.[0]??p.dayDividers),launcherContent:m(e.launcherContent,Y,r?.[2]??p.launcherContent),launcherFill:m(e.launcherFill,q,r?.[1]??p.launcherFill),launcherShape:m(e.launcherShape,B,r?.[0]??p.launcherShape),launcherSize:m(e.launcherSize,j,r?.[3]??p.launcherSize),nameAvatar:L(e.nameAvatar,s?.[1]??p.nameAvatar),namePlacement:m(e.namePlacement,W,s?.[0]??p.namePlacement),skin:m(e.skin,G,p.skin),stampContent:m(e.stampContent,X,i?.[2]??p.stampContent),stampPlacement:m(e.stampPlacement,J,i?.[1]??p.stampPlacement)};return c.stampPlacement==="beside_name"&&c.namePlacement==="hidden"&&(c.stampPlacement="under_turn"),c.namePlacement==="inline"&&c.bubbleStyle==="hairline"&&(c.namePlacement="above"),c}var ee={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=ee[t.find(i=>i.type==="weekday")?.value??""];if(!r)return false;let a=t.find(i=>i.type==="hour")?.value??"",s=t.find(i=>i.type==="minute")?.value??"",o=`${a}:${s}`;return n.windows.some(i=>i.days.includes(r)&&i.open<=o&&o<i.close)}var te="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},re={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;"},ae={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);"},ie={avatar:".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);}",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;}.launcher .live{width:9px;height:9px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}"},oe={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},se={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},le={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ce={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function I(n,e,t,r){return `.launcher{--fab-size:${ne[r]}px;${re[n]}${ae[e]}}${ie[t]}${oe[n]}${se[e]}${le[n]}${ce[n]}`}function H(n,e,t){let r=document.createDocumentFragment();if(n==="glyph"){let o=document.createElement("span");return o.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="${te}"/></svg>`,r.append(...o.childNodes),r}if(n==="avatar")return r.append(_(t[0],e),P()),r;let a=document.createElement("span");a.className="faces";let s=t.length>0?t.slice(0,2):[void 0];for(let o of s)a.append(_(o,e));return r.append(a,P()),r}function _(n,e){let t=document.createElement("span");return t.className="av",t.setAttribute("aria-hidden","true"),t.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),n&&(t.style.background=n.tone),t}function P(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var de={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",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`},v={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],teamFaces:[],...p},pe={concierge:".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}.composer{padding:12px 12px 14px;gap:8px}.composer input{border:0;background:var(--fill);height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",console:".panel{border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.16)}.header{background:var(--paper);color:var(--ink);border-bottom:1px solid var(--hairline)}.close{color:var(--ink-2)}",quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{height:42px;padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.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)}.close{color:var(--ink-2)}"},ue={hairline:".turn{max-width:100%;padding:13px 0;border-top:1px solid var(--hairline);background:none;border-radius:0}.log>.turn:first-child{border-top:0}.turn.end_user{align-self:stretch;display:flex;flex-direction:column;align-items:flex-end}.turn.end_user .body{background:var(--fill);color:var(--ink);border-radius:8px;padding:9px 12px;max-width:85%}",outlined:".turn{background:none;border:1px solid var(--hairline);border-radius:12px}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}",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}"},he={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".author{display:inline;margin-right:6px;font-weight:650}"},me=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .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}",ge='.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}"},be=".lat{font-size:11px;opacity:.7;margin-left:6px}";function F(n){let e=y(n),t=n.launcherPosition==="bottom_left"?"left":"right",r=n.accentColor;return `${`
|
|
1
|
+
'use strict';var D=Object.defineProperty;var K=(n,e,t)=>e in n?D(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var c=(n,e,t)=>K(n,typeof e!="symbol"?e+"":e,t);function N(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function P(n){return n.replace(/\/+$/,"")}var G="X-Prodantix-Conversation-Token",T="prodantix.chat.handle";function q(){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 x=class{constructor(e){this.options=e;c(this,"fetchImpl");c(this,"host");c(this,"storage");c(this,"handle");c(this,"identity",null);this.fetchImpl=N(e.fetchImpl),this.host=P(e.host),this.storage=e.storage??q(),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(T,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let r=this.handle;return r?(await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{body:e,pageContext:t},token:r.token}))?.turn??null:null}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(T);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{}return this.storage?.remove(T),null}async request(e,t,r={}){let a=this.fetchImpl;if(!a)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(o[G]=r.token);try{let s=await a(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:o,method:e}),i=await s.text();return s.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${s.status}`)),null)}catch(s){return this.options.onError?.(s),null}}};var Y={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function S(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=Y[t.find(i=>i.type==="weekday")?.value??""];if(!r)return false;let a=t.find(i=>i.type==="hour")?.value??"",o=t.find(i=>i.type==="minute")?.value??"",s=`${a}:${o}`;return n.windows.some(i=>i.days.includes(r)&&i.open<=s&&s<i.close)}var p={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"],W=["round","square"],J=["rounded","tailed"],V=["filled","outlined"],X=["circle","pill","squircle"],Z=["filled","outlined"],Q=["avatar","glyph","team_faces"],ee=["large","medium","small"],te=["above","hidden","inline"],ne=["beside_name","none","under_turn"],re=["time","time_and_latency"],g=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,I=(n,e)=>typeof n=="boolean"?n:e,ae={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"]},ie={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},oe={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"]},se={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},le={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function k(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:ae[t],a=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=a===void 0?void 0:ie[a],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=s===void 0?void 0:oe[s],u=typeof e.skin=="string"?e.skin:void 0,d=u===void 0?void 0:se[u],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,h=l===void 0?void 0:le[l],f={bubbleFill:g(e.bubbleFill,V,h?.[1]??p.bubbleFill),bubbleShape:g(e.bubbleShape,J,h?.[0]??p.bubbleShape),composerShape:g(e.composerShape,W,d?.[1]??p.composerShape),dayDividers:I(e.dayDividers,i?.[0]??p.dayDividers),launcherContent:g(e.launcherContent,Q,r?.[2]??p.launcherContent),launcherFill:g(e.launcherFill,Z,r?.[1]??p.launcherFill),launcherShape:g(e.launcherShape,X,r?.[0]??p.launcherShape),launcherSize:g(e.launcherSize,ee,r?.[3]??p.launcherSize),nameAvatar:I(e.nameAvatar,o?.[1]??p.nameAvatar),namePlacement:g(e.namePlacement,te,o?.[0]??p.namePlacement),skin:g(e.skin,j,d?.[0]??p.skin),stampContent:g(e.stampContent,re,i?.[2]??p.stampContent),stampPlacement:g(e.stampPlacement,ne,i?.[1]??p.stampPlacement)};return f.stampPlacement==="beside_name"&&f.namePlacement==="hidden"&&(f.stampPlacement="under_turn"),f}function H(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 ce="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",de={large:66,medium:56,small:46},pe={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;"},ue={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;}"},me=".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}",ge={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},fe={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},be={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ye={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function R(n,e,t,r){return `.launcher{--fab-size:${de[r]}px;${pe[n]}${ue[e]}}${he[t]}${me}${ge[n]}${fe[e]}${be[n]}${ye[n]}`}function O(n,e,t,r=a=>a){let a=document.createDocumentFragment();if(n==="glyph"){let i=document.createElement("span");return i.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="${ce}"/></svg>`,a.append(...i.childNodes,A()),a}if(n==="avatar")return a.append(F(t[0],e,r),A()),a;let o=document.createElement("span");o.className="faces";let s=t.length>0?t.slice(0,2):[void 0];for(let i of s)o.append(F(i,e,r));return a.append(o,A()),a}function F(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 a=document.createElement("img");return a.alt="",a.src=t(n.avatarUrl),r.append(a),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function A(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var xe={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",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`},b={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],teamFaces:[],...p};function ve(n){return n.team.length>0?n.team:n.teamFaces}var Se={quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.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)}.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}"},ke={round:".composer{padding:12px 12px 14px;gap:8px}.composer input{height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:44px;border-radius:8px;padding:0 12px}"},Ce={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}"},Ee={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}"},Ae=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .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}",Le='.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}"},_e=".lat{font-size:11px;opacity:.7;margin-left:6px}";function M(n){let e=k(n),t=n.launcherPosition==="bottom_left"?"left":"right",r=n.accentColor;return `${`
|
|
2
2
|
:host {
|
|
3
3
|
all: initial; --a: ${r};
|
|
4
4
|
--paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
|
|
5
|
-
--fill: #f1f5f9; --hairline: #e2e8f0; --
|
|
5
|
+
--fill: #f1f5f9; --hairline: #e2e8f0; --ink-2: rgba(0,0,0,.72);
|
|
6
6
|
--online: oklch(53.8% 0.1274 163.23);
|
|
7
7
|
color-scheme: light dark;
|
|
8
8
|
}
|
|
9
9
|
@media (prefers-color-scheme: dark) {
|
|
10
10
|
:host {
|
|
11
11
|
--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
12
|
-
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --
|
|
12
|
+
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
13
13
|
--online: oklch(72% 0.13 163.23);
|
|
14
14
|
}
|
|
15
15
|
}
|
|
@@ -54,8 +54,9 @@
|
|
|
54
54
|
.prompt:focus-visible { outline: 2px solid ${r}; outline-offset: 2px; }
|
|
55
55
|
.av { width: 30px; height: 30px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 650; color: #fff; background: #7c3f3f; }
|
|
56
56
|
.av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
|
|
57
|
+
.av img { width: 100%; height: 100%; display: block; object-fit: cover; border-radius: inherit; }
|
|
57
58
|
.composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--hairline); }
|
|
58
|
-
.composer input { flex: 1; padding:
|
|
59
|
+
.composer input { flex: 1; min-width: 0; height: 44px; padding: 0 12px; border: 0; border-radius: 8px; font-size: 14px; background: var(--fill); color: var(--ink); }
|
|
59
60
|
.composer input:focus-visible { outline: 2px solid ${r}; }
|
|
60
61
|
.composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${r}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 14.5px; font-weight: 550; }
|
|
61
62
|
.composer button .sendglyph { display: none; width: 19px; height: 19px; }
|
|
@@ -64,5 +65,5 @@
|
|
|
64
65
|
.panel { animation: rise 180ms ease-out; }
|
|
65
66
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
66
67
|
}
|
|
67
|
-
`}${pe[e.skin]}${I(e.launcherShape,e.launcherFill,e.launcherContent,e.launcherSize)}${ue[e.bubbleStyle]}${he[e.namePlacement]}${e.nameAvatar?me:""}${e.dayDividers?ge:""}${fe[e.stampPlacement]}${e.stampContent==="time_and_latency"?be:""}`}var xe=["end_user","agent","ai"];function ye(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var x=class{constructor(e,t,r={},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,"lastFocused",null);l(this,"unread",0);this.strings={...de,...r},this.appearance={...v,...a},this.settings=y({...v,...a}),this.root=e.attachShadow({mode:"closed"});let s=document.createElement("style");if(s.textContent=F({...v,...a}),this.root.append(s),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.append(H(this.settings.launcherContent,this.strings,this.appearance.teamFaces)),this.settings.launcherShape==="pill"){let o=document.createElement("span");o.className="label",o.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(o);}this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.launcher.append(this.badge),this.root.append(this.launcher);}toggle(){this.panel?this.close():this.open();}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className="panel",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("h2");r.textContent=this.strings.title;let a=document.createElement("button");a.className="close",a.type="button",a.setAttribute("aria-label",this.strings.closeLabel),a.textContent="\xD7",a.addEventListener("click",()=>this.close()),t.append(r,a);let s=document.createElement("div");s.className="log",s.setAttribute("role","log"),s.setAttribute("aria-live","polite"),s.setAttribute("aria-label",this.strings.title);let o=document.createElement("form");o.className="composer";let i=document.createElement("input");i.type="text",i.setAttribute("aria-label",this.strings.inputPlaceholder),i.placeholder=this.strings.inputPlaceholder;let c=document.createElement("button");c.type="submit",c.setAttribute("aria-label",this.strings.sendLabel),c.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 h=document.createElement("span");h.className="sendtext",h.textContent=this.strings.sendLabel,c.append(h),o.append(i,c),o.addEventListener("submit",g=>{g.preventDefault(),this.submit(i,s);}),e.append(t,s,o),e.addEventListener("keydown",g=>this.onKeydown(g,e,a)),this.root.append(e),this.panel=e,i.focus();let d=await this.client.load();d&&d.turns.length>0?this.renderThread(s,d):this.renderFirstRun(s,i),!N(this.appearance.availability,new Date)&&this.appearance.awayMessage.trim()&&this.renderAway(s);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let a=document.createElement("h3");a.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let s=document.createElement("p");s.textContent=this.strings.emptyBody,r.append(a,s);for(let o of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=o,i.addEventListener("click",()=>{t.value=o,this.submit(t,e);}),r.append(i);}e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim();if(!r)return;e.value="",t.querySelector(".empty")?.remove();let a=await this.client.send(r,ye());a&&this.appendTurn(t,a);}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t){e.querySelector(".empty")?.remove();let r=xe.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,s=document.createElement("div");if(s.className=`turn ${r}`,r!=="end_user"&&a.nameAvatar){let d=document.createElement("span");d.className=r==="ai"?"av bot":"av",d.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel.slice(0,2).toUpperCase(),d.setAttribute("aria-hidden","true"),s.append(d);}let i=document.createElement("div");if(i.className="body",r!=="end_user"&&a.namePlacement!=="hidden"||r==="ai"&&a.namePlacement==="hidden"){let d=document.createElement("div");d.className=r==="ai"?"author ai":"author",d.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel,a.stampPlacement==="beside_name"&&d.append(this.stamp(t)),i.append(d);}let h=document.createElement("div");h.textContent=t.body,i.append(h),a.stampPlacement==="under_turn"&&i.append(this.stamp(t)),s.append(i),e.append(s),e.scrollTop=e.scrollHeight;}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 a=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(a.length===0)return;let s=a[0],o=a[a.length-1],i=this.root.activeElement;e.shiftKey&&i===s?(e.preventDefault(),o.focus()):!e.shiftKey&&i===o?(e.preventDefault(),s.focus()):i===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));}};function R(n){return `40${JSON.stringify(n)}`}function O(){return "3"}function M(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=E(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),a=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=E(a);return {kind:"connectError",message:typeof o?.message=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let s=E(a);return !Array.isArray(s)||typeof s[0]!="string"?{kind:"other"}:{kind:"event",name:s[0],payload:s[1]}}function E(n){try{return JSON.parse(n)}catch{return null}}var ve="/socket.io/?EIO=4&transport=websocket",S=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??Se,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=M(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(R(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(O());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 Se(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}function Ge(n){let e=globalThis.document;if(!e)throw new Error("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 b(n),a=new x(t,r,n.strings,n.appearance),s=new Set,o,i=null,c=n.pollIntervalMs??15e3,h=u=>{s.has(u.id)||u.authorKind==="end_user"||(s.add(u.id),a.onIncomingTurn(u));},d=async()=>{if(!r.hasThread)return;let u=await r.load();if(u){for(let f of u.turns)h(f);s=new Set(u.turns.map(f=>f.id));}},g=()=>{o||c<=0||(o=setInterval(()=>void d(),c));},T=()=>{o&&clearInterval(o),o=void 0;},k=()=>{if(i||!n.socketHost)return;let u=r.socketAuth;u&&(i=new S({auth:u,host:n.socketHost,onClosed:f=>{i=null,g(),f&&k();},onReady:T,onTurn:h,socketFactory:n.socketFactory}),i.open());};return g(),k(),{close:()=>a.close(),destroy:()=>{T(),i?.close(),i=null,a.close(),t.remove();},identify:u=>r.identify(u),open:()=>{a.open().then(k);}}}exports.ChatClient=b;exports.ChatPanel=x;exports.DEFAULT_APPEARANCE=v;exports.DEFAULT_APPEARANCE_SETTINGS=p;exports.mountChat=Ge;exports.panelStyles=F;exports.resolveAppearance=y;//# sourceMappingURL=chat.cjs.map
|
|
68
|
+
`}${ke[e.composerShape]}${Se[e.skin]}${R(e.launcherShape,e.launcherFill,e.launcherContent,e.launcherSize)}${Ce[e.bubbleShape]}${Ee[e.bubbleFill]}${Te[e.namePlacement]}${e.nameAvatar?Ae:""}${e.dayDividers?Le:""}${we[e.stampPlacement]}${e.stampContent==="time_and_latency"?_e:""}`}var Ne=["end_user","agent","ai"];function Pe(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var v=class{constructor(e,t,r={},a={}){this.host=e;this.client=t;c(this,"root");c(this,"strings");c(this,"settings");c(this,"appearance");c(this,"launcher");c(this,"badge");c(this,"panel",null);c(this,"lastFocused",null);c(this,"unread",0);this.strings={...xe,...r},this.appearance={...b,...a},this.settings=k({...b,...a}),this.root=e.attachShadow({mode:"closed"});let o=document.createElement("style");if(o.textContent=M({...b,...a}),this.root.append(o),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.append(O(this.settings.launcherContent,this.strings,ve(this.appearance),s=>this.client.avatarUrl(s))),this.settings.launcherShape==="pill"){let s=document.createElement("span");s.className="label",s.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(s);}this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.launcher.append(this.badge),this.root.append(this.launcher);}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.launcher.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="panel",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("h2");r.textContent=this.strings.title;let a=document.createElement("button");a.className="close",a.type="button",a.setAttribute("aria-label",this.strings.closeLabel),a.textContent="\xD7",a.addEventListener("click",()=>this.close()),t.append(r,a);let o=document.createElement("div");o.className="log",o.setAttribute("role","log"),o.setAttribute("aria-live","polite"),o.setAttribute("aria-label",this.strings.title);let s=document.createElement("form");s.className="composer";let i=document.createElement("input");i.type="text",i.setAttribute("aria-label",this.strings.inputPlaceholder),i.placeholder=this.strings.inputPlaceholder;let u=document.createElement("button");u.type="submit",u.setAttribute("aria-label",this.strings.sendLabel),u.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 d=document.createElement("span");d.className="sendtext",d.textContent=this.strings.sendLabel,u.append(d),s.append(i,u),s.addEventListener("submit",h=>{h.preventDefault(),this.submit(i,o);}),e.append(t,o,s),e.addEventListener("keydown",h=>this.onKeydown(h,e,a)),this.root.append(e),this.panel=e,i.focus();let l=await this.client.load();l&&l.turns.length>0?this.renderThread(o,l):this.renderFirstRun(o,i),!S(this.appearance.availability,new Date)&&this.appearance.awayMessage.trim()&&this.renderAway(o);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let a=document.createElement("h3");a.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,r.append(a,o);for(let s of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=s,i.addEventListener("click",()=>{t.value=s,this.submit(t,e);}),r.append(i);}e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim();if(!r)return;e.value="",t.querySelector(".empty")?.remove();let a=await this.client.send(r,Pe());a&&this.appendTurn(t,a);}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t){e.querySelector(".empty")?.remove();let r=Ne.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${r}`,r!=="end_user"&&a.nameAvatar){let l=document.createElement("span");if(l.className=r==="ai"?"av bot":"av",l.setAttribute("aria-hidden","true"),r==="agent"&&t.authorAvatarUrl){let h=document.createElement("img");h.alt="",h.src=this.client.avatarUrl(t.authorAvatarUrl),l.append(h);}else l.textContent=r==="ai"?this.strings.aiLabel:H(this.agentName(t));o.append(l);}let i=document.createElement("div");i.className="body";let u=r!=="end_user"&&a.namePlacement!=="hidden",d=document.createElement("div");if(d.textContent=t.body,u||r==="ai"&&a.namePlacement==="hidden"){let l=document.createElement("div");l.className=r==="ai"?"author ai":"author",l.textContent=r==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&l.append(this.stamp(t)),a.namePlacement==="inline"?(l.classList.add("below"),i.append(d,l)):i.append(l,d);}else i.append(d);a.stampPlacement==="under_turn"&&i.append(this.stamp(t)),o.append(i),e.append(o),e.scrollTop=e.scrollHeight;}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 a=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(a.length===0)return;let o=a[0],s=a[a.length-1],i=this.root.activeElement;e.shiftKey&&i===o?(e.preventDefault(),s.focus()):!e.shiftKey&&i===s?(e.preventDefault(),o.focus()):i===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));}};function $(n){return `40${JSON.stringify(n)}`}function z(){return "3"}function U(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 s=L(t);return {kind:"open",pingInterval:typeof s?.pingInterval=="number"?s.pingInterval:25e3,pingTimeout:typeof s?.pingTimeout=="number"?s.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),a=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let s=L(a);return {kind:"connectError",message:typeof s?.message=="string"?s.message:"refused"}}if(r!=="2")return {kind:"other"};let o=L(a);return !Array.isArray(o)||typeof o[0]!="string"?{kind:"other"}:{kind:"event",name:o[0],payload:o[1]}}function L(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",C=class{constructor(e){this.options=e;c(this,"socket",null);c(this,"heartbeat",null);c(this,"ready",false);c(this,"closed",false);c(this,"heartbeatWindow",45e3);c(this,"factory");c(this,"setTimer");c(this,"clearTimer");this.factory=e.socketFactory??Fe,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(/\/+$/,"")}${Ie}`,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=U(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send($(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(z());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 Fe(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var He=6e4;function nt(n){let e=globalThis.document;if(!e)throw new Error("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 x(n),a=new v(t,r,n.strings,n.appearance),o=n.appearance?.availability??b.availability,s,i=()=>{a.setOpenNow(S(o,new Date)),s=setTimeout(i,He);};i();let u=new Set,d,l=null,h=n.pollIntervalMs??15e3,f=m=>{u.has(m.id)||m.authorKind==="end_user"||(u.add(m.id),a.onIncomingTurn(m));},B=async()=>{if(!r.hasThread)return;let m=await r.load();if(m){for(let y of m.turns)f(y);u=new Set(m.turns.map(y=>y.id));}},w=()=>{d||h<=0||(d=setInterval(()=>void B(),h));},_=()=>{d&&clearInterval(d),d=void 0;},E=()=>{if(l||!n.socketHost)return;let m=r.socketAuth;m&&(l=new C({auth:m,host:n.socketHost,onClosed:y=>{l=null,w(),y&&E();},onReady:_,onTurn:f,socketFactory:n.socketFactory}),l.open());};return w(),E(),{close:()=>a.close(),destroy:()=>{_(),clearTimeout(s),l?.close(),l=null,a.close(),t.remove();},identify:m=>r.identify(m),open:()=>{a.open().then(E);}}}exports.ChatClient=x;exports.ChatPanel=v;exports.DEFAULT_APPEARANCE=b;exports.DEFAULT_APPEARANCE_SETTINGS=p;exports.mountChat=nt;exports.panelStyles=M;exports.resolveAppearance=k;//# sourceMappingURL=chat.cjs.map
|
|
68
69
|
//# sourceMappingURL=chat.cjs.map
|
package/dist/chat.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as ChatClient, M as MessengerConfig, A as AppearanceSettings, a as ChatTurn, b as ChatIdentity, c as ChatClientOptions } from './config-
|
|
2
|
-
export { B as
|
|
1
|
+
import { C as ChatClient, M as MessengerConfig, A as AppearanceSettings, a as ChatTurn, b as ChatIdentity, c as ChatClientOptions } from './config-BD9kg-c4.cjs';
|
|
2
|
+
export { B as BubbleFill, d as BubbleShape, e as ChatStorage, f as ChatThread, g as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, L as LauncherContent, h as LauncherFill, i as LauncherShape, j as LauncherSize, k as MessengerSkin, N as NamePlacement, S as StampContent, l as StampPlacement, r as resolveAppearance } from './config-BD9kg-c4.cjs';
|
|
3
3
|
import { S as SocketFactory } from './types-DjMXp6Wg.cjs';
|
|
4
4
|
import './http-BCh716Vs.cjs';
|
|
5
5
|
|
|
@@ -16,7 +16,7 @@ interface ChatStrings {
|
|
|
16
16
|
emptyTitle: string;
|
|
17
17
|
emptyBody: string;
|
|
18
18
|
}
|
|
19
|
-
type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'starterPrompts' | 'teamFaces'> & AppearanceSettings;
|
|
19
|
+
type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'starterPrompts' | 'team' | 'teamFaces'> & AppearanceSettings;
|
|
20
20
|
declare const DEFAULT_APPEARANCE: MessengerAppearance;
|
|
21
21
|
declare function panelStyles(appearance: MessengerAppearance): string;
|
|
22
22
|
declare class ChatPanel {
|
|
@@ -33,6 +33,7 @@ declare class ChatPanel {
|
|
|
33
33
|
private unread;
|
|
34
34
|
constructor(host: HTMLElement, client: ChatClient, strings?: Partial<ChatStrings>, appearance?: Partial<MessengerAppearance>);
|
|
35
35
|
private toggle;
|
|
36
|
+
setOpenNow(open: boolean): void;
|
|
36
37
|
open(): Promise<void>;
|
|
37
38
|
private renderFirstRun;
|
|
38
39
|
private renderAway;
|
|
@@ -41,6 +42,7 @@ declare class ChatPanel {
|
|
|
41
42
|
private submit;
|
|
42
43
|
private renderThread;
|
|
43
44
|
private appendTurn;
|
|
45
|
+
private agentName;
|
|
44
46
|
private stamp;
|
|
45
47
|
private onKeydown;
|
|
46
48
|
private renderBadge;
|
package/dist/chat.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as ChatClient, M as MessengerConfig, A as AppearanceSettings, a as ChatTurn, b as ChatIdentity, c as ChatClientOptions } from './config-
|
|
2
|
-
export { B as
|
|
1
|
+
import { C as ChatClient, M as MessengerConfig, A as AppearanceSettings, a as ChatTurn, b as ChatIdentity, c as ChatClientOptions } from './config-BR_iYD-k.js';
|
|
2
|
+
export { B as BubbleFill, d as BubbleShape, e as ChatStorage, f as ChatThread, g as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, L as LauncherContent, h as LauncherFill, i as LauncherShape, j as LauncherSize, k as MessengerSkin, N as NamePlacement, S as StampContent, l as StampPlacement, r as resolveAppearance } from './config-BR_iYD-k.js';
|
|
3
3
|
import { S as SocketFactory } from './types-DjMXp6Wg.js';
|
|
4
4
|
import './http-BCh716Vs.js';
|
|
5
5
|
|
|
@@ -16,7 +16,7 @@ interface ChatStrings {
|
|
|
16
16
|
emptyTitle: string;
|
|
17
17
|
emptyBody: string;
|
|
18
18
|
}
|
|
19
|
-
type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'starterPrompts' | 'teamFaces'> & AppearanceSettings;
|
|
19
|
+
type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'starterPrompts' | 'team' | 'teamFaces'> & AppearanceSettings;
|
|
20
20
|
declare const DEFAULT_APPEARANCE: MessengerAppearance;
|
|
21
21
|
declare function panelStyles(appearance: MessengerAppearance): string;
|
|
22
22
|
declare class ChatPanel {
|
|
@@ -33,6 +33,7 @@ declare class ChatPanel {
|
|
|
33
33
|
private unread;
|
|
34
34
|
constructor(host: HTMLElement, client: ChatClient, strings?: Partial<ChatStrings>, appearance?: Partial<MessengerAppearance>);
|
|
35
35
|
private toggle;
|
|
36
|
+
setOpenNow(open: boolean): void;
|
|
36
37
|
open(): Promise<void>;
|
|
37
38
|
private renderFirstRun;
|
|
38
39
|
private renderAway;
|
|
@@ -41,6 +42,7 @@ declare class ChatPanel {
|
|
|
41
42
|
private submit;
|
|
42
43
|
private renderThread;
|
|
43
44
|
private appendTurn;
|
|
45
|
+
private agentName;
|
|
44
46
|
private stamp;
|
|
45
47
|
private onKeydown;
|
|
46
48
|
private renderBadge;
|
package/dist/chat.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import {c,a as a$2,b as b$1}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var z="X-Prodantix-Conversation-Token",C="prodantix.chat.handle";function $(){let a=globalThis.localStorage;if(a)return {get:e=>a.getItem(e),remove:e=>a.removeItem(e),set:(e,t)=>a.setItem(e,t)}}var b=class{constructor(e){this.options=e;a(this,"fetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=a$1(e.fetchImpl),this.host=d(e.host),this.storage=e.storage??$(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}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(C,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?(await this.request("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/turns`,{body:{body:e,pageContext:t},token:n.token}))?.turn??null:null}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(C);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{}return this.storage?.remove(C),null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let s={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(s[z]=n.token);try{let o=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:s,method:e}),i=await o.text();return o.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${o.status}`)),null)}catch(o){return this.options.onError?.(o),null}}};var p={bubbleStyle:"tailed",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"concierge",stampContent:"time",stampPlacement:"none"},O=["concierge","console","quiet"],D=["hairline","outlined","rounded","tailed"],U=["circle","pill","squircle"],B=["filled","outlined"],K=["avatar","glyph","team_faces"],q=["large","medium","small"],Y=["above","hidden","inline"],G=["beside_name","none","under_turn"],W=["time","time_and_latency"],m=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,_=(a,e)=>typeof a=="boolean"?a:e,j={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"]},X={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Z={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"]};function y(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:j[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,s=r===void 0?void 0:X[r],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=o===void 0?void 0:Z[o],c={bubbleStyle:m(e.bubbleStyle,D,p.bubbleStyle),dayDividers:_(e.dayDividers,i?.[0]??p.dayDividers),launcherContent:m(e.launcherContent,K,n?.[2]??p.launcherContent),launcherFill:m(e.launcherFill,B,n?.[1]??p.launcherFill),launcherShape:m(e.launcherShape,U,n?.[0]??p.launcherShape),launcherSize:m(e.launcherSize,q,n?.[3]??p.launcherSize),nameAvatar:_(e.nameAvatar,s?.[1]??p.nameAvatar),namePlacement:m(e.namePlacement,Y,s?.[0]??p.namePlacement),skin:m(e.skin,O,p.skin),stampContent:m(e.stampContent,W,i?.[2]??p.stampContent),stampPlacement:m(e.stampPlacement,G,i?.[1]??p.stampPlacement)};return c.stampPlacement==="beside_name"&&c.namePlacement==="hidden"&&(c.stampPlacement="under_turn"),c.namePlacement==="inline"&&c.bubbleStyle==="hairline"&&(c.namePlacement="above"),c}var J={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function N(a,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:a.timezone,weekday:"short"}).formatToParts(e),n=J[t.find(i=>i.type==="weekday")?.value??""];if(!n)return false;let r=t.find(i=>i.type==="hour")?.value??"",s=t.find(i=>i.type==="minute")?.value??"",o=`${r}:${s}`;return a.windows.some(i=>i.days.includes(n)&&i.open<=o&&o<i.close)}var V="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",Q={large:66,medium:56,small:46},ee={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;"},te={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);"},ne={avatar:".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);}",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;}.launcher .live{width:9px;height:9px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}"},ae={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}"},ie={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 M(a,e,t,n){return `.launcher{--fab-size:${Q[n]}px;${ee[a]}${te[e]}}${ne[t]}${ae[a]}${re[e]}${ie[a]}${oe[a]}`}function F(a,e,t){let n=document.createDocumentFragment();if(a==="glyph"){let o=document.createElement("span");return o.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="${V}"/></svg>`,n.append(...o.childNodes),n}if(a==="avatar")return n.append(H(t[0],e),I()),n;let r=document.createElement("span");r.className="faces";let s=t.length>0?t.slice(0,2):[void 0];for(let o of s)r.append(H(o,e));return n.append(r,I()),n}function H(a,e){let t=document.createElement("span");return t.className="av",t.setAttribute("aria-hidden","true"),t.textContent=a?a.initials:e.agentLabel.slice(0,2).toUpperCase(),a&&(t.style.background=a.tone),t}function I(){let a=document.createElement("span");return a.className="live",a.setAttribute("aria-hidden","true"),a}var se={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",sendLabel:"Send",timeLabel:a=>{let e=new Date(a);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:a=>`${a} unread`},v={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],teamFaces:[],...p},le={concierge:".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}.composer{padding:12px 12px 14px;gap:8px}.composer input{border:0;background:var(--fill);height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",console:".panel{border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.16)}.header{background:var(--paper);color:var(--ink);border-bottom:1px solid var(--hairline)}.close{color:var(--ink-2)}",quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{height:42px;padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.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)}.close{color:var(--ink-2)}"},ce={hairline:".turn{max-width:100%;padding:13px 0;border-top:1px solid var(--hairline);background:none;border-radius:0}.log>.turn:first-child{border-top:0}.turn.end_user{align-self:stretch;display:flex;flex-direction:column;align-items:flex-end}.turn.end_user .body{background:var(--fill);color:var(--ink);border-radius:8px;padding:9px 12px;max-width:85%}",outlined:".turn{background:none;border:1px solid var(--hairline);border-radius:12px}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}",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={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".author{display:inline;margin-right:6px;font-weight:650}"},pe=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .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}",ue='.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}"},me=".lat{font-size:11px;opacity:.7;margin-left:6px}";function R(a){let e=y(a),t=a.launcherPosition==="bottom_left"?"left":"right",n=a.accentColor;return `${`
|
|
1
|
+
import {c,a as a$2,b as b$1}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var B="X-Prodantix-Conversation-Token",E="prodantix.chat.handle";function D(){let a=globalThis.localStorage;if(a)return {get:e=>a.getItem(e),remove:e=>a.removeItem(e),set:(e,t)=>a.setItem(e,t)}}var x=class{constructor(e){this.options=e;a(this,"fetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=a$1(e.fetchImpl),this.host=d(e.host),this.storage=e.storage??D(),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(E,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?(await this.request("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/turns`,{body:{body:e,pageContext:t},token:n.token}))?.turn??null:null}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(E);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{}return this.storage?.remove(E),null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(o[B]=n.token);try{let s=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),i=await s.text();return s.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${s.status}`)),null)}catch(s){return this.options.onError?.(s),null}}};var q={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function S(a,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:a.timezone,weekday:"short"}).formatToParts(e),n=q[t.find(i=>i.type==="weekday")?.value??""];if(!n)return false;let r=t.find(i=>i.type==="hour")?.value??"",o=t.find(i=>i.type==="minute")?.value??"",s=`${r}:${o}`;return a.windows.some(i=>i.days.includes(n)&&i.open<=s&&s<i.close)}var p={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"},K=["quiet","standard"],Y=["round","square"],G=["rounded","tailed"],W=["filled","outlined"],j=["circle","pill","squircle"],X=["filled","outlined"],Z=["avatar","glyph","team_faces"],J=["large","medium","small"],V=["above","hidden","inline"],Q=["beside_name","none","under_turn"],ee=["time","time_and_latency"],g=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,I=(a,e)=>typeof a=="boolean"?a:e,te={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"]},ne={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ae={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"]},re={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},ie={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function k(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:te[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=r===void 0?void 0:ne[r],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=s===void 0?void 0:ae[s],u=typeof e.skin=="string"?e.skin:void 0,d=u===void 0?void 0:re[u],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,h=l===void 0?void 0:ie[l],f={bubbleFill:g(e.bubbleFill,W,h?.[1]??p.bubbleFill),bubbleShape:g(e.bubbleShape,G,h?.[0]??p.bubbleShape),composerShape:g(e.composerShape,Y,d?.[1]??p.composerShape),dayDividers:I(e.dayDividers,i?.[0]??p.dayDividers),launcherContent:g(e.launcherContent,Z,n?.[2]??p.launcherContent),launcherFill:g(e.launcherFill,X,n?.[1]??p.launcherFill),launcherShape:g(e.launcherShape,j,n?.[0]??p.launcherShape),launcherSize:g(e.launcherSize,J,n?.[3]??p.launcherSize),nameAvatar:I(e.nameAvatar,o?.[1]??p.nameAvatar),namePlacement:g(e.namePlacement,V,o?.[0]??p.namePlacement),skin:g(e.skin,K,d?.[0]??p.skin),stampContent:g(e.stampContent,ee,i?.[2]??p.stampContent),stampPlacement:g(e.stampPlacement,Q,i?.[1]??p.stampPlacement)};return f.stampPlacement==="beside_name"&&f.namePlacement==="hidden"&&(f.stampPlacement="under_turn"),f}function M(a){let e=a.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 oe="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",se={large:66,medium:56,small:46},le={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;"},ce={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);"},de={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;}"},pe=".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}",ue={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},he={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},me={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ge={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function $(a,e,t,n){return `.launcher{--fab-size:${se[n]}px;${le[a]}${ce[e]}}${de[t]}${pe}${ue[a]}${he[e]}${me[a]}${ge[a]}`}function z(a,e,t,n=r=>r){let r=document.createDocumentFragment();if(a==="glyph"){let i=document.createElement("span");return i.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="${oe}"/></svg>`,r.append(...i.childNodes,T()),r}if(a==="avatar")return r.append(R(t[0],e,n),T()),r;let o=document.createElement("span");o.className="faces";let s=t.length>0?t.slice(0,2):[void 0];for(let i of s)o.append(R(i,e,n));return r.append(o,T()),r}function R(a,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),a&&(n.style.background=a.tone),a?.avatarUrl){let r=document.createElement("img");return r.alt="",r.src=t(a.avatarUrl),n.append(r),n}return n.textContent=a?a.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function T(){let a=document.createElement("span");return a.className="live",a.setAttribute("aria-hidden","true"),a}var fe={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",sendLabel:"Send",timeLabel:a=>{let e=new Date(a);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:a=>`${a} unread`},b={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],teamFaces:[],...p};function be(a){return a.team.length>0?a.team:a.teamFaces}var ye={quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.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)}.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}"},xe={round:".composer{padding:12px 12px 14px;gap:8px}.composer input{height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:44px;border-radius:8px;padding:0 12px}"},ve={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}"},Se={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},ke={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}"},Ce=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .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)}',Ee={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}"},Te=".lat{font-size:11px;opacity:.7;margin-left:6px}";function O(a){let e=k(a),t=a.launcherPosition==="bottom_left"?"left":"right",n=a.accentColor;return `${`
|
|
2
2
|
:host {
|
|
3
3
|
all: initial; --a: ${n};
|
|
4
4
|
--paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
|
|
5
|
-
--fill: #f1f5f9; --hairline: #e2e8f0; --
|
|
5
|
+
--fill: #f1f5f9; --hairline: #e2e8f0; --ink-2: rgba(0,0,0,.72);
|
|
6
6
|
--online: oklch(53.8% 0.1274 163.23);
|
|
7
7
|
color-scheme: light dark;
|
|
8
8
|
}
|
|
9
9
|
@media (prefers-color-scheme: dark) {
|
|
10
10
|
:host {
|
|
11
11
|
--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
12
|
-
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --
|
|
12
|
+
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
13
13
|
--online: oklch(72% 0.13 163.23);
|
|
14
14
|
}
|
|
15
15
|
}
|
|
@@ -54,8 +54,9 @@ import {c,a as a$2,b as b$1}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./
|
|
|
54
54
|
.prompt:focus-visible { outline: 2px solid ${n}; outline-offset: 2px; }
|
|
55
55
|
.av { width: 30px; height: 30px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 650; color: #fff; background: #7c3f3f; }
|
|
56
56
|
.av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
|
|
57
|
+
.av img { width: 100%; height: 100%; display: block; object-fit: cover; border-radius: inherit; }
|
|
57
58
|
.composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--hairline); }
|
|
58
|
-
.composer input { flex: 1; padding:
|
|
59
|
+
.composer input { flex: 1; min-width: 0; height: 44px; padding: 0 12px; border: 0; border-radius: 8px; font-size: 14px; background: var(--fill); color: var(--ink); }
|
|
59
60
|
.composer input:focus-visible { outline: 2px solid ${n}; }
|
|
60
61
|
.composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${n}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 14.5px; font-weight: 550; }
|
|
61
62
|
.composer button .sendglyph { display: none; width: 19px; height: 19px; }
|
|
@@ -64,5 +65,5 @@ import {c,a as a$2,b as b$1}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./
|
|
|
64
65
|
.panel { animation: rise 180ms ease-out; }
|
|
65
66
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
66
67
|
}
|
|
67
|
-
`}${
|
|
68
|
+
`}${xe[e.composerShape]}${ye[e.skin]}${$(e.launcherShape,e.launcherFill,e.launcherContent,e.launcherSize)}${ve[e.bubbleShape]}${Se[e.bubbleFill]}${ke[e.namePlacement]}${e.nameAvatar?Ce:""}${e.dayDividers?Ae:""}${Ee[e.stampPlacement]}${e.stampContent==="time_and_latency"?Te:""}`}var Le=["end_user","agent","ai"];function we(){let a=globalThis.location;if(a)return {host:a.host,path:a.pathname,title:document.title}}var v=class{constructor(e,t,n={},r={}){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,"lastFocused",null);a(this,"unread",0);this.strings={...fe,...n},this.appearance={...b,...r},this.settings=k({...b,...r}),this.root=e.attachShadow({mode:"closed"});let o=document.createElement("style");if(o.textContent=O({...b,...r}),this.root.append(o),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.append(z(this.settings.launcherContent,this.strings,be(this.appearance),s=>this.client.avatarUrl(s))),this.settings.launcherShape==="pill"){let s=document.createElement("span");s.className="label",s.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(s);}this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.launcher.append(this.badge),this.root.append(this.launcher);}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.launcher.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="panel",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("h2");n.textContent=this.strings.title;let r=document.createElement("button");r.className="close",r.type="button",r.setAttribute("aria-label",this.strings.closeLabel),r.textContent="\xD7",r.addEventListener("click",()=>this.close()),t.append(n,r);let o=document.createElement("div");o.className="log",o.setAttribute("role","log"),o.setAttribute("aria-live","polite"),o.setAttribute("aria-label",this.strings.title);let s=document.createElement("form");s.className="composer";let i=document.createElement("input");i.type="text",i.setAttribute("aria-label",this.strings.inputPlaceholder),i.placeholder=this.strings.inputPlaceholder;let u=document.createElement("button");u.type="submit",u.setAttribute("aria-label",this.strings.sendLabel),u.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 d=document.createElement("span");d.className="sendtext",d.textContent=this.strings.sendLabel,u.append(d),s.append(i,u),s.addEventListener("submit",h=>{h.preventDefault(),this.submit(i,o);}),e.append(t,o,s),e.addEventListener("keydown",h=>this.onKeydown(h,e,r)),this.root.append(e),this.panel=e,i.focus();let l=await this.client.load();l&&l.turns.length>0?this.renderThread(o,l):this.renderFirstRun(o,i),!S(this.appearance.availability,new Date)&&this.appearance.awayMessage.trim()&&this.renderAway(o);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let r=document.createElement("h3");r.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(r,o);for(let s of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=s,i.addEventListener("click",()=>{t.value=s,this.submit(t,e);}),n.append(i);}e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim();if(!n)return;e.value="",t.querySelector(".empty")?.remove();let r=await this.client.send(n,we());r&&this.appendTurn(t,r);}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t){e.querySelector(".empty")?.remove();let n=Le.includes(t.authorKind)?t.authorKind:"agent",r=this.settings,o=document.createElement("div");if(o.className=`turn ${n}`,n!=="end_user"&&r.nameAvatar){let l=document.createElement("span");if(l.className=n==="ai"?"av bot":"av",l.setAttribute("aria-hidden","true"),n==="agent"&&t.authorAvatarUrl){let h=document.createElement("img");h.alt="",h.src=this.client.avatarUrl(t.authorAvatarUrl),l.append(h);}else l.textContent=n==="ai"?this.strings.aiLabel:M(this.agentName(t));o.append(l);}let i=document.createElement("div");i.className="body";let u=n!=="end_user"&&r.namePlacement!=="hidden",d=document.createElement("div");if(d.textContent=t.body,u||n==="ai"&&r.namePlacement==="hidden"){let l=document.createElement("div");l.className=n==="ai"?"author ai":"author",l.textContent=n==="ai"?this.strings.aiLabel:this.agentName(t),r.stampPlacement==="beside_name"&&l.append(this.stamp(t)),r.namePlacement==="inline"?(l.classList.add("below"),i.append(d,l)):i.append(l,d);}else i.append(d);r.stampPlacement==="under_turn"&&i.append(this.stamp(t)),o.append(i),e.append(o),e.scrollTop=e.scrollHeight;}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 r=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let o=r[0],s=r[r.length-1],i=this.root.activeElement;e.shiftKey&&i===o?(e.preventDefault(),s.focus()):!e.shiftKey&&i===s?(e.preventDefault(),o.focus()):i===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));}};var Pe="/socket.io/?EIO=4&transport=websocket",C=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??_e,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(/\/+$/,"")}${Pe}`,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$2(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 _e(a){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(a)}var Ne=6e4;function Ze(a){let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=a.mountPoint??e.createElement("div");a.mountPoint||e.body.append(t);let n=new x(a),r=new v(t,n,a.strings,a.appearance),o=a.appearance?.availability??b.availability,s,i=()=>{r.setOpenNow(S(o,new Date)),s=setTimeout(i,Ne);};i();let u=new Set,d,l=null,h=a.pollIntervalMs??15e3,f=m=>{u.has(m.id)||m.authorKind==="end_user"||(u.add(m.id),r.onIncomingTurn(m));},U=async()=>{if(!n.hasThread)return;let m=await n.load();if(m){for(let y of m.turns)f(y);u=new Set(m.turns.map(y=>y.id));}},L=()=>{d||h<=0||(d=setInterval(()=>void U(),h));},w=()=>{d&&clearInterval(d),d=void 0;},A=()=>{if(l||!a.socketHost)return;let m=n.socketAuth;m&&(l=new C({auth:m,host:a.socketHost,onClosed:y=>{l=null,L(),y&&A();},onReady:w,onTurn:f,socketFactory:a.socketFactory}),l.open());};return L(),A(),{close:()=>r.close(),destroy:()=>{w(),clearTimeout(s),l?.close(),l=null,r.close(),t.remove();},identify:m=>n.identify(m),open:()=>{r.open().then(A);}}}export{x as ChatClient,v as ChatPanel,b as DEFAULT_APPEARANCE,p as DEFAULT_APPEARANCE_SETTINGS,Ze as mountChat,O as panelStyles,k as resolveAppearance};//# sourceMappingURL=chat.js.map
|
|
68
69
|
//# sourceMappingURL=chat.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c as c$2,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {a as a$1,d,b as b$1,c as c$1}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var p=class extends Error{constructor(t,n,r){super(n,r);a(this,"code");this.code=t,this.name="ProdantixError";}},b=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},y=class extends p{constructor(t,n){super("validation",n);a(this,"field");this.field=t,this.name="ValidationError";}},l=class extends p{constructor(t,n,r){super("transport",t,r);a(this,"status");this.status=n,this.name="TransportError";}};var v=class{constructor(){a(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};function $e(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new v}return new v}var V={now:()=>new Date};function I(s){return s.toISOString()}var de=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ue=/^(?:\$|[a-z])[a-z0-9_.]*$/;function j(s){let e=0;for(let t of s)e+=1;return e}function H(s){return de.test(s)}function he(s){return ue.test(s)}function U(s){let e=j(s);if(e<1||e>200)throw new y("distinct_id","distinct_id must be between 1 and 200 characters")}function B(s){let e=j(s);if(e<1||e>200)throw new y("event_name","event_name must be between 1 and 200 characters");if(!he(s))throw new y("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var J="prodantix-js",z="0.0.1";function pe(){return globalThis.crypto}function fe(s){s[6]=s[6]&15|64,s[8]=s[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(s[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ge(){let s=pe();if(s?.randomUUID)return s.randomUUID();let e=new Uint8Array(16);if(s?.getRandomValues)s.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return fe(e)}var Q={uuid:ge};var me=s=>{};function G(s){if(!s.apiKey||!H(s.apiKey))throw new b("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new b("host is required (the ingest base URL)");let e=d(s.host),t=s.defaultProperties,n=s.storage??new v;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??V,consent:s.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:s.flagsHost?d(s.flagsHost):e,flushAt:s.flushAt??20,flushIntervalMs:s.flushIntervalMs??1e4,host:e,ids:s.ids??Q,locale:s.locale,maxQueueSize:s.maxQueueSize??1e3,maxRetries:s.maxRetries??3,namespace:ye(s.apiKey),onError:s.onError??me,os:s.os,requestTimeoutMs:s.requestTimeoutMs??1e4,sdkName:s.sdkName??J,sdkVersion:s.sdkVersion??z,sessionTracking:s.sessionTracking??false,sharedStorage:s.sharedStorage??n,socketFactory:s.socketFactory,storage:n,streamFlags:s.streamFlags??false,transport:s.transport}}function ye(s){return s.slice(0,16)}var g=Symbol("absent");function ve(s,e){if(s==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,s))return t[s];let n=e.attributes??{};return Object.prototype.hasOwnProperty.call(n,s)?n[s]:g}function f(s){return s===g?"undefined":String(s)}function W(s){return s===g?Number.NaN:Number(s)}function Y(s){return s!==g&&s!==null&&s!==""}function X(s,e){if(!Array.isArray(e))return false;let t=f(s);return e.map(n=>String(n)).includes(t)}function Z(s,e){let t=ve(s.attribute,e),n=s.value;switch(s.op){case "is_set":return Y(t);case "is_not_set":return !Y(t);case "eq":return f(t)===f(n===void 0?g:n);case "neq":return f(t)!==f(n===void 0?g:n);case "contains":return f(t).includes(f(n===void 0?g:n));case "in":return X(t,n);case "not_in":return Array.isArray(n)?!X(t,n):false;case "gt":return w(t,n,(r,i)=>r>i);case "gte":return w(t,n,(r,i)=>r>=i);case "lt":return w(t,n,(r,i)=>r<i);case "lte":return w(t,n,(r,i)=>r<=i);case "in_cohort":return typeof n=="string"&&n!==""&&(e.cohorts??[]).includes(n);case "not_in_cohort":return typeof n=="string"&&n!==""&&!(e.cohorts??[]).includes(n);default:return false}}function w(s,e,t){let n=W(s),r=e===void 0?Number.NaN:W(e);return Number.isNaN(n)||Number.isNaN(r)?false:t(n,r)}function ee(s,e){let t=`${s}:${e}`,n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return (n>>>0)%100}function R(s,e){return s.targeting.length===0||s.targeting.every(t=>Z(t,e))}function te(s,e){let t=ee(s.key,e.distinctId),n=s.variations??[];if(n.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let r=0;for(let i=n.length-1;i>=0;i--)if(r+=n[i].weight,t<r)return n[i].key;return n[0].key}function M(s,e,t,n){for(let r of s.prerequisites??[]){if(n.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;n.push(i.key);let a=M(i,e,t,n)&&R(i,t)&&te(i,t)===r.variationKey;if(n.pop(),!a)return false}return true}function k(s,e,t){return s.enabled?M(s,e,t,[s.key])?R(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ee(s.key,t.distinctId)<s.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function Ge(s,e){return k(s,[],e)}function se(s,e){let t={};for(let n of s)t[n.key]=k(n,s,e).enabled;return t}function x(s,e,t){let n=s.variations??[],r=n[0];if(!r)return null;if(!s.enabled||!M(s,e,t,[s.key])||!R(s,t))return r;let i=te(s,t);return n.find(a=>a.key===i)??r}function We(s,e){return x(s,[],e)}function Ye(s,e,t){let n=s.find(r=>r.key===e);return n?x(n,s,t)?.value??null:null}function ne(s){return s.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}var F=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,n=b$1(),r=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function S(s){if(typeof s!="string")return;let e=Array.from(s).length;return e>=1&&e<=200?s:void 0}function T(s,e){return `pdx.${s}.${e}`}var re="consent";function be(s){if(typeof s!="string")return null;try{let e=JSON.parse(s);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function ke(s,e){return be(s.getItem(T(e,re)))}function xe(s,e,t){let n=T(e,re);if(typeof t.identityLink!="boolean"){s.removeItem(n);return}s.setItem(n,JSON.stringify({identityLink:t.identityLink}));}function nt(s,e,t,n){let r=T(t,"anonymous_id"),i=S(e.getItem(r))??S(s.getItem(r));return e.setItem(r,n),s.setItem(r,n),i!==void 0&&i!==n?i:void 0}var E=class{constructor(e,t,n,r){this.storage=e;this.shared=t;this.ids=n;this.namespace=r;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");this.refresh();}refresh(){let e=S(this.shared.getItem(this.key("anonymous_id"))),t=S(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let n=S(this.storage.getItem(this.key("distinct_id")));n?(this.distinctId=n,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return ke(this.shared,this.namespace)}setConsent(e){xe(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,n=this.storage.getItem(this.key("linked_anonymous_id")),r=t||n!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return T(this.namespace,e)}};var _=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),n=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,n,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new l(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let n=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(n,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,n){let r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...n,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var c={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",screen:"$screen",set:"$set"},Se=[{emittedBy:"web",meaning:"A click anywhere on the page, with the element that was clicked. The web SDK sends it by default; autocapture: false or autocaptureOptions.clicks: false turns it off.",name:c.autocapture,properties:["$event_type","$el_tag","$el_text","$el_id","$el_classes","$el_href","$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A page shown, including every client-side navigation the History API makes: one per distinct path and query.",name:c.pageview,properties:["$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"flutter",meaning:"A named route pushed or replaced in a Flutter app, the mobile counterpart of $pageview.",name:c.screen,properties:["screen"]},{emittedBy:"every",meaning:"A person becomes known by a distinct id. The anonymous trail before it is joined to them, and any traits ride along under $set.",name:c.identify,properties:["$anon_distinct_id","$set"]},{emittedBy:"every",meaning:"A second id for the same person, so events sent under either resolve to one profile.",name:c.createAlias,properties:["alias"]},{emittedBy:"every",meaning:"The person is placed in a group such as a company or a team; group properties ride along under $set.",name:c.group,properties:["$group_type","$group_key","$set"]},{emittedBy:"every",meaning:"Person properties written without an identify: $set overwrites, $set_once fills only what is still empty.",name:c.set,properties:["$set","$set_once"]},{emittedBy:"every",meaning:"A flag was evaluated for this person, sent once per distinct answer. Experiments attribute exposure from it.",name:c.featureFlagCalled,properties:["$feature_flag","$feature_flag_response"]}],dt=s=>s.startsWith("$"),ut=s=>Se.find(e=>e.name===s);function ie(s){return s>=400&&s<500&&s!==429}var C=class{constructor(e={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=a$1(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??c$1,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let n=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,n);if(a.ok)return;if(ie(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);r=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&ie(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,n){let r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:n,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};function oe(s,e,t){B(s.eventName),U(s.distinctId);let n={distinct_id:s.distinctId,event_id:s.eventId??t.uuid(),event_name:s.eventName,properties:s.properties??{},schema_version:1,timestamp:I(s.timestamp??e.now())};return s.context&&(n.context=s.context),s.sessionId&&(n.session_id=s.sessionId),n}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,A=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"pending",null);a(this,"lastKey","");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??Fe,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(/\/+$/,"")}${Ie}`,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(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c$2(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$2());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;return}if(t.name==="flagChange"){let n=t.payload?.key;this.lastKey=typeof n=="string"?n:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},we));}}}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 Fe(s){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(s)}var $=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;a(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var Ee={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function ae(s){return `pdx.${s}.session`}function Ft(s,e,t,n){let r={id:t.id,lastActivityAt:n,startedAt:t.startedAt};s.setItem(ae(e),JSON.stringify(r));}var P=class{constructor(e,t,n,r,i=Ee){this.storage=e;this.ids=t;this.clock=n;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let n=this.live(this.read(),e),r=n!==void 0&&n.id!==t.id?n:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return ae(this.namespace)}};var Te="queue",_e=1e3,le=3e4,q=s=>{let e={};return s.avatar!==void 0&&(e.$avatar=s.avatar),s.email!==void 0&&(e.$email=s.email),s.name!==void 0&&(e.$name=s.name),s.phone!==void 0&&(e.$phone=s.phone),e},N=class{constructor(e){a(this,"config");a(this,"identity");a(this,"session");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");a(this,"membershipCache");a(this,"stream");a(this,"shutDown",false);a(this,"exposures",new Set);this.config=G(e),this.identity=new E(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new P(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new $(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new p("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new C({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new _({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let n={...this.config.defaultProperties(),...t.properties??{}},r=oe({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:n,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(n){this.config.onError(n);}}identify(e,t={}){this.identity.refresh();let n=this.identity.identify(e),r={};n.anonymousToLink!==void 0&&(r.$anon_distinct_id=n.anonymousToLink);let i={...q(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{properties:r});}link(e,t,n){let r={$anon_distinct_id:t},i=q(n??{});Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(c.createAlias,{properties:{alias:e}});}group(e,t,n){let r={$group_key:t,$group_type:e};n&&(r.$set=n),this.capture(c.group,{properties:r});}setPersonProperties(e,t){let n={};e&&(n.$set=e),t&&(n.$set_once=t),this.capture(c.set,{properties:n});}setPersonTraits(e){let t=q(e);Object.keys(t).length!==0&&this.capture(c.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let n=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(n)),n}async getVariant(e){let t=await this.getAllFlags(),n=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,n?.key??String(t[e]??false)),n}async getVariantLocal(e,t={}){let n=await this.flagSnapshot(),r=n.flags.find(ce=>ce.key===e),i=await this.localContext(t,n.flags),a=r?x(r,n.flags,i):null,d=r?k(r,n.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let n=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(n)||(this.exposures.add(n),this.capture(c.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return se(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let n=await this.flagSnapshot(),r=n.flags.find(d=>d.key===e),i=await this.localContext(t,n.flags),a=r?k(r,n.flags,i).enabled:false;return this.recordExposure(e,(r?x(r,n.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let n=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&ne(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&i-this.membershipCache.fetchedAt<le?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(n),this.membershipCache={cohorts:r,distinctId:n,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:n,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<le)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new A({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(n=>this.config.onError(n));},onClosed:n=>{this.stream=void 0,n&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(_e);try{await this.transport.send({body:{events:e,sent_at:I(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Te}`}};function Dt(s){return new N(s)}export{ut as A,C as B,N as C,Dt as D,p as a,b,y as c,l as d,v as e,$e as f,V as g,ge as h,j as i,J as j,z as k,ye as l,Z as m,ee as n,Ge as o,se as p,We as q,Ye as r,F as s,be as t,nt as u,_ as v,Ft as w,c as x,Se as y,dt as z};//# sourceMappingURL=chunk-ESOQKMEE.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-ESOQKMEE.js.map
|
|
@@ -6,6 +6,8 @@ interface ChatTurn {
|
|
|
6
6
|
authorId: string | null;
|
|
7
7
|
body: string;
|
|
8
8
|
createdAt: string;
|
|
9
|
+
authorName?: string | null;
|
|
10
|
+
authorAvatarUrl?: string | null;
|
|
9
11
|
}
|
|
10
12
|
interface ChatThread {
|
|
11
13
|
id: string;
|
|
@@ -43,6 +45,7 @@ declare class ChatClient {
|
|
|
43
45
|
private identity;
|
|
44
46
|
constructor(options: ChatClientOptions);
|
|
45
47
|
get hasThread(): boolean;
|
|
48
|
+
avatarUrl(url: string): string;
|
|
46
49
|
get socketAuth(): {
|
|
47
50
|
conversationId: string;
|
|
48
51
|
conversationToken: string;
|
|
@@ -56,8 +59,10 @@ declare class ChatClient {
|
|
|
56
59
|
private request;
|
|
57
60
|
}
|
|
58
61
|
|
|
59
|
-
type MessengerSkin = '
|
|
60
|
-
type
|
|
62
|
+
type MessengerSkin = 'quiet' | 'standard';
|
|
63
|
+
type ComposerShape = 'round' | 'square';
|
|
64
|
+
type BubbleShape = 'rounded' | 'tailed';
|
|
65
|
+
type BubbleFill = 'filled' | 'outlined';
|
|
61
66
|
type LauncherShape = 'circle' | 'pill' | 'squircle';
|
|
62
67
|
type LauncherFill = 'filled' | 'outlined';
|
|
63
68
|
type LauncherContent = 'avatar' | 'glyph' | 'team_faces';
|
|
@@ -66,7 +71,9 @@ type NamePlacement = 'above' | 'hidden' | 'inline';
|
|
|
66
71
|
type StampPlacement = 'beside_name' | 'none' | 'under_turn';
|
|
67
72
|
type StampContent = 'time' | 'time_and_latency';
|
|
68
73
|
interface AppearanceSettings {
|
|
69
|
-
|
|
74
|
+
bubbleFill: BubbleFill;
|
|
75
|
+
bubbleShape: BubbleShape;
|
|
76
|
+
composerShape: ComposerShape;
|
|
70
77
|
dayDividers: boolean;
|
|
71
78
|
launcherContent: LauncherContent;
|
|
72
79
|
launcherFill: LauncherFill;
|
|
@@ -92,6 +99,12 @@ type Availability = {
|
|
|
92
99
|
};
|
|
93
100
|
|
|
94
101
|
interface TeamFace {
|
|
102
|
+
name: string;
|
|
103
|
+
initials: string;
|
|
104
|
+
tone: string;
|
|
105
|
+
avatarUrl: string | null;
|
|
106
|
+
}
|
|
107
|
+
interface TypedFace {
|
|
95
108
|
initials: string;
|
|
96
109
|
tone: string;
|
|
97
110
|
}
|
|
@@ -107,7 +120,8 @@ interface MessengerConfig extends AppearanceSettings {
|
|
|
107
120
|
availability: Availability;
|
|
108
121
|
version: string;
|
|
109
122
|
starterPrompts: string[];
|
|
110
|
-
teamFaces:
|
|
123
|
+
teamFaces: TypedFace[];
|
|
124
|
+
team: TeamFace[];
|
|
111
125
|
socketUrl: string;
|
|
112
126
|
}
|
|
113
127
|
interface MessengerConfigOptions {
|
|
@@ -122,4 +136,4 @@ declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
|
|
|
122
136
|
declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
|
|
123
137
|
declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
|
|
124
138
|
|
|
125
|
-
export { type AppearanceSettings as A, type
|
|
139
|
+
export { type AppearanceSettings as A, type BubbleFill as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type BubbleShape as d, type ChatStorage as e, type ChatThread as f, type ComposerShape as g, type LauncherFill as h, type LauncherShape as i, type LauncherSize as j, type MessengerSkin as k, type StampPlacement as l, MESSENGER_CACHE_KEY as m, type MessengerConfigOptions as n, cachedMessengerConfig as o, fetchMessengerConfig as p, resolveAppearance as r };
|
|
@@ -6,6 +6,8 @@ interface ChatTurn {
|
|
|
6
6
|
authorId: string | null;
|
|
7
7
|
body: string;
|
|
8
8
|
createdAt: string;
|
|
9
|
+
authorName?: string | null;
|
|
10
|
+
authorAvatarUrl?: string | null;
|
|
9
11
|
}
|
|
10
12
|
interface ChatThread {
|
|
11
13
|
id: string;
|
|
@@ -43,6 +45,7 @@ declare class ChatClient {
|
|
|
43
45
|
private identity;
|
|
44
46
|
constructor(options: ChatClientOptions);
|
|
45
47
|
get hasThread(): boolean;
|
|
48
|
+
avatarUrl(url: string): string;
|
|
46
49
|
get socketAuth(): {
|
|
47
50
|
conversationId: string;
|
|
48
51
|
conversationToken: string;
|
|
@@ -56,8 +59,10 @@ declare class ChatClient {
|
|
|
56
59
|
private request;
|
|
57
60
|
}
|
|
58
61
|
|
|
59
|
-
type MessengerSkin = '
|
|
60
|
-
type
|
|
62
|
+
type MessengerSkin = 'quiet' | 'standard';
|
|
63
|
+
type ComposerShape = 'round' | 'square';
|
|
64
|
+
type BubbleShape = 'rounded' | 'tailed';
|
|
65
|
+
type BubbleFill = 'filled' | 'outlined';
|
|
61
66
|
type LauncherShape = 'circle' | 'pill' | 'squircle';
|
|
62
67
|
type LauncherFill = 'filled' | 'outlined';
|
|
63
68
|
type LauncherContent = 'avatar' | 'glyph' | 'team_faces';
|
|
@@ -66,7 +71,9 @@ type NamePlacement = 'above' | 'hidden' | 'inline';
|
|
|
66
71
|
type StampPlacement = 'beside_name' | 'none' | 'under_turn';
|
|
67
72
|
type StampContent = 'time' | 'time_and_latency';
|
|
68
73
|
interface AppearanceSettings {
|
|
69
|
-
|
|
74
|
+
bubbleFill: BubbleFill;
|
|
75
|
+
bubbleShape: BubbleShape;
|
|
76
|
+
composerShape: ComposerShape;
|
|
70
77
|
dayDividers: boolean;
|
|
71
78
|
launcherContent: LauncherContent;
|
|
72
79
|
launcherFill: LauncherFill;
|
|
@@ -92,6 +99,12 @@ type Availability = {
|
|
|
92
99
|
};
|
|
93
100
|
|
|
94
101
|
interface TeamFace {
|
|
102
|
+
name: string;
|
|
103
|
+
initials: string;
|
|
104
|
+
tone: string;
|
|
105
|
+
avatarUrl: string | null;
|
|
106
|
+
}
|
|
107
|
+
interface TypedFace {
|
|
95
108
|
initials: string;
|
|
96
109
|
tone: string;
|
|
97
110
|
}
|
|
@@ -107,7 +120,8 @@ interface MessengerConfig extends AppearanceSettings {
|
|
|
107
120
|
availability: Availability;
|
|
108
121
|
version: string;
|
|
109
122
|
starterPrompts: string[];
|
|
110
|
-
teamFaces:
|
|
123
|
+
teamFaces: TypedFace[];
|
|
124
|
+
team: TeamFace[];
|
|
111
125
|
socketUrl: string;
|
|
112
126
|
}
|
|
113
127
|
interface MessengerConfigOptions {
|
|
@@ -122,4 +136,4 @@ declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
|
|
|
122
136
|
declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
|
|
123
137
|
declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
|
|
124
138
|
|
|
125
|
-
export { type AppearanceSettings as A, type
|
|
139
|
+
export { type AppearanceSettings as A, type BubbleFill as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type BubbleShape as d, type ChatStorage as e, type ChatThread as f, type ComposerShape as g, type LauncherFill as h, type LauncherShape as i, type LauncherSize as j, type MessengerSkin as k, type StampPlacement as l, MESSENGER_CACHE_KEY as m, type MessengerConfigOptions as n, cachedMessengerConfig as o, fetchMessengerConfig as p, resolveAppearance as r };
|