@prodantix/sdk 0.2.0 → 0.3.0-beta.379

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chat.js CHANGED
@@ -1,45 +1,105 @@
1
- import {c,a as a$2,b as b$1}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var z="X-Prodantix-Conversation-Token",C="prodantix.chat.handle";function $(){let a=globalThis.localStorage;if(a)return {get:e=>a.getItem(e),remove:e=>a.removeItem(e),set:(e,t)=>a.setItem(e,t)}}var b=class{constructor(e){this.options=e;a(this,"fetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=a$1(e.fetchImpl),this.host=d(e.host),this.storage=e.storage??$(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(C,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?(await this.request("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/turns`,{body:{body:e,pageContext:t},token:n.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(C);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch{}return this.storage?.remove(C),null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let s={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(s[z]=n.token);try{let o=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:s,method:e}),i=await o.text();return o.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${o.status}`)),null)}catch(o){return this.options.onError?.(o),null}}};var p={bubbleStyle:"tailed",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"concierge",stampContent:"time",stampPlacement:"none"},O=["concierge","console","quiet"],D=["hairline","outlined","rounded","tailed"],U=["circle","pill","squircle"],B=["filled","outlined"],K=["avatar","glyph","team_faces"],q=["large","medium","small"],Y=["above","hidden","inline"],G=["beside_name","none","under_turn"],W=["time","time_and_latency"],m=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,_=(a,e)=>typeof a=="boolean"?a:e,j={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},X={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Z={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]};function y(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:j[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,s=r===void 0?void 0:X[r],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=o===void 0?void 0:Z[o],c={bubbleStyle:m(e.bubbleStyle,D,p.bubbleStyle),dayDividers:_(e.dayDividers,i?.[0]??p.dayDividers),launcherContent:m(e.launcherContent,K,n?.[2]??p.launcherContent),launcherFill:m(e.launcherFill,B,n?.[1]??p.launcherFill),launcherShape:m(e.launcherShape,U,n?.[0]??p.launcherShape),launcherSize:m(e.launcherSize,q,n?.[3]??p.launcherSize),nameAvatar:_(e.nameAvatar,s?.[1]??p.nameAvatar),namePlacement:m(e.namePlacement,Y,s?.[0]??p.namePlacement),skin:m(e.skin,O,p.skin),stampContent:m(e.stampContent,W,i?.[2]??p.stampContent),stampPlacement:m(e.stampPlacement,G,i?.[1]??p.stampPlacement)};return c.stampPlacement==="beside_name"&&c.namePlacement==="hidden"&&(c.stampPlacement="under_turn"),c.namePlacement==="inline"&&c.bubbleStyle==="hairline"&&(c.namePlacement="above"),c}var J={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function N(a,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:a.timezone,weekday:"short"}).formatToParts(e),n=J[t.find(i=>i.type==="weekday")?.value??""];if(!n)return false;let r=t.find(i=>i.type==="hour")?.value??"",s=t.find(i=>i.type==="minute")?.value??"",o=`${r}:${s}`;return a.windows.some(i=>i.days.includes(n)&&i.open<=o&&o<i.close)}var V="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",Q={large:66,medium:56,small:46},ee={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},te={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},ne={avatar:".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}.launcher .live{width:9px;height:9px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}"},ae={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},re={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},ie={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},oe={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function M(a,e,t,n){return `.launcher{--fab-size:${Q[n]}px;${ee[a]}${te[e]}}${ne[t]}${ae[a]}${re[e]}${ie[a]}${oe[a]}`}function F(a,e,t){let n=document.createDocumentFragment();if(a==="glyph"){let o=document.createElement("span");return o.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${V}"/></svg>`,n.append(...o.childNodes),n}if(a==="avatar")return n.append(H(t[0],e),I()),n;let r=document.createElement("span");r.className="faces";let s=t.length>0?t.slice(0,2):[void 0];for(let o of s)r.append(H(o,e));return n.append(r,I()),n}function H(a,e){let t=document.createElement("span");return t.className="av",t.setAttribute("aria-hidden","true"),t.textContent=a?a.initials:e.agentLabel.slice(0,2).toUpperCase(),a&&(t.style.background=a.tone),t}function I(){let a=document.createElement("span");return a.className="live",a.setAttribute("aria-hidden","true"),a}var se={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",sendLabel:"Send",timeLabel:a=>{let e=new Date(a);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:a=>`${a} unread`},v={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],teamFaces:[],...p},le={concierge:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}.composer{padding:12px 12px 14px;gap:8px}.composer input{border:0;background:var(--fill);height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",console:".panel{border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.16)}.header{background:var(--paper);color:var(--ink);border-bottom:1px solid var(--hairline)}.close{color:var(--ink-2)}",quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{height:42px;padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.close{color:var(--ink-2)}"},ce={hairline:".turn{max-width:100%;padding:13px 0;border-top:1px solid var(--hairline);background:none;border-radius:0}.log>.turn:first-child{border-top:0}.turn.end_user{align-self:stretch;display:flex;flex-direction:column;align-items:flex-end}.turn.end_user .body{background:var(--fill);color:var(--ink);border-radius:8px;padding:9px 12px;max-width:85%}",outlined:".turn{background:none;border:1px solid var(--hairline);border-radius:12px}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}",rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},de={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".author{display:inline;margin-right:6px;font-weight:650}"},pe=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",ue='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',he={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},me=".lat{font-size:11px;opacity:.7;margin-left:6px}";function R(a){let e=y(a),t=a.launcherPosition==="bottom_left"?"left":"right",n=a.accentColor;return `${`
1
+ import {c,a as a$2,b}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var q="X-Prodantix-Conversation-Token",L="prodantix.chat.handle";function K(){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 k=class{constructor(e){this.options=e;a(this,"fetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=a$1(e.fetchImpl),this.host=d(e.host),this.storage=e.storage??K(),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(L,JSON.stringify(this.handle)),true)}async send(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?(await this.request("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/turns`,{body:{body:e,pageContext:t},token:n.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(L);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(L),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[q]=n.token);try{let c=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),i=await c.text();return c.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${c.status}`)),null)}catch(c){return this.options.onError?.(c),null}}};var Y={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=Y[t.find(i=>i.type==="weekday")?.value??""];if(!n)return false;let r=t.find(i=>i.type==="hour")?.value??"",o=t.find(i=>i.type==="minute")?.value??"",c=`${r}:${o}`;return a.windows.some(i=>i.days.includes(n)&&i.open<=c&&c<i.close)}var u={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"],G=["rounded","tailed"],X=["filled","outlined"],Z=["circle","pill","squircle"],J=["filled","outlined"],V=["avatar","glyph","team_faces"],Q=["large","medium","small"],ee=["above","hidden","inline"],te=["beside_name","none","under_turn"],ne=["time","time_and_latency"],f=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,$=(a,e)=>typeof a=="boolean"?a:e,ae={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},re={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ie={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"]},oe={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},se={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function C(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:ae[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=r===void 0?void 0:re[r],c=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,i=c===void 0?void 0:ie[c],h=typeof e.skin=="string"?e.skin:void 0,d=h===void 0?void 0:oe[h],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,p=l===void 0?void 0:se[l],m={bubbleFill:f(e.bubbleFill,X,p?.[1]??u.bubbleFill),bubbleShape:f(e.bubbleShape,G,p?.[0]??u.bubbleShape),composerShape:f(e.composerShape,j,d?.[1]??u.composerShape),dayDividers:$(e.dayDividers,i?.[0]??u.dayDividers),launcherContent:f(e.launcherContent,V,n?.[2]??u.launcherContent),launcherFill:f(e.launcherFill,J,n?.[1]??u.launcherFill),launcherShape:f(e.launcherShape,Z,n?.[0]??u.launcherShape),launcherSize:f(e.launcherSize,Q,n?.[3]??u.launcherSize),nameAvatar:$(e.nameAvatar,o?.[1]??u.nameAvatar),namePlacement:f(e.namePlacement,ee,o?.[0]??u.namePlacement),skin:f(e.skin,W,d?.[0]??u.skin),stampContent:f(e.stampContent,ne,i?.[2]??u.stampContent),stampPlacement:f(e.stampPlacement,te,i?.[1]??u.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function z(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 le="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",ce={large:66,medium:56,small:46},de={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;"},pe={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},he={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},ue=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",me={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ge={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},fe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},be={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function U(a,e,t,n){return `.launcher{--fab-size:${ce[n]}px;${de[a]}${pe[e]}}${he[t]}${ue}${me[a]}${ge[e]}${fe[a]}${be[a]}`}function B(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="${le}"/></svg>`,r.append(...o.childNodes,P()),r}return a==="avatar"?(r.append(O(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(O(r,e,t));return n}function O(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 ye={agentLabel:"Agent",aiLabel:"AI",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.",inputPlaceholder:"Type a message",launcherLabel:"Chat with us",replyTime:"Usually replying in a few minutes",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`},x={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...u},xe={quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .status{color:var(--ink-3)}.header .av,.header .status .live{box-shadow:0 0 0 2px var(--paper)}.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}"},ve={round:".composer{padding:12px 12px 14px;gap:8px}.composer input{height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:44px;border-radius:8px;padding:0 12px}"},Se={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}"},ke={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ce={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}"},we=".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}"},Ee=".lat{font-size:11px;opacity:.7;margin-left:6px}",D=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
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 Le(a){return a==="light"?"":a==="dark"?`:host { ${D} }`:`@media (prefers-color-scheme: dark) {
4
+ :host {
5
+ ${D}
6
+ }
7
+ }`}function N(a,e="system"){let t=C(a),n=a.launcherPosition==="bottom_left"?"left":"right",r=a.accentColor;return `${`
2
8
  :host {
3
- all: initial; --a: ${n};
9
+ /* The widget sits above the host page's own furniture. The reset above sends
10
+ z-index back to auto, so without this the launcher and panel stack at the
11
+ document floor and anything the page raises (a cookie bar, a dev chip)
12
+ draws over them: the WebMCP chip covered the launcher on clepit's landing.
13
+ Below the 32-bit ceiling so a host can still put something over us
14
+ deliberately. */
15
+ all: initial; z-index: 2147483000; --a: ${r};
4
16
  --paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
5
- --fill: #f1f5f9; --hairline: #e2e8f0; --field: #cbd5e1; --ink-2: rgba(0,0,0,.72);
17
+ --fill: #f1f5f9; --hairline: #e2e8f0; --ink-2: rgba(0,0,0,.72);
6
18
  --online: oklch(53.8% 0.1274 163.23);
7
- color-scheme: light dark;
8
- }
9
- @media (prefers-color-scheme: dark) {
10
- :host {
11
- --paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
12
- --fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --field: rgba(255,255,255,.22); --ink-2: rgba(255,255,255,.70);
13
- --online: oklch(72% 0.13 163.23);
14
- }
19
+ color-scheme: ${e==="system"?"light dark":e};
15
20
  }
21
+ ${Le(e)}
16
22
  * { box-sizing: border-box; font-family: system-ui, sans-serif; }
17
23
  .launcher {
18
- position: fixed; ${t}: ${a.launcherOffsetX}px; bottom: ${a.launcherOffsetY}px; width: 56px; height: 56px;
24
+ z-index: 2147483000; position: fixed; ${n}: ${a.launcherOffsetX}px; bottom: ${a.launcherOffsetY}px; width: 56px; height: 56px;
19
25
  border-radius: 28px; border: none; cursor: pointer;
20
26
  display: inline-flex; align-items: center; justify-content: center;
21
- background: ${n}; color: #fff; font-size: 24px;
27
+ background: ${r}; color: #fff; font-size: 24px;
22
28
  box-shadow: 0 4px 12px rgba(0,0,0,.2);
23
29
  }
24
30
  .launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
31
+ /* A BACKGROUND change, never a position change. Nothing else in the fleet
32
+ moves under the pointer: .button[data-variant] and .iconButton all hover by
33
+ background alone. This used to lift by translateY(-1px), which made the one
34
+ control a visitor is meant to click the only element in the product that
35
+ shifted when pointed at. */
36
+ .launcher { transition: background-color 120ms ease; }
37
+ .launcher:hover { background: color-mix(in srgb, #000 12%, ${r}); }
38
+ .launcher:active { background: color-mix(in srgb, #000 20%, ${r}); }
39
+ @media (prefers-reduced-motion: reduce) {
40
+ .launcher { transition: none; }
41
+ }
25
42
  .badge {
26
43
  position: absolute; top: -4px; right: -4px; min-width: 20px; height: 20px;
27
44
  border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px;
28
45
  display: flex; align-items: center; justify-content: center; padding: 0 4px;
29
46
  }
47
+ /* renderBadge hides this with the hidden attribute, which is UA display:none
48
+ and is beaten by ANY author display. The rule above is one, so the badge
49
+ rendered for every visitor with no unread messages: an empty red circle on
50
+ the launcher, in production, for as long as it has shipped. The hiding code
51
+ read as if it worked, which is why nothing caught it. Keep this rule beside
52
+ the one that needs it. */
53
+ .badge[hidden] { display: none; }
30
54
  .panel {
31
- position: fixed; ${t}: ${a.launcherOffsetX}px; bottom: ${a.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
55
+ z-index: 2147483001; position: fixed; ${n}: ${a.launcherOffsetX}px; bottom: ${a.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
32
56
  height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
33
57
  border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
34
58
  display: flex; flex-direction: column; overflow: hidden;
35
59
  }
36
- .header { padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
60
+ .header { position: relative; padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
37
61
  .header h2 { margin: 0; font-size: 15px; }
38
- .close { background: none; border: none; color: #fff; cursor: pointer; font-size: 18px; }
39
- .close:focus-visible { outline: 2px solid #fff; }
62
+ /* Sized from the Configure tab's own head: 36px faces overlapping by 12, the
63
+ status line 12.5px at 80% under the title. The ring is the header's own
64
+ ground so overlapping faces separate from it and from each other. */
65
+ .header .faces { display: flex; }
66
+ .header .av { width: 36px; height: 36px; box-shadow: 0 0 0 2px var(--a); }
67
+ .header .av + .av { margin-left: -12px; }
68
+ .headmain { display: flex; flex-direction: column; }
69
+ .header .status { display: flex; align-items: center; gap: 6px; margin: 5px 0 0; font-size: 12.5px; color: rgb(255 255 255 / 80%); }
70
+ /* The dot's ring is the PAPER, not the accent. An accent ring on the standard
71
+ skin is the header's own background and draws nothing, which is how this
72
+ shipped looking ringless beside a preview that had one. The faces above keep
73
+ the accent ring, which is a different job: separating two overlapping discs
74
+ from each other and from the header. */
75
+ .header .status .live { flex: none; width: 10px; height: 10px; border-radius: 50%; background: var(--online); box-shadow: 0 0 0 2px var(--paper); }
76
+ /* Hours, the same fact the launcher's dot carries. A green dot and a sentence
77
+ promising a reply in minutes are both claims about somebody being there, so
78
+ outside the project's hours neither is drawn: the away message in the thread
79
+ is what speaks then. */
80
+ .panel.closed .status { display: none; }
81
+ /* Pinned rather than laid out: the standard skin turns this header into a
82
+ column so the title can carry a line under it, and a close button that is
83
+ merely a flex sibling then stacks BELOW the title on the left, which is where
84
+ clepit's landing showed it. */
85
+ .header .close { position: absolute; top: 8px; right: 8px; }
86
+ /* The fleet's icon button: a padded square, a radius, and a hover that tints
87
+ the background. This carried none of them, so the messenger's close was the
88
+ one icon button in the product with no radius and no hover at all. The tint
89
+ is mixed from currentColor rather than a fixed white because the header is
90
+ the accent on some skins and the paper on others. */
91
+ .close {
92
+ display: inline-flex; align-items: center; justify-content: center;
93
+ width: 32px; height: 32px; padding: 0;
94
+ background: none; border: none; border-radius: 8px;
95
+ color: inherit; cursor: pointer; font-size: 18px; line-height: 1;
96
+ transition: background-color 120ms ease;
97
+ }
98
+ .close:hover { background: color-mix(in srgb, currentColor 14%, transparent); }
99
+ .close:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
40
100
  .log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
41
101
  .turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
42
- .turn.end_user { align-self: flex-end; background: ${n}; color: #fff; }
102
+ .turn.end_user { align-self: flex-end; background: ${r}; color: #fff; }
43
103
  .turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
44
104
  .author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
45
105
  .away { background: var(--fill); border: 1px solid var(--hairline); border-radius: 8px; padding: 8px 12px; font-size: 13.5px; color: var(--ink-2); }
@@ -51,18 +111,21 @@ import {c,a as a$2,b as b$1}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./
51
111
  font-family: inherit; font-size: 13.5px; font-weight: 500; color: var(--ink);
52
112
  background: none; border: 1px solid var(--hairline); border-radius: 8px; cursor: pointer;
53
113
  }
54
- .prompt:focus-visible { outline: 2px solid ${n}; outline-offset: 2px; }
114
+ .prompt:focus-visible { outline: 2px solid ${r}; outline-offset: 2px; }
55
115
  .av { width: 30px; height: 30px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 650; color: #fff; background: #7c3f3f; }
56
116
  .av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
117
+ .av img { width: 100%; height: 100%; display: block; object-fit: cover; border-radius: inherit; }
57
118
  .composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--hairline); }
58
- .composer input { flex: 1; padding: 8px 10px; border: 1px solid var(--field); border-radius: 8px; font-size: 14px; background: transparent; color: var(--ink); }
59
- .composer input:focus-visible { outline: 2px solid ${n}; }
60
- .composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${n}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 14.5px; font-weight: 550; }
119
+ .composer input { flex: 1; min-width: 0; height: 44px; padding: 0 12px; border: 0; border-radius: 8px; font-size: 14px; background: var(--fill); color: var(--ink); }
120
+ .composer input:focus-visible { outline: 2px solid ${r}; }
121
+ .composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${r}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 14.5px; font-weight: 550; }
122
+ .composer button:hover { background: color-mix(in srgb, #000 12%, ${r}); }
123
+ .composer button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
61
124
  .composer button .sendglyph { display: none; width: 19px; height: 19px; }
62
125
  .composer button:focus-visible { outline: 2px solid #0b0e14; }
63
126
  @media (prefers-reduced-motion: no-preference) {
64
127
  .panel { animation: rise 180ms ease-out; }
65
128
  @keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
66
129
  }
67
- `}${le[e.skin]}${M(e.launcherShape,e.launcherFill,e.launcherContent,e.launcherSize)}${ce[e.bubbleStyle]}${de[e.namePlacement]}${e.nameAvatar?pe:""}${e.dayDividers?ue:""}${he[e.stampPlacement]}${e.stampContent==="time_and_latency"?me:""}`}var ge=["end_user","agent","ai"];function fe(){let a=globalThis.location;if(a)return {host:a.host,path:a.pathname,title:document.title}}var x=class{constructor(e,t,n={},r={}){this.host=e;this.client=t;a(this,"root");a(this,"strings");a(this,"settings");a(this,"appearance");a(this,"launcher");a(this,"badge");a(this,"panel",null);a(this,"lastFocused",null);a(this,"unread",0);this.strings={...se,...n},this.appearance={...v,...r},this.settings=y({...v,...r}),this.root=e.attachShadow({mode:"closed"});let s=document.createElement("style");if(s.textContent=R({...v,...r}),this.root.append(s),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.append(F(this.settings.launcherContent,this.strings,this.appearance.teamFaces)),this.settings.launcherShape==="pill"){let o=document.createElement("span");o.className="label",o.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(o);}this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.launcher.append(this.badge),this.root.append(this.launcher);}toggle(){this.panel?this.close():this.open();}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className="panel",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=document.createElement("h2");n.textContent=this.strings.title;let r=document.createElement("button");r.className="close",r.type="button",r.setAttribute("aria-label",this.strings.closeLabel),r.textContent="\xD7",r.addEventListener("click",()=>this.close()),t.append(n,r);let s=document.createElement("div");s.className="log",s.setAttribute("role","log"),s.setAttribute("aria-live","polite"),s.setAttribute("aria-label",this.strings.title);let o=document.createElement("form");o.className="composer";let i=document.createElement("input");i.type="text",i.setAttribute("aria-label",this.strings.inputPlaceholder),i.placeholder=this.strings.inputPlaceholder;let c=document.createElement("button");c.type="submit",c.setAttribute("aria-label",this.strings.sendLabel),c.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let h=document.createElement("span");h.className="sendtext",h.textContent=this.strings.sendLabel,c.append(h),o.append(i,c),o.addEventListener("submit",g=>{g.preventDefault(),this.submit(i,s);}),e.append(t,s,o),e.addEventListener("keydown",g=>this.onKeydown(g,e,r)),this.root.append(e),this.panel=e,i.focus();let d=await this.client.load();d&&d.turns.length>0?this.renderThread(s,d):this.renderFirstRun(s,i),!N(this.appearance.availability,new Date)&&this.appearance.awayMessage.trim()&&this.renderAway(s);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let r=document.createElement("h3");r.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let s=document.createElement("p");s.textContent=this.strings.emptyBody,n.append(r,s);for(let o of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=o,i.addEventListener("click",()=>{t.value=o,this.submit(t,e);}),n.append(i);}e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim();if(!n)return;e.value="",t.querySelector(".empty")?.remove();let r=await this.client.send(n,fe());r&&this.appendTurn(t,r);}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t){e.querySelector(".empty")?.remove();let n=ge.includes(t.authorKind)?t.authorKind:"agent",r=this.settings,s=document.createElement("div");if(s.className=`turn ${n}`,n!=="end_user"&&r.nameAvatar){let d=document.createElement("span");d.className=n==="ai"?"av bot":"av",d.textContent=n==="ai"?this.strings.aiLabel:this.strings.agentLabel.slice(0,2).toUpperCase(),d.setAttribute("aria-hidden","true"),s.append(d);}let i=document.createElement("div");if(i.className="body",n!=="end_user"&&r.namePlacement!=="hidden"||n==="ai"&&r.namePlacement==="hidden"){let d=document.createElement("div");d.className=n==="ai"?"author ai":"author",d.textContent=n==="ai"?this.strings.aiLabel:this.strings.agentLabel,r.stampPlacement==="beside_name"&&d.append(this.stamp(t)),i.append(d);}let h=document.createElement("div");h.textContent=t.body,i.append(h),r.stampPlacement==="under_turn"&&i.append(this.stamp(t)),s.append(i),e.append(s),e.scrollTop=e.scrollHeight;}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,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 s=r[0],o=r[r.length-1],i=this.root.activeElement;e.shiftKey&&i===s?(e.preventDefault(),o.focus()):!e.shiftKey&&i===o?(e.preventDefault(),s.focus()):i===null&&(e.preventDefault(),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 be="/socket.io/?EIO=4&transport=websocket",S=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??xe,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(/\/+$/,"")}${be}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$1());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function xe(a){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(a)}function Re(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 b(a),r=new x(t,n,a.strings,a.appearance),s=new Set,o,i=null,c=a.pollIntervalMs??15e3,h=u=>{s.has(u.id)||u.authorKind==="end_user"||(s.add(u.id),r.onIncomingTurn(u));},d=async()=>{if(!n.hasThread)return;let u=await n.load();if(u){for(let f of u.turns)h(f);s=new Set(u.turns.map(f=>f.id));}},g=()=>{o||c<=0||(o=setInterval(()=>void d(),c));},A=()=>{o&&clearInterval(o),o=void 0;},k=()=>{if(i||!a.socketHost)return;let u=n.socketAuth;u&&(i=new S({auth:u,host:a.socketHost,onClosed:f=>{i=null,g(),f&&k();},onReady:A,onTurn:h,socketFactory:a.socketFactory}),i.open());};return g(),k(),{close:()=>r.close(),destroy:()=>{A(),i?.close(),i=null,r.close(),t.remove();},identify:u=>n.identify(u),open:()=>{r.open().then(k);}}}export{b as ChatClient,x as ChatPanel,v as DEFAULT_APPEARANCE,p as DEFAULT_APPEARANCE_SETTINGS,Re as mountChat,R as panelStyles,y as resolveAppearance};//# sourceMappingURL=chat.js.map
130
+ `}${ve[t.composerShape]}${xe[t.skin]}${U(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Se[t.bubbleShape]}${ke[t.bubbleFill]}${Ce[t.namePlacement]}${t.nameAvatar?we:""}${t.dayDividers?Te:""}${Ae[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ee:""}`}var Pe=["end_user","agent","ai"];function _e(){let a=globalThis.location;if(a)return {host:a.host,path:a.pathname,title:document.title}}var w=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,"openNow");a(this,"style");a(this,"scheme");this.strings={...ye,...n},this.appearance={...x,...r},this.settings=C({...x,...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=N(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={...x,...e},this.settings=C(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=N(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,b=>this.client.avatarUrl(b)));let r=document.createElement("div");r.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let c=document.createElement("p");c.className="status";let i=document.createElement("span");i.className="live",i.setAttribute("aria-hidden","true"),c.append(i,this.strings.replyTime),r.append(o,c);let h=document.createElement("button");h.className="close",h.type="button",h.setAttribute("aria-label",this.strings.closeLabel),h.textContent="\xD7",h.addEventListener("click",()=>this.close()),t.append(r,h);let d=document.createElement("div");d.className="log",d.setAttribute("role","log"),d.setAttribute("aria-live","polite"),d.setAttribute("aria-label",this.strings.title);let l=document.createElement("form");l.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let v=document.createElement("span");v.className="sendtext",v.textContent=this.strings.sendLabel,m.append(v),l.append(p,m),l.addEventListener("submit",b=>{b.preventDefault(),this.submit(p,d);}),e.append(t,d,l),e.addEventListener("keydown",b=>this.onKeydown(b,e,h)),this.root.append(e),this.panel=e,p.focus();let y=await this.client.load();y&&y.turns.length>0?this.renderThread(d,y):this.renderFirstRun(d,p),this.openNow||this.renderAway(d);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let r=document.createElement("h3");r.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(r,o);for(let c of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=c,i.addEventListener("click",()=>{t.value=c,this.submit(t,e);}),n.append(i);}e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim();if(!n)return;e.value="",t.querySelector(".empty")?.remove();let r=await this.client.send(n,_e());r&&this.appendTurn(t,r);}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t){e.querySelector(".empty")?.remove();let n=Pe.includes(t.authorKind)?t.authorKind:"agent",r=this.settings,o=document.createElement("div");if(o.className=`turn ${n}`,n!=="end_user"&&r.nameAvatar){let l=document.createElement("span");if(l.className=n==="ai"?"av bot":"av",l.setAttribute("aria-hidden","true"),n==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),l.append(p);}else l.textContent=n==="ai"?this.strings.aiLabel:z(this.agentName(t));o.append(l);}let i=document.createElement("div");i.className="body";let h=n!=="end_user"&&r.namePlacement!=="hidden",d=document.createElement("div");if(d.textContent=t.body,h||n==="ai"&&r.namePlacement==="hidden"){let l=document.createElement("div");l.className=n==="ai"?"author ai":"author",l.textContent=n==="ai"?this.strings.aiLabel:this.agentName(t),r.stampPlacement==="beside_name"&&l.append(this.stamp(t)),r.namePlacement==="inline"?(l.classList.add("below"),i.append(d,l)):i.append(l,d);}else i.append(d);r.stampPlacement==="under_turn"&&i.append(this.stamp(t)),o.append(i),e.append(o),e.scrollTop=e.scrollHeight;}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let r=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let o=r[0],c=r[r.length-1],i=this.root.activeElement;e.shiftKey&&i===o?(e.preventDefault(),c.focus()):!e.shiftKey&&i===c?(e.preventDefault(),o.focus()):i===null&&(e.preventDefault(),n.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};var Ne="/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??He,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(/\/+$/,"")}${Ne}`,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 He(a){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(a)}var Fe=6e4;function Ve(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 k(a),r=new w(t,n,a.strings,a.appearance),o=a.appearance?.availability??x.availability,c,i=()=>{r.setOpenNow(T(o,new Date)),c=setTimeout(i,Fe);};i();let h=new Set,d,l=null,p=a.pollIntervalMs??15e3,m=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),r.onIncomingTurn(g));},v=async()=>{if(!n.hasThread)return;let g=await n.load();if(g){for(let S of g.turns)m(S);h=new Set(g.turns.map(S=>S.id));}},y=()=>{d||p<=0||(d=setInterval(()=>void v(),p));},b=()=>{d&&clearInterval(d),d=void 0;},E=()=>{if(l||!a.socketHost)return;let g=n.socketAuth;g&&(l=new A({auth:g,host:a.socketHost,onClosed:S=>{l=null,y(),S&&E();},onReady:b,onTurn:m,socketFactory:a.socketFactory}),l.open());};return y(),E(),{close:()=>r.close(),destroy:()=>{b(),clearTimeout(c),l?.close(),l=null,r.close(),t.remove();},identify:g=>n.identify(g),open:()=>{r.open().then(E);}}}export{k as ChatClient,w as ChatPanel,x as DEFAULT_APPEARANCE,u as DEFAULT_APPEARANCE_SETTINGS,Ve as mountChat,N as panelStyles,C as resolveAppearance};//# sourceMappingURL=chat.js.map
68
131
  //# sourceMappingURL=chat.js.map
@@ -0,0 +1,2 @@
1
+ import {c as c$2,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {a as a$1,d,b as b$1,c as c$1}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var p=class extends Error{constructor(t,n,r){super(n,r);a(this,"code");this.code=t,this.name="ProdantixError";}},b=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},y=class extends p{constructor(t,n){super("validation",n);a(this,"field");this.field=t,this.name="ValidationError";}},l=class extends p{constructor(t,n,r){super("transport",t,r);a(this,"status");this.status=n,this.name="TransportError";}};var v=class{constructor(){a(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};function $e(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new v}return new v}var V={now:()=>new Date};function I(s){return s.toISOString()}var de=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ue=/^(?:\$|[a-z])[a-z0-9_.]*$/;function j(s){let e=0;for(let t of s)e+=1;return e}function H(s){return de.test(s)}function he(s){return ue.test(s)}function U(s){let e=j(s);if(e<1||e>200)throw new y("distinct_id","distinct_id must be between 1 and 200 characters")}function B(s){let e=j(s);if(e<1||e>200)throw new y("event_name","event_name must be between 1 and 200 characters");if(!he(s))throw new y("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var J="prodantix-js",z="0.0.1";function pe(){return globalThis.crypto}function fe(s){s[6]=s[6]&15|64,s[8]=s[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(s[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ge(){let s=pe();if(s?.randomUUID)return s.randomUUID();let e=new Uint8Array(16);if(s?.getRandomValues)s.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return fe(e)}var Q={uuid:ge};var me=s=>{};function G(s){if(!s.apiKey||!H(s.apiKey))throw new b("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new b("host is required (the ingest base URL)");let e=d(s.host),t=s.defaultProperties,n=s.storage??new v;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??V,consent:s.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:s.flagsHost?d(s.flagsHost):e,flushAt:s.flushAt??20,flushIntervalMs:s.flushIntervalMs??1e4,host:e,ids:s.ids??Q,locale:s.locale,maxQueueSize:s.maxQueueSize??1e3,maxRetries:s.maxRetries??3,namespace:ye(s.apiKey),onError:s.onError??me,os:s.os,requestTimeoutMs:s.requestTimeoutMs??1e4,sdkName:s.sdkName??J,sdkVersion:s.sdkVersion??z,sessionTracking:s.sessionTracking??false,sharedStorage:s.sharedStorage??n,socketFactory:s.socketFactory,storage:n,streamFlags:s.streamFlags??false,transport:s.transport}}function ye(s){return s.slice(0,16)}var g=Symbol("absent");function ve(s,e){if(s==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,s))return t[s];let n=e.attributes??{};return Object.prototype.hasOwnProperty.call(n,s)?n[s]:g}function f(s){return s===g?"undefined":String(s)}function W(s){return s===g?Number.NaN:Number(s)}function Y(s){return s!==g&&s!==null&&s!==""}function X(s,e){if(!Array.isArray(e))return false;let t=f(s);return e.map(n=>String(n)).includes(t)}function Z(s,e){let t=ve(s.attribute,e),n=s.value;switch(s.op){case "is_set":return Y(t);case "is_not_set":return !Y(t);case "eq":return f(t)===f(n===void 0?g:n);case "neq":return f(t)!==f(n===void 0?g:n);case "contains":return f(t).includes(f(n===void 0?g:n));case "in":return X(t,n);case "not_in":return Array.isArray(n)?!X(t,n):false;case "gt":return w(t,n,(r,i)=>r>i);case "gte":return w(t,n,(r,i)=>r>=i);case "lt":return w(t,n,(r,i)=>r<i);case "lte":return w(t,n,(r,i)=>r<=i);case "in_cohort":return typeof n=="string"&&n!==""&&(e.cohorts??[]).includes(n);case "not_in_cohort":return typeof n=="string"&&n!==""&&!(e.cohorts??[]).includes(n);default:return false}}function w(s,e,t){let n=W(s),r=e===void 0?Number.NaN:W(e);return Number.isNaN(n)||Number.isNaN(r)?false:t(n,r)}function ee(s,e){let t=`${s}:${e}`,n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return (n>>>0)%100}function R(s,e){return s.targeting.length===0||s.targeting.every(t=>Z(t,e))}function te(s,e){let t=ee(s.key,e.distinctId),n=s.variations??[];if(n.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let r=0;for(let i=n.length-1;i>=0;i--)if(r+=n[i].weight,t<r)return n[i].key;return n[0].key}function M(s,e,t,n){for(let r of s.prerequisites??[]){if(n.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;n.push(i.key);let a=M(i,e,t,n)&&R(i,t)&&te(i,t)===r.variationKey;if(n.pop(),!a)return false}return true}function k(s,e,t){return s.enabled?M(s,e,t,[s.key])?R(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ee(s.key,t.distinctId)<s.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function Ge(s,e){return k(s,[],e)}function se(s,e){let t={};for(let n of s)t[n.key]=k(n,s,e).enabled;return t}function x(s,e,t){let n=s.variations??[],r=n[0];if(!r)return null;if(!s.enabled||!M(s,e,t,[s.key])||!R(s,t))return r;let i=te(s,t);return n.find(a=>a.key===i)??r}function We(s,e){return x(s,[],e)}function Ye(s,e,t){let n=s.find(r=>r.key===e);return n?x(n,s,t)?.value??null:null}function ne(s){return s.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}var F=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,n=b$1(),r=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function S(s){if(typeof s!="string")return;let e=Array.from(s).length;return e>=1&&e<=200?s:void 0}function T(s,e){return `pdx.${s}.${e}`}var re="consent";function be(s){if(typeof s!="string")return null;try{let e=JSON.parse(s);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function ke(s,e){return be(s.getItem(T(e,re)))}function xe(s,e,t){let n=T(e,re);if(typeof t.identityLink!="boolean"){s.removeItem(n);return}s.setItem(n,JSON.stringify({identityLink:t.identityLink}));}function nt(s,e,t,n){let r=T(t,"anonymous_id"),i=S(e.getItem(r))??S(s.getItem(r));return e.setItem(r,n),s.setItem(r,n),i!==void 0&&i!==n?i:void 0}var E=class{constructor(e,t,n,r){this.storage=e;this.shared=t;this.ids=n;this.namespace=r;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");this.refresh();}refresh(){let e=S(this.shared.getItem(this.key("anonymous_id"))),t=S(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let n=S(this.storage.getItem(this.key("distinct_id")));n?(this.distinctId=n,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return ke(this.shared,this.namespace)}setConsent(e){xe(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,n=this.storage.getItem(this.key("linked_anonymous_id")),r=t||n!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return T(this.namespace,e)}};var _=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),n=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,n,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new l(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let n=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(n,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,n){let r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...n,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var c={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",screen:"$screen",set:"$set"},Se=[{emittedBy:"web",meaning:"A click anywhere on the page, with the element that was clicked. The web SDK sends it by default; autocapture: false or autocaptureOptions.clicks: false turns it off.",name:c.autocapture,properties:["$event_type","$el_tag","$el_text","$el_id","$el_classes","$el_href","$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A page shown, including every client-side navigation the History API makes: one per distinct path and query.",name:c.pageview,properties:["$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"flutter",meaning:"A named route pushed or replaced in a Flutter app, the mobile counterpart of $pageview.",name:c.screen,properties:["screen"]},{emittedBy:"every",meaning:"A person becomes known by a distinct id. The anonymous trail before it is joined to them, and any traits ride along under $set.",name:c.identify,properties:["$anon_distinct_id","$set"]},{emittedBy:"every",meaning:"A second id for the same person, so events sent under either resolve to one profile.",name:c.createAlias,properties:["alias"]},{emittedBy:"every",meaning:"The person is placed in a group such as a company or a team; group properties ride along under $set.",name:c.group,properties:["$group_type","$group_key","$set"]},{emittedBy:"every",meaning:"Person properties written without an identify: $set overwrites, $set_once fills only what is still empty.",name:c.set,properties:["$set","$set_once"]},{emittedBy:"every",meaning:"A flag was evaluated for this person, sent once per distinct answer. Experiments attribute exposure from it.",name:c.featureFlagCalled,properties:["$feature_flag","$feature_flag_response"]}],dt=s=>s.startsWith("$"),ut=s=>Se.find(e=>e.name===s);function ie(s){return s>=400&&s<500&&s!==429}var C=class{constructor(e={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=a$1(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??c$1,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let n=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,n);if(a.ok)return;if(ie(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);r=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&ie(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,n){let r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:n,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};function oe(s,e,t){B(s.eventName),U(s.distinctId);let n={distinct_id:s.distinctId,event_id:s.eventId??t.uuid(),event_name:s.eventName,properties:s.properties??{},schema_version:1,timestamp:I(s.timestamp??e.now())};return s.context&&(n.context=s.context),s.sessionId&&(n.session_id=s.sessionId),n}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,A=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"pending",null);a(this,"lastKey","");a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??Fe,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ie}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c$2(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$2());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let n=t.payload?.key;this.lastKey=typeof n=="string"?n:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},we));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Fe(s){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(s)}var $=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;a(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var Ee={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function ae(s){return `pdx.${s}.session`}function Ft(s,e,t,n){let r={id:t.id,lastActivityAt:n,startedAt:t.startedAt};s.setItem(ae(e),JSON.stringify(r));}var P=class{constructor(e,t,n,r,i=Ee){this.storage=e;this.ids=t;this.clock=n;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let n=this.live(this.read(),e),r=n!==void 0&&n.id!==t.id?n:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return ae(this.namespace)}};var Te="queue",_e=1e3,le=3e4,q=s=>{let e={};return s.avatar!==void 0&&(e.$avatar=s.avatar),s.email!==void 0&&(e.$email=s.email),s.name!==void 0&&(e.$name=s.name),s.phone!==void 0&&(e.$phone=s.phone),e},N=class{constructor(e){a(this,"config");a(this,"identity");a(this,"session");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");a(this,"membershipCache");a(this,"stream");a(this,"shutDown",false);a(this,"exposures",new Set);this.config=G(e),this.identity=new E(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new P(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new $(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new p("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new C({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new _({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let n={...this.config.defaultProperties(),...t.properties??{}},r=oe({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:n,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(n){this.config.onError(n);}}identify(e,t={}){this.identity.refresh();let n=this.identity.identify(e),r={};n.anonymousToLink!==void 0&&(r.$anon_distinct_id=n.anonymousToLink);let i={...q(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{properties:r});}link(e,t,n){let r={$anon_distinct_id:t},i=q(n??{});Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(c.createAlias,{properties:{alias:e}});}group(e,t,n){let r={$group_key:t,$group_type:e};n&&(r.$set=n),this.capture(c.group,{properties:r});}setPersonProperties(e,t){let n={};e&&(n.$set=e),t&&(n.$set_once=t),this.capture(c.set,{properties:n});}setPersonTraits(e){let t=q(e);Object.keys(t).length!==0&&this.capture(c.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let n=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(n)),n}async getVariant(e){let t=await this.getAllFlags(),n=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,n?.key??String(t[e]??false)),n}async getVariantLocal(e,t={}){let n=await this.flagSnapshot(),r=n.flags.find(ce=>ce.key===e),i=await this.localContext(t,n.flags),a=r?x(r,n.flags,i):null,d=r?k(r,n.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let n=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(n)||(this.exposures.add(n),this.capture(c.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return se(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let n=await this.flagSnapshot(),r=n.flags.find(d=>d.key===e),i=await this.localContext(t,n.flags),a=r?k(r,n.flags,i).enabled:false;return this.recordExposure(e,(r?x(r,n.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let n=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&ne(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&i-this.membershipCache.fetchedAt<le?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(n),this.membershipCache={cohorts:r,distinctId:n,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:n,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<le)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new A({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(n=>this.config.onError(n));},onClosed:n=>{this.stream=void 0,n&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(_e);try{await this.transport.send({body:{events:e,sent_at:I(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Te}`}};function Dt(s){return new N(s)}export{ut as A,C as B,N as C,Dt as D,p as a,b,y as c,l as d,v as e,$e as f,V as g,ge as h,j as i,J as j,z as k,ye as l,Z as m,ee as n,Ge as o,se as p,We as q,Ye as r,F as s,be as t,nt as u,_ as v,Ft as w,c as x,Se as y,dt as z};//# sourceMappingURL=chunk-ESOQKMEE.js.map
2
+ //# sourceMappingURL=chunk-ESOQKMEE.js.map
@@ -6,6 +6,8 @@ interface ChatTurn {
6
6
  authorId: string | null;
7
7
  body: string;
8
8
  createdAt: string;
9
+ authorName?: string | null;
10
+ authorAvatarUrl?: string | null;
9
11
  }
10
12
  interface ChatThread {
11
13
  id: string;
@@ -43,6 +45,7 @@ declare class ChatClient {
43
45
  private identity;
44
46
  constructor(options: ChatClientOptions);
45
47
  get hasThread(): boolean;
48
+ avatarUrl(url: string): string;
46
49
  get socketAuth(): {
47
50
  conversationId: string;
48
51
  conversationToken: string;
@@ -56,8 +59,10 @@ declare class ChatClient {
56
59
  private request;
57
60
  }
58
61
 
59
- type MessengerSkin = 'concierge' | 'console' | 'quiet';
60
- type BubbleStyle = 'hairline' | 'outlined' | 'rounded' | 'tailed';
62
+ type MessengerSkin = 'quiet' | 'standard';
63
+ type ComposerShape = 'round' | 'square';
64
+ type BubbleShape = 'rounded' | 'tailed';
65
+ type BubbleFill = 'filled' | 'outlined';
61
66
  type LauncherShape = 'circle' | 'pill' | 'squircle';
62
67
  type LauncherFill = 'filled' | 'outlined';
63
68
  type LauncherContent = 'avatar' | 'glyph' | 'team_faces';
@@ -66,7 +71,9 @@ type NamePlacement = 'above' | 'hidden' | 'inline';
66
71
  type StampPlacement = 'beside_name' | 'none' | 'under_turn';
67
72
  type StampContent = 'time' | 'time_and_latency';
68
73
  interface AppearanceSettings {
69
- bubbleStyle: BubbleStyle;
74
+ bubbleFill: BubbleFill;
75
+ bubbleShape: BubbleShape;
76
+ composerShape: ComposerShape;
70
77
  dayDividers: boolean;
71
78
  launcherContent: LauncherContent;
72
79
  launcherFill: LauncherFill;
@@ -92,8 +99,10 @@ type Availability = {
92
99
  };
93
100
 
94
101
  interface TeamFace {
102
+ name: string;
95
103
  initials: string;
96
104
  tone: string;
105
+ avatarUrl: string | null;
97
106
  }
98
107
 
99
108
  interface MessengerConfig extends AppearanceSettings {
@@ -107,7 +116,7 @@ interface MessengerConfig extends AppearanceSettings {
107
116
  availability: Availability;
108
117
  version: string;
109
118
  starterPrompts: string[];
110
- teamFaces: TeamFace[];
119
+ team: TeamFace[];
111
120
  socketUrl: string;
112
121
  }
113
122
  interface MessengerConfigOptions {
@@ -122,4 +131,4 @@ declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
122
131
  declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
123
132
  declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
124
133
 
125
- export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type LauncherFill as f, type LauncherShape as g, type LauncherSize as h, type MessengerSkin as i, type StampPlacement as j, MESSENGER_CACHE_KEY as k, type MessengerConfigOptions as l, cachedMessengerConfig as m, fetchMessengerConfig as n, resolveAppearance as r };
134
+ export { type AppearanceSettings as A, type BubbleFill as B, type ChatThread as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type PageContext as P, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type BubbleShape as d, ChatClient as e, type ChatStorage as f, type ComposerShape as g, type LauncherFill as h, type LauncherShape as i, type LauncherSize as j, type MessengerSkin as k, type StampPlacement as l, MESSENGER_CACHE_KEY as m, type MessengerConfigOptions as n, cachedMessengerConfig as o, fetchMessengerConfig as p, resolveAppearance as r };
@@ -6,6 +6,8 @@ interface ChatTurn {
6
6
  authorId: string | null;
7
7
  body: string;
8
8
  createdAt: string;
9
+ authorName?: string | null;
10
+ authorAvatarUrl?: string | null;
9
11
  }
10
12
  interface ChatThread {
11
13
  id: string;
@@ -43,6 +45,7 @@ declare class ChatClient {
43
45
  private identity;
44
46
  constructor(options: ChatClientOptions);
45
47
  get hasThread(): boolean;
48
+ avatarUrl(url: string): string;
46
49
  get socketAuth(): {
47
50
  conversationId: string;
48
51
  conversationToken: string;
@@ -56,8 +59,10 @@ declare class ChatClient {
56
59
  private request;
57
60
  }
58
61
 
59
- type MessengerSkin = 'concierge' | 'console' | 'quiet';
60
- type BubbleStyle = 'hairline' | 'outlined' | 'rounded' | 'tailed';
62
+ type MessengerSkin = 'quiet' | 'standard';
63
+ type ComposerShape = 'round' | 'square';
64
+ type BubbleShape = 'rounded' | 'tailed';
65
+ type BubbleFill = 'filled' | 'outlined';
61
66
  type LauncherShape = 'circle' | 'pill' | 'squircle';
62
67
  type LauncherFill = 'filled' | 'outlined';
63
68
  type LauncherContent = 'avatar' | 'glyph' | 'team_faces';
@@ -66,7 +71,9 @@ type NamePlacement = 'above' | 'hidden' | 'inline';
66
71
  type StampPlacement = 'beside_name' | 'none' | 'under_turn';
67
72
  type StampContent = 'time' | 'time_and_latency';
68
73
  interface AppearanceSettings {
69
- bubbleStyle: BubbleStyle;
74
+ bubbleFill: BubbleFill;
75
+ bubbleShape: BubbleShape;
76
+ composerShape: ComposerShape;
70
77
  dayDividers: boolean;
71
78
  launcherContent: LauncherContent;
72
79
  launcherFill: LauncherFill;
@@ -92,8 +99,10 @@ type Availability = {
92
99
  };
93
100
 
94
101
  interface TeamFace {
102
+ name: string;
95
103
  initials: string;
96
104
  tone: string;
105
+ avatarUrl: string | null;
97
106
  }
98
107
 
99
108
  interface MessengerConfig extends AppearanceSettings {
@@ -107,7 +116,7 @@ interface MessengerConfig extends AppearanceSettings {
107
116
  availability: Availability;
108
117
  version: string;
109
118
  starterPrompts: string[];
110
- teamFaces: TeamFace[];
119
+ team: TeamFace[];
111
120
  socketUrl: string;
112
121
  }
113
122
  interface MessengerConfigOptions {
@@ -122,4 +131,4 @@ declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
122
131
  declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
123
132
  declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
124
133
 
125
- export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type LauncherFill as f, type LauncherShape as g, type LauncherSize as h, type MessengerSkin as i, type StampPlacement as j, MESSENGER_CACHE_KEY as k, type MessengerConfigOptions as l, cachedMessengerConfig as m, fetchMessengerConfig as n, resolveAppearance as r };
134
+ export { type AppearanceSettings as A, type BubbleFill as B, type ChatThread as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type PageContext as P, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type BubbleShape as d, ChatClient as e, type ChatStorage as f, type ComposerShape as g, type LauncherFill as h, type LauncherShape as i, type LauncherSize as j, type MessengerSkin as k, type StampPlacement as l, MESSENGER_CACHE_KEY as m, type MessengerConfigOptions as n, cachedMessengerConfig as o, fetchMessengerConfig as p, resolveAppearance as r };
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var le=Object.defineProperty;var de=(n,e,t)=>e in n?le(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var d=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},m=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},h=class extends d{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends d{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function y(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var j=n=>new Promise(e=>{setTimeout(e,n);});function p(n){return n.replace(/\/+$/,"")}var v=class{constructor(){o(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);}};var G={now:()=>new Date};function I(n){return n.toISOString()}function ue(){return globalThis.crypto}function he(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[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 pe(){let n=ue();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return he(e)}var J={uuid:pe};var fe=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ge=/^(?:\$|[a-z])[a-z0-9_.]*$/;function U(n){let e=0;for(let t of n)e+=1;return e}function H(n){return fe.test(n)}function me(n){return ge.test(n)}function z(n){let e=U(n);if(e<1||e>200)throw new h("distinct_id","distinct_id must be between 1 and 200 characters")}function B(n){let e=U(n);if(e<1||e>200)throw new h("event_name","event_name must be between 1 and 200 characters");if(!me(n))throw new h("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var P="prodantix-js",R="0.0.1";var ye=n=>{};function Q(n){if(!n.apiKey||!H(n.apiKey))throw new m("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new m("host is required (the ingest base URL)");let e=p(n.host),t=n.defaultProperties,s=n.storage??new v;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??G,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?p(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??J,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:ve(n.apiKey),onError:n.onError??ye,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??P,sdkVersion:n.sdkVersion??R,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function ve(n){return n.slice(0,16)}function W(n,e,t){B(n.eventName),z(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:I(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function ke(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:g}function f(n){return n===g?"undefined":String(n)}function X(n){return n===g?Number.NaN:Number(n)}function Y(n){return n!==g&&n!==null&&n!==""}function Z(n,e){if(!Array.isArray(e))return false;let t=f(n);return e.map(s=>String(s)).includes(t)}function N(n,e){let t=ke(n.attribute,e),s=n.value;switch(n.op){case "is_set":return Y(t);case "is_not_set":return !Y(t);case "eq":return f(t)===f(s===void 0?g:s);case "neq":return f(t)!==f(s===void 0?g:s);case "contains":return f(t).includes(f(s===void 0?g:s));case "in":return Z(t,s);case "not_in":return Array.isArray(s)?!Z(t,s):false;case "gt":return F(t,s,(r,i)=>r>i);case "gte":return F(t,s,(r,i)=>r>=i);case "lt":return F(t,s,(r,i)=>r<i);case "lte":return F(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function F(n,e,t){let s=X(n),r=e===void 0?Number.NaN:X(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function O(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function M(n,e){return n.targeting.length===0||n.targeting.every(t=>N(t,e))}function ee(n,e){let t=O(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function $(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(l=>l.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=$(i,e,t,s)&&M(i,t)&&ee(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function k(n,e,t){return n.enabled?$(n,e,t,[n.key])?M(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:O(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function be(n,e){return k(n,[],e)}function q(n,e){let t={};for(let s of n)t[s.key]=k(s,n,e).enabled;return t}function b(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!$(n,e,t,[n.key])||!M(n,t))return r;let i=ee(n,t);return s.find(a=>a.key===i)??r}function xe(n,e){return b(n,[],e)}function Ee(n,e,t){let s=n.find(r=>r.key===e);return s?b(s,n,t)?.value??null:null}function te(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ne(n){return `40${JSON.stringify(n)}`}function se(){return "3"}function re(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 a=K(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=K(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=K(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function K(n){try{return JSON.parse(n)}catch{return null}}var Se="/socket.io/?EIO=4&transport=websocket",Ie=250,C=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Fe,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Se}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.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=re(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ne({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(se());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 s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Ie));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Fe(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var x=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=u(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function L(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function D(n,e){return `pdx.${n}.${e}`}var ie="consent";function Ce(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);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 Te(n,e){return Ce(n.getItem(D(e,ie)))}function we(n,e,t){let s=D(e,ie);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var T=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=L(this.shared.getItem(this.key("anonymous_id"))),t=L(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 s=L(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,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 Te(this.shared,this.namespace)}setConsent(e){we(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return D(this.namespace,e)}};var E=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var w=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(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 _e={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Ae(n){return `pdx.${n}.session`}var _=class{constructor(e,t,s,r,i=_e){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return Ae(this.namespace)}};function oe(n){return n>=400&&n<500&&n!==429}var S=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=y(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??j,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(oe(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&oe(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Pe="queue",Re=1e3,ae=3e4,V=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},A=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Q(e),this.identity=new T(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 _(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new w(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new d("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new S({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({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 s={...this.config.defaultProperties(),...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...V(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=V(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture("$group",{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture("$set",{properties:s});}setPersonTraits(e){let t=V(e);Object.keys(t).length!==0&&this.capture("$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 s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(ce=>ce.key===e),i=await this.localContext(t,s.flags),a=r?b(r,s.flags,i):null,l=r?k(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture("$feature_flag_called",{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 q(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(l=>l.key===e),i=await this.localContext(t,s.flags),a=r?k(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?b(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&te(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<ae?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ae)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 C({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&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(Re);try{await this.transport.send({body:{events:e,sent_at:I(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Pe}`}};function Ne(n){return new A(n)}exports.ConfigError=m;exports.FetchTransport=S;exports.FlagsClient=x;exports.MemoryStorage=v;exports.MessagesClient=E;exports.ProdantixClient=A;exports.ProdantixError=d;exports.SDK_NAME=P;exports.SDK_VERSION=R;exports.TransportError=c;exports.ValidationError=h;exports.assignVariant=xe;exports.bucket=O;exports.createClient=Ne;exports.evaluateAll=q;exports.evaluateFlag=be;exports.getVariant=Ee;exports.matches=N;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var ue=Object.defineProperty;var pe=(n,e,t)=>e in n?ue(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>pe(n,typeof e!="symbol"?e+"":e,t);var u=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},h=class extends u{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},l=class extends u{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function v(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function p(){let n=globalThis.AbortController;return n?new n:void 0}var G=n=>new Promise(e=>{setTimeout(e,n);});function f(n){return n.replace(/\/+$/,"")}var k=class{constructor(){o(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);}};var J={now:()=>new Date};function F(n){return n.toISOString()}function he(){return globalThis.crypto}function fe(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[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 n=he();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return fe(e)}var H={uuid:ge};var me=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ye=/^(?:\$|[a-z])[a-z0-9_.]*$/;function U(n){let e=0;for(let t of n)e+=1;return e}function B(n){return me.test(n)}function ve(n){return ye.test(n)}function z(n){let e=U(n);if(e<1||e>200)throw new h("distinct_id","distinct_id must be between 1 and 200 characters")}function Q(n){let e=U(n);if(e<1||e>200)throw new h("event_name","event_name must be between 1 and 200 characters");if(!ve(n))throw new h("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var $="prodantix-js",N="0.0.1";var ke=n=>{};function Y(n){if(!n.apiKey||!B(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=f(n.host),t=n.defaultProperties,s=n.storage??new k;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??J,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?f(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??H,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:be(n.apiKey),onError:n.onError??ke,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??$,sdkVersion:n.sdkVersion??N,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function be(n){return n.slice(0,16)}function W(n,e,t){Q(n.eventName),z(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:F(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var m=Symbol("absent");function Ee(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:m}function g(n){return n===m?"undefined":String(n)}function X(n){return n===m?Number.NaN:Number(n)}function Z(n){return n!==m&&n!==null&&n!==""}function ee(n,e){if(!Array.isArray(e))return false;let t=g(n);return e.map(s=>String(s)).includes(t)}function R(n,e){let t=Ee(n.attribute,e),s=n.value;switch(n.op){case "is_set":return Z(t);case "is_not_set":return !Z(t);case "eq":return g(t)===g(s===void 0?m:s);case "neq":return g(t)!==g(s===void 0?m:s);case "contains":return g(t).includes(g(s===void 0?m:s));case "in":return ee(t,s);case "not_in":return Array.isArray(s)?!ee(t,s):false;case "gt":return C(t,s,(r,i)=>r>i);case "gte":return C(t,s,(r,i)=>r>=i);case "lt":return C(t,s,(r,i)=>r<i);case "lte":return C(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function C(n,e,t){let s=X(n),r=e===void 0?Number.NaN:X(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function M(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function O(n,e){return n.targeting.length===0||n.targeting.every(t=>R(t,e))}function te(n,e){let t=M(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function q(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=q(i,e,t,s)&&O(i,t)&&te(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function b(n,e,t){return n.enabled?q(n,e,t,[n.key])?O(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:M(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function xe(n,e){return b(n,[],e)}function K(n,e){let t={};for(let s of n)t[s.key]=b(s,n,e).enabled;return t}function E(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!q(n,e,t,[n.key])||!O(n,t))return r;let i=te(n,t);return s.find(a=>a.key===i)??r}function Se(n,e){return E(n,[],e)}function Ie(n,e,t){let s=n.find(r=>r.key===e);return s?E(s,n,t)?.value??null:null}function ne(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function se(n){return `40${JSON.stringify(n)}`}function re(){return "3"}function ie(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 a=L(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=L(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=L(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function L(n){try{return JSON.parse(n)}catch{return null}}var Fe="/socket.io/?EIO=4&transport=websocket",Ce=250,T=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Te,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Fe}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.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=ie(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(se({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(re());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 s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Ce));}}}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 Te(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var x=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=v(e.fetch),this.host=f(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=p(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function D(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function V(n,e){return `pdx.${n}.${e}`}var oe="consent";function we(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);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 _e(n,e){return we(n.getItem(V(e,oe)))}function Ae(n,e,t){let s=V(e,oe);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var w=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=D(this.shared.getItem(this.key("anonymous_id"))),t=D(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 s=D(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,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 _e(this.shared,this.namespace)}setConsent(e){Ae(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return V(this.namespace,e)}};var S=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=v(e.fetch),this.host=f(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new l(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var _=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(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 Pe={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function $e(n){return `pdx.${n}.session`}var A=class{constructor(e,t,s,r,i=Pe){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return $e(this.namespace)}};var c={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",screen:"$screen",set:"$set"},ae=[{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"]}],Ne=n=>n.startsWith("$"),Re=n=>ae.find(e=>e.name===n);function le(n){return n>=400&&n<500&&n!==429}var I=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=v(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??G,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(le(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);r=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&le(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Me="queue",Oe=1e3,ce=3e4,j=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},P=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Y(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 _(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new I({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new S({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 s={...this.config.defaultProperties(),...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...j(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=j(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(c.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(c.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(c.set,{properties:s});}setPersonTraits(e){let t=j(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 s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(de=>de.key===e),i=await this.localContext(t,s.flags),a=r?E(r,s.flags,i):null,d=r?b(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),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 K(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(d=>d.key===e),i=await this.localContext(t,s.flags),a=r?b(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?E(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&ne(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<ce?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ce)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 T({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&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(Oe);try{await this.transport.send({body:{events:e,sent_at:F(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}.${Me}`}};function qe(n){return new P(n)}exports.ConfigError=y;exports.FetchTransport=I;exports.FlagsClient=x;exports.MemoryStorage=k;exports.MessagesClient=S;exports.ProdantixClient=P;exports.ProdantixError=u;exports.SDK_NAME=$;exports.SDK_VERSION=N;exports.SYSTEM_EVENT=c;exports.SYSTEM_EVENTS=ae;exports.TransportError=l;exports.ValidationError=h;exports.assignVariant=Se;exports.bucket=M;exports.createClient=qe;exports.evaluateAll=K;exports.evaluateFlag=xe;exports.getVariant=Ie;exports.isSystemEventName=Ne;exports.matches=R;exports.systemEvent=Re;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map