@prodantix/sdk 0.6.0 → 0.7.0-beta.437

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.
Files changed (39) hide show
  1. package/README.md +19 -0
  2. package/dist/chat.cjs +19 -18
  3. package/dist/chat.d.cts +125 -7
  4. package/dist/chat.d.ts +125 -7
  5. package/dist/chat.js +21 -20
  6. package/dist/chunk-D6PMLUYA.js +2 -0
  7. package/dist/{client-BO7f6q5k.d.cts → client-CL6Xvhay.d.cts} +2 -1
  8. package/dist/{client-BQlU_3Dc.d.ts → client-QyKW0LFW.d.ts} +2 -1
  9. package/dist/{config-DqC0lcr7.d.ts → config-6ulvfBFp.d.ts} +33 -1
  10. package/dist/{config-CMF9zz1a.d.cts → config-g14Jiv1t.d.cts} +33 -1
  11. package/dist/csp.cjs +2 -2
  12. package/dist/csp.d.cts +9 -10
  13. package/dist/csp.d.ts +9 -10
  14. package/dist/csp.js +2 -2
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.d.cts +5 -5
  17. package/dist/index.d.ts +5 -5
  18. package/dist/index.js +1 -1
  19. package/dist/messenger-files.iife.js +2 -0
  20. package/dist/messenger-help.iife.js +3 -0
  21. package/dist/messenger.cjs +1 -1
  22. package/dist/messenger.d.cts +1 -1
  23. package/dist/messenger.d.ts +1 -1
  24. package/dist/messenger.iife.js +7 -6
  25. package/dist/messenger.js +1 -1
  26. package/dist/node.cjs +1 -1
  27. package/dist/node.d.cts +2 -2
  28. package/dist/node.d.ts +2 -2
  29. package/dist/node.js +1 -1
  30. package/dist/{transport-CqAmRbpQ.d.ts → transport-DKFvkfX4.d.ts} +1 -1
  31. package/dist/{transport-Cy42FY5A.d.cts → transport-DN9pXyrX.d.cts} +1 -1
  32. package/dist/{types-DjMXp6Wg.d.cts → types-Q2VNlJbG.d.cts} +1 -0
  33. package/dist/{types-DjMXp6Wg.d.ts → types-Q2VNlJbG.d.ts} +1 -0
  34. package/dist/web.cjs +1 -1
  35. package/dist/web.d.cts +9 -4
  36. package/dist/web.d.ts +9 -4
  37. package/dist/web.js +1 -1
  38. package/package.json +1 -1
  39. package/dist/chunk-4RLPQZ5L.js +0 -2
