@prodantix/sdk 0.0.1 → 0.1.0-beta.348

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 (44) hide show
  1. package/README.md +11 -4
  2. package/dist/chat.cjs +65 -0
  3. package/dist/chat.d.cts +64 -0
  4. package/dist/chat.d.ts +64 -0
  5. package/dist/chat.js +65 -0
  6. package/dist/chunk-5XGN7UAV.js +2 -0
  7. package/dist/chunk-CSIP3PZ7.js +2 -0
  8. package/dist/chunk-V77KYPOF.js +2 -0
  9. package/dist/chunk-VG77TYVX.js +2 -0
  10. package/dist/client-Ca6xJESF.d.ts +105 -0
  11. package/dist/client-y1xyVF6C.d.cts +105 -0
  12. package/dist/config-B-cTz9n1.d.ts +94 -0
  13. package/dist/config-OP9Csae6.d.cts +94 -0
  14. package/dist/csp.cjs +3 -0
  15. package/dist/csp.d.cts +37 -0
  16. package/dist/csp.d.ts +37 -0
  17. package/dist/csp.js +3 -0
  18. package/dist/http-BCh716Vs.d.cts +14 -0
  19. package/dist/http-BCh716Vs.d.ts +14 -0
  20. package/dist/index.cjs +1 -1
  21. package/dist/index.d.cts +28 -6
  22. package/dist/index.d.ts +28 -6
  23. package/dist/index.js +1 -1
  24. package/dist/messenger.cjs +2 -0
  25. package/dist/messenger.d.cts +2 -0
  26. package/dist/messenger.d.ts +2 -0
  27. package/dist/messenger.iife.js +65 -0
  28. package/dist/messenger.js +2 -0
  29. package/dist/node.cjs +1 -1
  30. package/dist/node.d.cts +2 -1
  31. package/dist/node.d.ts +2 -1
  32. package/dist/node.js +1 -1
  33. package/dist/{transport-By6wsdny.d.ts → transport-Bj4nXmgt.d.cts} +3 -15
  34. package/dist/{transport-B3PxeUxW.d.cts → transport-CTPih3Jj.d.ts} +3 -15
  35. package/dist/types-68Sc11g8.d.cts +105 -0
  36. package/dist/types-68Sc11g8.d.ts +105 -0
  37. package/dist/web.cjs +1 -1
  38. package/dist/web.d.cts +4 -2
  39. package/dist/web.d.ts +4 -2
  40. package/dist/web.js +1 -1
  41. package/package.json +19 -3
  42. package/dist/chunk-FIZWZVZG.js +0 -2
  43. package/dist/client-B1bcIuD8.d.cts +0 -133
  44. package/dist/client-B1bcIuD8.d.ts +0 -133
package/README.md CHANGED
@@ -1,7 +1,14 @@
1
1
  # Prodantix SDK
2
2
 
