@prodantix/sdk 0.5.0 → 0.6.0-beta.421
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/README.md +14 -1
- package/dist/chat.cjs +6 -6
- package/dist/chat.js +6 -6
- package/dist/chunk-4RLPQZ5L.js +2 -0
- package/dist/chunk-ODN4ZELX.js +2 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/messenger.cjs +1 -1
- package/dist/messenger.iife.js +6 -6
- package/dist/messenger.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.js +1 -1
- package/dist/web.cjs +1 -1
- package/dist/web.d.cts +5 -1
- package/dist/web.d.ts +5 -1
- package/dist/web.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-ESOQKMEE.js +0 -2
- package/dist/chunk-VG77TYVX.js +0 -2
package/README.md
CHANGED
|
@@ -42,7 +42,20 @@ identified id stays per origin in `localStorage` and never enters the cookie. Pa
|
|
|
42
42
|
to name the domain (a site whose subdomains belong to different tenants must), or `sharedStorage`
|
|
43
43
|
to write no cookie. The queue persists in `localStorage`, delivery is by `navigator.sendBeacon`
|
|
44
44
|
on page hide, and pageviews and clicks are autocaptured. Pass `autocapture: false` to disable
|
|
45
|
-
capture, or `autocaptureOptions: { pageviews, clicks }` to tune it.
|
|
45
|
+
capture, or `autocaptureOptions: { pageviews, clicks }` to tune it.
|
|
46
|
+
|
|
47
|
+
Autocapture collects no customer content by default. A click records the element's tag, id and
|
|
48
|
+
classes and the link it points at, but not the element's text unless you pass
|
|
49
|
+
`autocaptureOptions: { captureElementText: true }`. Every captured address, `$current_url`,
|
|
50
|
+
`$referrer` and a link's `$el_href`, keeps its origin and path and drops its query and fragment,
|
|
51
|
+
where tokens, invite codes and email addresses travel; a link that is not a web address keeps
|
|
52
|
+
only its scheme, such as `mailto:`. Mark an element with `data-pdx-no-capture` or the
|
|
53
|
+
`pdx-no-capture` class, or list CSS selectors in `autocaptureOptions.maskSelectors`, and a click
|
|
54
|
+
on it or anything inside it still counts but carries no text, id, classes or link. Inputs,
|
|
55
|
+
textareas, selects and any `password`, `email` or `tel` field never carry content, whatever the
|
|
56
|
+
options say. A selector that does not parse is skipped and reported to `onError` once.
|
|
57
|
+
|
|
58
|
+
A session id is minted per
|
|
46
59
|
visit (thirty minutes idle, twenty-four hours at most) and stamped on every event; pass
|
|
47
60
|
`sessionTracking: false` to stop it.
|
|
48
61
|
|
package/dist/chat.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
'use strict';var Y=Object.defineProperty;var W=(n,e,t)=>e in n?Y(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var p=(n,e,t)=>W(n,typeof e!="symbol"?e+"":e,t);function H(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function $(n){return n.replace(/\/+$/,"")}var M="X-Prodantix-Conversation-Token",A="prodantix.chat.handle";function J(){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 C=class{constructor(e){this.options=e;p(this,"fetchImpl");p(this,"fileFetchImpl");p(this,"host");p(this,"storage");p(this,"handle");p(this,"identity",null);this.fetchImpl=H(e.fetchImpl),this.fileFetchImpl=e.fileFetchImpl??((t,r)=>fetch(t,r)),this.host=$(e.host),this.storage=e.storage??J(),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(A,JSON.stringify(this.handle)),true)}async send(e,t,r){if(!await this.ensureThread())return null;let a=this.handle;return a?(await this.request("POST",`/v1/conversations/${encodeURIComponent(a.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:a.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async 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(A);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(A),null}async fileRequest(e,t,r,a,o){let i={authorization:`Bearer ${this.options.apiKey}`,[M]:r};o&&(i["content-type"]=o.type||"application/octet-stream");try{let s=await this.fileFetchImpl(`${this.host}${t}`,{body:o,headers:i,method:e});if(s.ok)return await a(s);this.options.onError?.(new Error(`prodantix chat ${t}: ${s.status}`));}catch(s){this.options.onError?.(s);}return 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[M]=r.token);try{let i=await a(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:o,method:e}),s=await i.text();return i.ok?s?JSON.parse(s):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${i.status}`)),null)}catch(i){return this.options.onError?.(i),null}}};var V={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function w(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=V[t.find(s=>s.type==="weekday")?.value??""];if(!r)return false;let a=t.find(s=>s.type==="hour")?.value??"",o=t.find(s=>s.type==="minute")?.value??"",i=`${a}:${o}`;return n.windows.some(s=>s.days.includes(r)&&s.open<=i&&i<s.close)}var g={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"},X=["quiet","standard"],Z=["round","square"],Q=["rounded","tailed"],ee=["filled","outlined"],te=["circle","pill","squircle"],ne=["filled","outlined"],re=["avatar","glyph","team_faces"],ae=["large","medium","small"],ie=["above","hidden","inline"],oe=["beside_name","none","under_turn"],se=["time","time_and_latency"],x=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,O=(n,e)=>typeof n=="boolean"?n:e,le={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"]},ce={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},de={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"]},pe={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},ue={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function E(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:le[t],a=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=a===void 0?void 0:ce[a],i=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=i===void 0?void 0:de[i],d=typeof e.skin=="string"?e.skin:void 0,u=d===void 0?void 0:pe[d],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,l=c===void 0?void 0:ue[c],h={bubbleFill:x(e.bubbleFill,ee,l?.[1]??g.bubbleFill),bubbleShape:x(e.bubbleShape,Q,l?.[0]??g.bubbleShape),composerShape:x(e.composerShape,Z,u?.[1]??g.composerShape),dayDividers:O(e.dayDividers,s?.[0]??g.dayDividers),launcherContent:x(e.launcherContent,re,r?.[2]??g.launcherContent),launcherFill:x(e.launcherFill,ne,r?.[1]??g.launcherFill),launcherShape:x(e.launcherShape,te,r?.[0]??g.launcherShape),launcherSize:x(e.launcherSize,ae,r?.[3]??g.launcherSize),nameAvatar:O(e.nameAvatar,o?.[1]??g.nameAvatar),namePlacement:x(e.namePlacement,ie,o?.[0]??g.namePlacement),skin:x(e.skin,X,u?.[0]??g.skin),stampContent:x(e.stampContent,se,s?.[2]??g.stampContent),stampPlacement:x(e.stampPlacement,oe,s?.[1]??g.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function z(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 he="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",me={large:66,medium:56,small:46},ge={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},fe={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},be={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;}"},xe=".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}",ye={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ve={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},ke={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Se={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function U(n,e,t,r){return `.launcher{--fab-size:${me[r]}px;${ge[n]}${fe[e]}}${be[t]}${xe}${ye[n]}${ve[e]}${ke[n]}${Se[n]}`}function B(n,e,t,r=a=>a){let a=document.createDocumentFragment();if(n==="glyph"||t.length===0){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="${he}"/></svg>`,a.append(...o.childNodes,N()),a}return n==="avatar"?(a.append(D(t[0],e,r),N()),a):(a.append(P(t,e,r),N()),a)}function P(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let a of n.slice(0,2))r.append(D(a,e,t));return r}function D(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n?.avatarUrl){let 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 N(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Ce={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},S={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...g},Ee={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Te={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},we={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}"},Le={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ae={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}"},Ne=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Pe='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',_e={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Fe=".lat{font-size:11px;opacity:.7;margin-left:6px}",Ie=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}";function Re(n){let e=n==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${e+26}px}.composer button.clip{position:absolute;top:50%;left:${e-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}function _(n){return n<999500?`${Math.max(1,Math.round(n/1e3))} KB`:`${(n/1e6).toFixed(1)} MB`}var G=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
'use strict';var V=Object.defineProperty;var X=(n,e,t)=>e in n?V(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var d=(n,e,t)=>X(n,typeof e!="symbol"?e+"":e,t);var L=class extends Error{constructor(t,r,a){super(r,a);d(this,"code");this.code=t,this.name="ProdantixError";}},A=class extends L{constructor(e){super("config",e),this.name="ConfigError";}};var v=class extends L{constructor(t,r,a){super("transport",t,a);d(this,"status");this.status=r,this.name="TransportError";}};function O(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function z(n){return n.replace(/\/+$/,"")}var U="X-Prodantix-Conversation-Token",_="prodantix.chat.handle";function Z(){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 E=class{constructor(e){this.options=e;d(this,"fetchImpl");d(this,"fileFetchImpl");d(this,"host");d(this,"storage");d(this,"handle");d(this,"identity",null);this.fetchImpl=O(e.fetchImpl),this.fileFetchImpl=e.fileFetchImpl??((t,r)=>fetch(t,r)),this.host=z(e.host),this.storage=e.storage??Z(),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(_,JSON.stringify(this.handle)),true)}async send(e,t,r){if(!await this.ensureThread())return null;let a=this.handle;return a?(await this.request("POST",`/v1/conversations/${encodeURIComponent(a.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:a.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async 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(_);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(_),null}async fileRequest(e,t,r,a,o){let i={authorization:`Bearer ${this.options.apiKey}`,[U]:r};o&&(i["content-type"]=o.type||"application/octet-stream");try{let s=await this.fileFetchImpl(`${this.host}${t}`,{body:o,headers:i,method:e});if(s.ok)return await a(s);this.options.onError?.(new v(`prodantix chat ${t}: ${s.status}`,s.status));}catch(s){this.options.onError?.(s);}return null}async request(e,t,r={}){let a=this.fetchImpl;if(!a)return this.options.onError?.(new v("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(o[U]=r.token);try{let i=await a(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:o,method:e}),s=await i.text();return i.ok?s?JSON.parse(s):{}:(this.options.onError?.(new v(`prodantix chat ${t}: ${i.status}`,i.status)),null)}catch(i){return this.options.onError?.(i),null}}};var Q={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=Q[t.find(s=>s.type==="weekday")?.value??""];if(!r)return false;let a=t.find(s=>s.type==="hour")?.value??"",o=t.find(s=>s.type==="minute")?.value??"",i=`${a}:${o}`;return n.windows.some(s=>s.days.includes(r)&&s.open<=i&&i<s.close)}var g={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"},ee=["quiet","standard"],te=["round","square"],ne=["rounded","tailed"],re=["filled","outlined"],ae=["circle","pill","squircle"],ie=["filled","outlined"],oe=["avatar","glyph","team_faces"],se=["large","medium","small"],le=["above","hidden","inline"],ce=["beside_name","none","under_turn"],de=["time","time_and_latency"],x=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,B=(n,e)=>typeof n=="boolean"?n:e,pe={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"]},ue={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},he={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},me={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},ge={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function T(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:pe[t],a=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=a===void 0?void 0:ue[a],i=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=i===void 0?void 0:he[i],p=typeof e.skin=="string"?e.skin:void 0,u=p===void 0?void 0:me[p],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,l=c===void 0?void 0:ge[c],h={bubbleFill:x(e.bubbleFill,re,l?.[1]??g.bubbleFill),bubbleShape:x(e.bubbleShape,ne,l?.[0]??g.bubbleShape),composerShape:x(e.composerShape,te,u?.[1]??g.composerShape),dayDividers:B(e.dayDividers,s?.[0]??g.dayDividers),launcherContent:x(e.launcherContent,oe,r?.[2]??g.launcherContent),launcherFill:x(e.launcherFill,ie,r?.[1]??g.launcherFill),launcherShape:x(e.launcherShape,ae,r?.[0]??g.launcherShape),launcherSize:x(e.launcherSize,se,r?.[3]??g.launcherSize),nameAvatar:B(e.nameAvatar,o?.[1]??g.nameAvatar),namePlacement:x(e.namePlacement,le,o?.[0]??g.namePlacement),skin:x(e.skin,ee,u?.[0]??g.skin),stampContent:x(e.stampContent,de,s?.[2]??g.stampContent),stampPlacement:x(e.stampPlacement,ce,s?.[1]??g.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function D(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 fe="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",be={large:66,medium:56,small:46},xe={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},ye={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},ve={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;}"},ke=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",Se={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Ce={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},Ee={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Te={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function G(n,e,t,r){return `.launcher{--fab-size:${be[r]}px;${xe[n]}${ye[e]}}${ve[t]}${ke}${Se[n]}${Ce[e]}${Ee[n]}${Te[n]}`}function K(n,e,t,r=a=>a){let a=document.createDocumentFragment();if(n==="glyph"||t.length===0){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="${fe}"/></svg>`,a.append(...o.childNodes,F()),a}return n==="avatar"?(a.append(q(t[0],e,r),F()),a):(a.append(I(t,e,r),F()),a)}function I(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let a of n.slice(0,2))r.append(q(a,e,t));return r}function q(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 F(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var we={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},C={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...g},Le={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Ae={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Ne={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Pe={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},_e={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Fe=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Ie='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Re={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},He=".lat{font-size:11px;opacity:.7;margin-left:6px}",$e=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}";function Me(n){let e=n==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${e+26}px}.composer button.clip{position:absolute;top:50%;left:${e-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}function R(n){return n<999500?`${Math.max(1,Math.round(n/1e3))} KB`:`${(n/1e6).toFixed(1)} MB`}var j=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
-
--online: oklch(72% 0.13 163.23);`;function
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function Oe(n){return n==="light"?"":n==="dark"?`:host { ${j} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
5
|
-
${
|
|
5
|
+
${j}
|
|
6
6
|
}
|
|
7
|
-
}`}var
|
|
7
|
+
}`}var ze=/https?:\/\/[^\s<>"]+/g,Ue=/[.,;:!?)]$/,Be=n=>{let e=n;for(;Ue.test(e);){let t=e.split("(").length-1,r=e.split(")").length-1;if(e.endsWith(")")&&t>=r)break;e=e.slice(0,-1);}return e};function De(n,e){let t=0;for(let r of e.matchAll(ze)){let a=r.index??0,o=Be(r[0]);a>t&&n.append(e.slice(t,a));let i=document.createElement("a");i.href=o,i.target="_blank",i.rel="noopener noreferrer",i.textContent=o,n.append(i),t=a+o.length;}t<e.length&&n.append(e.slice(t));}var Ge=["P","BR","STRONG","EM","A","UL","OL","LI"],Ke=n=>typeof n=="object"&&n!==null&&"html"in n&&typeof n.html=="string"&&"text"in n&&typeof n.text=="string",qe=(n,e)=>e.name==="class"||e.name==="data-block-type"?true:n!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),je=n=>[...n.querySelectorAll("*")].every(e=>Ge.includes(e.tagName)&&[...e.attributes].every(t=>qe(e.tagName,t)));function H(n,e="system"){let t=T(n),r=n.launcherPosition==="bottom_left"?"left":"right",a=n.accentColor;return `${`
|
|
8
8
|
:host {
|
|
9
9
|
all: initial; z-index: 2147483000; --a: ${a};
|
|
10
10
|
--paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
--online: oklch(53.8% 0.1274 163.23);
|
|
13
13
|
color-scheme: ${e==="system"?"light dark":e};
|
|
14
14
|
}
|
|
15
|
-
${
|
|
15
|
+
${Oe(e)}
|
|
16
16
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
17
17
|
.launcher {
|
|
18
18
|
z-index: 2147483000; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
|
|
@@ -102,5 +102,5 @@ ${He(e)}
|
|
|
102
102
|
.panel { animation: rise 180ms ease-out; }
|
|
103
103
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
104
104
|
}
|
|
105
|
-
`}${Te[t.composerShape]}${Ee[t.skin]}${U(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${we[t.bubbleShape]}${Le[t.bubbleFill]}${Ae[t.namePlacement]}${t.nameAvatar?Ne:""}${t.dayDividers?Pe:""}${_e[t.stampPlacement]}${t.stampContent==="time_and_latency"?Fe:""}${Ie}${n.attachments?.enabled?Re(t.composerShape):""}`}var Ke=["end_user","agent","ai"];function qe(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var je='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>',Ye='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',T=class{constructor(e,t,r={},a={},o={}){this.host=e;this.client=t;p(this,"root");p(this,"strings");p(this,"settings");p(this,"appearance");p(this,"launcher");p(this,"badge");p(this,"panel",null);p(this,"lastFocused",null);p(this,"unread",0);p(this,"pendingTurns",0);p(this,"openNow");p(this,"style");p(this,"scheme");p(this,"picked",null);p(this,"objectUrls",[]);this.strings={...Ce,...r},this.appearance={...S,...a},this.settings=E({...S,...a}),this.root=e.attachShadow({mode:o.shadowMode??"closed"}),this.openNow=w(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=F(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(B(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...S,...e},this.settings=E(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=F(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=this.appearance.team??[];r.length>0&&t.append(P(r,this.strings,f=>this.client.avatarUrl(f)));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let i=document.createElement("p");i.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),i.append(s,this.strings.replyTime),a.append(o,i);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=Ye,d.addEventListener("click",()=>this.close()),t.append(a,d);let u=document.createElement("div");u.className="log",u.setAttribute("role","log"),u.setAttribute("aria-live","polite"),u.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let l=document.createElement("input");l.type="text",l.setAttribute("aria-label",this.strings.inputPlaceholder),l.placeholder=this.strings.inputPlaceholder;let h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.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 y=document.createElement("span");y.className="sendtext",y.textContent=this.strings.sendLabel,h.append(y);let v=this.appearance.attachments;if(v?.enabled&&this.client.upload){let f=document.createElement("span");f.className="field";let m=document.createElement("input");m.type="file",m.accept=v.accept.join(","),m.hidden=true,m.addEventListener("change",()=>{let R=m.files?.[0];m.value="",R&&this.pick(u,c,v,R);});let b=document.createElement("button");b.type="button",b.className="clip",b.setAttribute("aria-label",this.strings.attachLabel),b.innerHTML=je,b.addEventListener("click",()=>m.click()),f.append(b,l,m),c.append(f,h);}else c.append(l,h);c.addEventListener("submit",f=>{f.preventDefault(),this.submit(l,u);}),e.append(t,u,c),e.addEventListener("keydown",f=>this.onKeydown(f,e,d)),this.root.append(e),this.panel=e,l.focus();let k=await this.client.load();k&&k.turns.length>0?this.renderThread(u,k):this.renderFirstRun(u,l),this.openNow||this.renderAway(t);}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),this.appearance.starterPrompts.filter(Be).forEach((s,d)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${d}`;let l=document.createElement("template");l.innerHTML=s.html,Ge(l.content)?c.append(l.content):c.textContent=s.text;for(let y of c.querySelectorAll("a"))y.target="_blank",y.rel="noopener noreferrer";let h=document.createElement("button");h.className="promptpress",h.type="button",h.setAttribute("aria-labelledby",c.id),h.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),u.append(c,h),r.append(u);}),e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let a=document.createElement("span");a.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,a),e.after(t);}pick(e,t,r,a){let o=a.size>r.maxBytes||!r.accept.includes(a.type);for(let l of this.root.querySelectorAll(o?".ferr":".file,.ferr"))l.remove();if(o){let l=document.createElement("p");l.className="ferr",l.setAttribute("role","alert"),l.textContent=this.strings.fileRefusal(_(a.size),`${r.maxBytes/1e6} MB`),t.before(l),e.scrollTop=e.scrollHeight;return}this.picked=a;let i=document.createElement("span");i.className="file";let s;if(a.type==="application/pdf")s=document.createElement("b"),s.textContent="PDF";else {let l=document.createElement("img");l.className="th",l.alt="",l.src=this.objectUrl(a),s=l;}let d=document.createElement("span");d.className="name",d.textContent=a.name;let u=document.createElement("span");u.className="sz",u.textContent=`\xB7 ${_(a.size)}`;let c=document.createElement("button");c.type="button",c.className="x",c.setAttribute("aria-label",this.strings.removeFileLabel),c.textContent="\xD7",c.addEventListener("click",()=>{this.picked=null,i.remove();}),i.append(s,d,u,c),t.before(i),e.scrollTop=e.scrollHeight;}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.panel=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),a=this.picked;if(!(!r&&!a)){e.value="",this.picked=null;for(let o of this.root.querySelectorAll(".file,.ferr"))o.remove();await this.sendBody(t,r,a);}}async sendBody(e,t,r=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let a=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);a.setAttribute("data-pending","");let o=r?await this.client.upload?.(r):void 0,i=o===null?null:await this.client.send(t,qe(),o?[o.id]:void 0);if(a.removeAttribute("data-pending"),i){a.dataset.turnId=i.id;return}this.markFailed(e,a,t,r);}markFailed(e,t,r,a){t.setAttribute("data-failed","");let o=document.createElement("button");o.type="button",o.className="retry",o.textContent=this.strings.retryLabel,o.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,a);}),(t.querySelector(".body")??t).append(o);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){e.querySelector(".empty")?.remove();let a=Ke.includes(t.authorKind)?t.authorKind:"agent",o=this.settings,i=document.createElement("div");if(i.className=`turn ${a}`,i.dataset.turnId=t.id,a!=="end_user"&&o.nameAvatar){let l=document.createElement("span");if(l.className=a==="ai"?"av bot":"av",l.setAttribute("aria-hidden","true"),a==="agent"&&t.authorAvatarUrl){let h=document.createElement("img");h.alt="",h.src=this.client.avatarUrl(t.authorAvatarUrl),l.append(h);}else {l.textContent=a==="ai"?this.strings.aiLabel:z(this.agentName(t));let h=a==="agent"?this.appearance.team?.find(y=>y.name===t.authorName)?.tone:void 0;h&&(l.style.background=h);}i.append(l);}let d=document.createElement("div");if(d.className="body",a==="end_user"){r&&this.drawFile(d,r.name,r.type,r.size,Promise.resolve(r));for(let l of t.attachments??[])this.drawFile(d,l.name,l.contentType,l.bytes,this.client.file?.(l.url)??Promise.resolve(null));}let u=a!=="end_user"&&o.namePlacement!=="hidden",c=document.createElement("div");if(a==="ai"?ze(c,t.body):c.textContent=t.body,u||a==="ai"&&o.namePlacement==="hidden"){let l=document.createElement("div");l.className=a==="ai"?"author ai":"author",l.textContent=a==="ai"?this.strings.aiLabel:this.agentName(t),o.stampPlacement==="beside_name"&&l.append(this.stamp(t)),o.namePlacement==="inline"?(l.classList.add("below"),d.append(c,l)):d.append(l,c);}else t.body&&d.append(c);return o.stampPlacement==="under_turn"&&d.append(this.stamp(t)),i.append(d),e.append(i),e.scrollTop=e.scrollHeight,i}drawFile(e,t,r,a,o){let i=document.createElement("a");if(r==="application/pdf"){i.className="pdfc",i.download=t;let s=document.createElement("b");s.textContent="PDF",i.append(s,`${t} \xB7 ${_(a)}`);}else {i.className="att",i.target="_blank",i.rel="noopener noreferrer";let s=document.createElement("img");s.alt=t,s.addEventListener("load",()=>{let d=i.closest(".log");d&&(d.scrollTop=d.scrollHeight);}),i.append(s);}e.append(i),o.then(s=>{s&&(i.href=this.objectUrl(s),i.querySelector("img")?.setAttribute("src",i.href));});}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],i=a[a.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),i.focus()):!e.shiftKey&&s===i?(e.preventDefault(),o.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function K(n){return `40${JSON.stringify(n)}`}function q(){return "3"}function j(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 i=I(t);return {kind:"open",pingInterval:typeof i?.pingInterval=="number"?i.pingInterval:25e3,pingTimeout:typeof i?.pingTimeout=="number"?i.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 i=I(a);return {kind:"connectError",message:typeof i?.message=="string"?i.message:"refused"}}if(r!=="2")return {kind:"other"};let o=I(a);return !Array.isArray(o)||typeof o[0]!="string"?{kind:"other"}:{kind:"event",name:o[0],payload:o[1]}}function I(n){try{return JSON.parse(n)}catch{return null}}var We="/socket.io/?EIO=4&transport=websocket",L=class{constructor(e){this.options=e;p(this,"socket",null);p(this,"heartbeat",null);p(this,"ready",false);p(this,"closed",false);p(this,"heartbeatWindow",45e3);p(this,"factory");p(this,"setTimer");p(this,"clearTimer");this.factory=e.socketFactory??Je,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(/\/+$/,"")}${We}`,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=j(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(K(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(q());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 Je(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var Ve=6e4;function xt(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 C(n),a=new T(t,r,n.strings,n.appearance),o=n.appearance?.availability??S.availability,i,s=()=>{a.setOpenNow(w(o,new Date)),i=setTimeout(s,Ve);};s();let d=new Set,u,c=null,l=n.pollIntervalMs??15e3,h=m=>{d.has(m.id)||m.authorKind==="end_user"||(d.add(m.id),a.onIncomingTurn(m));},y=async()=>{if(!r.hasThread)return;let m=await r.load();if(m){for(let b of m.turns)h(b);d=new Set(m.turns.map(b=>b.id));}},v=()=>{u||l<=0||(u=setInterval(()=>void y(),l));},k=()=>{u&&clearInterval(u),u=void 0;},f=()=>{if(c||!n.socketHost)return;let m=r.socketAuth;m&&(c=new L({auth:m,host:n.socketHost,onClosed:b=>{c=null,v(),b&&f();},onReady:k,onTurn:h,socketFactory:n.socketFactory}),c.open());};return v(),f(),{close:()=>a.close(),destroy:()=>{k(),clearTimeout(i),c?.close(),c=null,a.close(),t.remove();},identify:m=>r.identify(m),open:()=>{a.open().then(f);}}}exports.ChatClient=C;exports.ChatPanel=T;exports.DEFAULT_APPEARANCE=S;exports.DEFAULT_APPEARANCE_SETTINGS=g;exports.mountChat=xt;exports.panelStyles=F;exports.resolveAppearance=E;//# sourceMappingURL=chat.cjs.map
|
|
105
|
+
`}${Ae[t.composerShape]}${Le[t.skin]}${G(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ne[t.bubbleShape]}${Pe[t.bubbleFill]}${_e[t.namePlacement]}${t.nameAvatar?Fe:""}${t.dayDividers?Ie:""}${Re[t.stampPlacement]}${t.stampContent==="time_and_latency"?He:""}${$e}${n.attachments?.enabled?Me(t.composerShape):""}`}var Ye=["end_user","agent","ai"];function We(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var Je='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>',Ve='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',w=class{constructor(e,t,r={},a={},o={}){this.host=e;this.client=t;d(this,"root");d(this,"strings");d(this,"settings");d(this,"appearance");d(this,"launcher");d(this,"badge");d(this,"panel",null);d(this,"lastFocused",null);d(this,"unread",0);d(this,"pendingTurns",0);d(this,"openNow");d(this,"style");d(this,"scheme");d(this,"picked",null);d(this,"objectUrls",[]);this.strings={...we,...r},this.appearance={...C,...a},this.settings=T({...C,...a}),this.root=e.attachShadow({mode:o.shadowMode??"closed"}),this.openNow=N(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=H(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(K(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...C,...e},this.settings=T(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=H(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=this.appearance.team??[];r.length>0&&t.append(I(r,this.strings,f=>this.client.avatarUrl(f)));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let i=document.createElement("p");i.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),i.append(s,this.strings.replyTime),a.append(o,i);let p=document.createElement("button");p.className="close",p.type="button",p.setAttribute("aria-label",this.strings.closeLabel),p.innerHTML=Ve,p.addEventListener("click",()=>this.close()),t.append(a,p);let u=document.createElement("div");u.className="log",u.setAttribute("role","log"),u.setAttribute("aria-live","polite"),u.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let l=document.createElement("input");l.type="text",l.setAttribute("aria-label",this.strings.inputPlaceholder),l.placeholder=this.strings.inputPlaceholder;let h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.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 y=document.createElement("span");y.className="sendtext",y.textContent=this.strings.sendLabel,h.append(y);let k=this.appearance.attachments;if(k?.enabled&&this.client.upload){let f=document.createElement("span");f.className="field";let m=document.createElement("input");m.type="file",m.accept=k.accept.join(","),m.hidden=true,m.addEventListener("change",()=>{let M=m.files?.[0];m.value="",M&&this.pick(u,c,k,M);});let b=document.createElement("button");b.type="button",b.className="clip",b.setAttribute("aria-label",this.strings.attachLabel),b.innerHTML=Je,b.addEventListener("click",()=>m.click()),f.append(b,l,m),c.append(f,h);}else c.append(l,h);c.addEventListener("submit",f=>{f.preventDefault(),this.submit(l,u);}),e.append(t,u,c),e.addEventListener("keydown",f=>this.onKeydown(f,e,p)),this.root.append(e),this.panel=e,l.focus();let S=await this.client.load();S&&S.turns.length>0?this.renderThread(u,S):this.renderFirstRun(u,l),this.openNow||this.renderAway(t);}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),this.appearance.starterPrompts.filter(Ke).forEach((s,p)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${p}`;let l=document.createElement("template");l.innerHTML=s.html,je(l.content)?c.append(l.content):c.textContent=s.text;for(let y of c.querySelectorAll("a"))y.target="_blank",y.rel="noopener noreferrer";let h=document.createElement("button");h.className="promptpress",h.type="button",h.setAttribute("aria-labelledby",c.id),h.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),u.append(c,h),r.append(u);}),e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let a=document.createElement("span");a.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,a),e.after(t);}pick(e,t,r,a){let o=a.size>r.maxBytes||!r.accept.includes(a.type);for(let l of this.root.querySelectorAll(o?".ferr":".file,.ferr"))l.remove();if(o){let l=document.createElement("p");l.className="ferr",l.setAttribute("role","alert"),l.textContent=this.strings.fileRefusal(R(a.size),`${r.maxBytes/1e6} MB`),t.before(l),e.scrollTop=e.scrollHeight;return}this.picked=a;let i=document.createElement("span");i.className="file";let s;if(a.type==="application/pdf")s=document.createElement("b"),s.textContent="PDF";else {let l=document.createElement("img");l.className="th",l.alt="",l.src=this.objectUrl(a),s=l;}let p=document.createElement("span");p.className="name",p.textContent=a.name;let u=document.createElement("span");u.className="sz",u.textContent=`\xB7 ${R(a.size)}`;let c=document.createElement("button");c.type="button",c.className="x",c.setAttribute("aria-label",this.strings.removeFileLabel),c.textContent="\xD7",c.addEventListener("click",()=>{this.picked=null,i.remove();}),i.append(s,p,u,c),t.before(i),e.scrollTop=e.scrollHeight;}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.panel=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),a=this.picked;if(!(!r&&!a)){e.value="",this.picked=null;for(let o of this.root.querySelectorAll(".file,.ferr"))o.remove();await this.sendBody(t,r,a);}}async sendBody(e,t,r=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let a=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);a.setAttribute("data-pending","");let o=r?await this.client.upload?.(r):void 0,i=o===null?null:await this.client.send(t,We(),o?[o.id]:void 0);if(a.removeAttribute("data-pending"),i){a.dataset.turnId=i.id;return}this.markFailed(e,a,t,r);}markFailed(e,t,r,a){t.setAttribute("data-failed","");let o=document.createElement("button");o.type="button",o.className="retry",o.textContent=this.strings.retryLabel,o.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,a);}),(t.querySelector(".body")??t).append(o);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){e.querySelector(".empty")?.remove();let a=Ye.includes(t.authorKind)?t.authorKind:"agent",o=this.settings,i=document.createElement("div");if(i.className=`turn ${a}`,i.dataset.turnId=t.id,a!=="end_user"&&o.nameAvatar){let l=document.createElement("span");if(l.className=a==="ai"?"av bot":"av",l.setAttribute("aria-hidden","true"),a==="agent"&&t.authorAvatarUrl){let h=document.createElement("img");h.alt="",h.src=this.client.avatarUrl(t.authorAvatarUrl),l.append(h);}else {l.textContent=a==="ai"?this.strings.aiLabel:D(this.agentName(t));let h=a==="agent"?this.appearance.team?.find(y=>y.name===t.authorName)?.tone:void 0;h&&(l.style.background=h);}i.append(l);}let p=document.createElement("div");if(p.className="body",a==="end_user"){r&&this.drawFile(p,r.name,r.type,r.size,Promise.resolve(r));for(let l of t.attachments??[])this.drawFile(p,l.name,l.contentType,l.bytes,this.client.file?.(l.url)??Promise.resolve(null));}let u=a!=="end_user"&&o.namePlacement!=="hidden",c=document.createElement("div");if(a==="ai"?De(c,t.body):c.textContent=t.body,u||a==="ai"&&o.namePlacement==="hidden"){let l=document.createElement("div");l.className=a==="ai"?"author ai":"author",l.textContent=a==="ai"?this.strings.aiLabel:this.agentName(t),o.stampPlacement==="beside_name"&&l.append(this.stamp(t)),o.namePlacement==="inline"?(l.classList.add("below"),p.append(c,l)):p.append(l,c);}else t.body&&p.append(c);return o.stampPlacement==="under_turn"&&p.append(this.stamp(t)),i.append(p),e.append(i),e.scrollTop=e.scrollHeight,i}drawFile(e,t,r,a,o){let i=document.createElement("a");if(r==="application/pdf"){i.className="pdfc",i.download=t;let s=document.createElement("b");s.textContent="PDF",i.append(s,`${t} \xB7 ${R(a)}`);}else {i.className="att",i.target="_blank",i.rel="noopener noreferrer";let s=document.createElement("img");s.alt=t,s.addEventListener("load",()=>{let p=i.closest(".log");p&&(p.scrollTop=p.scrollHeight);}),i.append(s);}e.append(i),o.then(s=>{s&&(i.href=this.objectUrl(s),i.querySelector("img")?.setAttribute("src",i.href));});}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],i=a[a.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),i.focus()):!e.shiftKey&&s===i?(e.preventDefault(),o.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function Y(n){return `40${JSON.stringify(n)}`}function W(){return "3"}function J(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 i=$(t);return {kind:"open",pingInterval:typeof i?.pingInterval=="number"?i.pingInterval:25e3,pingTimeout:typeof i?.pingTimeout=="number"?i.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 i=$(a);return {kind:"connectError",message:typeof i?.message=="string"?i.message:"refused"}}if(r!=="2")return {kind:"other"};let o=$(a);return !Array.isArray(o)||typeof o[0]!="string"?{kind:"other"}:{kind:"event",name:o[0],payload:o[1]}}function $(n){try{return JSON.parse(n)}catch{return null}}var Xe="/socket.io/?EIO=4&transport=websocket",P=class{constructor(e){this.options=e;d(this,"socket",null);d(this,"heartbeat",null);d(this,"ready",false);d(this,"closed",false);d(this,"heartbeatWindow",45e3);d(this,"factory");d(this,"setTimer");d(this,"clearTimer");this.factory=e.socketFactory??Ze,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Xe}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=J(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(Y(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(W());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let r=t.payload?.turn;r&&this.options.onTurn(r);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ze(n){let e=globalThis.WebSocket;if(!e)throw new v("no WebSocket");return new e(n)}var Qe=6e4;function wt(n){let e=globalThis.document;if(!e)throw new A("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 E(n),a=new w(t,r,n.strings,n.appearance),o=n.appearance?.availability??C.availability,i,s=()=>{a.setOpenNow(N(o,new Date)),i=setTimeout(s,Qe);};s();let p=new Set,u,c=null,l=n.pollIntervalMs??15e3,h=m=>{p.has(m.id)||m.authorKind==="end_user"||(p.add(m.id),a.onIncomingTurn(m));},y=async()=>{if(!r.hasThread)return;let m=await r.load();if(m){for(let b of m.turns)h(b);p=new Set(m.turns.map(b=>b.id));}},k=()=>{u||l<=0||(u=setInterval(()=>void y(),l));},S=()=>{u&&clearInterval(u),u=void 0;},f=()=>{if(c||!n.socketHost)return;let m=r.socketAuth;m&&(c=new P({auth:m,host:n.socketHost,onClosed:b=>{c=null,k(),b&&f();},onReady:S,onTurn:h,socketFactory:n.socketFactory}),c.open());};return k(),f(),{close:()=>a.close(),destroy:()=>{S(),clearTimeout(i),c?.close(),c=null,a.close(),t.remove();},identify:m=>r.identify(m),open:()=>{a.open().then(f);}}}exports.ChatClient=E;exports.ChatPanel=w;exports.DEFAULT_APPEARANCE=C;exports.DEFAULT_APPEARANCE_SETTINGS=g;exports.mountChat=wt;exports.panelStyles=H;exports.resolveAppearance=T;//# sourceMappingURL=chat.cjs.map
|
|
106
106
|
//# sourceMappingURL=chat.cjs.map
|
package/dist/chat.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {c,a as a$2,b}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var U="X-Prodantix-Conversation-Token",A="prodantix.chat.handle";function G(){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 C=class{constructor(e){this.options=e;a(this,"fetchImpl");a(this,"fileFetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=a$1(e.fetchImpl),this.fileFetchImpl=e.fileFetchImpl??((t,n)=>fetch(t,n)),this.host=d(e.host),this.storage=e.storage??G(),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(A,JSON.stringify(this.handle)),true)}async send(e,t,n){if(!await this.ensureThread())return null;let r=this.handle;return r?(await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{attachmentIds:n,body:e,pageContext:t},token:r.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async n=>JSON.parse(await n.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,n=>n.blob()):null}async 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(A);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(A),null}async fileRequest(e,t,n,r,o){let i={authorization:`Bearer ${this.options.apiKey}`,[U]:n};o&&(i["content-type"]=o.type||"application/octet-stream");try{let s=await this.fileFetchImpl(`${this.host}${t}`,{body:o,headers:i,method:e});if(s.ok)return await r(s);this.options.onError?.(new Error(`prodantix chat ${t}: ${s.status}`));}catch(s){this.options.onError?.(s);}return 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[U]=n.token);try{let i=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),s=await i.text();return i.ok?s?JSON.parse(s):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${i.status}`)),null)}catch(i){return this.options.onError?.(i),null}}};var Y={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function L(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=Y[t.find(s=>s.type==="weekday")?.value??""];if(!n)return false;let r=t.find(s=>s.type==="hour")?.value??"",o=t.find(s=>s.type==="minute")?.value??"",i=`${r}:${o}`;return a.windows.some(s=>s.days.includes(n)&&s.open<=i&&i<s.close)}var g={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"},W=["quiet","standard"],J=["round","square"],X=["rounded","tailed"],Z=["filled","outlined"],V=["circle","pill","squircle"],Q=["filled","outlined"],ee=["avatar","glyph","team_faces"],te=["large","medium","small"],ne=["above","hidden","inline"],re=["beside_name","none","under_turn"],ae=["time","time_and_latency"],x=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,B=(a,e)=>typeof a=="boolean"?a:e,ie={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"]},oe={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},se={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"]},le={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},ce={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function w(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:ie[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=r===void 0?void 0:oe[r],i=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=i===void 0?void 0:se[i],d=typeof e.skin=="string"?e.skin:void 0,u=d===void 0?void 0:le[d],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,l=c===void 0?void 0:ce[c],h={bubbleFill:x(e.bubbleFill,Z,l?.[1]??g.bubbleFill),bubbleShape:x(e.bubbleShape,X,l?.[0]??g.bubbleShape),composerShape:x(e.composerShape,J,u?.[1]??g.composerShape),dayDividers:B(e.dayDividers,s?.[0]??g.dayDividers),launcherContent:x(e.launcherContent,ee,n?.[2]??g.launcherContent),launcherFill:x(e.launcherFill,Q,n?.[1]??g.launcherFill),launcherShape:x(e.launcherShape,V,n?.[0]??g.launcherShape),launcherSize:x(e.launcherSize,te,n?.[3]??g.launcherSize),nameAvatar:B(e.nameAvatar,o?.[1]??g.nameAvatar),namePlacement:x(e.namePlacement,ne,o?.[0]??g.namePlacement),skin:x(e.skin,W,u?.[0]??g.skin),stampContent:x(e.stampContent,ae,s?.[2]??g.stampContent),stampPlacement:x(e.stampPlacement,re,s?.[1]??g.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function O(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 de="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",pe={large:66,medium:56,small:46},ue={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},he={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);"},me={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;}"},ge=".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}",fe={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},be={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},xe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ye={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function D(a,e,t,n){return `.launcher{--fab-size:${pe[n]}px;${ue[a]}${he[e]}}${me[t]}${ge}${fe[a]}${be[e]}${xe[a]}${ye[a]}`}function q(a,e,t,n=r=>r){let r=document.createDocumentFragment();if(a==="glyph"||t.length===0){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="${de}"/></svg>`,r.append(...o.childNodes,P()),r}return a==="avatar"?(r.append(K(t[0],e,n),P()),r):(r.append(_(t,e,n),P()),r)}function _(a,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let r of a.slice(0,2))n.append(K(r,e,t));return n}function K(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 P(){let a=document.createElement("span");return a.className="live",a.setAttribute("aria-hidden","true"),a}var ve={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(a,e)=>`That file is ${a}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel: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`},k={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...g},Se={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},ke={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},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}"},we={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ee={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Le=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Te='.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)}',Ae={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}"},Pe=".lat{font-size:11px;opacity:.7;margin-left:6px}",_e=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}";function Ne(a){let e=a==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${e+26}px}.composer button.clip{position:absolute;top:50%;left:${e-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}function N(a){return a<999500?`${Math.max(1,Math.round(a/1e3))} KB`:`${(a/1e6).toFixed(1)} MB`}var j=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
import {c,a as a$1,b as b$1}from'./chunk-V77KYPOF.js';import {e,h,d,b}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var O="X-Prodantix-Conversation-Token",P="prodantix.chat.handle";function W(){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 w=class{constructor(e$1){this.options=e$1;a(this,"fetchImpl");a(this,"fileFetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=e(e$1.fetchImpl),this.fileFetchImpl=e$1.fileFetchImpl??((t,n)=>fetch(t,n)),this.host=h(e$1.host),this.storage=e$1.storage??W(),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(P,JSON.stringify(this.handle)),true)}async send(e,t,n){if(!await this.ensureThread())return null;let r=this.handle;return r?(await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{attachmentIds:n,body:e,pageContext:t},token:r.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async n=>JSON.parse(await n.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,n=>n.blob()):null}async 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(P);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(P),null}async fileRequest(e,t,n,r,o){let i={authorization:`Bearer ${this.options.apiKey}`,[O]:n};o&&(i["content-type"]=o.type||"application/octet-stream");try{let s=await this.fileFetchImpl(`${this.host}${t}`,{body:o,headers:i,method:e});if(s.ok)return await r(s);this.options.onError?.(new d(`prodantix chat ${t}: ${s.status}`,s.status));}catch(s){this.options.onError?.(s);}return null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new d("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(o[O]=n.token);try{let i=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),s=await i.text();return i.ok?s?JSON.parse(s):{}:(this.options.onError?.(new d(`prodantix chat ${t}: ${i.status}`,i.status)),null)}catch(i){return this.options.onError?.(i),null}}};var J={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function T(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(s=>s.type==="weekday")?.value??""];if(!n)return false;let r=t.find(s=>s.type==="hour")?.value??"",o=t.find(s=>s.type==="minute")?.value??"",i=`${r}:${o}`;return a.windows.some(s=>s.days.includes(n)&&s.open<=i&&i<s.close)}var g={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"},X=["quiet","standard"],Z=["round","square"],V=["rounded","tailed"],Q=["filled","outlined"],ee=["circle","pill","squircle"],te=["filled","outlined"],ne=["avatar","glyph","team_faces"],re=["large","medium","small"],ae=["above","hidden","inline"],ie=["beside_name","none","under_turn"],oe=["time","time_and_latency"],x=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,D=(a,e)=>typeof a=="boolean"?a:e,se={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"]},le={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ce={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"]},de={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},pe={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function E(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:se[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=r===void 0?void 0:le[r],i=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=i===void 0?void 0:ce[i],d=typeof e.skin=="string"?e.skin:void 0,u=d===void 0?void 0:de[d],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,l=c===void 0?void 0:pe[c],h={bubbleFill:x(e.bubbleFill,Q,l?.[1]??g.bubbleFill),bubbleShape:x(e.bubbleShape,V,l?.[0]??g.bubbleShape),composerShape:x(e.composerShape,Z,u?.[1]??g.composerShape),dayDividers:D(e.dayDividers,s?.[0]??g.dayDividers),launcherContent:x(e.launcherContent,ne,n?.[2]??g.launcherContent),launcherFill:x(e.launcherFill,te,n?.[1]??g.launcherFill),launcherShape:x(e.launcherShape,ee,n?.[0]??g.launcherShape),launcherSize:x(e.launcherSize,re,n?.[3]??g.launcherSize),nameAvatar:D(e.nameAvatar,o?.[1]??g.nameAvatar),namePlacement:x(e.namePlacement,ae,o?.[0]??g.namePlacement),skin:x(e.skin,X,u?.[0]??g.skin),stampContent:x(e.stampContent,oe,s?.[2]??g.stampContent),stampPlacement:x(e.stampPlacement,ie,s?.[1]??g.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function q(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 ue="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",he={large:66,medium:56,small:46},me={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;"},ge={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);"},fe={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;}"},be=".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}",xe={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ye={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},ve={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Se={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function K(a,e,t,n){return `.launcher{--fab-size:${he[n]}px;${me[a]}${ge[e]}}${fe[t]}${be}${xe[a]}${ye[e]}${ve[a]}${Se[a]}`}function j(a,e,t,n=r=>r){let r=document.createDocumentFragment();if(a==="glyph"||t.length===0){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="${ue}"/></svg>`,r.append(...o.childNodes,_()),r}return a==="avatar"?(r.append(G(t[0],e,n),_()),r):(r.append(N(t,e,n),_()),r)}function N(a,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let r of a.slice(0,2))n.append(G(r,e,t));return n}function G(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 _(){let a=document.createElement("span");return a.className="live",a.setAttribute("aria-hidden","true"),a}var ke={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(a,e)=>`That file is ${a}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel: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`},C={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...g},Ce={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},we={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Ee={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}"},Le={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.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Pe='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',_e={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}"},Ne=".lat{font-size:11px;opacity:.7;margin-left:6px}",Fe=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}";function He(a){let e=a==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${e+26}px}.composer button.clip{position:absolute;top:50%;left:${e-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}function F(a){return a<999500?`${Math.max(1,Math.round(a/1e3))} KB`:`${(a/1e6).toFixed(1)} MB`}var Y=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
-
--online: oklch(72% 0.13 163.23);`;function
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function Re(a){return a==="light"?"":a==="dark"?`:host { ${Y} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
5
|
-
${
|
|
5
|
+
${Y}
|
|
6
6
|
}
|
|
7
|
-
}`}var
|
|
7
|
+
}`}var Ie=/https?:\/\/[^\s<>"]+/g,$e=/[.,;:!?)]$/,Me=a=>{let e=a;for(;$e.test(e);){let t=e.split("(").length-1,n=e.split(")").length-1;if(e.endsWith(")")&&t>=n)break;e=e.slice(0,-1);}return e};function ze(a,e){let t=0;for(let n of e.matchAll(Ie)){let r=n.index??0,o=Me(n[0]);r>t&&a.append(e.slice(t,r));let i=document.createElement("a");i.href=o,i.target="_blank",i.rel="noopener noreferrer",i.textContent=o,a.append(i),t=r+o.length;}t<e.length&&a.append(e.slice(t));}var Ue=["P","BR","STRONG","EM","A","UL","OL","LI"],Be=a=>typeof a=="object"&&a!==null&&"html"in a&&typeof a.html=="string"&&"text"in a&&typeof a.text=="string",Oe=(a,e)=>e.name==="class"||e.name==="data-block-type"?true:a!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),De=a=>[...a.querySelectorAll("*")].every(e=>Ue.includes(e.tagName)&&[...e.attributes].every(t=>Oe(e.tagName,t)));function H(a,e="system"){let t=E(a),n=a.launcherPosition==="bottom_left"?"left":"right",r=a.accentColor;return `${`
|
|
8
8
|
:host {
|
|
9
9
|
all: initial; z-index: 2147483000; --a: ${r};
|
|
10
10
|
--paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
|
|
@@ -12,7 +12,7 @@ import {c,a as a$2,b}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-V
|
|
|
12
12
|
--online: oklch(53.8% 0.1274 163.23);
|
|
13
13
|
color-scheme: ${e==="system"?"light dark":e};
|
|
14
14
|
}
|
|
15
|
-
${
|
|
15
|
+
${Re(e)}
|
|
16
16
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
17
17
|
.launcher {
|
|
18
18
|
z-index: 2147483000; position: fixed; ${n}: ${a.launcherOffsetX}px; bottom: ${a.launcherOffsetY}px; width: 56px; height: 56px;
|
|
@@ -102,5 +102,5 @@ ${Fe(e)}
|
|
|
102
102
|
.panel { animation: rise 180ms ease-out; }
|
|
103
103
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
104
104
|
}
|
|
105
|
-
`}${ke[t.composerShape]}${Se[t.skin]}${D(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ce[t.bubbleShape]}${we[t.bubbleFill]}${Ee[t.namePlacement]}${t.nameAvatar?Le:""}${t.dayDividers?Te:""}${Ae[t.stampPlacement]}${t.stampContent==="time_and_latency"?Pe:""}${_e}${a.attachments?.enabled?Ne(t.composerShape):""}`}var Oe=["end_user","agent","ai"];function De(){let a=globalThis.location;if(a)return {host:a.host,path:a.pathname,title:document.title}}var qe='<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="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>',Ke='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',E=class{constructor(e,t,n={},r={},o={}){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);a(this,"pendingTurns",0);a(this,"openNow");a(this,"style");a(this,"scheme");a(this,"picked",null);a(this,"objectUrls",[]);this.strings={...ve,...n},this.appearance={...k,...r},this.settings=w({...k,...r}),this.root=e.attachShadow({mode:o.shadowMode??"closed"}),this.openNow=L(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=F(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(q(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...k,...e},this.settings=w(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=F(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=this.appearance.team??[];n.length>0&&t.append(_(n,this.strings,f=>this.client.avatarUrl(f)));let r=document.createElement("div");r.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let i=document.createElement("p");i.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),i.append(s,this.strings.replyTime),r.append(o,i);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=Ke,d.addEventListener("click",()=>this.close()),t.append(r,d);let u=document.createElement("div");u.className="log",u.setAttribute("role","log"),u.setAttribute("aria-live","polite"),u.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let l=document.createElement("input");l.type="text",l.setAttribute("aria-label",this.strings.inputPlaceholder),l.placeholder=this.strings.inputPlaceholder;let h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.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 y=document.createElement("span");y.className="sendtext",y.textContent=this.strings.sendLabel,h.append(y);let v=this.appearance.attachments;if(v?.enabled&&this.client.upload){let f=document.createElement("span");f.className="field";let m=document.createElement("input");m.type="file",m.accept=v.accept.join(","),m.hidden=true,m.addEventListener("change",()=>{let H=m.files?.[0];m.value="",H&&this.pick(u,c,v,H);});let b=document.createElement("button");b.type="button",b.className="clip",b.setAttribute("aria-label",this.strings.attachLabel),b.innerHTML=qe,b.addEventListener("click",()=>m.click()),f.append(b,l,m),c.append(f,h);}else c.append(l,h);c.addEventListener("submit",f=>{f.preventDefault(),this.submit(l,u);}),e.append(t,u,c),e.addEventListener("keydown",f=>this.onKeydown(f,e,d)),this.root.append(e),this.panel=e,l.focus();let S=await this.client.load();S&&S.turns.length>0?this.renderThread(u,S):this.renderFirstRun(u,l),this.openNow||this.renderAway(t);}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),this.appearance.starterPrompts.filter(ze).forEach((s,d)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${d}`;let l=document.createElement("template");l.innerHTML=s.html,Be(l.content)?c.append(l.content):c.textContent=s.text;for(let y of c.querySelectorAll("a"))y.target="_blank",y.rel="noopener noreferrer";let h=document.createElement("button");h.className="promptpress",h.type="button",h.setAttribute("aria-labelledby",c.id),h.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),u.append(c,h),n.append(u);}),e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away";let n=document.createElement("span");n.className="awayglyph",n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(n,r),e.after(t);}pick(e,t,n,r){let o=r.size>n.maxBytes||!n.accept.includes(r.type);for(let l of this.root.querySelectorAll(o?".ferr":".file,.ferr"))l.remove();if(o){let l=document.createElement("p");l.className="ferr",l.setAttribute("role","alert"),l.textContent=this.strings.fileRefusal(N(r.size),`${n.maxBytes/1e6} MB`),t.before(l),e.scrollTop=e.scrollHeight;return}this.picked=r;let i=document.createElement("span");i.className="file";let s;if(r.type==="application/pdf")s=document.createElement("b"),s.textContent="PDF";else {let l=document.createElement("img");l.className="th",l.alt="",l.src=this.objectUrl(r),s=l;}let d=document.createElement("span");d.className="name",d.textContent=r.name;let u=document.createElement("span");u.className="sz",u.textContent=`\xB7 ${N(r.size)}`;let c=document.createElement("button");c.type="button",c.className="x",c.setAttribute("aria-label",this.strings.removeFileLabel),c.textContent="\xD7",c.addEventListener("click",()=>{this.picked=null,i.remove();}),i.append(s,d,u,c),t.before(i),e.scrollTop=e.scrollHeight;}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.panel=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim(),r=this.picked;if(!(!n&&!r)){e.value="",this.picked=null;for(let o of this.root.querySelectorAll(".file,.ferr"))o.remove();await this.sendBody(t,n,r);}}async sendBody(e,t,n=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let r=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},n);r.setAttribute("data-pending","");let o=n?await this.client.upload?.(n):void 0,i=o===null?null:await this.client.send(t,De(),o?[o.id]:void 0);if(r.removeAttribute("data-pending"),i){r.dataset.turnId=i.id;return}this.markFailed(e,r,t,n);}markFailed(e,t,n,r){t.setAttribute("data-failed","");let o=document.createElement("button");o.type="button",o.className="retry",o.textContent=this.strings.retryLabel,o.addEventListener("click",()=>{t.remove(),this.sendBody(e,n,r);}),(t.querySelector(".body")??t).append(o);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t,n=null){e.querySelector(".empty")?.remove();let r=Oe.includes(t.authorKind)?t.authorKind:"agent",o=this.settings,i=document.createElement("div");if(i.className=`turn ${r}`,i.dataset.turnId=t.id,r!=="end_user"&&o.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:O(this.agentName(t));let h=r==="agent"?this.appearance.team?.find(y=>y.name===t.authorName)?.tone:void 0;h&&(l.style.background=h);}i.append(l);}let d=document.createElement("div");if(d.className="body",r==="end_user"){n&&this.drawFile(d,n.name,n.type,n.size,Promise.resolve(n));for(let l of t.attachments??[])this.drawFile(d,l.name,l.contentType,l.bytes,this.client.file?.(l.url)??Promise.resolve(null));}let u=r!=="end_user"&&o.namePlacement!=="hidden",c=document.createElement("div");if(r==="ai"?$e(c,t.body):c.textContent=t.body,u||r==="ai"&&o.namePlacement==="hidden"){let l=document.createElement("div");l.className=r==="ai"?"author ai":"author",l.textContent=r==="ai"?this.strings.aiLabel:this.agentName(t),o.stampPlacement==="beside_name"&&l.append(this.stamp(t)),o.namePlacement==="inline"?(l.classList.add("below"),d.append(c,l)):d.append(l,c);}else t.body&&d.append(c);return o.stampPlacement==="under_turn"&&d.append(this.stamp(t)),i.append(d),e.append(i),e.scrollTop=e.scrollHeight,i}drawFile(e,t,n,r,o){let i=document.createElement("a");if(n==="application/pdf"){i.className="pdfc",i.download=t;let s=document.createElement("b");s.textContent="PDF",i.append(s,`${t} \xB7 ${N(r)}`);}else {i.className="att",i.target="_blank",i.rel="noopener noreferrer";let s=document.createElement("img");s.alt=t,s.addEventListener("load",()=>{let d=i.closest(".log");d&&(d.scrollTop=d.scrollHeight);}),i.append(s);}e.append(i),o.then(s=>{s&&(i.href=this.objectUrl(s),i.querySelector("img")?.setAttribute("src",i.href));});}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],i=r[r.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),i.focus()):!e.shiftKey&&s===i?(e.preventDefault(),o.focus()):s===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 je="/socket.io/?EIO=4&transport=websocket",T=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??Ge,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(/\/+$/,"")}${je}`,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());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 Ge(a){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(a)}var Ye=6e4;function ut(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 C(a),r=new E(t,n,a.strings,a.appearance),o=a.appearance?.availability??k.availability,i,s=()=>{r.setOpenNow(L(o,new Date)),i=setTimeout(s,Ye);};s();let d=new Set,u,c=null,l=a.pollIntervalMs??15e3,h=m=>{d.has(m.id)||m.authorKind==="end_user"||(d.add(m.id),r.onIncomingTurn(m));},y=async()=>{if(!n.hasThread)return;let m=await n.load();if(m){for(let b of m.turns)h(b);d=new Set(m.turns.map(b=>b.id));}},v=()=>{u||l<=0||(u=setInterval(()=>void y(),l));},S=()=>{u&&clearInterval(u),u=void 0;},f=()=>{if(c||!a.socketHost)return;let m=n.socketAuth;m&&(c=new T({auth:m,host:a.socketHost,onClosed:b=>{c=null,v(),b&&f();},onReady:S,onTurn:h,socketFactory:a.socketFactory}),c.open());};return v(),f(),{close:()=>r.close(),destroy:()=>{S(),clearTimeout(i),c?.close(),c=null,r.close(),t.remove();},identify:m=>n.identify(m),open:()=>{r.open().then(f);}}}export{C as ChatClient,E as ChatPanel,k as DEFAULT_APPEARANCE,g as DEFAULT_APPEARANCE_SETTINGS,ut as mountChat,F as panelStyles,w as resolveAppearance};//# sourceMappingURL=chat.js.map
|
|
105
|
+
`}${we[t.composerShape]}${Ce[t.skin]}${K(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ee[t.bubbleShape]}${Le[t.bubbleFill]}${Te[t.namePlacement]}${t.nameAvatar?Ae:""}${t.dayDividers?Pe:""}${_e[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ne:""}${Fe}${a.attachments?.enabled?He(t.composerShape):""}`}var qe=["end_user","agent","ai"];function Ke(){let a=globalThis.location;if(a)return {host:a.host,path:a.pathname,title:document.title}}var je='<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="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>',Ge='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',L=class{constructor(e,t,n={},r={},o={}){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);a(this,"pendingTurns",0);a(this,"openNow");a(this,"style");a(this,"scheme");a(this,"picked",null);a(this,"objectUrls",[]);this.strings={...ke,...n},this.appearance={...C,...r},this.settings=E({...C,...r}),this.root=e.attachShadow({mode:o.shadowMode??"closed"}),this.openNow=T(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=H(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(j(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...C,...e},this.settings=E(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=H(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=this.appearance.team??[];n.length>0&&t.append(N(n,this.strings,f=>this.client.avatarUrl(f)));let r=document.createElement("div");r.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let i=document.createElement("p");i.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),i.append(s,this.strings.replyTime),r.append(o,i);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=Ge,d.addEventListener("click",()=>this.close()),t.append(r,d);let u=document.createElement("div");u.className="log",u.setAttribute("role","log"),u.setAttribute("aria-live","polite"),u.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let l=document.createElement("input");l.type="text",l.setAttribute("aria-label",this.strings.inputPlaceholder),l.placeholder=this.strings.inputPlaceholder;let h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.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 y=document.createElement("span");y.className="sendtext",y.textContent=this.strings.sendLabel,h.append(y);let v=this.appearance.attachments;if(v?.enabled&&this.client.upload){let f=document.createElement("span");f.className="field";let m=document.createElement("input");m.type="file",m.accept=v.accept.join(","),m.hidden=true,m.addEventListener("change",()=>{let R=m.files?.[0];m.value="",R&&this.pick(u,c,v,R);});let b=document.createElement("button");b.type="button",b.className="clip",b.setAttribute("aria-label",this.strings.attachLabel),b.innerHTML=je,b.addEventListener("click",()=>m.click()),f.append(b,l,m),c.append(f,h);}else c.append(l,h);c.addEventListener("submit",f=>{f.preventDefault(),this.submit(l,u);}),e.append(t,u,c),e.addEventListener("keydown",f=>this.onKeydown(f,e,d)),this.root.append(e),this.panel=e,l.focus();let S=await this.client.load();S&&S.turns.length>0?this.renderThread(u,S):this.renderFirstRun(u,l),this.openNow||this.renderAway(t);}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),this.appearance.starterPrompts.filter(Be).forEach((s,d)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${d}`;let l=document.createElement("template");l.innerHTML=s.html,De(l.content)?c.append(l.content):c.textContent=s.text;for(let y of c.querySelectorAll("a"))y.target="_blank",y.rel="noopener noreferrer";let h=document.createElement("button");h.className="promptpress",h.type="button",h.setAttribute("aria-labelledby",c.id),h.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),u.append(c,h),n.append(u);}),e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away";let n=document.createElement("span");n.className="awayglyph",n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(n,r),e.after(t);}pick(e,t,n,r){let o=r.size>n.maxBytes||!n.accept.includes(r.type);for(let l of this.root.querySelectorAll(o?".ferr":".file,.ferr"))l.remove();if(o){let l=document.createElement("p");l.className="ferr",l.setAttribute("role","alert"),l.textContent=this.strings.fileRefusal(F(r.size),`${n.maxBytes/1e6} MB`),t.before(l),e.scrollTop=e.scrollHeight;return}this.picked=r;let i=document.createElement("span");i.className="file";let s;if(r.type==="application/pdf")s=document.createElement("b"),s.textContent="PDF";else {let l=document.createElement("img");l.className="th",l.alt="",l.src=this.objectUrl(r),s=l;}let d=document.createElement("span");d.className="name",d.textContent=r.name;let u=document.createElement("span");u.className="sz",u.textContent=`\xB7 ${F(r.size)}`;let c=document.createElement("button");c.type="button",c.className="x",c.setAttribute("aria-label",this.strings.removeFileLabel),c.textContent="\xD7",c.addEventListener("click",()=>{this.picked=null,i.remove();}),i.append(s,d,u,c),t.before(i),e.scrollTop=e.scrollHeight;}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.panel=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim(),r=this.picked;if(!(!n&&!r)){e.value="",this.picked=null;for(let o of this.root.querySelectorAll(".file,.ferr"))o.remove();await this.sendBody(t,n,r);}}async sendBody(e,t,n=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let r=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},n);r.setAttribute("data-pending","");let o=n?await this.client.upload?.(n):void 0,i=o===null?null:await this.client.send(t,Ke(),o?[o.id]:void 0);if(r.removeAttribute("data-pending"),i){r.dataset.turnId=i.id;return}this.markFailed(e,r,t,n);}markFailed(e,t,n,r){t.setAttribute("data-failed","");let o=document.createElement("button");o.type="button",o.className="retry",o.textContent=this.strings.retryLabel,o.addEventListener("click",()=>{t.remove(),this.sendBody(e,n,r);}),(t.querySelector(".body")??t).append(o);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t,n=null){e.querySelector(".empty")?.remove();let r=qe.includes(t.authorKind)?t.authorKind:"agent",o=this.settings,i=document.createElement("div");if(i.className=`turn ${r}`,i.dataset.turnId=t.id,r!=="end_user"&&o.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:q(this.agentName(t));let h=r==="agent"?this.appearance.team?.find(y=>y.name===t.authorName)?.tone:void 0;h&&(l.style.background=h);}i.append(l);}let d=document.createElement("div");if(d.className="body",r==="end_user"){n&&this.drawFile(d,n.name,n.type,n.size,Promise.resolve(n));for(let l of t.attachments??[])this.drawFile(d,l.name,l.contentType,l.bytes,this.client.file?.(l.url)??Promise.resolve(null));}let u=r!=="end_user"&&o.namePlacement!=="hidden",c=document.createElement("div");if(r==="ai"?ze(c,t.body):c.textContent=t.body,u||r==="ai"&&o.namePlacement==="hidden"){let l=document.createElement("div");l.className=r==="ai"?"author ai":"author",l.textContent=r==="ai"?this.strings.aiLabel:this.agentName(t),o.stampPlacement==="beside_name"&&l.append(this.stamp(t)),o.namePlacement==="inline"?(l.classList.add("below"),d.append(c,l)):d.append(l,c);}else t.body&&d.append(c);return o.stampPlacement==="under_turn"&&d.append(this.stamp(t)),i.append(d),e.append(i),e.scrollTop=e.scrollHeight,i}drawFile(e,t,n,r,o){let i=document.createElement("a");if(n==="application/pdf"){i.className="pdfc",i.download=t;let s=document.createElement("b");s.textContent="PDF",i.append(s,`${t} \xB7 ${F(r)}`);}else {i.className="att",i.target="_blank",i.rel="noopener noreferrer";let s=document.createElement("img");s.alt=t,s.addEventListener("load",()=>{let d=i.closest(".log");d&&(d.scrollTop=d.scrollHeight);}),i.append(s);}e.append(i),o.then(s=>{s&&(i.href=this.objectUrl(s),i.querySelector("img")?.setAttribute("src",i.href));});}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],i=r[r.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),i.focus()):!e.shiftKey&&s===i?(e.preventDefault(),o.focus()):s===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 Ye="/socket.io/?EIO=4&transport=websocket",A=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??We,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ye}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$1(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$1());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function We(a){let e=globalThis.WebSocket;if(!e)throw new d("no WebSocket");return new e(a)}var Je=6e4;function bt(a){let e=globalThis.document;if(!e)throw new b("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 w(a),r=new L(t,n,a.strings,a.appearance),o=a.appearance?.availability??C.availability,i,s=()=>{r.setOpenNow(T(o,new Date)),i=setTimeout(s,Je);};s();let d=new Set,u,c=null,l=a.pollIntervalMs??15e3,h=m=>{d.has(m.id)||m.authorKind==="end_user"||(d.add(m.id),r.onIncomingTurn(m));},y=async()=>{if(!n.hasThread)return;let m=await n.load();if(m){for(let b of m.turns)h(b);d=new Set(m.turns.map(b=>b.id));}},v=()=>{u||l<=0||(u=setInterval(()=>void y(),l));},S=()=>{u&&clearInterval(u),u=void 0;},f=()=>{if(c||!a.socketHost)return;let m=n.socketAuth;m&&(c=new A({auth:m,host:a.socketHost,onClosed:b=>{c=null,v(),b&&f();},onReady:S,onTurn:h,socketFactory:a.socketFactory}),c.open());};return v(),f(),{close:()=>r.close(),destroy:()=>{S(),clearTimeout(i),c?.close(),c=null,r.close(),t.remove();},identify:m=>n.identify(m),open:()=>{r.open().then(f);}}}export{w as ChatClient,L as ChatPanel,C as DEFAULT_APPEARANCE,g as DEFAULT_APPEARANCE_SETTINGS,bt as mountChat,H as panelStyles,E as resolveAppearance};//# sourceMappingURL=chat.js.map
|
|
106
106
|
//# sourceMappingURL=chat.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c as c$1,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {e,h,d,f as f$1,g,a as a$1,b as b$1,c as c$2}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var m=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 Ce(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new m}return new m}var V={now:()=>new Date};function S(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 c$2("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 c$2("event_name","event_name must be between 1 and 200 characters");if(!he(s))throw new c$2("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$1("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new b$1("host is required (the ingest base URL)");let e=h(s.host),t=s.defaultProperties,n=s.storage??new m;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??V,consent:s.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:s.flagsHost?h(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 f=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]:f}function p(s){return s===f?"undefined":String(s)}function W(s){return s===f?Number.NaN:Number(s)}function Y(s){return s!==f&&s!==null&&s!==""}function X(s,e){if(!Array.isArray(e))return false;let t=p(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 p(t)===p(n===void 0?f:n);case "neq":return p(t)!==p(n===void 0?f:n);case "contains":return p(t).includes(p(n===void 0?f:n));case "in":return X(t,n);case "not_in":return Array.isArray(n)?!X(t,n):false;case "gt":return x(t,n,(i,r)=>i>r);case "gte":return x(t,n,(i,r)=>i>=r);case "lt":return x(t,n,(i,r)=>i<r);case "lte":return x(t,n,(i,r)=>i<=r);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 x(s,e,t){let n=W(s),i=e===void 0?Number.NaN:W(e);return Number.isNaN(n)||Number.isNaN(i)?false:t(n,i)}function ee(s,e){let t=`${s}:${e}`,n=2166136261;for(let i=0;i<t.length;i++)n^=t.charCodeAt(i),n=Math.imul(n,16777619);return (n>>>0)%100}function P(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 i=0;for(let r=n.length-1;r>=0;r--)if(i+=n[r].weight,t<i)return n[r].key;return n[0].key}function R(s,e,t,n){for(let i of s.prerequisites??[]){if(n.includes(i.flagKey))return false;let r=e.find(d=>d.key===i.flagKey);if(!r||!r.enabled)return false;n.push(r.key);let a=R(r,e,t,n)&&P(r,t)&&te(r,t)===i.variationKey;if(n.pop(),!a)return false}return true}function y(s,e,t){return s.enabled?R(s,e,t,[s.key])?P(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 ze(s,e){return y(s,[],e)}function se(s,e){let t={};for(let n of s)t[n.key]=y(n,s,e).enabled;return t}function v(s,e,t){let n=s.variations??[],i=n[0];if(!i)return null;if(!s.enabled||!R(s,e,t,[s.key])||!P(s,t))return i;let r=te(s,t);return n.find(a=>a.key===r)??i}function Qe(s,e){return v(s,[],e)}function Ge(s,e,t){let n=s.find(i=>i.key===e);return n?v(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 I=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`flags request failed with status ${a.status}`,a.status);let d$1=JSON.parse(await a.text());return {flags:d$1.flags??{},variants:d$1.variants??{}}}finally{r!==void 0&&clearTimeout(r);}}async snapshot(){let e=this.fetch;if(!e)throw new d("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,n=f$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let r=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!r.ok)throw new d(`flag snapshot request failed with status ${r.status}`,r.status);let a=JSON.parse(await r.text()),d$1={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d$1.socketUrl=a.socketUrl),d$1}finally{i!==void 0&&clearTimeout(i);}}async memberships(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{r!==void 0&&clearTimeout(r);}}};function b(s){if(typeof s!="string")return;let e=Array.from(s).length;return e>=1&&e<=200?s:void 0}function F(s,e){return `pdx.${s}.${e}`}var ie="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(F(e,ie)))}function Se(s,e,t){let n=F(e,ie);if(typeof t.identityLink!="boolean"){s.removeItem(n);return}s.setItem(n,JSON.stringify({identityLink:t.identityLink}));}function tt(s,e,t,n){let i=F(t,"anonymous_id"),r=b(e.getItem(i))??b(s.getItem(i));return e.setItem(i,n),s.setItem(i,n),r!==void 0&&r!==n?r:void 0}var w=class{constructor(e,t,n,i){this.storage=e;this.shared=t;this.ids=n;this.namespace=i;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");this.refresh();}refresh(){let e=b(this.shared.getItem(this.key("anonymous_id"))),t=b(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=b(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){Se(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,n=this.storage.getItem(this.key("linked_anonymous_id")),i=t||n!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!i||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 F(this.namespace,e)}};var E=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),n=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,i=await this.request(t,n,{headers:this.authHeaders(),method:"GET"});if(!i.ok)throw new d(`inbox request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).messages??[]}async markRead(e,t){let n=this.requireFetch(),i=`${this.host}/v1/messages/read`,r=await this.request(n,i,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!r.ok)throw new d(`mark-read request failed with status ${r.status}`,r.status)}requireFetch(){if(!this.fetch)throw new d("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,n){let i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...n,signal:i?.signal})}finally{r!==void 0&&clearTimeout(r);}}};var c={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",screen:"$screen",set:"$set"},xe=[{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"]}],lt=s=>s.startsWith("$"),ct=s=>xe.find(e=>e.name===s);function re(s){return s>=400&&s<500&&s!==429}var T=class{constructor(e$1={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=e(e$1.fetch),this.maxRetries=e$1.maxRetries??3,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4,this.baseDelayMs=e$1.baseDelayMs??500,this.maxDelayMs=e$1.maxDelayMs??3e4,this.sleep=e$1.sleep??g,this.random=e$1.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=JSON.stringify(e.body),i;for(let r=0;r<=this.maxRetries;r+=1){try{let a=await this.attempt(t,e,n);if(a.ok)return;if(re(a.status))throw new d(`ingest rejected batch with status ${a.status}`,a.status);i=new d(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof d&&a.status!==void 0&&re(a.status))throw a;i=a;}r<this.maxRetries&&await this.sleep(this.backoff(r));}throw new d("ingest delivery failed after retries",void 0,{cause:i})}async attempt(e,t,n){let i=f$1(),r=i?setTimeout(()=>i.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:i?.signal})}finally{r!==void 0&&clearTimeout(r);}}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:S(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,_=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$1(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 d("no WebSocket");return new e(s)}var C=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 wt(s,e,t,n){let i={id:t.id,lastActivityAt:n,startedAt:t.startedAt};s.setItem(ae(e),JSON.stringify(i));}var A=class{constructor(e,t,n,i,r=Ee){this.storage=e;this.ids=t;this.clock=n;this.namespace=i;this.options=r;}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),i=n!==void 0&&n.id!==t.id?n:t;return this.write({...i,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,M=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},q=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 w(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 A(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new C(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new a$1("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new T({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new I({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new E({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??{}},i=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(i);}catch(n){this.config.onError(n);}}identify(e,t={}){this.identity.refresh();let n=this.identity.identify(e),i={};n.anonymousToLink!==void 0&&(i.$anon_distinct_id=n.anonymousToLink);let r={...M(t.traits??{}),...t.set??{}};Object.keys(r).length>0&&(i.$set=r),this.capture(c.identify,{properties:i});}link(e,t,n){let i={$anon_distinct_id:t},r=M(n??{});Object.keys(r).length>0&&(i.$set=r),this.capture(c.identify,{distinctId:e,properties:i});}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 i={$group_key:t,$group_type:e};n&&(i.$set=n),this.capture(c.group,{properties:i});}setPersonProperties(e,t){let n={};e&&(n.$set=e),t&&(n.$set_once=t),this.capture(c.set,{properties:n});}setPersonTraits(e){let t=M(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(),i=n.flags.find(ce=>ce.key===e),r=await this.localContext(t,n.flags),a=i?v(i,n.flags,r):null,d=i?y(i,n.flags,r).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(),i=n.flags.find(d=>d.key===e),r=await this.localContext(t,n.flags),a=i?y(i,n.flags,r).enabled:false;return this.recordExposure(e,(i?v(i,n.flags,r)?.key:void 0)??String(a)),a}async localContext(e,t){let n=this.identity.getDistinctId(),i=e.cohorts;if(i===void 0&&ne(t)){let r=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&r-this.membershipCache.fetchedAt<le?i=this.membershipCache.cohorts:(i=await this.flagsClient.memberships(n),this.membershipCache={cohorts:i,distinctId:n,fetchedAt:r});}return {attributes:e.attributes,cohorts:i,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 _({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:S(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 Lt(s){return new q(s)}export{m as a,Ce as b,V as c,ge as d,j as e,J as f,z as g,ye as h,Z as i,ee as j,ze as k,se as l,Qe as m,Ge as n,I as o,be as p,tt as q,E as r,wt as s,c as t,xe as u,lt as v,ct as w,T as x,q as y,Lt as z};//# sourceMappingURL=chunk-4RLPQZ5L.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-4RLPQZ5L.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-5XGN7UAV.js';var n=class extends Error{constructor(r,o,i){super(o,i);a$1(this,"code");this.code=r,this.name="ProdantixError";}},a=class extends n{constructor(t){super("config",t),this.name="ConfigError";}},l=class extends n{constructor(r,o){super("validation",o);a$1(this,"field");this.field=r,this.name="ValidationError";}},c=class extends n{constructor(r,o,i){super("transport",r,i);a$1(this,"status");this.status=o,this.name="TransportError";}};function p(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function h(){let e=globalThis.AbortController;return e?new e:void 0}var g=e=>new Promise(t=>{setTimeout(t,e);});function f(e){return e.replace(/\/+$/,"")}export{n as a,a as b,l as c,c as d,p as e,h as f,g,f as h};//# sourceMappingURL=chunk-ODN4ZELX.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-ODN4ZELX.js.map
|