@@ -1,10 +1,10 @@
1
- (function(){'use strict';var de=Object.defineProperty;var pe=(n,e,t)=>e in n?de(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var m=(n,e,t)=>pe(n,typeof e!="symbol"?e+"":e,t);var P=class extends Error{constructor(t,r,i){super(r,i);m(this,"code");this.code=t,this.name="ProdantixError";}},N=class extends P{constructor(e){super("config",e),this.name="ConfigError";}};var C=class extends P{constructor(t,r,i){super("transport",t,i);m(this,"status");this.status=r,this.name="TransportError";}};function _(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function F(n){return n.replace(/\/+$/,"")}var j="X-Prodantix-Conversation-Token",O="prodantix.chat.handle";function ue(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var I=class{constructor(e){this.options=e;m(this,"fetchImpl");m(this,"fileFetchImpl");m(this,"host");m(this,"storage");m(this,"handle");m(this,"identity",null);var t,r;this.fetchImpl=_(e.fetchImpl),this.fileFetchImpl=(t=e.fileFetchImpl)!=null?t:((i,o)=>fetch(i,o)),this.host=F(e.host),this.storage=(r=e.storage)!=null?r:ue(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,i,o;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(o=this.storage)==null||o.set(O,JSON.stringify(this.handle)),true)}async send(e,t,r){var a;if(!await this.ensureThread())return null;let i=this.handle;if(!i)return null;let o=await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token});return (a=o==null?void 0:o.turn)!=null?a:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r,i,o;let e=(t=this.storage)==null?void 0:t.get(O);if(!e)return null;try{let a=JSON.parse(e);if(typeof a.conversationId=="string"&&typeof a.token=="string")return {conversationId:a.conversationId,token:a.token}}catch(a){(i=(r=this.options).onError)==null||i.call(r,a);}return (o=this.storage)==null||o.remove(O),null}async fileRequest(e,t,r,i,o){var s,d,p,c;let a={authorization:`Bearer ${this.options.apiKey}`,[j]:r};o&&(a["content-type"]=o.type||"application/octet-stream");try{let l=await this.fileFetchImpl(`${this.host}${t}`,{body:o,headers:a,method:e});if(l.ok)return await i(l);(d=(s=this.options).onError)==null||d.call(s,new C(`prodantix chat ${t}: ${l.status}`,l.status));}catch(l){(c=(p=this.options).onError)==null||c.call(p,l);}return null}async request(e,t,r={}){var a,s,d,p,c,l;let i=this.fetchImpl;if(!i)return (s=(a=this.options).onError)==null||s.call(a,new C("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(o[j]=r.token);try{let u=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:o,method:e}),g=await u.text();return u.ok?g?JSON.parse(g):{}:((p=(d=this.options).onError)==null||p.call(d,new C(`prodantix chat ${t}: ${u.status}`,u.status)),null)}catch(u){return (l=(c=this.options).onError)==null||l.call(c,u),null}}};var he={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function M(n,e){var s,d,p,c,l,u;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=he[(d=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?d:""];if(!r)return false;let i=(c=(p=t.find(g=>g.type==="hour"))==null?void 0:p.value)!=null?c:"",o=(u=(l=t.find(g=>g.type==="minute"))==null?void 0:l.value)!=null?u:"",a=`${i}:${o}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=a&&a<g.close)}var k={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},me=["quiet","standard"],ge=["round","square"],fe=["rounded","tailed"],be=["filled","outlined"],xe=["circle","pill","squircle"],ye=["filled","outlined"],ve=["avatar","glyph","team_faces"],Se=["large","medium","small"],ke=["above","hidden","inline"],Ce=["beside_name","none","under_turn"],Ee=["time","time_and_latency"],E=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,W=(n,e)=>typeof n=="boolean"?n:e,we={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},Te={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Ae={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},Le={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Pe={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function H(n){var g,v,S,f,b,h,x,w,y,T,K,G,q;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:we[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=i===void 0?void 0:Te[i],a=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=a===void 0?void 0:Ae[a],d=typeof e.skin=="string"?e.skin:void 0,p=d===void 0?void 0:Le[d],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,l=c===void 0?void 0:Pe[c],u={bubbleFill:E(e.bubbleFill,be,(g=l==null?void 0:l[1])!=null?g:k.bubbleFill),bubbleShape:E(e.bubbleShape,fe,(v=l==null?void 0:l[0])!=null?v:k.bubbleShape),composerShape:E(e.composerShape,ge,(S=p==null?void 0:p[1])!=null?S:k.composerShape),dayDividers:W(e.dayDividers,(f=s==null?void 0:s[0])!=null?f:k.dayDividers),launcherContent:E(e.launcherContent,ve,(b=r==null?void 0:r[2])!=null?b:k.launcherContent),launcherFill:E(e.launcherFill,ye,(h=r==null?void 0:r[1])!=null?h:k.launcherFill),launcherShape:E(e.launcherShape,xe,(x=r==null?void 0:r[0])!=null?x:k.launcherShape),launcherSize:E(e.launcherSize,Se,(w=r==null?void 0:r[3])!=null?w:k.launcherSize),nameAvatar:W(e.nameAvatar,(y=o==null?void 0:o[1])!=null?y:k.nameAvatar),namePlacement:E(e.namePlacement,ke,(T=o==null?void 0:o[0])!=null?T:k.namePlacement),skin:E(e.skin,me,(K=p==null?void 0:p[0])!=null?K:k.skin),stampContent:E(e.stampContent,Ee,(G=s==null?void 0:s[2])!=null?G:k.stampContent),stampPlacement:E(e.stampPlacement,Ce,(q=s==null?void 0:s[1])!=null?q:k.stampPlacement)};return u.stampPlacement==="beside_name"&&u.namePlacement==="hidden"&&(u.stampPlacement="under_turn"),u}function Y(n){var r,i,o,a;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(i=e[1])==null?void 0:i.slice(0,1)}`:(a=(o=e[0])==null?void 0:o.slice(0,2))!=null?a:"").toUpperCase()}var Ne="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",_e={large:66,medium:56,small:46},Fe={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;"},Ie={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},Me={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},He=".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}",$e={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}"},Oe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Ue={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function J(n,e,t,r){return `.launcher{--fab-size:${_e[r]}px;${Fe[n]}${Ie[e]}}${Me[t]}${He}${$e[n]}${Re[e]}${Oe[n]}${Ue[n]}`}function X(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="glyph"||t.length===0){let o=document.createElement("span");return o.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${Ne}"/></svg>`,i.append(...o.childNodes,U()),i}return n==="avatar"?(i.append(V(t[0],e,r),U()),i):(i.append(z(t,e,r),U()),i)}function z(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(V(i,e,t));return r}function V(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function U(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var ze={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},A={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...k},Be={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},De={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Ke={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Ge={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},qe={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},je=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",We='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Ye={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Je=".lat{font-size:11px;opacity:.7;margin-left:6px}",Xe=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}";function Ve(n){let e=n==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${e+26}px}.composer button.clip{position:absolute;top:50%;left:${e-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}function B(n){return n<999500?`${Math.max(1,Math.round(n/1e3))} KB`:`${(n/1e6).toFixed(1)} MB`}var Q=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
1
+ (function(){'use strict';var ce=Object.defineProperty;var de=(n,e,t)=>e in n?ce(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var h=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var P=class extends Error{constructor(t,r,i){super(r,i);h(this,"code");this.code=t,this.name="ProdantixError";}},N=class extends P{constructor(e){super("config",e),this.name="ConfigError";}};var E=class extends P{constructor(t,r,i){super("transport",t,i);h(this,"status");this.status=r,this.name="TransportError";}};function _(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function F(n){return n.replace(/\/+$/,"")}var q="X-Prodantix-Conversation-Token",O="prodantix.chat.handle";function pe(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var H=class{constructor(e){this.options=e;h(this,"fetchImpl");h(this,"fileFetchImpl");h(this,"host");h(this,"storage");h(this,"handle");h(this,"identity",null);var t,r;this.fetchImpl=_(e.fetchImpl),this.fileFetchImpl=(t=e.fileFetchImpl)!=null?t:((i,a)=>fetch(i,a)),this.host=F(e.host),this.storage=(r=e.storage)!=null?r:pe(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,i,a;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(a=this.storage)==null||a.set(O,JSON.stringify(this.handle)),true)}async send(e,t,r){var o;if(!await this.ensureThread())return null;let i=this.handle;if(!i)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token});return (o=a==null?void 0:a.turn)!=null?o:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async helpCentre(e,t){let r=Object.entries({...t,...this.options.locale?{lang:this.options.locale}:{}}).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return this.request("GET",`/v1/messenger/articles${e}${r?`?${r}`:""}`)}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r,i,a;let e=(t=this.storage)==null?void 0:t.get(O);if(!e)return null;try{let o=JSON.parse(e);if(typeof o.conversationId=="string"&&typeof o.token=="string")return {conversationId:o.conversationId,token:o.token}}catch(o){(i=(r=this.options).onError)==null||i.call(r,o);}return (a=this.storage)==null||a.remove(O),null}async fileRequest(e,t,r,i,a){var s,p,d,l;let o={authorization:`Bearer ${this.options.apiKey}`,[q]:r};a&&(o["content-type"]=a.type||"application/octet-stream");try{let c=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:o,method:e});if(c.ok)return await i(c);(p=(s=this.options).onError)==null||p.call(s,new E(`prodantix chat ${t}: ${c.status}`,c.status));}catch(c){(l=(d=this.options).onError)==null||l.call(d,c);}return null}async request(e,t,r={}){var o,s,p,d,l,c;let i=this.fetchImpl;if(!i)return (s=(o=this.options).onError)==null||s.call(o,new E("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[q]=r.token);try{let m=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),g=await m.text();return m.ok?g?JSON.parse(g):{}:((d=(p=this.options).onError)==null||d.call(p,new E(`prodantix chat ${t}: ${m.status}`,m.status)),null)}catch(m){return (c=(l=this.options).onError)==null||c.call(l,m),null}}};var ue={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function I(n,e){var s,p,d,l,c,m;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=ue[(p=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?p:""];if(!r)return false;let i=(l=(d=t.find(g=>g.type==="hour"))==null?void 0:d.value)!=null?l:"",a=(m=(c=t.find(g=>g.type==="minute"))==null?void 0:c.value)!=null?m:"",o=`${i}:${a}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=o&&o<g.close)}var k={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},he=["quiet","standard"],me=["round","square"],ge=["rounded","tailed"],fe=["filled","outlined"],be=["circle","pill","squircle"],ye=["filled","outlined"],xe=["avatar","glyph","team_faces"],ve=["large","medium","small"],Se=["above","hidden","inline"],Ce=["beside_name","none","under_turn"],ke=["time","time_and_latency"],T=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,j=(n,e)=>typeof n=="boolean"?n:e,Ee={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},Te={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},we={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},Ae={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Le={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function M(n){var g,C,S,f,y,u,v,b,x,w,B,D,G;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:Ee[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:Te[i],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:we[o],p=typeof e.skin=="string"?e.skin:void 0,d=p===void 0?void 0:Ae[p],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=l===void 0?void 0:Le[l],m={bubbleFill:T(e.bubbleFill,fe,(g=c==null?void 0:c[1])!=null?g:k.bubbleFill),bubbleShape:T(e.bubbleShape,ge,(C=c==null?void 0:c[0])!=null?C:k.bubbleShape),composerShape:T(e.composerShape,me,(S=d==null?void 0:d[1])!=null?S:k.composerShape),dayDividers:j(e.dayDividers,(f=s==null?void 0:s[0])!=null?f:k.dayDividers),launcherContent:T(e.launcherContent,xe,(y=r==null?void 0:r[2])!=null?y:k.launcherContent),launcherFill:T(e.launcherFill,ye,(u=r==null?void 0:r[1])!=null?u:k.launcherFill),launcherShape:T(e.launcherShape,be,(v=r==null?void 0:r[0])!=null?v:k.launcherShape),launcherSize:T(e.launcherSize,ve,(b=r==null?void 0:r[3])!=null?b:k.launcherSize),nameAvatar:j(e.nameAvatar,(x=a==null?void 0:a[1])!=null?x:k.nameAvatar),namePlacement:T(e.namePlacement,Se,(w=a==null?void 0:a[0])!=null?w:k.namePlacement),skin:T(e.skin,he,(B=d==null?void 0:d[0])!=null?B:k.skin),stampContent:T(e.stampContent,ke,(D=s==null?void 0:s[2])!=null?D:k.stampContent),stampPlacement:T(e.stampPlacement,Ce,(G=s==null?void 0:s[1])!=null?G:k.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function W(n){var r,i,a,o;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(i=e[1])==null?void 0:i.slice(0,1)}`:(o=(a=e[0])==null?void 0:a.slice(0,2))!=null?o:"").toUpperCase()}var Pe="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",Ne={large:66,medium:56,small:46},_e={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},Fe={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},He={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},Ie=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",Me={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Re={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},$e={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Oe={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function Y(n,e,t,r){return `.launcher{--fab-size:${Ne[r]}px;${_e[n]}${Fe[e]}}${He[t]}${Ie}${Me[n]}${Re[e]}${$e[n]}${Oe[n]}`}function J(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${Pe}"/></svg>`,i.append(...a.childNodes,K()),i}return n==="avatar"?(i.append(X(t[0],e,r),K()),i):(i.append(U(t,e,r),K()),i)}function U(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(X(i,e,t));return r}function X(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function K(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Ke={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},L={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...k},Ue={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},ze={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Be={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},De={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ge={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},qe=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",je='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',We={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Ye=".lat{font-size:11px;opacity:.7;margin-left:6px}",V=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
2
2
  --fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
3
- --online: oklch(72% 0.13 163.23);`;function Qe(n){return n==="light"?"":n==="dark"?`:host { ${Q} }`:`@media (prefers-color-scheme: dark) {
3
+ --online: oklch(72% 0.13 163.23);`;function Je(n){return n==="light"?"":n==="dark"?`:host { ${V} }`:`@media (prefers-color-scheme: dark) {
4
4
  :host {
5
- ${Q}
5
+ ${V}
6
6
  }
7
- }`}var Ze=/https?:\/\/[^\s<>"]+/g,et=/[.,;:!?)]$/,tt=n=>{let e=n;for(;et.test(e);){let t=e.split("(").length-1,r=e.split(")").length-1;if(e.endsWith(")")&&t>=r)break;e=e.slice(0,-1);}return e};function nt(n,e){var r;let t=0;for(let i of e.matchAll(Ze)){let o=(r=i.index)!=null?r:0,a=tt(i[0]);o>t&&n.append(e.slice(t,o));let s=document.createElement("a");s.href=a,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,n.append(s),t=o+a.length;}t<e.length&&n.append(e.slice(t));}var rt=["P","BR","STRONG","EM","A","UL","OL","LI"],it=n=>typeof n=="object"&&n!==null&&"html"in n&&typeof n.html=="string"&&"text"in n&&typeof n.text=="string",at=(n,e)=>e.name==="class"||e.name==="data-block-type"?true:n!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),ot=n=>[...n.querySelectorAll("*")].every(e=>rt.includes(e.tagName)&&[...e.attributes].every(t=>at(e.tagName,t)));function Z(n,e="system"){var a;let t=H(n),r=n.launcherPosition==="bottom_left"?"left":"right",i=n.accentColor;return `${`
7
+ }`}var Xe=/https?:\/\/[^\s<>"]+/g,Ve=/[.,;:!?)]$/,Qe=n=>{let e=n;for(;Ve.test(e);){let t=e.split("(").length-1,r=e.split(")").length-1;if(e.endsWith(")")&&t>=r)break;e=e.slice(0,-1);}return e};function Ze(n,e){var r;let t=0;for(let i of e.matchAll(Xe)){let a=(r=i.index)!=null?r:0,o=Qe(i[0]);a>t&&n.append(e.slice(t,a));let s=document.createElement("a");s.href=o,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o,n.append(s),t=a+o.length;}t<e.length&&n.append(e.slice(t));}var et=["P","BR","STRONG","EM","A","UL","OL","LI"],tt=n=>typeof n=="object"&&n!==null&&"html"in n&&typeof n.html=="string"&&"text"in n&&typeof n.text=="string",nt=(n,e)=>e.name==="class"||e.name==="data-block-type"?true:n!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),rt=n=>[...n.querySelectorAll("*")].every(e=>et.includes(e.tagName)&&[...e.attributes].every(t=>nt(e.tagName,t)));function it(n,e="system"){let t=M(n),r=n.launcherPosition==="bottom_left"?"left":"right",i=n.accentColor;return `${`
8
8
  :host {
9
9
  all: initial; z-index: 2147483000; --a: ${i};
10
10
  --paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
@@ -12,7 +12,7 @@
12
12
  --online: oklch(53.8% 0.1274 163.23);
13
13
  color-scheme: ${e==="system"?"light dark":e};
14
14
  }
15
- ${Qe(e)}
15
+ ${Je(e)}
16
16
  * { box-sizing: border-box; font-family: system-ui, sans-serif; }
17
17
  .launcher {
18
18
  z-index: 2147483000; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
@@ -102,5 +102,6 @@ ${Qe(e)}
102
102
  .panel { animation: rise 180ms ease-out; }
103
103
  @keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
104
104
  }
105
- `}${De[t.composerShape]}${Be[t.skin]}${J(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ke[t.bubbleShape]}${Ge[t.bubbleFill]}${qe[t.namePlacement]}${t.nameAvatar?je:""}${t.dayDividers?We:""}${Ye[t.stampPlacement]}${t.stampContent==="time_and_latency"?Je:""}${Xe}${(a=n.attachments)!=null&&a.enabled?Ve(t.composerShape):""}`}var st=["end_user","agent","ai"];function lt(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var ct='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>',dt='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',$=class{constructor(e,t,r={},i={},o={}){this.host=e;this.client=t;m(this,"root");m(this,"strings");m(this,"settings");m(this,"appearance");m(this,"launcher");m(this,"badge");m(this,"panel",null);m(this,"lastFocused",null);m(this,"unread",0);m(this,"pendingTurns",0);m(this,"openNow");m(this,"style");m(this,"scheme");m(this,"picked",null);m(this,"objectUrls",[]);var a;this.strings={...ze,...r},this.appearance={...A,...i},this.settings=H({...A,...i}),this.root=e.attachShadow({mode:(a=o.shadowMode)!=null?a:"closed"}),this.openNow=M(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=Z(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(X(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={...A,...e},this.settings=H(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=Z(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var f;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=(f=this.appearance.team)!=null?f:[];r.length>0&&t.append(z(r,this.strings,b=>this.client.avatarUrl(b)));let i=document.createElement("div");i.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let a=document.createElement("p");a.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),a.append(s,this.strings.replyTime),i.append(o,a);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=dt,d.addEventListener("click",()=>this.close()),t.append(i,d);let p=document.createElement("div");p.className="log",p.setAttribute("role","log"),p.setAttribute("aria-live","polite"),p.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let l=document.createElement("input");l.type="text",l.setAttribute("aria-label",this.strings.inputPlaceholder),l.placeholder=this.strings.inputPlaceholder;let u=document.createElement("button");u.type="submit",u.setAttribute("aria-label",this.strings.sendLabel),u.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let g=document.createElement("span");g.className="sendtext",g.textContent=this.strings.sendLabel,u.append(g);let v=this.appearance.attachments;if(v!=null&&v.enabled&&this.client.upload){let b=document.createElement("span");b.className="field";let h=document.createElement("input");h.type="file",h.accept=v.accept.join(","),h.hidden=true,h.addEventListener("change",()=>{var y;let w=(y=h.files)==null?void 0:y[0];h.value="",w&&this.pick(p,c,v,w);});let x=document.createElement("button");x.type="button",x.className="clip",x.setAttribute("aria-label",this.strings.attachLabel),x.innerHTML=ct,x.addEventListener("click",()=>h.click()),b.append(x,l,h),c.append(b,u);}else c.append(l,u);c.addEventListener("submit",b=>{b.preventDefault(),this.submit(l,p);}),e.append(t,p,c),e.addEventListener("keydown",b=>this.onKeydown(b,e,d)),this.root.append(e),this.panel=e,l.focus();let S=await this.client.load();S&&S.turns.length>0?this.renderThread(p,S):this.renderFirstRun(p,l),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,r.append(i,o),this.appearance.starterPrompts.filter(it).forEach((s,d)=>{let p=document.createElement("div");p.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${d}`;let l=document.createElement("template");l.innerHTML=s.html,ot(l.content)?c.append(l.content):c.textContent=s.text;for(let g of c.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let u=document.createElement("button");u.className="promptpress",u.type="button",u.setAttribute("aria-labelledby",c.id),u.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),p.append(c,u),r.append(p);}),e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}pick(e,t,r,i){let o=i.size>r.maxBytes||!r.accept.includes(i.type);for(let l of this.root.querySelectorAll(o?".ferr":".file,.ferr"))l.remove();if(o){let l=document.createElement("p");l.className="ferr",l.setAttribute("role","alert"),l.textContent=this.strings.fileRefusal(B(i.size),`${r.maxBytes/1e6} MB`),t.before(l),e.scrollTop=e.scrollHeight;return}this.picked=i;let a=document.createElement("span");a.className="file";let s;if(i.type==="application/pdf")s=document.createElement("b"),s.textContent="PDF";else {let l=document.createElement("img");l.className="th",l.alt="",l.src=this.objectUrl(i),s=l;}let d=document.createElement("span");d.className="name",d.textContent=i.name;let p=document.createElement("span");p.className="sz",p.textContent=`\xB7 ${B(i.size)}`;let c=document.createElement("button");c.type="button",c.className="x",c.setAttribute("aria-label",this.strings.removeFileLabel),c.textContent="\xD7",c.addEventListener("click",()=>{this.picked=null,a.remove();}),a.append(s,d,p,c),t.before(a),e.scrollTop=e.scrollHeight;}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.panel=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let o of this.root.querySelectorAll(".file,.ferr"))o.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){var s,d,p;(s=e.querySelector(".empty"))==null||s.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let o=r?await((p=(d=this.client).upload)==null?void 0:p.call(d,r)):void 0,a=o===null?null:await this.client.send(t,lt(),o?[o.id]:void 0);if(i.removeAttribute("data-pending"),a){i.dataset.turnId=a.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){var a;t.setAttribute("data-failed","");let o=document.createElement("button");o.type="button",o.className="retry",o.textContent=this.strings.retryLabel,o.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),((a=t.querySelector(".body"))!=null?a:t).append(o);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){var l,u,g,v,S,f,b;(l=e.querySelector(".empty"))==null||l.remove();let i=st.includes(t.authorKind)?t.authorKind:"agent",o=this.settings,a=document.createElement("div");if(a.className=`turn ${i}`,a.dataset.turnId=t.id,i!=="end_user"&&o.nameAvatar){let h=document.createElement("span");if(h.className=i==="ai"?"av bot":"av",h.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let x=document.createElement("img");x.alt="",x.src=this.client.avatarUrl(t.authorAvatarUrl),h.append(x);}else {h.textContent=i==="ai"?this.strings.aiLabel:Y(this.agentName(t));let x=i==="agent"?(g=(u=this.appearance.team)==null?void 0:u.find(w=>w.name===t.authorName))==null?void 0:g.tone:void 0;x&&(h.style.background=x);}a.append(h);}let d=document.createElement("div");if(d.className="body",i==="end_user"){r&&this.drawFile(d,r.name,r.type,r.size,Promise.resolve(r));for(let h of (v=t.attachments)!=null?v:[])this.drawFile(d,h.name,h.contentType,h.bytes,(b=(f=(S=this.client).file)==null?void 0:f.call(S,h.url))!=null?b:Promise.resolve(null));}let p=i!=="end_user"&&o.namePlacement!=="hidden",c=document.createElement("div");if(i==="ai"?nt(c,t.body):c.textContent=t.body,p||i==="ai"&&o.namePlacement==="hidden"){let h=document.createElement("div");h.className=i==="ai"?"author ai":"author",h.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),o.stampPlacement==="beside_name"&&h.append(this.stamp(t)),o.namePlacement==="inline"?(h.classList.add("below"),d.append(c,h)):d.append(h,c);}else t.body&&d.append(c);return o.stampPlacement==="under_turn"&&d.append(this.stamp(t)),a.append(d),e.append(a),e.scrollTop=e.scrollHeight,a}drawFile(e,t,r,i,o){let a=document.createElement("a");if(r==="application/pdf"){a.className="pdfc",a.download=t;let s=document.createElement("b");s.textContent="PDF",a.append(s,`${t} \xB7 ${B(i)}`);}else {a.className="att",a.target="_blank",a.rel="noopener noreferrer";let s=document.createElement("img");s.alt=t,s.addEventListener("load",()=>{let d=a.closest(".log");d&&(d.scrollTop=d.scrollHeight);}),a.append(s);}e.append(a),o.then(s=>{var d;s&&(a.href=this.objectUrl(s),(d=a.querySelector("img"))==null||d.setAttribute("src",a.href));});}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let o=i[0],a=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),a.focus()):!e.shiftKey&&s===a?(e.preventDefault(),o.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function ee(n){return `40${JSON.stringify(n)}`}function te(){return "3"}function ne(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=D(t);return {kind:"open",pingInterval:typeof(a==null?void 0:a.pingInterval)=="number"?a.pingInterval:25e3,pingTimeout:typeof(a==null?void 0:a.pingTimeout)=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=D(i);return {kind:"connectError",message:typeof(a==null?void 0:a.message)=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let o=D(i);return !Array.isArray(o)||typeof o[0]!="string"?{kind:"other"}:{kind:"event",name:o[0],payload:o[1]}}function D(n){try{return JSON.parse(n)}catch(e){return null}}var pt="/socket.io/?EIO=4&transport=websocket",R=class{constructor(e){this.options=e;m(this,"socket",null);m(this,"heartbeat",null);m(this,"ready",false);m(this,"closed",false);m(this,"heartbeatWindow",45e3);m(this,"factory");m(this,"setTimer");m(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ut,this.setTimer=(r=e.setTimer)!=null?r:((o,a)=>setTimeout(o,a)),this.clearTimer=(i=e.clearTimer)!=null?i:(o=>clearTimeout(o));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${pt}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,o,a;let t=ne(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(ee(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(te());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(o=this.socket)==null||o.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(a=t.payload)==null?void 0:a.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ut(n){let e=globalThis.WebSocket;if(!e)throw new C("no WebSocket");return new e(n)}var ht=6e4;function re(n){var b,h,x,w;let e=globalThis.document;if(!e)throw new N("prodantix chat requires a document; mount it in the browser");let t=(b=n.mountPoint)!=null?b:e.createElement("div");n.mountPoint||e.body.append(t);let r=new I(n),i=new $(t,r,n.strings,n.appearance),o=(x=(h=n.appearance)==null?void 0:h.availability)!=null?x:A.availability,a,s=()=>{i.setOpenNow(M(o,new Date)),a=setTimeout(s,ht);};s();let d=new Set,p,c=null,l=(w=n.pollIntervalMs)!=null?w:15e3,u=y=>{d.has(y.id)||y.authorKind==="end_user"||(d.add(y.id),i.onIncomingTurn(y));},g=async()=>{if(!r.hasThread)return;let y=await r.load();if(y){for(let T of y.turns)u(T);d=new Set(y.turns.map(T=>T.id));}},v=()=>{p||l<=0||(p=setInterval(()=>void g(),l));},S=()=>{p&&clearInterval(p),p=void 0;},f=()=>{if(c||!n.socketHost)return;let y=r.socketAuth;y&&(c=new R({auth:y,host:n.socketHost,onClosed:T=>{c=null,v(),T&&f();},onReady:S,onTurn:u,socketFactory:n.socketFactory}),c.open());};return v(),f(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(a),c==null||c.close(),c=null,i.close(),t.remove();},identify:y=>r.identify(y),open:()=>{i.open().then(f);}}}var mt="prodantix.messenger.config",ie=n=>{var t,r,i,o;let e=(t=n.navigator)==null?void 0:t.languages;return Array.isArray(e)&&e.length>0?e.join(","):((r=n.navigator)==null?void 0:r.language)||((o=(i=n.document)==null?void 0:i.documentElement)==null?void 0:o.lang)||void 0},ae=(n,e)=>`${mt}:${n}:${e!=null?e:""}`;function oe(n,e,t){let r=n==null?void 0:n.get(ae(e,t));if(!r)return null;try{let i=JSON.parse(r);return (i==null?void 0:i.apiKey)===e?i.config:null}catch(i){return null}}async function se(n){var o,a,s,d,p;let e=_(n.fetchImpl);if(!e)return (o=n.onError)==null||o.call(n,new C("no fetch available for the prodantix messenger")),null;let t=F(n.host),r=ae(n.apiKey,n.locale),i=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let c=await e(`${t}/v1/messenger/config${i}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!c.ok)return (a=n.onError)==null||a.call(n,new C(`prodantix messenger config: ${c.status}`,c.status)),null;let l=JSON.parse(await c.text());return l.enabled?((d=n.storage)==null||d.set(r,JSON.stringify({apiKey:n.apiKey,config:l})),l):((s=n.storage)==null||s.remove(r),l)}catch(c){return (p=n.onError)==null||p.call(n,c),null}}var gt=["close","identify","open","shutdown","toggle"],L="[prodantix/messenger]";function ft(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!gt.includes(r)||e(r,...i);}}function bt(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function ce(n,e={}){var g,v,S;let t=(g=e.warn)!=null?g:(f=>console.warn(f)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${L} no project key on the install snippet; nothing will load.`),null;let o=bt((v=e.scriptSrc)!=null?v:xt(n));if(!o)return t(`${L} could not tell which host served this script; nothing will load.`),null;let a=yt(n),s=ie(n),d=oe(a,i,s),p=await se({apiKey:i,host:o,locale:s,onError:f=>t(`${L} settings could not be read: ${String(f)}`),storage:a}),c=p!=null?p:d;if(!c)return t(`${L} no settings available; the messenger will not render.`),null;if(!c.enabled)return null;let l=re({apiKey:i,appearance:c,distinctId:St(n,a),host:o,socketHost:c.socketUrl||void 0}),u=(f,...b)=>{if((f==="open"||f==="toggle")&&l.open(),f==="close"&&l.close(),f==="shutdown"&&l.destroy(),f==="identify"){let h=vt(b[0]);if(!h){console.error(`${L} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}l.identify(h);}};return ft((S=r==null?void 0:r.q)!=null?S:[],u),n.prodantix=Object.assign((f,...b)=>u(f,...b),{k:i,q:[]}),l}function xt(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function yt(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function vt(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var le="prodantix.messenger.anon";function St(n,e){var i,o,a;let t=e==null?void 0:e.get(le);if(t)return t;let r=`anon_${(a=(o=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:o.call(i))!=null?a:Math.random().toString(36).slice(2)}`;return e==null||e.set(le,r),r}ce(window);})();//# sourceMappingURL=messenger.iife.js.map
105
+ .scrim,.grip{display:none}@media (max-width:770px){.panel{inset:auto 0 0;width:100%;max-width:none;height:86dvh;max-height:86dvh}:host .panel{border-bottom-left-radius:0;border-bottom-right-radius:0}.scrim{display:block;position:fixed;inset:0;z-index:2147483000;background:rgb(15 23 42/.24)}.grip{display:block;position:absolute;top:7px;left:calc(50% - 17px);width:34px;height:4px;border-radius:2px;background:currentColor;opacity:.45}.panel:not([data-dragging]){transition:translate .2s}.composer{padding-bottom:max(12px,env(safe-area-inset-bottom))}}
106
+ `}${ze[t.composerShape]}${Ue[t.skin]}${Y(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Be[t.bubbleShape]}${De[t.bubbleFill]}${Ge[t.namePlacement]}${t.nameAvatar?qe:""}${t.dayDividers?je:""}${We[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ye:""}`}var at=["end_user","agent","ai"];function ot(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var st='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',R=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;h(this,"root");h(this,"strings");h(this,"settings");h(this,"appearance");h(this,"launcher");h(this,"badge");h(this,"panel",null);h(this,"scrim",null);h(this,"lastFocused",null);h(this,"unread",0);h(this,"pendingTurns",0);h(this,"openNow");h(this,"styles");h(this,"scheme");h(this,"picked",null);h(this,"objectUrls",[]);h(this,"helpLoader");h(this,"kit",null);h(this,"kitLoad",null);h(this,"filesLoader");h(this,"filesKit",null);h(this,"filesLoad",null);var o;this.strings={...Ke,...r},this.appearance={...L,...i},this.settings=M({...L,...i}),this.root=e.attachShadow({mode:(o=a.shadowMode)!=null?o:"closed"}),this.openNow=I(this.appearance.availability,new Date),this.scheme=a.scheme,this.helpLoader=a.help,this.filesLoader=a.files,this.styles=dt(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(J(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...L,...e},this.settings=M(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){var e;this.styles(`${it(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(((e=this.appearance.attachments)==null?void 0:e.enabled)===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):((this.kitLoad)!=null||(this.kitLoad=this.helpLoader().then(t=>(this.kit=t,this.paint(),t))),this.kitLoad)}loadFiles(){return this.filesLoader?((this.filesLoad)!=null||(this.filesLoad=this.filesLoader().then(t=>(this.filesKit=t,this.paint(),t))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var v;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("span");r.className="grip",r.setAttribute("aria-hidden","true"),t.append(r);let i=(v=this.appearance.team)!=null?v:[];i.length>0&&t.append(U(i,this.strings,b=>this.client.avatarUrl(b)));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let s=document.createElement("p");s.className="status";let p=document.createElement("span");p.className="live",p.setAttribute("aria-hidden","true"),s.append(p,this.strings.replyTime),a.append(o,s);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=st,d.addEventListener("click",()=>this.close()),t.append(a,d);let l=document.createElement("div");l.className="log",l.setAttribute("role","log"),l.setAttribute("aria-live","polite"),l.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let m=document.createElement("input");m.type="text",m.setAttribute("aria-label",this.strings.inputPlaceholder),m.placeholder=this.strings.inputPlaceholder;let g=document.createElement("button");g.type="submit",g.setAttribute("aria-label",this.strings.sendLabel),g.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let C=document.createElement("span");C.className="sendtext",C.textContent=this.strings.sendLabel,g.append(C),c.append(m,g),c.addEventListener("submit",b=>{b.preventDefault(),this.submit(m,l);}),e.append(t,l,c),e.addEventListener("keydown",b=>this.onKeydown(b,e,d));let S=document.createElement("div");S.className="scrim",S.addEventListener("click",()=>this.close()),this.root.append(S,e),this.panel=e,this.scrim=S,ct(e,()=>this.close()),m.focus();let f=this.appearance.attachments,[y]=await Promise.all([this.client.load(),this.loadKit(),f!=null&&f.enabled&&this.client.upload?this.loadFiles():null]);if(y!=null&&y.turns.some(b=>{var x;return (x=b.attachments)==null?void 0:x.length})&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&(f!=null&&f.enabled)&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:b=>{this.picked=b;},objectUrl:b=>this.objectUrl(b),removeFileLabel:this.strings.removeFileLabel,root:this.root},c,m,l,f);let u=this.helpHost();(u==null?void 0:u.placement)==="tab"&&u.host.source.collections&&u.host.source.collectionArticles&&u.kit.helpTab(u.host),(u==null?void 0:u.placement)==="while_typing"&&u.kit.whileTyping(u.host,m,c),y&&y.turns.length>0?this.renderThread(l,y):this.renderFirstRun(l,m),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,r.append(i);let a=this.helpHost();if((a==null?void 0:a.placement)==="first_view")a.kit.firstView(a.host,r);else {let s=document.createElement("p");s.textContent=this.strings.emptyBody,r.append(s);}this.appearance.starterPrompts.filter(tt).forEach((s,p)=>{let d=document.createElement("div");d.className="prompt";let l=document.createElement("div");l.className="promptwords",l.id=`prompt-${p}`;let c=document.createElement("template");c.innerHTML=s.html,rt(c.content)?l.append(c.content):l.textContent=s.text;for(let g of l.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let m=document.createElement("button");m.className="promptpress",m.type="button",m.setAttribute("aria-labelledby",l.id),m.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),d.append(l,m),r.append(d);}),e.replaceChildren(r);}helpHost(){let e=this.appearance.help,{kit:t,panel:r}=this,i=e&&t&&r?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:r,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){var e;if(this.panel){this.panel.remove(),(e=this.scrim)==null||e.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let t of this.objectUrls)URL.revokeObjectURL(t);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){var t;if(this.panel&&((t=e.attachments)!=null&&t.length)&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){var s,p,d;(s=e.querySelector(".empty"))==null||s.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let a=r?await((d=(p=this.client).upload)==null?void 0:d.call(p,r)):void 0,o=a===null?null:await this.client.send(t,ot(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),o){i.dataset.turnId=o.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){var o;t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),((o=t.querySelector(".body"))!=null?o:t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){var c,m,g,C,S,f,y;(c=e.querySelector(".empty"))==null||c.remove();let i=at.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${i}`,o.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let u=document.createElement("span");if(u.className=i==="ai"?"av bot":"av",u.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let v=document.createElement("img");v.alt="",v.src=this.client.avatarUrl(t.authorAvatarUrl),u.append(v);}else {u.textContent=i==="ai"?this.strings.aiLabel:W(this.agentName(t));let v=i==="agent"?(g=(m=this.appearance.team)==null?void 0:m.find(b=>b.name===t.authorName))==null?void 0:g.tone:void 0;v&&(u.style.background=v);}o.append(u);}let p=document.createElement("div");if(p.className="body",i==="end_user"){let u=this.filesKit,v=b=>this.objectUrl(b);r&&(u==null||u.drawFile(p,r.name,r.type,r.size,Promise.resolve(r),v));for(let b of (C=t.attachments)!=null?C:[])u==null||u.drawFile(p,b.name,b.contentType,b.bytes,(y=(f=(S=this.client).file)==null?void 0:f.call(S,b.url))!=null?y:Promise.resolve(null),v);}let d=i!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(i==="ai"?Ze(l,t.body):l.textContent=t.body,d||i==="ai"&&a.namePlacement==="hidden"){let u=document.createElement("div");u.className=i==="ai"?"author ai":"author",u.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&u.append(this.stamp(t)),a.namePlacement==="inline"?(u.classList.add("below"),p.append(l,u)):p.append(u,l);}else t.body&&p.append(l);return a.stampPlacement==="under_turn"&&p.append(this.stamp(t)),o.append(p),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(p=>!p.closest("[hidden]")&&!p.hidden);if(i.length===0)return;let a=i[0],o=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},lt="(max-width: 770px)";function ct(n,e){let t=null;n.addEventListener("pointerdown",i=>{var o,s;if(t||i.button!==0||!((o=globalThis.matchMedia)!=null&&o.call(globalThis,lt).matches))return;let a=i.target;if(!(a!=null&&a.closest("a, button, input, textarea, iframe"))){for(;a&&a!==n;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},(s=n.setPointerCapture)==null||s.call(n,i.pointerId),n.dataset.dragging="";}}),n.addEventListener("pointermove",i=>{if((t==null?void 0:t.id)!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),n.style.translate=`0 ${t.offset}px`;});let r=i=>{let a=t;if((a==null?void 0:a.id)!==i.pointerId)return;t=null,delete n.dataset.dragging;let o=a.offset>Math.min(72,n.getBoundingClientRect().height*.4),s=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;o||s?e():n.style.translate="";};n.addEventListener("pointerup",r),n.addEventListener("pointercancel",r);}var dt=n=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in n&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return n.adoptedStyleSheets=[t],r=>t.replaceSync(r)}let e=document.createElement("style");return n.append(e),t=>{e.textContent=t;}};function Q(n){return `40${JSON.stringify(n)}`}function Z(){return "3"}function ee(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=z(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=z(i);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let a=z(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function z(n){try{return JSON.parse(n)}catch(e){return null}}var pt="/socket.io/?EIO=4&transport=websocket",$=class{constructor(e){this.options=e;h(this,"socket",null);h(this,"heartbeat",null);h(this,"ready",false);h(this,"closed",false);h(this,"heartbeatWindow",45e3);h(this,"factory");h(this,"setTimer");h(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ut,this.setTimer=(r=e.setTimer)!=null?r:((a,o)=>setTimeout(a,o)),this.clearTimer=(i=e.clearTimer)!=null?i:(a=>clearTimeout(a));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${pt}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,a,o;let t=ee(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(Q(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(Z());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(a=this.socket)==null||a.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ut(n){let e=globalThis.WebSocket;if(!e)throw new E("no WebSocket");return new e(n)}var ht=6e4;function te(n){var y,u,v,b;let e=globalThis.document;if(!e)throw new N("prodantix chat requires a document; mount it in the browser");let t=(y=n.mountPoint)!=null?y:e.createElement("div");n.mountPoint||e.body.append(t);let r=new H(n),i=new R(t,r,n.strings,n.appearance,{files:n.files,help:n.help}),a=(v=(u=n.appearance)==null?void 0:u.availability)!=null?v:L.availability,o,s=()=>{i.setOpenNow(I(a,new Date)),o=setTimeout(s,ht);};s();let p=new Set,d,l=null,c=(b=n.pollIntervalMs)!=null?b:15e3,m=x=>{p.has(x.id)||x.authorKind==="end_user"||(p.add(x.id),i.onIncomingTurn(x));},g=async()=>{if(!r.hasThread)return;let x=await r.load();if(x){for(let w of x.turns)m(w);p=new Set(x.turns.map(w=>w.id));}},C=()=>{d||c<=0||(d=setInterval(()=>void g(),c));},S=()=>{d&&clearInterval(d),d=void 0;},f=()=>{if(l||!n.socketHost)return;let x=r.socketAuth;x&&(l=new $({auth:x,host:n.socketHost,onClosed:w=>{l=null,C(),w&&f();},onReady:S,onTurn:m,socketFactory:n.socketFactory}),l.open());};return C(),f(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(o),l==null||l.close(),l=null,i.close(),t.remove();},identify:x=>r.identify(x),open:()=>{i.open().then(f);}}}var mt="prodantix.messenger.config",ne=n=>{var t,r,i,a;let e=(t=n.navigator)==null?void 0:t.languages;return Array.isArray(e)&&e.length>0?e.join(","):((r=n.navigator)==null?void 0:r.language)||((a=(i=n.document)==null?void 0:i.documentElement)==null?void 0:a.lang)||void 0},re=(n,e)=>`${mt}:${n}:${e!=null?e:""}`;function ie(n,e,t){let r=n==null?void 0:n.get(re(e,t));if(!r)return null;try{let i=JSON.parse(r);return (i==null?void 0:i.apiKey)===e?i.config:null}catch(i){return null}}async function ae(n){var a,o,s,p,d;let e=_(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new E("no fetch available for the prodantix messenger")),null;let t=F(n.host),r=re(n.apiKey,n.locale),i=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let l=await e(`${t}/v1/messenger/config${i}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!l.ok)return (o=n.onError)==null||o.call(n,new E(`prodantix messenger config: ${l.status}`,l.status)),null;let c=JSON.parse(await l.text());return c.enabled?((p=n.storage)==null||p.set(r,JSON.stringify({apiKey:n.apiKey,config:c})),c):((s=n.storage)==null||s.remove(r),c)}catch(l){return (d=n.onError)==null||d.call(n,l),null}}var gt=["close","identify","open","shutdown","toggle"],A="[prodantix/messenger]";function ft(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!gt.includes(r)||e(r,...i);}}function bt(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}function se(n,e,t,r,i){return new Promise(a=>{let o=n.document.createElement("script");o.src=e,o.onload=()=>{var p;let s=(p=r())!=null?p:null;s||i(`${A} the ${t} script registered nothing.`),a(s);},o.onerror=()=>{i(`${A} the ${t} script could not load from ${new URL(e).origin}.`),a(null);},n.document.head.append(o);})}var yt=(n,e,t)=>se(n,`${e}/messenger-help.js`,"help centre",()=>n.prodantixMessengerHelp,t),xt=(n,e,t)=>se(n,`${e}/messenger-files.js`,"files",()=>n.prodantixMessengerFiles,t);async function le(n,e={}){var g,C,S;let t=(g=e.warn)!=null?g:(f=>console.warn(f)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${A} no project key on the install snippet; nothing will load.`),null;let a=bt((C=e.scriptSrc)!=null?C:vt(n));if(!a)return t(`${A} could not tell which host served this script; nothing will load.`),null;let o=St(n),s=ne(n),p=ie(o,i,s),d=await ae({apiKey:i,host:a,locale:s,onError:f=>t(`${A} settings could not be read: ${String(f)}`),storage:o}),l=d!=null?d:p;if(!l)return t(`${A} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let c=te({apiKey:i,appearance:l,distinctId:kt(n,o),files:()=>xt(n,a,t),help:l.help?()=>yt(n,a,t):void 0,host:a,locale:s,socketHost:l.socketUrl||void 0}),m=(f,...y)=>{if((f==="open"||f==="toggle")&&c.open(),f==="close"&&c.close(),f==="shutdown"&&c.destroy(),f==="identify"){let u=Ct(y[0]);if(!u){console.error(`${A} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}c.identify(u);}};return ft((S=r==null?void 0:r.q)!=null?S:[],m),n.prodantix=Object.assign((f,...y)=>m(f,...y),{k:i,q:[]}),c}function vt(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function St(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function Ct(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var oe="prodantix.messenger.anon";function kt(n,e){var i,a,o;let t=e==null?void 0:e.get(oe);if(t)return t;let r=`anon_${(o=(a=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:a.call(i))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(oe,r),r}le(window);})();//# sourceMappingURL=messenger.iife.js.map
106
107
  //# sourceMappingURL=messenger.iife.js.map
package/dist/messenger.js CHANGED
@@ -1,2 +1,2 @@
1
- import {e,d as d$1,h}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var f="prodantix.messenger.config",u=e=>{let r=e.navigator?.languages;return Array.isArray(r)&&r.length>0?r.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},l=(e,r)=>`${f}:${e}:${r??""}`;function p(e,r,s){let n=e?.get(l(r,s));if(!n)return null;try{let a=JSON.parse(n);return a?.apiKey===r?a.config:null}catch{return null}}async function d(e$1){let r=e(e$1.fetchImpl);if(!r)return e$1.onError?.(new d$1("no fetch available for the prodantix messenger")),null;let s=h(e$1.host),n=l(e$1.apiKey,e$1.locale),a=e$1.locale?`?locale=${encodeURIComponent(e$1.locale)}`:"";try{let t=await r(`${s}/v1/messenger/config${a}`,{headers:{authorization:`Bearer ${e$1.apiKey}`},method:"GET"});if(!t.ok)return e$1.onError?.(new d$1(`prodantix messenger config: ${t.status}`,t.status)),null;let o=JSON.parse(await t.text());return o.enabled?(e$1.storage?.set(n,JSON.stringify({apiKey:e$1.apiKey,config:o})),o):(e$1.storage?.remove(n),o)}catch(t){return e$1.onError?.(t),null}}export{f as MESSENGER_CACHE_KEY,l as cacheKeyFor,p as cachedMessengerConfig,d as fetchMessengerConfig,u as localeCandidates};//# sourceMappingURL=messenger.js.map
1
+ import {e,d as d$1,h}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var f="prodantix.messenger.config",m=e=>{let t=e.navigator?.languages;return Array.isArray(t)&&t.length>0?t.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},l=(e,t)=>`${f}:${e}:${t??""}`;function u(e,t,i){let n=e?.get(l(t,i));if(!n)return null;try{let a=JSON.parse(n);return a?.apiKey===t?a.config:null}catch{return null}}async function d(e$1){let t=e(e$1.fetchImpl);if(!t)return e$1.onError?.(new d$1("no fetch available for the prodantix messenger")),null;let i=h(e$1.host),n=l(e$1.apiKey,e$1.locale),a=e$1.locale?`?locale=${encodeURIComponent(e$1.locale)}`:"";try{let r=await t(`${i}/v1/messenger/config${a}`,{headers:{authorization:`Bearer ${e$1.apiKey}`},method:"GET"});if(!r.ok)return e$1.onError?.(new d$1(`prodantix messenger config: ${r.status}`,r.status)),null;let s=JSON.parse(await r.text());return s.enabled?(e$1.storage?.set(n,JSON.stringify({apiKey:e$1.apiKey,config:s})),s):(e$1.storage?.remove(n),s)}catch(r){return e$1.onError?.(r),null}}export{f as MESSENGER_CACHE_KEY,l as cacheKeyFor,u as cachedMessengerConfig,d as fetchMessengerConfig,m as localeCandidates};//# sourceMappingURL=messenger.js.map
2
2
  //# sourceMappingURL=messenger.js.map
package/dist/node.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var fe=Object.defineProperty;var ge=(n,e,t)=>e in n?fe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ge(n,typeof e!="symbol"?e+"":e,t);var p=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends p{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends p{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 V=n=>new Promise(e=>{setTimeout(e,n);});function h(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 b(n){return n.toISOString()}function me(){return globalThis.crypto}function ye(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 ve(){let n=me();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 ye(e)}var G={uuid:ve};var ke=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var be=/^(?:\$|[a-z])[a-z0-9_.]*$/;function x(n){let e=0;for(let t of n)e+=1;return e}function J(n){return ke.test(n)}function xe(n){return be.test(n)}function H(n){let e=x(n);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=x(n);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!xe(n))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var B="prodantix-js",z="0.0.1";var Ee=n=>{};function Q(n){if(!n.apiKey||!J(n.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new v("host is required (the ingest base URL)");let e=h(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?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??G,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:$(n.apiKey),onError:n.onError??Ee,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??B,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function $(n){return n.slice(0,16)}function W(n,e,t){U(n.eventName),H(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:b(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function Se(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 Y(n){return n===g?Number.NaN:Number(n)}function X(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 ee(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(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 E(t,s,(r,i)=>r>i);case "gte":return E(t,s,(r,i)=>r>=i);case "lt":return E(t,s,(r,i)=>r<i);case "lte":return E(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 E(n,e,t){let s=Y(n),r=e===void 0?Number.NaN:Y(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function te(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 N(n,e){return n.targeting.length===0||n.targeting.every(t=>ee(t,e))}function ne(n,e){let t=te(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 R(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=R(i,e,t,s)&&N(i,t)&&ne(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?R(n,e,t,[n.key])?N(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:te(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 se(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function O(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!R(n,e,t,[n.key])||!N(n,t))return r;let i=ne(n,t);return s.find(a=>a.key===i)??r}function re(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ie(n){return `40${JSON.stringify(n)}`}function oe(){return "3"}function ae(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=M(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=M(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=M(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function M(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,I=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??Ce,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(/\/+$/,"")}${Ie}`,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=ae(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ie({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(oe());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);},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 Ce(n){let e=globalThis.WebSocket;if(!e)throw new c("no WebSocket");return new e(n)}var w=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(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 q(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function L(n,e){return `pdx.${n}.${e}`}var ce="consent";function K(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 Fe(n,e){return K(n.getItem(L(e,ce)))}function Te(n,e,t){let s=L(e,ce);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=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=q(this.shared.getItem(this.key("anonymous_id"))),t=q(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=q(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 Fe(this.shared,this.namespace)}setConsent(e){Te(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 L(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(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 T=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)}};var d={createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",set:"$set"};function de(n){return n>=400&&n<500&&n!==429}var A=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??V,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(de(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&&de(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",$e=1e3,le=3e4,D=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=Q(e),this.identity=new C(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 T(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 A({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new w({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({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={...D(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=D(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(d.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(d.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(d.set,{properties:s});}setPersonTraits(e){let t=D(e);Object.keys(t).length!==0&&this.capture(d.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(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?O(r,s.flags,i):null,l=r?S(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(d.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 s=await this.flagSnapshot(),r=s.flags.find(l=>l.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?O(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&&re(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<le?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<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 I({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($e);try{await this.transport.send({body:{events:e,sent_at:b(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}`}};var Ne=200;function ue(){return globalThis.process}function Re(n){ue()?.on("beforeExit",()=>{n.flush();});}function Xt(n){let e=ue(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new P(t);return Re(s),s}function Zt(n,e){let t=$(e),s=Oe(n,`pdx_${t}`);if(s===void 0)return null;let r=Me(s);if(r===void 0)return null;let i=pe(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:K(r[`pdx.${t}.consent`]),sessionId:qe(r[`pdx.${t}.session`])}}function Oe(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Me(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function pe(n){if(typeof n!="string")return;let e=x(n);return e>=1&&e<=Ne?n:void 0}function qe(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:pe(e.id)??null}catch{return null}}exports.createNodeClient=Xt;exports.readSharedIdentity=Zt;//# sourceMappingURL=node.cjs.map
1
+ 'use strict';var fe=Object.defineProperty;var ge=(n,e,t)=>e in n?fe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ge(n,typeof e!="symbol"?e+"":e,t);var p=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends p{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends p{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 V=n=>new Promise(e=>{setTimeout(e,n);});function h(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 b(n){return n.toISOString()}function me(){return globalThis.crypto}function ye(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 ve(){let n=me();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 ye(e)}var G={uuid:ve};var ke=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var be=/^(?:\$|[a-z])[a-z0-9_.]*$/;function x(n){let e=0;for(let t of n)e+=1;return e}function J(n){return ke.test(n)}function xe(n){return be.test(n)}function H(n){let e=x(n);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=x(n);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!xe(n))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var B="prodantix-js",z="0.7.0";var Ee=n=>{};function Q(n){if(!n.apiKey||!J(n.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new v("host is required (the ingest base URL)");let e=h(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??{},describeElement:n.describeElement,flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??G,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:$(n.apiKey),onError:n.onError??Ee,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??B,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function $(n){return n.slice(0,16)}function W(n,e,t){U(n.eventName),H(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:b(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function Se(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 Y(n){return n===g?Number.NaN:Number(n)}function X(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 ee(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(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 E(t,s,(r,i)=>r>i);case "gte":return E(t,s,(r,i)=>r>=i);case "lt":return E(t,s,(r,i)=>r<i);case "lte":return E(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 E(n,e,t){let s=Y(n),r=e===void 0?Number.NaN:Y(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function te(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 N(n,e){return n.targeting.length===0||n.targeting.every(t=>ee(t,e))}function ne(n,e){let t=te(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 R(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=R(i,e,t,s)&&N(i,t)&&ne(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?R(n,e,t,[n.key])?N(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:te(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 se(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function O(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!R(n,e,t,[n.key])||!N(n,t))return r;let i=ne(n,t);return s.find(a=>a.key===i)??r}function re(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ie(n){return `40${JSON.stringify(n)}`}function oe(){return "3"}function ae(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=M(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=M(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=M(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function M(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,I=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??Ce,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(/\/+$/,"")}${Ie}`,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=ae(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ie({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(oe());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);},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 Ce(n){let e=globalThis.WebSocket;if(!e)throw new c("no WebSocket");return new e(n)}var w=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(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 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 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()),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 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 q(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function L(n,e){return `pdx.${n}.${e}`}var ce="consent";function K(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 Fe(n,e){return K(n.getItem(L(e,ce)))}function Te(n,e,t){let s=L(e,ce);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=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=q(this.shared.getItem(this.key("anonymous_id"))),t=q(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=q(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 Fe(this.shared,this.namespace)}setConsent(e){Te(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 L(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(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 T=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)}};var l={createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",set:"$set"};function le(n){return n>=400&&n<500&&n!==429}var A=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??V,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(le(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&&le(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",$e=1e3,de=3e4,D=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=Q(e),this.identity=new C(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 T(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 A({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new w({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({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.element===void 0?{}:this.config.describeElement?.(t.element)??{},...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={...D(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(l.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=D(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(l.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(l.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(l.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(l.set,{properties:s});}setPersonTraits(e){let t=D(e);Object.keys(t).length!==0&&this.capture(l.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(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?O(r,s.flags,i):null,d=r?S(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(l.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 s=await this.flagSnapshot(),r=s.flags.find(d=>d.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?O(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&&re(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<de?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<de)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 I({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($e);try{await this.transport.send({body:{events:e,sent_at:b(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}`}};var Ne=200;function ue(){return globalThis.process}function Re(n){ue()?.on("beforeExit",()=>{n.flush();});}function Xt(n){let e=ue(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new P(t);return Re(s),s}function Zt(n,e){let t=$(e),s=Oe(n,`pdx_${t}`);if(s===void 0)return null;let r=Me(s);if(r===void 0)return null;let i=pe(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:K(r[`pdx.${t}.consent`]),sessionId:qe(r[`pdx.${t}.session`])}}function Oe(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Me(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function pe(n){if(typeof n!="string")return;let e=x(n);return e>=1&&e<=Ne?n:void 0}function qe(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:pe(e.id)??null}catch{return null}}exports.createNodeClient=Xt;exports.readSharedIdentity=Zt;//# sourceMappingURL=node.cjs.map
2
2
  //# sourceMappingURL=node.cjs.map
package/dist/node.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as ProdantixClient } from './client-BO7f6q5k.cjs';
2
- import { b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.cjs';
1
+ import { P as ProdantixClient } from './client-CL6Xvhay.cjs';
2
+ import { b as Consent, P as ProdantixConfig } from './types-Q2VNlJbG.cjs';
3
3
 
4
4
  /** What the web SDK's cookie says about the visitor on this request: the
5
5
  * anonymous id every subdomain of the site shares, the session it is in, and
package/dist/node.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as ProdantixClient } from './client-BQlU_3Dc.js';
2
- import { b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.js';
1
+ import { P as ProdantixClient } from './client-QyKW0LFW.js';
2
+ import { b as Consent, P as ProdantixConfig } from './types-Q2VNlJbG.js';
3
3
 
4
4
  /** What the web SDK's cookie says about the visitor on this request: the
5
5
  * anonymous id every subdomain of the site shares, the session it is in, and
package/dist/node.js CHANGED
@@ -1,2 +1,2 @@
1
- import {y as y$1,h as h$1,p as p$1,e}from'./chunk-4RLPQZ5L.js';import'./chunk-V77KYPOF.js';import'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var a=200;function f(){return globalThis.process}function p(t){f()?.on("beforeExit",()=>{t.flush();});}function h(t){let n=f(),e={...t,os:t.os??(n?.platform?n.platform.slice(0,50):void 0),streamFlags:t.streamFlags??true},r=new y$1(e);return p(r),r}function w(t,n){let e=h$1(n),r=m(t,`pdx_${e}`);if(r===void 0)return null;let o=g(r);if(o===void 0)return null;let i=l(o[`pdx.${e}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:p$1(o[`pdx.${e}.consent`]),sessionId:y(o[`pdx.${e}.session`])}}function m(t,n){let e=`${n}=`;for(let r of t.split(";")){let o=r.trim();if(o.startsWith(e))return o.slice(e.length)}}function g(t){try{let n=JSON.parse(decodeURIComponent(t));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function l(t){if(typeof t!="string")return;let n=e(t);return n>=1&&n<=a?t:void 0}function y(t){if(typeof t!="string")return null;try{let n=JSON.parse(t);return n===null||typeof n!="object"||typeof n.startedAt!="number"||typeof n.lastActivityAt!="number"?null:l(n.id)??null}catch{return null}}export{h as createNodeClient,w as readSharedIdentity};//# sourceMappingURL=node.js.map
1
+ import {y as y$1,h as h$1,p as p$1,e}from'./chunk-D6PMLUYA.js';import'./chunk-V77KYPOF.js';import'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var a=200;function f(){return globalThis.process}function p(t){f()?.on("beforeExit",()=>{t.flush();});}function h(t){let n=f(),e={...t,os:t.os??(n?.platform?n.platform.slice(0,50):void 0),streamFlags:t.streamFlags??true},r=new y$1(e);return p(r),r}function w(t,n){let e=h$1(n),r=m(t,`pdx_${e}`);if(r===void 0)return null;let o=g(r);if(o===void 0)return null;let i=l(o[`pdx.${e}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:p$1(o[`pdx.${e}.consent`]),sessionId:y(o[`pdx.${e}.session`])}}function m(t,n){let e=`${n}=`;for(let r of t.split(";")){let o=r.trim();if(o.startsWith(e))return o.slice(e.length)}}function g(t){try{let n=JSON.parse(decodeURIComponent(t));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function l(t){if(typeof t!="string")return;let n=e(t);return n>=1&&n<=a?t:void 0}function y(t){if(typeof t!="string")return null;try{let n=JSON.parse(t);return n===null||typeof n!="object"||typeof n.startedAt!="number"||typeof n.lastActivityAt!="number"?null:l(n.id)??null}catch{return null}}export{h as createNodeClient,w as readSharedIdentity};//# sourceMappingURL=node.js.map
2
2
  //# sourceMappingURL=node.js.map
@@ -1,5 +1,5 @@
1
1
  import { F as FetchLike } from './http-BCh716Vs.js';
2
- import { T as Transport, i as TransportRequest } from './types-DjMXp6Wg.js';
2
+ import { T as Transport, i as TransportRequest } from './types-Q2VNlJbG.js';
3
3
 
4
4
  interface FetchTransportOptions {
5
5
  baseDelayMs?: number;
@@ -1,5 +1,5 @@
1
1
  import { F as FetchLike } from './http-BCh716Vs.cjs';
2
- import { T as Transport, i as TransportRequest } from './types-DjMXp6Wg.cjs';
2
+ import { T as Transport, i as TransportRequest } from './types-Q2VNlJbG.cjs';
3
3
 
4
4
  interface FetchTransportOptions {
5
5
  baseDelayMs?: number;
@@ -91,6 +91,7 @@ interface ProdantixConfig {
91
91
  * shared store when the client is built, so the answer survives the page. */
92
92
  consent?: Consent;
93
93
  defaultProperties?: EventProperties | (() => EventProperties);
94
+ describeElement?: (element: unknown) => EventProperties;
94
95
  flagsHost?: string;
95
96
  flushAt?: number;
96
97
  flushIntervalMs?: number;
@@ -91,6 +91,7 @@ interface ProdantixConfig {
91
91
  * shared store when the client is built, so the answer survives the page. */
92
92
  consent?: Consent;
93
93
  defaultProperties?: EventProperties | (() => EventProperties);
94
+ describeElement?: (element: unknown) => EventProperties;
94
95
  flagsHost?: string;
95
96
  flushAt?: number;
96
97
  flushIntervalMs?: number;