3
- Isomorphic, zero-dependency analytics + feature-flag client for Prodantix. Runs in the
4
- browser, Node, and edge runtimes. Ships dual ESM/CJS with full TypeScript types.
3
+ Isomorphic, zero-dependency analytics + feature-flag client for [Prodantix](https://prodantix.com).
4
+ Runs in the browser, Node, and edge runtimes. Ships dual ESM/CJS with full TypeScript types.
5
+
6
+ ## Docs
7
+
8
+ - [Quickstart](https://prodantix.com/en/docs/quickstart): install and send a first event
9
+ - [Get an API key](https://prodantix.com/en/docs/keys): signup, project creation, where the key lives
10
+ - [API reference](https://prodantix.com/en/docs/api): every REST operation, rendered
11
+ - React apps: pair with [`@prodantix/react`](https://www.npmjs.com/package/@prodantix/react), the provider + hook adapter
5
12
 
6
13
  ## Install
7
14
 
@@ -74,8 +81,8 @@ anywhere.
74
81
 
75
82
  | Option | Default | Notes |
76
83
  | --- | --- | --- |
77
- | `apiKey` | | Public project key (`pdx_pub_…`). Required. |
78
- | `host` | | Ingest base URL. Required. |
84
+ | `apiKey` | required | Public project key (`pdx_pub_…`). Required. |
85
+ | `host` | required | Ingest base URL. Required. |
79
86
  | `flagsHost` | `host` | Flag-eval base URL (`GET /v1/flags`). |
80
87
  | `flushAt` | `20` | Flush when this many events are queued. |
81
88
  | `flushIntervalMs` | `10000` | Periodic flush interval; `0` disables the timer. |
package/dist/chat.cjs ADDED
@@ -0,0 +1,65 @@
1
+ 'use strict';var I=Object.defineProperty;var O=(n,e,t)=>e in n?I(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var l=(n,e,t)=>O(n,typeof e!="symbol"?e+"":e,t);function w(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function A(n){return n.replace(/\/+$/,"")}var H="X-Prodantix-Conversation-Token",E="prodantix.chat.handle";function M(){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 f=class{constructor(e){this.options=e;l(this,"fetchImpl");l(this,"host");l(this,"storage");l(this,"handle");l(this,"identity",null);this.fetchImpl=w(e.fetchImpl),this.host=A(e.host),this.storage=e.storage??M(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(E,JSON.stringify(this.handle)),true)}async send(e){if(!await this.ensureThread())return null;let t=this.handle;return t?(await this.request("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/turns`,{body:{body:e},token:t.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(E);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch{}return this.storage?.remove(E),null}async request(e,t,r={}){let i=this.fetchImpl;if(!i)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[H]=r.token);try{let s=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),o=await s.text();return s.ok?o?JSON.parse(o):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${s.status}`)),null)}catch(s){return this.options.onError?.(s),null}}};var h={bubbleStyle:"tailed",launcherStyle:"circle_outlined",namePlacement:"avatar_only",skin:"concierge",timestampStyle:"cluster"},F=["concierge","console","quiet"],R=["avatar_circle","circle_filled","circle_outlined","pill_labelled","pill_team","squircle_filled"],$=["hairline","outlined","rounded","tailed"],K=["above","avatar_only","gutter","hidden","inline"],z=["cluster","latency","none","trailing","with_name"],b=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t;function y(n){let e={bubbleStyle:b(n?.bubbleStyle,$,h.bubbleStyle),launcherStyle:b(n?.launcherStyle,R,h.launcherStyle),namePlacement:b(n?.namePlacement,K,h.namePlacement),skin:b(n?.skin,F,h.skin),timestampStyle:b(n?.timestampStyle,z,h.timestampStyle)};return (e.namePlacement==="avatar_only"||e.namePlacement==="hidden")&&(e.timestampStyle==="with_name"||e.timestampStyle==="latency")&&(e.timestampStyle="trailing"),e.namePlacement==="inline"&&e.bubbleStyle==="hairline"&&(e.namePlacement="above"),e}var G={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},v={accentColor:"#5b5bff",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],...h},B={concierge:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}.composer{padding:12px 12px 14px;gap:8px}.composer input{border:0;background:var(--fill);height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",console:".panel{border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.16)}.header{background:var(--paper);color:var(--ink);border-bottom:1px solid var(--hairline)}.close{color:var(--ink-2)}",quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{height:42px;padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.close{color:var(--ink-2)}"},D={avatar_circle:".launcher{width:60px;height:60px;border-radius:30px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2)}",circle_filled:".launcher{width:56px;height:56px;border-radius:28px;background:var(--a);color:#fff}",circle_outlined:".launcher{width:46px;height:46px;border-radius:23px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);font-size:21px}.badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;border-radius:10px;font-size:11.5px}",pill_labelled:".launcher{width:auto;height:52px;border-radius:26px;padding:0 22px;gap:10px;background:var(--a);color:#fff;font-size:14.5px;font-weight:600}",pill_team:".launcher{width:auto;height:54px;border-radius:27px;padding:0 20px 0 8px;gap:10px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink);font-size:14px;font-weight:600}.badge{position:static;background:var(--a)}",squircle_filled:".launcher{width:56px;height:56px;border-radius:16px;background:var(--a);color:#fff}"},q={hairline:".turn{max-width:100%;padding:13px 0;border-top:1px solid var(--hairline);background:none;border-radius:0}.log>.turn:first-child{border-top:0}.turn.end_user{align-self:stretch;display:flex;flex-direction:column;align-items:flex-end}.turn.end_user .body{background:var(--fill);color:var(--ink);border-radius:8px;padding:9px 12px;max-width:85%}",outlined:".turn{background:none;border:1px solid var(--hairline);border-radius:12px}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}",rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},U={above:"",avatar_only:".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .body{background:var(--fill);padding:9px 13px;border-radius:inherit}",gutter:".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".author{display:inline;margin-right:6px;font-weight:650}"},j={cluster:'.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)}',latency:".stamp{font-size:11px;opacity:.7;margin-left:6px}.lat{font-size:11px;opacity:.7;margin-left:6px}",none:"",trailing:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}",with_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}"};function N(n){let e=y(n),t=n.launcherPosition==="bottom_left"?"left":"right",r=n.accentColor;return `${`
2
+ :host {
3
+ all: initial; --a: ${r};
4
+ --paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
5
+ --fill: #f1f5f9; --hairline: #e2e8f0; --field: #cbd5e1; --ink-2: rgba(0,0,0,.72);
6
+ color-scheme: light dark;
7
+ }
8
+ @media (prefers-color-scheme: dark) {
9
+ :host {
10
+ --paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
11
+ --fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --field: rgba(255,255,255,.22); --ink-2: rgba(255,255,255,.70);
12
+ }
13
+ }
14
+ * { box-sizing: border-box; font-family: system-ui, sans-serif; }
15
+ .launcher {
16
+ position: fixed; ${t}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
17
+ border-radius: 28px; border: none; cursor: pointer;
18
+ display: inline-flex; align-items: center; justify-content: center;
19
+ background: ${r}; color: #fff; font-size: 24px;
20
+ box-shadow: 0 4px 12px rgba(0,0,0,.2);
21
+ }
22
+ .launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
23
+ .badge {
24
+ position: absolute; top: -4px; right: -4px; min-width: 20px; height: 20px;
25
+ border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px;
26
+ display: flex; align-items: center; justify-content: center; padding: 0 4px;
27
+ }
28
+ .panel {
29
+ position: fixed; ${t}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
30
+ height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
31
+ border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
32
+ display: flex; flex-direction: column; overflow: hidden;
33
+ }
34
+ .header { padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
35
+ .header h2 { margin: 0; font-size: 15px; }
36
+ .close { background: none; border: none; color: #fff; cursor: pointer; font-size: 18px; }
37
+ .close:focus-visible { outline: 2px solid #fff; }
38
+ .log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
39
+ .turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
40
+ .turn.end_user { align-self: flex-end; background: ${r}; color: #fff; }
41
+ .turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
42
+ .author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
43
+ .empty { display: flex; flex-direction: column; gap: 8px; padding: 20px 16px; }
44
+ .empty h3 { margin: 0; font-size: 18px; font-weight: 640; letter-spacing: -.015em; }
45
+ .empty p { margin: 0 0 8px; font-size: 13.5px; color: var(--ink-2); }
46
+ .prompt {
47
+ display: flex; align-items: center; min-height: 44px; padding: 0 14px; text-align: left;
48
+ font-family: inherit; font-size: 13.5px; font-weight: 500; color: var(--ink);
49
+ background: none; border: 1px solid var(--hairline); border-radius: 8px; cursor: pointer;
50
+ }
51
+ .prompt:focus-visible { outline: 2px solid ${r}; outline-offset: 2px; }
52
+ .av { width: 30px; height: 30px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 650; color: #fff; background: #7c3f3f; }
53
+ .av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
54
+ .composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--hairline); }
55
+ .composer input { flex: 1; padding: 8px 10px; border: 1px solid var(--field); border-radius: 8px; font-size: 14px; background: transparent; color: var(--ink); }
56
+ .composer input:focus-visible { outline: 2px solid ${r}; }
57
+ .composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${r}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 14.5px; font-weight: 550; }
58
+ .composer button .sendglyph { display: none; width: 19px; height: 19px; }
59
+ .composer button:focus-visible { outline: 2px solid #0b0e14; }
60
+ @media (prefers-reduced-motion: no-preference) {
61
+ .panel { animation: rise 180ms ease-out; }
62
+ @keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
63
+ }
64
+ `}${B[e.skin]}${D[e.launcherStyle]}${q[e.bubbleStyle]}${U[e.namePlacement]}${j[e.timestampStyle]}`}var W=["end_user","agent","ai"],x=class{constructor(e,t,r={},i={}){this.host=e;this.client=t;l(this,"root");l(this,"strings");l(this,"settings");l(this,"appearance");l(this,"launcher");l(this,"badge");l(this,"panel",null);l(this,"lastFocused",null);l(this,"unread",0);this.strings={...G,...r},this.appearance={...v,...i},this.settings=y({...v,...i}),this.root=e.attachShadow({mode:"closed"});let a=document.createElement("style");a.textContent=N({...v,...i}),this.root.append(a),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.textContent="\u{1F4AC}",this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.launcher.append(this.badge),this.root.append(this.launcher);}toggle(){this.panel?this.close():this.open();}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className="panel",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("h2");r.textContent=this.strings.title;let i=document.createElement("button");i.className="close",i.type="button",i.setAttribute("aria-label",this.strings.closeLabel),i.textContent="\xD7",i.addEventListener("click",()=>this.close()),t.append(r,i);let a=document.createElement("div");a.className="log",a.setAttribute("role","log"),a.setAttribute("aria-live","polite"),a.setAttribute("aria-label",this.strings.title);let s=document.createElement("form");s.className="composer";let o=document.createElement("input");o.type="text",o.setAttribute("aria-label",this.strings.inputPlaceholder),o.placeholder=this.strings.inputPlaceholder;let p=document.createElement("button");p.type="submit",p.setAttribute("aria-label",this.strings.sendLabel),p.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 u=document.createElement("span");u.className="sendtext",u.textContent=this.strings.sendLabel,p.append(u),s.append(o,p),s.addEventListener("submit",g=>{g.preventDefault(),this.submit(o,a);}),e.append(t,a,s),e.addEventListener("keydown",g=>this.onKeydown(g,e,i)),this.root.append(e),this.panel=e,o.focus();let d=await this.client.load();d&&d.turns.length>0?this.renderThread(a,d):this.renderFirstRun(a,o);}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 a=document.createElement("p");a.textContent=this.strings.emptyBody,r.append(i,a);for(let s of this.appearance.starterPrompts){let o=document.createElement("button");o.className="prompt",o.type="button",o.textContent=s,o.addEventListener("click",()=>{t.value=s,this.submit(t,e);}),r.append(o);}e.replaceChildren(r);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim();if(!r)return;e.value="",t.querySelector(".empty")?.remove();let i=await this.client.send(r);i&&this.appendTurn(t,i);}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t){e.querySelector(".empty")?.remove();let r=W.includes(t.authorKind)?t.authorKind:"agent",i=this.settings,a=document.createElement("div");if(a.className=`turn ${r}`,r!=="end_user"&&(i.namePlacement==="avatar_only"||i.namePlacement==="gutter")){let d=document.createElement("span");d.className=r==="ai"?"av bot":"av",d.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel.slice(0,2).toUpperCase(),d.setAttribute("aria-hidden","true"),a.append(d);}let o=document.createElement("div");if(o.className="body",r!=="end_user"&&i.namePlacement!=="hidden"&&!(i.namePlacement==="avatar_only"&&r==="agent")||r==="ai"&&i.namePlacement==="hidden"){let d=document.createElement("div");d.className=r==="ai"?"author ai":"author",d.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel,(i.timestampStyle==="with_name"||i.timestampStyle==="latency")&&d.append(this.stamp(t)),o.append(d);}let u=document.createElement("div");u.textContent=t.body,o.append(u),i.timestampStyle==="trailing"&&o.append(this.stamp(t)),a.append(o),e.append(a),e.scrollTop=e.scrollHeight;}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let a=i[0],s=i[i.length-1],o=this.root.activeElement;e.shiftKey&&o===a?(e.preventDefault(),s.focus()):!e.shiftKey&&o===s?(e.preventDefault(),a.focus()):o===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function _(n){return `40${JSON.stringify(n)}`}function P(){return "3"}function L(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let s=T(t);return {kind:"open",pingInterval:typeof s?.pingInterval=="number"?s.pingInterval:25e3,pingTimeout:typeof s?.pingTimeout=="number"?s.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let s=T(i);return {kind:"connectError",message:typeof s?.message=="string"?s.message:"refused"}}if(r!=="2")return {kind:"other"};let a=T(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function T(n){try{return JSON.parse(n)}catch{return null}}var Y="/socket.io/?EIO=4&transport=websocket",k=class{constructor(e){this.options=e;l(this,"socket",null);l(this,"heartbeat",null);l(this,"ready",false);l(this,"closed",false);l(this,"heartbeatWindow",45e3);l(this,"factory");l(this,"setTimer");l(this,"clearTimer");this.factory=e.socketFactory??J,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Y}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=L(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(_(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(P());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let r=t.payload?.turn;r&&this.options.onTurn(r);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function J(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}function ue(n){let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=n.mountPoint??e.createElement("div");n.mountPoint||e.body.append(t);let r=new f(n),i=new x(t,r,n.strings,n.appearance),a=new Set,s,o=null,p=n.pollIntervalMs??15e3,u=c=>{a.has(c.id)||c.authorKind==="end_user"||(a.add(c.id),i.onIncomingTurn(c));},d=async()=>{if(!r.hasThread)return;let c=await r.load();if(c){for(let m of c.turns)u(m);a=new Set(c.turns.map(m=>m.id));}},g=()=>{s||p<=0||(s=setInterval(()=>void d(),p));},C=()=>{s&&clearInterval(s),s=void 0;},S=()=>{if(o||!n.socketHost)return;let c=r.socketAuth;c&&(o=new k({auth:c,host:n.socketHost,onClosed:m=>{o=null,g(),m&&S();},onReady:C,onTurn:u,socketFactory:n.socketFactory}),o.open());};return g(),S(),{close:()=>i.close(),destroy:()=>{C(),o?.close(),o=null,i.close(),t.remove();},identify:c=>r.identify(c),open:()=>{i.open().then(S);}}}exports.ChatClient=f;exports.ChatPanel=x;exports.DEFAULT_APPEARANCE=v;exports.DEFAULT_APPEARANCE_SETTINGS=h;exports.mountChat=ue;exports.panelStyles=N;exports.resolveAppearance=y;//# sourceMappingURL=chat.cjs.map
65
+ //# sourceMappingURL=chat.cjs.map
@@ -0,0 +1,64 @@
1
+ import { C as ChatClient, M as MessengerConfig, A as AppearanceSettings, a as ChatTurn, b as ChatIdentity, c as ChatClientOptions } from './config-OP9Csae6.cjs';
2
+ export { B as BubbleStyle, d as ChatStorage, e as ChatThread, D as DEFAULT_APPEARANCE_SETTINGS, L as LauncherStyle, f as MessengerSkin, N as NamePlacement, T as TimestampStyle, r as resolveAppearance } from './config-OP9Csae6.cjs';
3
+ import { S as SocketFactory } from './types-68Sc11g8.cjs';
4
+ import './http-BCh716Vs.cjs';
5
+
6
+ interface ChatStrings {
7
+ launcherLabel: string;
8
+ title: string;
9
+ inputPlaceholder: string;
10
+ sendLabel: string;
11
+ closeLabel: string;
12
+ agentLabel: string;
13
+ aiLabel: string;
14
+ unreadLabel: (count: number) => string;
15
+ timeLabel: (createdAt: string) => string;
16
+ emptyTitle: string;
17
+ emptyBody: string;
18
+ }
19
+ type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'starterPrompts'> & AppearanceSettings;
20
+ declare const DEFAULT_APPEARANCE: MessengerAppearance;
21
+ declare function panelStyles(appearance: MessengerAppearance): string;
22
+ declare class ChatPanel {
23
+ private readonly host;
24
+ private readonly client;
25
+ private readonly root;
26
+ private readonly strings;
27
+ private readonly settings;
28
+ private readonly appearance;
29
+ private readonly launcher;
30
+ private readonly badge;
31
+ private panel;
32
+ private lastFocused;
33
+ private unread;
34
+ constructor(host: HTMLElement, client: ChatClient, strings?: Partial<ChatStrings>, appearance?: Partial<MessengerAppearance>);
35
+ private toggle;
36
+ open(): Promise<void>;
37
+ private renderFirstRun;
38
+ close(): void;
39
+ onIncomingTurn(turn: ChatTurn): void;
40
+ private submit;
41
+ private renderThread;
42
+ private appendTurn;
43
+ private stamp;
44
+ private onKeydown;
45
+ private renderBadge;
46
+ }
47
+
48
+ interface MountChatOptions extends ChatClientOptions {
49
+ mountPoint?: HTMLElement;
50
+ strings?: Partial<ChatStrings>;
51
+ appearance?: Partial<MessengerAppearance>;
52
+ pollIntervalMs?: number;
53
+ socketHost?: string;
54
+ socketFactory?: SocketFactory;
55
+ }
56
+ interface ChatHandle {
57
+ open(): void;
58
+ close(): void;
59
+ destroy(): void;
60
+ identify(identity: ChatIdentity): void;
61
+ }
62
+ declare function mountChat(options: MountChatOptions): ChatHandle;
63
+
64
+ export { AppearanceSettings, ChatClient, ChatClientOptions, type ChatHandle, ChatIdentity, ChatPanel, type ChatStrings, ChatTurn, DEFAULT_APPEARANCE, type MessengerAppearance, type MountChatOptions, mountChat, panelStyles };
package/dist/chat.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ import { C as ChatClient, M as MessengerConfig, A as AppearanceSettings, a as ChatTurn, b as ChatIdentity, c as ChatClientOptions } from './config-B-cTz9n1.js';
2
+ export { B as BubbleStyle, d as ChatStorage, e as ChatThread, D as DEFAULT_APPEARANCE_SETTINGS, L as LauncherStyle, f as MessengerSkin, N as NamePlacement, T as TimestampStyle, r as resolveAppearance } from './config-B-cTz9n1.js';
3
+ import { S as SocketFactory } from './types-68Sc11g8.js';
4
+ import './http-BCh716Vs.js';
5
+
6
+ interface ChatStrings {
7
+ launcherLabel: string;
8
+ title: string;
9
+ inputPlaceholder: string;
10
+ sendLabel: string;
11
+ closeLabel: string;
12
+ agentLabel: string;
13
+ aiLabel: string;
14
+ unreadLabel: (count: number) => string;
15
+ timeLabel: (createdAt: string) => string;
16
+ emptyTitle: string;
17
+ emptyBody: string;
18
+ }
19
+ type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'starterPrompts'> & AppearanceSettings;
20
+ declare const DEFAULT_APPEARANCE: MessengerAppearance;
21
+ declare function panelStyles(appearance: MessengerAppearance): string;
22
+ declare class ChatPanel {
23
+ private readonly host;
24
+ private readonly client;
25
+ private readonly root;
26
+ private readonly strings;
27
+ private readonly settings;
28
+ private readonly appearance;
29
+ private readonly launcher;
30
+ private readonly badge;
31
+ private panel;
32
+ private lastFocused;
33
+ private unread;
34
+ constructor(host: HTMLElement, client: ChatClient, strings?: Partial<ChatStrings>, appearance?: Partial<MessengerAppearance>);
35
+ private toggle;
36
+ open(): Promise<void>;
37
+ private renderFirstRun;
38
+ close(): void;
39
+ onIncomingTurn(turn: ChatTurn): void;
40
+ private submit;
41
+ private renderThread;
42
+ private appendTurn;
43
+ private stamp;
44
+ private onKeydown;
45
+ private renderBadge;
46
+ }
47
+
48
+ interface MountChatOptions extends ChatClientOptions {
49
+ mountPoint?: HTMLElement;
50
+ strings?: Partial<ChatStrings>;
51
+ appearance?: Partial<MessengerAppearance>;
52
+ pollIntervalMs?: number;
53
+ socketHost?: string;
54
+ socketFactory?: SocketFactory;
55
+ }
56
+ interface ChatHandle {
57
+ open(): void;
58
+ close(): void;
59
+ destroy(): void;
60
+ identify(identity: ChatIdentity): void;
61
+ }
62
+ declare function mountChat(options: MountChatOptions): ChatHandle;
63
+
64
+ export { AppearanceSettings, ChatClient, ChatClientOptions, type ChatHandle, ChatIdentity, ChatPanel, type ChatStrings, ChatTurn, DEFAULT_APPEARANCE, type MessengerAppearance, type MountChatOptions, mountChat, panelStyles };
package/dist/chat.js ADDED
@@ -0,0 +1,65 @@
1
+ import {c,a as a$2,b as b$1}from'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var I="X-Prodantix-Conversation-Token",T="prodantix.chat.handle";function H(){let r=globalThis.localStorage;if(r)return {get:e=>r.getItem(e),remove:e=>r.removeItem(e),set:(e,t)=>r.setItem(e,t)}}var f=class{constructor(e){this.options=e;a(this,"fetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=a$1(e.fetchImpl),this.host=d(e.host),this.storage=e.storage??H(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(T,JSON.stringify(this.handle)),true)}async send(e){if(!await this.ensureThread())return null;let t=this.handle;return t?(await this.request("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/turns`,{body:{body:e},token:t.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(T);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch{}return this.storage?.remove(T),null}async request(e,t,n={}){let a=this.fetchImpl;if(!a)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(o[I]=n.token);try{let l=await a(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),i=await l.text();return l.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${l.status}`)),null)}catch(l){return this.options.onError?.(l),null}}};var h={bubbleStyle:"tailed",launcherStyle:"circle_outlined",namePlacement:"avatar_only",skin:"concierge",timestampStyle:"cluster"},N=["concierge","console","quiet"],M=["avatar_circle","circle_filled","circle_outlined","pill_labelled","pill_team","squircle_filled"],$=["hairline","outlined","rounded","tailed"],F=["above","avatar_only","gutter","hidden","inline"],R=["cluster","latency","none","trailing","with_name"],b=(r,e,t)=>typeof r=="string"&&e.includes(r)?r:t;function y(r){let e={bubbleStyle:b(r?.bubbleStyle,$,h.bubbleStyle),launcherStyle:b(r?.launcherStyle,M,h.launcherStyle),namePlacement:b(r?.namePlacement,F,h.namePlacement),skin:b(r?.skin,N,h.skin),timestampStyle:b(r?.timestampStyle,R,h.timestampStyle)};return (e.namePlacement==="avatar_only"||e.namePlacement==="hidden")&&(e.timestampStyle==="with_name"||e.timestampStyle==="latency")&&(e.timestampStyle="trailing"),e.namePlacement==="inline"&&e.bubbleStyle==="hairline"&&(e.namePlacement="above"),e}var O={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",sendLabel:"Send",timeLabel:r=>{let e=new Date(r);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:r=>`${r} unread`},v={accentColor:"#5b5bff",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],...h},z={concierge:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}.composer{padding:12px 12px 14px;gap:8px}.composer input{border:0;background:var(--fill);height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",console:".panel{border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.16)}.header{background:var(--paper);color:var(--ink);border-bottom:1px solid var(--hairline)}.close{color:var(--ink-2)}",quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{height:42px;padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.close{color:var(--ink-2)}"},K={avatar_circle:".launcher{width:60px;height:60px;border-radius:30px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2)}",circle_filled:".launcher{width:56px;height:56px;border-radius:28px;background:var(--a);color:#fff}",circle_outlined:".launcher{width:46px;height:46px;border-radius:23px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);font-size:21px}.badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;border-radius:10px;font-size:11.5px}",pill_labelled:".launcher{width:auto;height:52px;border-radius:26px;padding:0 22px;gap:10px;background:var(--a);color:#fff;font-size:14.5px;font-weight:600}",pill_team:".launcher{width:auto;height:54px;border-radius:27px;padding:0 20px 0 8px;gap:10px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink);font-size:14px;font-weight:600}.badge{position:static;background:var(--a)}",squircle_filled:".launcher{width:56px;height:56px;border-radius:16px;background:var(--a);color:#fff}"},B={hairline:".turn{max-width:100%;padding:13px 0;border-top:1px solid var(--hairline);background:none;border-radius:0}.log>.turn:first-child{border-top:0}.turn.end_user{align-self:stretch;display:flex;flex-direction:column;align-items:flex-end}.turn.end_user .body{background:var(--fill);color:var(--ink);border-radius:8px;padding:9px 12px;max-width:85%}",outlined:".turn{background:none;border:1px solid var(--hairline);border-radius:12px}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}",rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},D={above:"",avatar_only:".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .body{background:var(--fill);padding:9px 13px;border-radius:inherit}",gutter:".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".author{display:inline;margin-right:6px;font-weight:650}"},q={cluster:'.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)}',latency:".stamp{font-size:11px;opacity:.7;margin-left:6px}.lat{font-size:11px;opacity:.7;margin-left:6px}",none:"",trailing:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}",with_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}"};function _(r){let e=y(r),t=r.launcherPosition==="bottom_left"?"left":"right",n=r.accentColor;return `${`
2
+ :host {
3
+ all: initial; --a: ${n};
4
+ --paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
5
+ --fill: #f1f5f9; --hairline: #e2e8f0; --field: #cbd5e1; --ink-2: rgba(0,0,0,.72);
6
+ color-scheme: light dark;
7
+ }
8
+ @media (prefers-color-scheme: dark) {
9
+ :host {
10
+ --paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
11
+ --fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --field: rgba(255,255,255,.22); --ink-2: rgba(255,255,255,.70);
12
+ }
13
+ }
14
+ * { box-sizing: border-box; font-family: system-ui, sans-serif; }
15
+ .launcher {
16
+ position: fixed; ${t}: ${r.launcherOffsetX}px; bottom: ${r.launcherOffsetY}px; width: 56px; height: 56px;
17
+ border-radius: 28px; border: none; cursor: pointer;
18
+ display: inline-flex; align-items: center; justify-content: center;
19
+ background: ${n}; color: #fff; font-size: 24px;
20
+ box-shadow: 0 4px 12px rgba(0,0,0,.2);
21
+ }
22
+ .launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
23
+ .badge {
24
+ position: absolute; top: -4px; right: -4px; min-width: 20px; height: 20px;
25
+ border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px;
26
+ display: flex; align-items: center; justify-content: center; padding: 0 4px;
27
+ }
28
+ .panel {
29
+ position: fixed; ${t}: ${r.launcherOffsetX}px; bottom: ${r.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
30
+ height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
31
+ border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
32
+ display: flex; flex-direction: column; overflow: hidden;
33
+ }
34
+ .header { padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
35
+ .header h2 { margin: 0; font-size: 15px; }
36
+ .close { background: none; border: none; color: #fff; cursor: pointer; font-size: 18px; }
37
+ .close:focus-visible { outline: 2px solid #fff; }
38
+ .log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
39
+ .turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
40
+ .turn.end_user { align-self: flex-end; background: ${n}; color: #fff; }
41
+ .turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
42
+ .author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
43
+ .empty { display: flex; flex-direction: column; gap: 8px; padding: 20px 16px; }
44
+ .empty h3 { margin: 0; font-size: 18px; font-weight: 640; letter-spacing: -.015em; }
45
+ .empty p { margin: 0 0 8px; font-size: 13.5px; color: var(--ink-2); }
46
+ .prompt {
47
+ display: flex; align-items: center; min-height: 44px; padding: 0 14px; text-align: left;
48
+ font-family: inherit; font-size: 13.5px; font-weight: 500; color: var(--ink);
49
+ background: none; border: 1px solid var(--hairline); border-radius: 8px; cursor: pointer;
50
+ }
51
+ .prompt:focus-visible { outline: 2px solid ${n}; outline-offset: 2px; }
52
+ .av { width: 30px; height: 30px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 650; color: #fff; background: #7c3f3f; }
53
+ .av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
54
+ .composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--hairline); }
55
+ .composer input { flex: 1; padding: 8px 10px; border: 1px solid var(--field); border-radius: 8px; font-size: 14px; background: transparent; color: var(--ink); }
56
+ .composer input:focus-visible { outline: 2px solid ${n}; }
57
+ .composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${n}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 14.5px; font-weight: 550; }
58
+ .composer button .sendglyph { display: none; width: 19px; height: 19px; }
59
+ .composer button:focus-visible { outline: 2px solid #0b0e14; }
60
+ @media (prefers-reduced-motion: no-preference) {
61
+ .panel { animation: rise 180ms ease-out; }
62
+ @keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
63
+ }
64
+ `}${z[e.skin]}${K[e.launcherStyle]}${B[e.bubbleStyle]}${D[e.namePlacement]}${q[e.timestampStyle]}`}var U=["end_user","agent","ai"],x=class{constructor(e,t,n={},a$1={}){this.host=e;this.client=t;a(this,"root");a(this,"strings");a(this,"settings");a(this,"appearance");a(this,"launcher");a(this,"badge");a(this,"panel",null);a(this,"lastFocused",null);a(this,"unread",0);this.strings={...O,...n},this.appearance={...v,...a$1},this.settings=y({...v,...a$1}),this.root=e.attachShadow({mode:"closed"});let o=document.createElement("style");o.textContent=_({...v,...a$1}),this.root.append(o),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.textContent="\u{1F4AC}",this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.launcher.append(this.badge),this.root.append(this.launcher);}toggle(){this.panel?this.close():this.open();}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className="panel",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=document.createElement("h2");n.textContent=this.strings.title;let a=document.createElement("button");a.className="close",a.type="button",a.setAttribute("aria-label",this.strings.closeLabel),a.textContent="\xD7",a.addEventListener("click",()=>this.close()),t.append(n,a);let o=document.createElement("div");o.className="log",o.setAttribute("role","log"),o.setAttribute("aria-live","polite"),o.setAttribute("aria-label",this.strings.title);let l=document.createElement("form");l.className="composer";let i=document.createElement("input");i.type="text",i.setAttribute("aria-label",this.strings.inputPlaceholder),i.placeholder=this.strings.inputPlaceholder;let p=document.createElement("button");p.type="submit",p.setAttribute("aria-label",this.strings.sendLabel),p.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 u=document.createElement("span");u.className="sendtext",u.textContent=this.strings.sendLabel,p.append(u),l.append(i,p),l.addEventListener("submit",g=>{g.preventDefault(),this.submit(i,o);}),e.append(t,o,l),e.addEventListener("keydown",g=>this.onKeydown(g,e,a)),this.root.append(e),this.panel=e,i.focus();let d=await this.client.load();d&&d.turns.length>0?this.renderThread(o,d):this.renderFirstRun(o,i);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let a=document.createElement("h3");a.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(a,o);for(let l of this.appearance.starterPrompts){let i=document.createElement("button");i.className="prompt",i.type="button",i.textContent=l,i.addEventListener("click",()=>{t.value=l,this.submit(t,e);}),n.append(i);}e.replaceChildren(n);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim();if(!n)return;e.value="",t.querySelector(".empty")?.remove();let a=await this.client.send(n);a&&this.appendTurn(t,a);}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t){e.querySelector(".empty")?.remove();let n=U.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${n}`,n!=="end_user"&&(a.namePlacement==="avatar_only"||a.namePlacement==="gutter")){let d=document.createElement("span");d.className=n==="ai"?"av bot":"av",d.textContent=n==="ai"?this.strings.aiLabel:this.strings.agentLabel.slice(0,2).toUpperCase(),d.setAttribute("aria-hidden","true"),o.append(d);}let i=document.createElement("div");if(i.className="body",n!=="end_user"&&a.namePlacement!=="hidden"&&!(a.namePlacement==="avatar_only"&&n==="agent")||n==="ai"&&a.namePlacement==="hidden"){let d=document.createElement("div");d.className=n==="ai"?"author ai":"author",d.textContent=n==="ai"?this.strings.aiLabel:this.strings.agentLabel,(a.timestampStyle==="with_name"||a.timestampStyle==="latency")&&d.append(this.stamp(t)),i.append(d);}let u=document.createElement("div");u.textContent=t.body,i.append(u),a.timestampStyle==="trailing"&&i.append(this.stamp(t)),o.append(i),e.append(o),e.scrollTop=e.scrollHeight;}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let a=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(a.length===0)return;let o=a[0],l=a[a.length-1],i=this.root.activeElement;e.shiftKey&&i===o?(e.preventDefault(),l.focus()):!e.shiftKey&&i===l?(e.preventDefault(),o.focus()):i===null&&(e.preventDefault(),n.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};var j="/socket.io/?EIO=4&transport=websocket",k=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??W,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${j}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$1());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function W(r){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(r)}function oe(r){let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=r.mountPoint??e.createElement("div");r.mountPoint||e.body.append(t);let n=new f(r),a=new x(t,n,r.strings,r.appearance),o=new Set,l,i=null,p=r.pollIntervalMs??15e3,u=c=>{o.has(c.id)||c.authorKind==="end_user"||(o.add(c.id),a.onIncomingTurn(c));},d=async()=>{if(!n.hasThread)return;let c=await n.load();if(c){for(let m of c.turns)u(m);o=new Set(c.turns.map(m=>m.id));}},g=()=>{l||p<=0||(l=setInterval(()=>void d(),p));},C=()=>{l&&clearInterval(l),l=void 0;},S=()=>{if(i||!r.socketHost)return;let c=n.socketAuth;c&&(i=new k({auth:c,host:r.socketHost,onClosed:m=>{i=null,g(),m&&S();},onReady:C,onTurn:u,socketFactory:r.socketFactory}),i.open());};return g(),S(),{close:()=>a.close(),destroy:()=>{C(),i?.close(),i=null,a.close(),t.remove();},identify:c=>n.identify(c),open:()=>{a.open().then(S);}}}export{f as ChatClient,x as ChatPanel,v as DEFAULT_APPEARANCE,h as DEFAULT_APPEARANCE_SETTINGS,oe as mountChat,_ as panelStyles,y as resolveAppearance};//# sourceMappingURL=chat.js.map
65
+ //# sourceMappingURL=chat.js.map
@@ -0,0 +1,2 @@
1
+ var d=Object.defineProperty;var e=(b,a,c)=>a in b?d(b,a,{enumerable:true,configurable:true,writable:true,value:c}):b[a]=c;var f=(b,a,c)=>e(b,typeof a!="symbol"?a+"":a,c);export{f as a};//# sourceMappingURL=chunk-5XGN7UAV.js.map
2
+ //# sourceMappingURL=chunk-5XGN7UAV.js.map
@@ -0,0 +1,2 @@
1
+ import {c as c$1,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {a as a$1,d,b as b$1,c}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var h=class extends Error{constructor(t,r,n){super(r,n);a(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends h{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends h{constructor(t,r){super("validation",r);a(this,"field");this.field=t,this.name="ValidationError";}},l=class extends h{constructor(t,r,n){super("transport",t,n);a(this,"status");this.status=r,this.name="TransportError";}};var y=class{constructor(){a(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};function be(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new y}return new y}var K="prodantix-js",D="0.0.1";var f=Symbol("absent");function ne(s,e){if(s==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,s))return t[s];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,s)?r[s]:f}function p(s){return s===f?"undefined":String(s)}function O(s){return s===f?Number.NaN:Number(s)}function N(s){return s!==f&&s!==null&&s!==""}function L(s,e){if(!Array.isArray(e))return false;let t=p(s);return e.map(r=>String(r)).includes(t)}function V(s,e){let t=ne(s.attribute,e),r=s.value;switch(s.op){case "is_set":return N(t);case "is_not_set":return !N(t);case "eq":return p(t)===p(r===void 0?f:r);case "neq":return p(t)!==p(r===void 0?f:r);case "contains":return p(t).includes(p(r===void 0?f:r));case "in":return L(t,r);case "not_in":return Array.isArray(r)?!L(t,r):false;case "gt":return k(t,r,(n,i)=>n>i);case "gte":return k(t,r,(n,i)=>n>=i);case "lt":return k(t,r,(n,i)=>n<i);case "lte":return k(t,r,(n,i)=>n<=i);case "in_cohort":return typeof r=="string"&&r!==""&&(e.cohorts??[]).includes(r);case "not_in_cohort":return typeof r=="string"&&r!==""&&!(e.cohorts??[]).includes(r);default:return false}}function k(s,e,t){let r=O(s),n=e===void 0?Number.NaN:O(e);return Number.isNaN(r)||Number.isNaN(n)?false:t(r,n)}function j(s,e){let t=`${s}:${e}`,r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return (r>>>0)%100}function _(s,e){return s.targeting.length===0||s.targeting.every(t=>V(t,e))}function U(s,e){let t=j(s.key,e.distinctId),r=s.variations??[];if(r.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let n=0;for(let i=r.length-1;i>=0;i--)if(n+=r[i].weight,t<n)return r[i].key;return r[0].key}function P(s,e,t,r){for(let n of s.prerequisites??[]){if(r.includes(n.flagKey))return false;let i=e.find(c=>c.key===n.flagKey);if(!i||!i.enabled)return false;r.push(i.key);let a=P(i,e,t,r)&&_(i,t)&&U(i,t)===n.variationKey;if(r.pop(),!a)return false}return true}function b(s,e,t){return s.enabled?P(s,e,t,[s.key])?_(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:j(s.key,t.distinctId)<s.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function Ee(s,e){return b(s,[],e)}function z(s,e){let t={};for(let r of s)t[r.key]=b(r,s,e).enabled;return t}function x(s,e,t){let r=s.variations??[],n=r[0];if(!n)return null;if(!s.enabled||!P(s,e,t,[s.key])||!_(s,t))return n;let i=U(s,t);return r.find(a=>a.key===i)??n}function Se(s,e){return x(s,[],e)}function Te(s,e,t){let r=s.find(n=>n.key===e);return r?x(r,s,t)?.value??null:null}function H(s){return s.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}var F=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let c=JSON.parse(await a.text());return {flags:c.flags??{},variants:c.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,r=b$1(),n=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),c={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(c.socketUrl=a.socketUrl),c}finally{n!==void 0&&clearTimeout(n);}}async memberships(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var w=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(t,r,{headers:this.authHeaders(),method:"GET"});if(!n.ok)throw new l(`inbox request failed with status ${n.status}`,n.status);return JSON.parse(await n.text()).messages??[]}async markRead(e,t){let r=this.requireFetch(),n=`${this.host}/v1/messages/read`,i=await this.request(r,n,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,r){let n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...r,signal:n?.signal})}finally{i!==void 0&&clearTimeout(i);}}};function J(s){return s>=400&&s<500&&s!==429}var I=class{constructor(e={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=a$1(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??c,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),n;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,r);if(a.ok)return;if(J(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);n=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&J(a.status))throw a;n=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:n})}async attempt(e,t,r){let n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:r,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:n?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Q={now:()=>new Date};function E(s){return s.toISOString()}function ie(){return globalThis.crypto}function oe(s){s[6]=s[6]&15|64,s[8]=s[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(s[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ae(){let s=ie();if(s?.randomUUID)return s.randomUUID();let e=new Uint8Array(16);if(s?.getRandomValues)s.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return oe(e)}var B={uuid:ae};var le=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ce=/^(?:\$|[a-z])[a-z0-9_.]*$/;function G(s){let e=0;for(let t of s)e+=1;return e}function W(s){return le.test(s)}function ue(s){return ce.test(s)}function X(s){let e=G(s);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function Y(s){let e=G(s);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!ue(s))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var de=s=>{};function Z(s){if(!s.apiKey||!W(s.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new v("host is required (the ingest base URL)");let e=d(s.host),t=s.defaultProperties;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??Q,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:s.flagsHost?d(s.flagsHost):e,flushAt:s.flushAt??20,flushIntervalMs:s.flushIntervalMs??1e4,host:e,ids:s.ids??B,locale:s.locale,maxQueueSize:s.maxQueueSize??1e3,maxRetries:s.maxRetries??3,namespace:s.apiKey.slice(0,16),onError:s.onError??de,os:s.os,requestTimeoutMs:s.requestTimeoutMs??1e4,sdkName:s.sdkName??K,sdkVersion:s.sdkVersion??D,socketFactory:s.socketFactory,storage:s.storage??new y,streamFlags:s.streamFlags??false,transport:s.transport}}function ee(s,e,t){Y(s.eventName),X(s.distinctId);let r={distinct_id:s.distinctId,event_id:s.eventId??t.uuid(),event_name:s.eventName,properties:s.properties??{},schema_version:1,timestamp:E(s.timestamp??e.now())};return s.context&&(r.context=s.context),s.sessionId&&(r.session_id=s.sessionId),r}var he="/socket.io/?EIO=4&transport=websocket",pe=250,S=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"pending",null);a(this,"lastKey","");a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??fe,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${he}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c$1(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$2());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let r=t.payload?.key;this.lastKey=typeof r=="string"?r:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},pe));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function fe(s){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(s)}var T=class{constructor(e,t,r){this.storage=e;this.ids=t;this.namespace=r;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=t.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let i=e.getItem(this.key("distinct_id"));i?(this.distinctId=i,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}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var C=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;a(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var ge="queue",me=1e3,te=3e4,se=s=>{let e={};return s.avatar!==void 0&&(e.$avatar=s.avatar),s.email!==void 0&&(e.$email=s.email),s.name!==void 0&&(e.$name=s.name),s.phone!==void 0&&(e.$phone=s.phone),e},R=class{constructor(e){a(this,"config");a(this,"identity");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");a(this,"membershipCache");a(this,"stream");a(this,"shutDown",false);a(this,"exposures",new Set);this.config=Z(e),this.identity=new T(this.config.storage,this.config.ids,this.config.namespace),this.queue=new C(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new h("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new I({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new w({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()}capture(e,t={}){try{let r={...this.config.defaultProperties(),...t.properties??{}},n=ee({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:t.sessionId,timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(r){this.config.onError(r);}}identify(e,t={}){let r=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),i=this.identity.identify(e),a={};n&&i.changed&&(a.$anon_distinct_id=r);let c={...se(t.traits??{}),...t.set??{}};Object.keys(c).length>0&&(a.$set=c),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,r){let n={$group_key:t,$group_type:e};r&&(n.$set=r),this.capture("$group",{properties:n});}setPersonProperties(e,t){let r={};e&&(r.$set=e),t&&(r.$set_once=t),this.capture("$set",{properties:r});}setPersonTraits(e){let t=se(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let r=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(r)),r}async getVariant(e){let t=await this.getAllFlags(),r=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,r?.key??String(t[e]??false)),r}async getVariantLocal(e,t={}){let r=await this.flagSnapshot(),n=r.flags.find(re=>re.key===e),i=await this.localContext(t,r.flags),a=n?x(n,r.flags,i):null,c=n?b(n,r.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(c)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let r=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(r)||(this.exposures.add(r),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return z(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let r=await this.flagSnapshot(),n=r.flags.find(c=>c.key===e),i=await this.localContext(t,r.flags),a=n?b(n,r.flags,i).enabled:false;return this.recordExposure(e,(n?x(n,r.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let r=this.identity.getDistinctId(),n=e.cohorts;if(n===void 0&&H(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&i-this.membershipCache.fetchedAt<te?n=this.membershipCache.cohorts:(n=await this.flagsClient.memberships(r),this.membershipCache={cohorts:n,distinctId:r,fetchedAt:i});}return {attributes:e.attributes,cohorts:n,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<te)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 S({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(r=>this.config.onError(r));},onClosed:r=>{this.stream=void 0,r&&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(me);try{await this.transport.send({body:{events:e,sent_at:E(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.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}.${ge}`}};function xt(s){return new R(s)}export{h as a,v as b,m as c,l as d,y as e,be as f,ae as g,K as h,D as i,V as j,j as k,Ee as l,z as m,Se as n,Te as o,F as p,w as q,I as r,R as s,xt as t};//# sourceMappingURL=chunk-CSIP3PZ7.js.map
2
+ //# sourceMappingURL=chunk-CSIP3PZ7.js.map
@@ -0,0 +1,2 @@
1
+ function c(e){return `40${JSON.stringify(e)}`}function N(){return "3"}function u(e){let t=e.charAt(0),o=e.slice(1);if(t==="2")return {kind:"ping"};if(t==="1")return {kind:"disconnect"};if(t==="0"){let n=E(o);return {kind:"open",pingInterval:typeof n?.pingInterval=="number"?n.pingInterval:25e3,pingTimeout:typeof n?.pingTimeout=="number"?n.pingTimeout:2e4}}if(t!=="4")return {kind:"other"};let r=o.charAt(0),s=o.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let n=E(s);return {kind:"connectError",message:typeof n?.message=="string"?n.message:"refused"}}if(r!=="2")return {kind:"other"};let i=E(s);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function E(e){try{return JSON.parse(e)}catch{return null}}export{c as a,N as b,u as c};//# sourceMappingURL=chunk-V77KYPOF.js.map
2
+ //# sourceMappingURL=chunk-V77KYPOF.js.map
@@ -0,0 +1,2 @@
1
+ function r(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function n(){let e=globalThis.AbortController;return e?new e:void 0}var o=e=>new Promise(t=>{setTimeout(t,e);});function i(e){return e.replace(/\/+$/,"")}export{r as a,n as b,o as c,i as d};//# sourceMappingURL=chunk-VG77TYVX.js.map
2
+ //# sourceMappingURL=chunk-VG77TYVX.js.map
@@ -0,0 +1,105 @@
1
+ import { d as EventProperties, P as ProdantixConfig, e as FlagVariant, I as InboxMessage } from './types-68Sc11g8.js';
2
+
3
+ interface LocalFlagContext {
4
+ attributes?: EventProperties;
5
+ /** The cohorts the current distinct id belongs to. When omitted and the
6
+ * snapshot names a cohort, the client fetches them once per distinct id. */
7
+ cohorts?: string[];
8
+ properties?: EventProperties;
9
+ }
10
+ interface CaptureOptions {
11
+ properties?: EventProperties;
12
+ sessionId?: string;
13
+ timestamp?: Date;
14
+ }
15
+ /**
16
+ * The profile keys the platform itself understands.
17
+ *
18
+ * They are ordinary properties on the wire; the only thing that makes them
19
+ * special is the `$` prefix, which is how this platform marks a name it owns
20
+ * rather than one the caller chose. Passing them through `traits` means never
21
+ * having to remember whether the console reads `email` or `$email`: an
22
+ * unprefixed `email` is a property of your own and stays one, and would never
23
+ * reach the Email column.
24
+ */
25
+ interface PersonTraits {
26
+ avatar?: string;
27
+ email?: string;
28
+ name?: string;
29
+ phone?: string;
30
+ }
31
+ interface IdentifyOptions {
32
+ /** Arbitrary profile properties your own code defines. */
33
+ set?: EventProperties;
34
+ /** The reserved traits the console renders as fields. */
35
+ traits?: PersonTraits;
36
+ }
37
+ declare class ProdantixClient {
38
+ private readonly config;
39
+ private readonly identity;
40
+ private readonly queue;
41
+ private readonly transport;
42
+ private readonly flagsClient;
43
+ private readonly messagesClient;
44
+ private readonly context;
45
+ private flushTimer?;
46
+ private flushing;
47
+ private cachedFlags?;
48
+ private cachedSnapshot?;
49
+ private membershipCache?;
50
+ private stream?;
51
+ private shutDown;
52
+ /** One `$feature_flag_called` per (distinct id, flag, response) per client
53
+ * lifetime: the experiment engine attributes on the FIRST exposure, so a
54
+ * second event for the same answer would only cost the project an event. */
55
+ private readonly exposures;
56
+ constructor(config: ProdantixConfig);
57
+ get distinctId(): string;
58
+ get anonymousId(): string;
59
+ capture(eventName: string, options?: CaptureOptions): void;
60
+ identify(distinctId: string, options?: IdentifyOptions): void;
61
+ alias(alias: string): void;
62
+ group(groupType: string, groupKey: string, properties?: EventProperties): void;
63
+ setPersonProperties(set?: EventProperties, setOnce?: EventProperties): void;
64
+ /**
65
+ * Attach the reserved traits to whoever is current, without an identify.
66
+ *
67
+ * This does NOT make the person identified: only `identify()` does that, so a
68
+ * trait set on an anonymous visitor leaves them anonymous and carrying an
69
+ * address, which is exactly what a newsletter signup before login looks like.
70
+ */
71
+ setPersonTraits(traits: PersonTraits): void;
72
+ getAllFlags(): Promise<Record<string, boolean>>;
73
+ isFeatureEnabled(key: string): Promise<boolean>;
74
+ /** The assigned variation for one flag, or null when the flag is unknown or
75
+ * carries no variations. Records the exposure either way. */
76
+ getVariant(key: string): Promise<FlagVariant | null>;
77
+ getVariantLocal(key: string, context?: LocalFlagContext): Promise<FlagVariant | null>;
78
+ private recordExposure;
79
+ getCachedFlag(key: string): boolean | undefined;
80
+ getLocalFlags(context?: LocalFlagContext): Promise<Record<string, boolean>>;
81
+ isFeatureEnabledLocal(key: string, context?: LocalFlagContext): Promise<boolean>;
82
+ /** The evaluation context for a local read. Memberships come from the caller
83
+ * when supplied, else from the server once per distinct id per snapshot
84
+ * TTL, and only when the snapshot names a cohort at all. */
85
+ private localContext;
86
+ private flagSnapshot;
87
+ /** Opens the flag stream once, when streaming was asked for and the snapshot
88
+ * names a gateway. A pushed change drops the cached snapshot and refetches
89
+ * it; a refused handshake stays closed, a dropped one reopens. */
90
+ private maybeStream;
91
+ getInbox(): Promise<InboxMessage[]>;
92
+ markMessageRead(messageId: string): Promise<void>;
93
+ flush(): Promise<void>;
94
+ reset(): void;
95
+ shutdown(): Promise<void>;
96
+ private enqueue;
97
+ private persistQueue;
98
+ private restoreQueue;
99
+ private startTimer;
100
+ private stopTimer;
101
+ private persistKey;
102
+ }
103
+ declare function createClient(config: ProdantixConfig): ProdantixClient;
104
+
105
+ export { type CaptureOptions as C, type IdentifyOptions as I, type LocalFlagContext as L, ProdantixClient as P, createClient as c };