@prodantix/sdk 0.6.0 → 0.7.0-beta.438

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 +23 -18
  3. package/dist/chat.d.cts +125 -7
  4. package/dist/chat.d.ts +125 -7
  5. package/dist/chat.js +25 -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-C9Njc6-j.d.ts} +34 -1
  10. package/dist/{config-CMF9zz1a.d.cts → config-CpfUyEw8.d.cts} +34 -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 +11 -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
package/dist/chat.d.ts CHANGED
@@ -1,8 +1,105 @@
1
- import { C as ChatThread, P as PageContext, a as ChatTurn, b as ChatUpload, M as MessengerConfig, A as AppearanceSettings, c as ChatIdentity, d as ChatClientOptions } from './config-DqC0lcr7.js';
2
- export { B as BubbleFill, e as BubbleShape, f as ChatAttachment, g as ChatClient, h as ChatStorage, i as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, j as FileResponseLike, L as LauncherContent, k as LauncherFill, l as LauncherShape, m as LauncherSize, n as MessengerSkin, N as NamePlacement, S as StampContent, o as StampPlacement, r as resolveAppearance } from './config-DqC0lcr7.js';
3
- import { S as SocketFactory } from './types-DjMXp6Wg.js';
1
+ import { A as ArticleHit, a as ArticleCollection, H as HelpWords, M as MessengerAttachments, b as AppearanceSettings, C as ChatThread, P as PageContext, c as ChatTurn, d as ChatUpload, e as MessengerConfig, f as ChatIdentity, g as ChatClientOptions } from './config-C9Njc6-j.js';
2
+ export { B as BubbleFill, h as BubbleShape, i as ChatAttachment, j as ChatClient, k as ChatStorage, l as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, m as FileResponseLike, L as LauncherContent, n as LauncherFill, o as LauncherShape, p as LauncherSize, q as MessengerSkin, N as NamePlacement, S as StampContent, r as StampPlacement, s as resolveAppearance } from './config-C9Njc6-j.js';
3
+ import { S as SocketFactory } from './types-Q2VNlJbG.js';
4
4
  import './http-BCh716Vs.js';
5
5
 
6
+ declare const SEARCH_PAUSE_MS = 300;
7
+ declare const TYPED_MINIMUM = 3;
8
+ declare const SUGGESTED = 3;
9
+ declare const HELP_CSS = "[hidden]{display:none!important}.hsearch{display:flex;align-items:center;gap:8px;height:40px;padding:0 12px;color:var(--ink-3);border:1px solid var(--hairline);border-radius:10px}.hsearch:focus-within{border-color:var(--a);box-shadow:0 0 0 3px color-mix(in srgb,var(--a) 20%,transparent)}.hsearch input{flex:1;min-width:0;height:100%;padding:0;border:0;outline:0;background:none;font:inherit;font-size:14px;color:var(--ink)}.hsearch input::placeholder{color:var(--ink-3)}.hsearch svg,.hrow svg{display:block;flex:none;width:16px;height:16px;fill:currentColor}.hlabel{margin:6px 0 0;font-size:12px;font-weight:600;color:var(--ink-3)}.hrows{display:flex;flex-direction:column}.hrow{display:flex;align-items:center;gap:10px;width:100%;padding:10px 2px;font:inherit;font-size:14px;color:var(--ink);text-align:left;background:none;border:0;border-bottom:1px solid var(--hairline);cursor:pointer}.hrow span{flex:1;min-width:0}.hrow small{font-size:12px;color:var(--ink-3)}.hrow svg{color:var(--ink-3)}.hrow:focus-visible{outline:2px solid var(--a);outline-offset:-2px}.hnone{margin:0;padding:10px 2px;font-size:13.5px;color:var(--ink-2)}.hview{flex:1;min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:10px;padding:16px}.htabs{display:grid;grid-template-columns:1fr 1fr;border-top:1px solid var(--hairline)}.htab{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 0 10px;font:inherit;font-size:11.5px;font-weight:550;color:var(--ink-3);background:none;border:0;cursor:pointer}.htab[aria-selected=\"true\"]{color:var(--a)}.htab svg{display:block;width:22px;height:22px;fill:currentColor}.htab:focus-visible{outline:2px solid var(--a);outline-offset:-2px}.hsugg{margin:0 10px 8px;padding:10px 12px 4px;border:1px solid var(--hairline);border-radius:10px}.hsugg p{margin:0 0 4px;font-size:12px;font-weight:600;color:var(--ink-3)}.hsugg .hrow{padding:8px 0;font-size:13.5px}.hsugg .hrow:last-child{border-bottom:0}.hreader{flex:1;min-height:0;display:flex;flex-direction:column}.hbar{flex:none;display:flex;align-items:center;gap:6px;height:52px;padding:0 8px;border-bottom:1px solid var(--hairline)}.hbar b{flex:1;min-width:0;font-size:14px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.hbtn{display:grid;place-items:center;flex:none;width:32px;height:32px;padding:0;border:0;border-radius:8px;background:none;color:var(--ink);cursor:pointer}.hbtn svg{display:block;width:20px;height:20px;fill:currentColor}.hbtn:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.hbtn:focus-visible{outline:2px solid var(--a)}.hreader iframe{flex:1;min-height:0;width:100%;border:0}.hblocked{flex:1;display:flex;flex-direction:column;gap:8px;padding:20px 18px}.hblocked h3{margin:0;font-size:18px;font-weight:640;letter-spacing:-.015em}.hblocked a{font-size:14px;color:var(--ink);text-decoration:underline}.hmore{flex:none;display:flex;align-items:center;justify-content:space-between;gap:10px;margin:6px 18px 16px;padding:12px 14px;font-size:13.5px;background:var(--fill);border-radius:10px}.hmore button{padding:7px 14px;font:inherit;font-size:13px;font-weight:600;color:#fff;white-space:nowrap;background:var(--a);border:0;border-radius:8px;cursor:pointer}.hmore button:focus-visible{outline:2px solid var(--ink);outline-offset:2px}.hrow,.htab,.hmore,.hlabel,.hnone,.hsugg p{line-height:1.45}";
10
+ declare function searchBox(words: HelpWords, onWords: (words: string) => void): HTMLElement;
11
+ declare function paused(run: (words: string) => void): (words: string) => void;
12
+ declare const isReadable: (hit: ArticleHit) => boolean;
13
+ declare function articleRows(rows: HTMLElement, found: readonly ArticleHit[], noMatches: string | null, onOpen: (hit: ArticleHit) => void): HTMLElement;
14
+ declare function collectionRows(rows: HTMLElement, collections: readonly ArticleCollection[], onOpen: (collection: ArticleCollection) => void): HTMLElement;
15
+ declare function emptyRows(): HTMLElement;
16
+ declare function helpTabs(words: HelpWords, onPick: (help: boolean) => void): HTMLElement;
17
+ declare function suggestions(words: HelpWords, hits: readonly ArticleHit[], onOpen: (hit: ArticleHit) => void): HTMLElement;
18
+ interface ReaderControls {
19
+ back: () => void;
20
+ close: () => void;
21
+ messageUs: () => void;
22
+ }
23
+ declare function frameAddress(embedUrl: string, scheme: 'dark' | 'light'): string;
24
+ declare function reader(hit: ArticleHit, words: HelpWords, closeLabel: string, scheme: 'dark' | 'light', controls: ReaderControls): HTMLElement;
25
+ interface HelpSource {
26
+ articles?(query: string): Promise<ArticleHit[]>;
27
+ popularArticles?(): Promise<ArticleHit[]>;
28
+ collections?(): Promise<ArticleCollection[]>;
29
+ collectionArticles?(collection: string): Promise<ArticleHit[]>;
30
+ }
31
+ type HelpRead = <T>(suffix: string, params: Record<string, string>) => Promise<T | null>;
32
+ declare function helpReads(read: HelpRead): Required<HelpSource>;
33
+ interface HelpHost {
34
+ close: () => void;
35
+ closeLabel: string;
36
+ panel: HTMLElement;
37
+ scheme: 'dark' | 'light' | 'system' | undefined;
38
+ source: HelpSource;
39
+ words: HelpWords;
40
+ }
41
+ type HelpClient = HelpSource & {
42
+ helpCentre?: HelpRead;
43
+ };
44
+ declare function hostOf(client: HelpClient, lent: Omit<HelpHost, 'source'>): HelpHost | null;
45
+ declare function setHelping(panel: HTMLElement, helping: boolean): void;
46
+ declare function showArticle(host: HelpHost, hit: ArticleHit): void;
47
+ declare function firstView(host: HelpHost, empty: HTMLElement): void;
48
+ declare function helpTab(host: HelpHost): void;
49
+ declare function whileTyping(host: HelpHost, input: HTMLInputElement, composer: HTMLElement): void;
50
+
51
+ declare const Articles_HELP_CSS: typeof HELP_CSS;
52
+ type Articles_HelpClient = HelpClient;
53
+ type Articles_HelpHost = HelpHost;
54
+ type Articles_HelpRead = HelpRead;
55
+ type Articles_HelpSource = HelpSource;
56
+ type Articles_ReaderControls = ReaderControls;
57
+ declare const Articles_SEARCH_PAUSE_MS: typeof SEARCH_PAUSE_MS;
58
+ declare const Articles_SUGGESTED: typeof SUGGESTED;
59
+ declare const Articles_TYPED_MINIMUM: typeof TYPED_MINIMUM;
60
+ declare const Articles_articleRows: typeof articleRows;
61
+ declare const Articles_collectionRows: typeof collectionRows;
62
+ declare const Articles_emptyRows: typeof emptyRows;
63
+ declare const Articles_firstView: typeof firstView;
64
+ declare const Articles_frameAddress: typeof frameAddress;
65
+ declare const Articles_helpReads: typeof helpReads;
66
+ declare const Articles_helpTab: typeof helpTab;
67
+ declare const Articles_helpTabs: typeof helpTabs;
68
+ declare const Articles_hostOf: typeof hostOf;
69
+ declare const Articles_isReadable: typeof isReadable;
70
+ declare const Articles_paused: typeof paused;
71
+ declare const Articles_reader: typeof reader;
72
+ declare const Articles_searchBox: typeof searchBox;
73
+ declare const Articles_setHelping: typeof setHelping;
74
+ declare const Articles_showArticle: typeof showArticle;
75
+ declare const Articles_suggestions: typeof suggestions;
76
+ declare const Articles_whileTyping: typeof whileTyping;
77
+ declare namespace Articles {
78
+ export { Articles_HELP_CSS as HELP_CSS, type Articles_HelpClient as HelpClient, type Articles_HelpHost as HelpHost, type Articles_HelpRead as HelpRead, type Articles_HelpSource as HelpSource, type Articles_ReaderControls as ReaderControls, Articles_SEARCH_PAUSE_MS as SEARCH_PAUSE_MS, Articles_SUGGESTED as SUGGESTED, Articles_TYPED_MINIMUM as TYPED_MINIMUM, Articles_articleRows as articleRows, Articles_collectionRows as collectionRows, Articles_emptyRows as emptyRows, Articles_firstView as firstView, Articles_frameAddress as frameAddress, Articles_helpReads as helpReads, Articles_helpTab as helpTab, Articles_helpTabs as helpTabs, Articles_hostOf as hostOf, Articles_isReadable as isReadable, Articles_paused as paused, Articles_reader as reader, Articles_searchBox as searchBox, Articles_setHelping as setHelping, Articles_showArticle as showArticle, Articles_suggestions as suggestions, Articles_whileTyping as whileTyping };
79
+ }
80
+
81
+ declare const filesCss: (taking: boolean, composerShape: AppearanceSettings["composerShape"]) => string;
82
+ declare function sizeOf(bytes: number): string;
83
+ interface FilesHost {
84
+ attachLabel: string;
85
+ removeFileLabel: string;
86
+ fileRefusal: (size: string, limit: string) => string;
87
+ objectUrl: (blob: Blob) => string;
88
+ root: ShadowRoot;
89
+ hold: (file: File | null) => void;
90
+ }
91
+ declare function attachField(host: FilesHost, composer: HTMLElement, input: HTMLInputElement, log: HTMLElement, files: MessengerAttachments): void;
92
+ declare function drawFile(parent: HTMLElement, name: string, type: string, bytes: number, blob: Promise<Blob | null>, objectUrl: (blob: Blob) => string): void;
93
+
94
+ type Files_FilesHost = FilesHost;
95
+ declare const Files_attachField: typeof attachField;
96
+ declare const Files_drawFile: typeof drawFile;
97
+ declare const Files_filesCss: typeof filesCss;
98
+ declare const Files_sizeOf: typeof sizeOf;
99
+ declare namespace Files {
100
+ export { type Files_FilesHost as FilesHost, Files_attachField as attachField, Files_drawFile as drawFile, Files_filesCss as filesCss, Files_sizeOf as sizeOf };
101
+ }
102
+
6
103
  interface ChatStrings {
7
104
  launcherLabel: string;
8
105
  title: string;
@@ -22,7 +119,7 @@ interface ChatStrings {
22
119
  removeFileLabel: string;
23
120
  fileRefusal: (size: string, limit: string) => string;
24
121
  }
25
- type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'attachments' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'starterPrompts' | 'team'> & AppearanceSettings;
122
+ type MessengerAppearance = Pick<MessengerConfig, 'accentColor' | 'attachments' | 'availability' | 'awayMessage' | 'greeting' | 'launcherOffsetX' | 'launcherOffsetY' | 'launcherPosition' | 'help' | 'poweredBy' | 'starterPrompts' | 'team'> & AppearanceSettings;
26
123
  declare const DEFAULT_APPEARANCE: MessengerAppearance;
27
124
  interface ChatSource {
28
125
  avatarUrl(url: string): string;
@@ -30,9 +127,18 @@ interface ChatSource {
30
127
  send(body: string, pageContext?: PageContext, attachmentIds?: string[]): Promise<ChatTurn | null>;
31
128
  upload?(file: File): Promise<ChatUpload | null>;
32
129
  file?(path: string): Promise<Blob | null>;
130
+ articles?(query: string): Promise<ArticleHit[]>;
131
+ popularArticles?(): Promise<ArticleHit[]>;
132
+ collections?(): Promise<ArticleCollection[]>;
133
+ collectionArticles?(collection: string): Promise<ArticleHit[]>;
134
+ helpCentre?<T>(suffix: string, params: Record<string, string>): Promise<T | null>;
33
135
  }
34
136
  type ChatScheme = 'dark' | 'light' | 'system';
137
+ type HelpKit = typeof Articles;
138
+ type FilesKit = typeof Files;
35
139
  interface ChatPanelOptions {
140
+ help?: () => Promise<HelpKit | null>;
141
+ files?: () => Promise<FilesKit | null>;
36
142
  scheme?: ChatScheme;
37
143
  shadowMode?: 'closed' | 'open';
38
144
  }
@@ -47,26 +153,37 @@ declare class ChatPanel {
47
153
  private readonly launcher;
48
154
  private readonly badge;
49
155
  private panel;
156
+ private scrim;
50
157
  private lastFocused;
51
158
  private unread;
52
159
  private pendingTurns;
53
160
  private openNow;
54
- private readonly style;
161
+ private readonly styles;
55
162
  private scheme;
56
163
  private picked;
57
164
  private objectUrls;
165
+ private readonly helpLoader;
166
+ private kit;
167
+ private kitLoad;
168
+ private readonly filesLoader;
169
+ private filesKit;
170
+ private filesLoad;
58
171
  constructor(host: HTMLElement, client: ChatSource, strings?: Partial<ChatStrings>, appearance?: Partial<MessengerAppearance>, options?: ChatPanelOptions);
59
172
  private drawLauncher;
60
173
  update(appearance: Partial<MessengerAppearance>, scheme?: ChatScheme): void;
174
+ private paint;
175
+ private loadKit;
176
+ private loadFiles;
61
177
  private toggle;
62
178
  setOpenNow(open: boolean): void;
63
179
  open(): Promise<void>;
64
180
  private renderFirstRun;
181
+ private helpHost;
65
182
  private renderAway;
66
- private pick;
67
183
  private objectUrl;
68
184
  close(): void;
69
185
  onIncomingTurn(turn: ChatTurn): void;
186
+ private takeTurn;
70
187
  private submit;
71
188
  /**
72
189
  * Draw the visitor's words, then send them.
@@ -95,7 +212,6 @@ declare class ChatPanel {
95
212
  private hasTurn;
96
213
  private renderThread;
97
214
  private appendTurn;
98
- private drawFile;
99
215
  private agentName;
100
216
  private stamp;
101
217
  private onKeydown;
@@ -109,6 +225,8 @@ interface MountChatOptions extends ChatClientOptions {
109
225
  pollIntervalMs?: number;
110
226
  socketHost?: string;
111
227
  socketFactory?: SocketFactory;
228
+ help?: () => Promise<HelpKit | null>;
229
+ files?: () => Promise<FilesKit | null>;
112
230
  }
113
231
  interface ChatHandle {
114
232
  open(): void;
package/dist/chat.js CHANGED
@@ -1,30 +1,30 @@
1
- import {c,a as a$1,b as b$1}from'./chunk-V77KYPOF.js';import {e,h,d,b}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var O="X-Prodantix-Conversation-Token",P="prodantix.chat.handle";function W(){let a=globalThis.localStorage;if(a)return {get:e=>a.getItem(e),remove:e=>a.removeItem(e),set:(e,t)=>a.setItem(e,t)}}var w=class{constructor(e$1){this.options=e$1;a(this,"fetchImpl");a(this,"fileFetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=e(e$1.fetchImpl),this.fileFetchImpl=e$1.fileFetchImpl??((t,n)=>fetch(t,n)),this.host=h(e$1.host),this.storage=e$1.storage??W(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(P,JSON.stringify(this.handle)),true)}async send(e,t,n){if(!await this.ensureThread())return null;let r=this.handle;return r?(await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{attachmentIds:n,body:e,pageContext:t},token:r.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async n=>JSON.parse(await n.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,n=>n.blob()):null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(P);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(P),null}async fileRequest(e,t,n,r,o){let i={authorization:`Bearer ${this.options.apiKey}`,[O]:n};o&&(i["content-type"]=o.type||"application/octet-stream");try{let s=await this.fileFetchImpl(`${this.host}${t}`,{body:o,headers:i,method:e});if(s.ok)return await r(s);this.options.onError?.(new d(`prodantix chat ${t}: ${s.status}`,s.status));}catch(s){this.options.onError?.(s);}return null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new d("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(o[O]=n.token);try{let i=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:o,method:e}),s=await i.text();return i.ok?s?JSON.parse(s):{}:(this.options.onError?.(new d(`prodantix chat ${t}: ${i.status}`,i.status)),null)}catch(i){return this.options.onError?.(i),null}}};var J={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function T(a,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:a.timezone,weekday:"short"}).formatToParts(e),n=J[t.find(s=>s.type==="weekday")?.value??""];if(!n)return false;let r=t.find(s=>s.type==="hour")?.value??"",o=t.find(s=>s.type==="minute")?.value??"",i=`${r}:${o}`;return a.windows.some(s=>s.days.includes(n)&&s.open<=i&&i<s.close)}var g={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},X=["quiet","standard"],Z=["round","square"],V=["rounded","tailed"],Q=["filled","outlined"],ee=["circle","pill","squircle"],te=["filled","outlined"],ne=["avatar","glyph","team_faces"],re=["large","medium","small"],ae=["above","hidden","inline"],ie=["beside_name","none","under_turn"],oe=["time","time_and_latency"],x=(a,e,t)=>typeof a=="string"&&e.includes(a)?a:t,D=(a,e)=>typeof a=="boolean"?a:e,se={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},le={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ce={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},de={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},pe={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function E(a){let e=typeof a=="object"&&a!==null?a:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:se[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=r===void 0?void 0:le[r],i=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=i===void 0?void 0:ce[i],d=typeof e.skin=="string"?e.skin:void 0,u=d===void 0?void 0:de[d],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,l=c===void 0?void 0:pe[c],h={bubbleFill:x(e.bubbleFill,Q,l?.[1]??g.bubbleFill),bubbleShape:x(e.bubbleShape,V,l?.[0]??g.bubbleShape),composerShape:x(e.composerShape,Z,u?.[1]??g.composerShape),dayDividers:D(e.dayDividers,s?.[0]??g.dayDividers),launcherContent:x(e.launcherContent,ne,n?.[2]??g.launcherContent),launcherFill:x(e.launcherFill,te,n?.[1]??g.launcherFill),launcherShape:x(e.launcherShape,ee,n?.[0]??g.launcherShape),launcherSize:x(e.launcherSize,re,n?.[3]??g.launcherSize),nameAvatar:D(e.nameAvatar,o?.[1]??g.nameAvatar),namePlacement:x(e.namePlacement,ae,o?.[0]??g.namePlacement),skin:x(e.skin,X,u?.[0]??g.skin),stampContent:x(e.stampContent,oe,s?.[2]??g.stampContent),stampPlacement:x(e.stampPlacement,ie,s?.[1]??g.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function q(a){let e=a.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var ue="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",he={large:66,medium:56,small:46},me={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},ge={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},fe={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},be=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",xe={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ye={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},ve={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Se={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function K(a,e,t,n){return `.launcher{--fab-size:${he[n]}px;${me[a]}${ge[e]}}${fe[t]}${be}${xe[a]}${ye[e]}${ve[a]}${Se[a]}`}function j(a,e,t,n=r=>r){let r=document.createDocumentFragment();if(a==="glyph"||t.length===0){let o=document.createElement("span");return o.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${ue}"/></svg>`,r.append(...o.childNodes,_()),r}return a==="avatar"?(r.append(G(t[0],e,n),_()),r):(r.append(N(t,e,n),_()),r)}function N(a,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let r of a.slice(0,2))n.append(G(r,e,t));return n}function G(a,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),a&&(n.style.background=a.tone),a?.avatarUrl){let r=document.createElement("img");return r.alt="",r.src=t(a.avatarUrl),n.append(r),n}return n.textContent=a?a.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function _(){let a=document.createElement("span");return a.className="live",a.setAttribute("aria-hidden","true"),a}var ke={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(a,e)=>`That file is ${a}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:a=>{let e=new Date(a);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:a=>`${a} unread`},C={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...g},Ce={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},we={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Ee={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Le={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Te={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Ae=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Pe='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',_e={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Ne=".lat{font-size:11px;opacity:.7;margin-left:6px}",Fe=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}";function He(a){let e=a==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${e+26}px}.composer button.clip{position:absolute;top:50%;left:${e-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}function F(a){return a<999500?`${Math.max(1,Math.round(a/1e3))} KB`:`${(a/1e6).toFixed(1)} MB`}var Y=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
1
+ import {c,a as a$1,b as b$1}from'./chunk-V77KYPOF.js';import {e,h,d,b}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var z="X-Prodantix-Conversation-Token",F="prodantix.chat.handle";function Y(){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 L=class{constructor(e$1){this.options=e$1;a(this,"fetchImpl");a(this,"fileFetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);this.fetchImpl=e(e$1.fetchImpl),this.fileFetchImpl=e$1.fileFetchImpl??((t,n)=>fetch(t,n)),this.host=h(e$1.host),this.storage=e$1.storage??Y(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(F,JSON.stringify(this.handle)),true)}async send(e,t,n){if(!await this.ensureThread())return null;let i=this.handle;return i?(await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:n,body:e,pageContext:t},token:i.token}))?.turn??null:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async n=>JSON.parse(await n.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,n=>n.blob()):null}async helpCentre(e,t){let n=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}${n?`?${n}`:""}`)}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(F);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(F),null}async fileRequest(e,t,n,i,a){let s={authorization:`Bearer ${this.options.apiKey}`,[z]:n};a&&(s["content-type"]=a.type||"application/octet-stream");try{let o=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:s,method:e});if(o.ok)return await i(o);this.options.onError?.(new d(`prodantix chat ${t}: ${o.status}`,o.status));}catch(o){this.options.onError?.(o);}return null}async request(e,t,n={}){let i=this.fetchImpl;if(!i)return this.options.onError?.(new d("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(a[z]=n.token);try{let s=await i(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:a,method:e}),o=await s.text();return s.ok?o?JSON.parse(o):{}:(this.options.onError?.(new d(`prodantix chat ${t}: ${s.status}`,s.status)),null)}catch(s){return this.options.onError?.(s),null}}};var W={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function A(r,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:r.timezone,weekday:"short"}).formatToParts(e),n=W[t.find(o=>o.type==="weekday")?.value??""];if(!n)return false;let i=t.find(o=>o.type==="hour")?.value??"",a=t.find(o=>o.type==="minute")?.value??"",s=`${i}:${a}`;return r.windows.some(o=>o.days.includes(n)&&o.open<=s&&s<o.close)}var f={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},J=["quiet","standard"],X=["round","square"],V=["rounded","tailed"],Z=["filled","outlined"],Q=["circle","pill","squircle"],ee=["filled","outlined"],te=["avatar","glyph","team_faces"],ne=["large","medium","small"],re=["above","hidden","inline"],ie=["beside_name","none","under_turn"],ae=["time","time_and_latency"],x=(r,e,t)=>typeof r=="string"&&e.includes(r)?r:t,B=(r,e)=>typeof r=="boolean"?r:e,oe={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"]},se={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},le={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"]},ce={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},de={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function T(r){let e=typeof r=="object"&&r!==null?r:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:oe[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:se[i],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,o=s===void 0?void 0:le[s],h=typeof e.skin=="string"?e.skin:void 0,u=h===void 0?void 0:ce[h],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,d=c===void 0?void 0:de[c],p={bubbleFill:x(e.bubbleFill,Z,d?.[1]??f.bubbleFill),bubbleShape:x(e.bubbleShape,V,d?.[0]??f.bubbleShape),composerShape:x(e.composerShape,X,u?.[1]??f.composerShape),dayDividers:B(e.dayDividers,o?.[0]??f.dayDividers),launcherContent:x(e.launcherContent,te,n?.[2]??f.launcherContent),launcherFill:x(e.launcherFill,ee,n?.[1]??f.launcherFill),launcherShape:x(e.launcherShape,Q,n?.[0]??f.launcherShape),launcherSize:x(e.launcherSize,ne,n?.[3]??f.launcherSize),nameAvatar:B(e.nameAvatar,a?.[1]??f.nameAvatar),namePlacement:x(e.namePlacement,re,a?.[0]??f.namePlacement),skin:x(e.skin,J,u?.[0]??f.skin),stampContent:x(e.stampContent,ae,o?.[2]??f.stampContent),stampPlacement:x(e.stampPlacement,ie,o?.[1]??f.stampPlacement)};return p.stampPlacement==="beside_name"&&p.namePlacement==="hidden"&&(p.stampPlacement="under_turn"),p}function O(r){let e=r.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var 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",he={large:66,medium:56,small:46},ue={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},me={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);"},ge={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;}"},fe=".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}",be={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},ye={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},xe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ve={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function K(r,e,t,n){return `.launcher{--fab-size:${he[n]}px;${ue[r]}${me[e]}}${ge[t]}${fe}${be[r]}${ye[e]}${xe[r]}${ve[r]}`}function D(r,e,t,n=i=>i){let i=document.createDocumentFragment();if(r==="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,_()),i}return r==="avatar"?(i.append(q(t[0],e,n),_()),i):(i.append(H(t,e,n),_()),i)}function H(r,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let i of r.slice(0,2))n.append(q(i,e,t));return n}function q(r,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),r&&(n.style.background=r.tone),r?.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(r.avatarUrl),n.append(i),n}return n.textContent=r?r.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function _(){let r=document.createElement("span");return r.className="live",r.setAttribute("aria-hidden","true"),r}var Se={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:(r,e)=>`That file is ${r}. 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: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`},w={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...f};function ke(r,e){let t=document.createElement("a");t.className="powered",t.href="https://prodantix.com",t.target="_blank",t.rel="noopener";let n=document.createElement("img");return n.src=e,n.alt="",n.width=12,n.height=12,t.append(n,r),t}var Ce={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},we={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Le={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}"},Te={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ee={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Ae=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Pe='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Fe={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},_e=".lat{font-size:11px;opacity:.7;margin-left:6px}",j=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
2
2
  --fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
3
- --online: oklch(72% 0.13 163.23);`;function Re(a){return a==="light"?"":a==="dark"?`:host { ${Y} }`:`@media (prefers-color-scheme: dark) {
3
+ --online: oklch(72% 0.13 163.23);`;function He(r){return r==="light"?"":r==="dark"?`:host { ${j} }`:`@media (prefers-color-scheme: dark) {
4
4
  :host {
5
- ${Y}
5
+ ${j}
6
6
  }
7
- }`}var Ie=/https?:\/\/[^\s<>"]+/g,$e=/[.,;:!?)]$/,Me=a=>{let e=a;for(;$e.test(e);){let t=e.split("(").length-1,n=e.split(")").length-1;if(e.endsWith(")")&&t>=n)break;e=e.slice(0,-1);}return e};function ze(a,e){let t=0;for(let n of e.matchAll(Ie)){let r=n.index??0,o=Me(n[0]);r>t&&a.append(e.slice(t,r));let i=document.createElement("a");i.href=o,i.target="_blank",i.rel="noopener noreferrer",i.textContent=o,a.append(i),t=r+o.length;}t<e.length&&a.append(e.slice(t));}var Ue=["P","BR","STRONG","EM","A","UL","OL","LI"],Be=a=>typeof a=="object"&&a!==null&&"html"in a&&typeof a.html=="string"&&"text"in a&&typeof a.text=="string",Oe=(a,e)=>e.name==="class"||e.name==="data-block-type"?true:a!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),De=a=>[...a.querySelectorAll("*")].every(e=>Ue.includes(e.tagName)&&[...e.attributes].every(t=>Oe(e.tagName,t)));function H(a,e="system"){let t=E(a),n=a.launcherPosition==="bottom_left"?"left":"right",r=a.accentColor;return `${`
7
+ }`}var Ne=/https?:\/\/[^\s<>"]+/g,Re=/[.,;:!?)]$/,Ie=r=>{let e=r;for(;Re.test(e);){let t=e.split("(").length-1,n=e.split(")").length-1;if(e.endsWith(")")&&t>=n)break;e=e.slice(0,-1);}return e};function $e(r,e){let t=0;for(let n of e.matchAll(Ne)){let i=n.index??0,a=Ie(n[0]);i>t&&r.append(e.slice(t,i));let s=document.createElement("a");s.href=a,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,r.append(s),t=i+a.length;}t<e.length&&r.append(e.slice(t));}var Me=["P","BR","STRONG","EM","A","UL","OL","LI"],Ue=r=>typeof r=="object"&&r!==null&&"html"in r&&typeof r.html=="string"&&"text"in r&&typeof r.text=="string",ze=(r,e)=>e.name==="class"||e.name==="data-block-type"?true:r!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),Be=r=>[...r.querySelectorAll("*")].every(e=>Me.includes(e.tagName)&&[...e.attributes].every(t=>ze(e.tagName,t)));function G(r,e="system"){let t=T(r),n=r.launcherPosition==="bottom_left"?"left":"right",i=r.accentColor;return `${`
8
8
  :host {
9
- all: initial; z-index: 2147483000; --a: ${r};
9
+ all: initial; z-index: 2147483000; --a: ${i};
10
10
  --paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
11
11
  --fill: #f1f5f9; --hairline: #e2e8f0; --ink-2: rgba(0,0,0,.72);
12
12
  --online: oklch(53.8% 0.1274 163.23);
13
13
  color-scheme: ${e==="system"?"light dark":e};
14
14
  }
15
- ${Re(e)}
15
+ ${He(e)}
16
16
  * { box-sizing: border-box; font-family: system-ui, sans-serif; }
17
17
  .launcher {
18
- z-index: 2147483000; position: fixed; ${n}: ${a.launcherOffsetX}px; bottom: ${a.launcherOffsetY}px; width: 56px; height: 56px;
18
+ z-index: 2147483000; position: fixed; ${n}: ${r.launcherOffsetX}px; bottom: ${r.launcherOffsetY}px; width: 56px; height: 56px;
19
19
  border-radius: 28px; border: none; cursor: pointer;
20
20
  display: inline-flex; align-items: center; justify-content: center;
21
- background: ${r}; color: #fff; font-size: 24px;
21
+ background: ${i}; color: #fff; font-size: 24px;
22
22
  box-shadow: 0 4px 12px rgba(0,0,0,.2);
23
23
  }
24
24
  .launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
25
25
  .launcher { transition: background-color 120ms ease; }
26
- .launcher:hover { background: color-mix(in srgb, #000 12%, ${r}); }
27
- .launcher:active { background: color-mix(in srgb, #000 20%, ${r}); }
26
+ .launcher:hover { background: color-mix(in srgb, #000 12%, ${i}); }
27
+ .launcher:active { background: color-mix(in srgb, #000 20%, ${i}); }
28
28
  @media (prefers-reduced-motion: reduce) {
29
29
  .launcher { transition: none; }
30
30
  }
@@ -35,7 +35,7 @@ ${Re(e)}
35
35
  }
36
36
  .badge[hidden] { display: none; }
37
37
  .panel {
38
- z-index: 2147483001; position: fixed; ${n}: ${a.launcherOffsetX}px; bottom: ${a.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
38
+ z-index: 2147483001; position: fixed; ${n}: ${r.launcherOffsetX}px; bottom: ${r.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
39
39
  height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
40
40
  border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
41
41
  display: flex; flex-direction: column; overflow: hidden;
@@ -62,14 +62,14 @@ ${Re(e)}
62
62
  .close:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
63
63
  .log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
64
64
  .turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
65
- .turn.end_user { align-self: flex-end; background: ${r}; color: #fff; }
65
+ .turn.end_user { align-self: flex-end; background: ${i}; color: #fff; }
66
66
  .turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
67
- .turn.ai a { color: ${r}; text-decoration: underline; overflow-wrap: anywhere; }
67
+ .turn.ai a { color: ${i}; text-decoration: underline; overflow-wrap: anywhere; }
68
68
  .author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
69
69
  .turn[data-pending] { opacity: .6; }
70
70
  .turn[data-failed] { opacity: 1; box-shadow: inset 0 0 0 1px #dc2626; }
71
71
  .retry { display: block; margin: 5px 0 0; padding: 0; background: none; border: 0; color: inherit; font: inherit; font-size: 11.5px; text-decoration: underline; cursor: pointer; opacity: .85; }
72
- .away { display: flex; gap: 10px; align-items: flex-start; margin: 12px 12px 0; padding: 10px 14px; font-size: 13px; line-height: 1.43; color: ${r}; background: color-mix(in srgb, ${r} 12%, transparent); border-radius: 4px; }
72
+ .away { display: flex; gap: 10px; align-items: flex-start; margin: 12px 12px 0; padding: 10px 14px; font-size: 13px; line-height: 1.43; color: ${i}; background: color-mix(in srgb, ${i} 12%, transparent); border-radius: 4px; }
73
73
  .awayglyph { flex: none; width: 16px; height: 16px; margin-top: 1px; border: 1.5px solid currentColor; border-radius: 50%; }
74
74
  .empty { display: flex; flex-direction: column; gap: 8px; padding: 20px 16px; }
75
75
  .empty h3 { margin: 0; font-size: 18px; font-weight: 640; letter-spacing: -.015em; }
@@ -84,23 +84,28 @@ ${Re(e)}
84
84
  .prompt p { margin: 0 0 16px; line-height: 1.6; }
85
85
  .prompt ul, .prompt ol { margin: 0 0 16px; padding-left: 32px; }
86
86
  .prompt li { margin: 8px 0; line-height: 1.6; }
87
- .prompt a { position: relative; z-index: 1; color: ${r}; text-decoration: underline; overflow-wrap: anywhere; }
87
+ .prompt a { position: relative; z-index: 1; color: ${i}; text-decoration: underline; overflow-wrap: anywhere; }
88
88
  .promptpress { position: absolute; inset: 0; padding: 0; background: none; border: 0; border-radius: inherit; cursor: pointer; }
89
- .promptpress:focus-visible { outline: 2px solid ${r}; outline-offset: 2px; }
89
+ .promptpress:focus-visible { outline: 2px solid ${i}; outline-offset: 2px; }
90
90
  .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: oklch(52% 0.17 22); }
91
91
  .av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
92
92
  .av img { width: 100%; height: 100%; display: block; object-fit: cover; border-radius: inherit; }
93
93
  .composer { display: flex; gap: 6px; padding: 10px; border-top: 1px solid var(--hairline); }
94
94
  .composer input { flex: 1; min-width: 0; height: 36px; padding: 0 12px; border: 0; border-radius: 8px; font-size: 14px; background: var(--fill); color: var(--ink); }
95
- .composer input:focus-visible { outline: 2px solid ${r}; }
96
- .composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 56px; height: 36px; padding: 0 14px; background: ${r}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 13.5px; font-weight: 550; }
97
- .composer button:hover { background: color-mix(in srgb, #000 12%, ${r}); }
95
+ .composer input:focus-visible { outline: 2px solid ${i}; }
96
+ .composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 56px; height: 36px; padding: 0 14px; background: ${i}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 13.5px; font-weight: 550; }
97
+ .composer button:hover { background: color-mix(in srgb, #000 12%, ${i}); }
98
98
  .composer button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
99
99
  .composer button .sendglyph { display: none; width: 17px; height: 17px; }
100
100
  .composer button:focus-visible { outline: 2px solid #0b0e14; }
101
+ .powered { display: flex; align-items: center; justify-content: center; gap: 4px; height: 24px; font-size: 11px; font-weight: 500; color: var(--ink-3); text-decoration: none; }
102
+ .powered:hover { color: var(--ink-2); }
103
+ .powered:focus-visible { outline: 2px solid var(--ink); outline-offset: -2px; }
104
+ .powered img { width: 12px; height: 12px; }
101
105
  @media (prefers-reduced-motion: no-preference) {
102
106
  .panel { animation: rise 180ms ease-out; }
103
107
  @keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
104
108
  }
105
- `}${we[t.composerShape]}${Ce[t.skin]}${K(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ee[t.bubbleShape]}${Le[t.bubbleFill]}${Te[t.namePlacement]}${t.nameAvatar?Ae:""}${t.dayDividers?Pe:""}${_e[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ne:""}${Fe}${a.attachments?.enabled?He(t.composerShape):""}`}var qe=["end_user","agent","ai"];function Ke(){let a=globalThis.location;if(a)return {host:a.host,path:a.pathname,title:document.title}}var je='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>',Ge='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',L=class{constructor(e,t,n={},r={},o={}){this.host=e;this.client=t;a(this,"root");a(this,"strings");a(this,"settings");a(this,"appearance");a(this,"launcher");a(this,"badge");a(this,"panel",null);a(this,"lastFocused",null);a(this,"unread",0);a(this,"pendingTurns",0);a(this,"openNow");a(this,"style");a(this,"scheme");a(this,"picked",null);a(this,"objectUrls",[]);this.strings={...ke,...n},this.appearance={...C,...r},this.settings=E({...C,...r}),this.root=e.attachShadow({mode:o.shadowMode??"closed"}),this.openNow=T(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=H(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(j(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...C,...e},this.settings=E(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=H(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=this.appearance.team??[];n.length>0&&t.append(N(n,this.strings,f=>this.client.avatarUrl(f)));let r=document.createElement("div");r.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let i=document.createElement("p");i.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),i.append(s,this.strings.replyTime),r.append(o,i);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=Ge,d.addEventListener("click",()=>this.close()),t.append(r,d);let u=document.createElement("div");u.className="log",u.setAttribute("role","log"),u.setAttribute("aria-live","polite"),u.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let l=document.createElement("input");l.type="text",l.setAttribute("aria-label",this.strings.inputPlaceholder),l.placeholder=this.strings.inputPlaceholder;let h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let y=document.createElement("span");y.className="sendtext",y.textContent=this.strings.sendLabel,h.append(y);let v=this.appearance.attachments;if(v?.enabled&&this.client.upload){let f=document.createElement("span");f.className="field";let m=document.createElement("input");m.type="file",m.accept=v.accept.join(","),m.hidden=true,m.addEventListener("change",()=>{let R=m.files?.[0];m.value="",R&&this.pick(u,c,v,R);});let b=document.createElement("button");b.type="button",b.className="clip",b.setAttribute("aria-label",this.strings.attachLabel),b.innerHTML=je,b.addEventListener("click",()=>m.click()),f.append(b,l,m),c.append(f,h);}else c.append(l,h);c.addEventListener("submit",f=>{f.preventDefault(),this.submit(l,u);}),e.append(t,u,c),e.addEventListener("keydown",f=>this.onKeydown(f,e,d)),this.root.append(e),this.panel=e,l.focus();let S=await this.client.load();S&&S.turns.length>0?this.renderThread(u,S):this.renderFirstRun(u,l),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let r=document.createElement("h3");r.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(r,o),this.appearance.starterPrompts.filter(Be).forEach((s,d)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${d}`;let l=document.createElement("template");l.innerHTML=s.html,De(l.content)?c.append(l.content):c.textContent=s.text;for(let y of c.querySelectorAll("a"))y.target="_blank",y.rel="noopener noreferrer";let h=document.createElement("button");h.className="promptpress",h.type="button",h.setAttribute("aria-labelledby",c.id),h.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),u.append(c,h),n.append(u);}),e.replaceChildren(n);}renderAway(e){let t=document.createElement("div");t.className="away";let n=document.createElement("span");n.className="awayglyph",n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(n,r),e.after(t);}pick(e,t,n,r){let o=r.size>n.maxBytes||!n.accept.includes(r.type);for(let l of this.root.querySelectorAll(o?".ferr":".file,.ferr"))l.remove();if(o){let l=document.createElement("p");l.className="ferr",l.setAttribute("role","alert"),l.textContent=this.strings.fileRefusal(F(r.size),`${n.maxBytes/1e6} MB`),t.before(l),e.scrollTop=e.scrollHeight;return}this.picked=r;let i=document.createElement("span");i.className="file";let s;if(r.type==="application/pdf")s=document.createElement("b"),s.textContent="PDF";else {let l=document.createElement("img");l.className="th",l.alt="",l.src=this.objectUrl(r),s=l;}let d=document.createElement("span");d.className="name",d.textContent=r.name;let u=document.createElement("span");u.className="sz",u.textContent=`\xB7 ${F(r.size)}`;let c=document.createElement("button");c.type="button",c.className="x",c.setAttribute("aria-label",this.strings.removeFileLabel),c.textContent="\xD7",c.addEventListener("click",()=>{this.picked=null,i.remove();}),i.append(s,d,u,c),t.before(i),e.scrollTop=e.scrollHeight;}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.panel=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let n=e.value.trim(),r=this.picked;if(!(!n&&!r)){e.value="",this.picked=null;for(let o of this.root.querySelectorAll(".file,.ferr"))o.remove();await this.sendBody(t,n,r);}}async sendBody(e,t,n=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let r=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},n);r.setAttribute("data-pending","");let o=n?await this.client.upload?.(n):void 0,i=o===null?null:await this.client.send(t,Ke(),o?[o.id]:void 0);if(r.removeAttribute("data-pending"),i){r.dataset.turnId=i.id;return}this.markFailed(e,r,t,n);}markFailed(e,t,n,r){t.setAttribute("data-failed","");let o=document.createElement("button");o.type="button",o.className="retry",o.textContent=this.strings.retryLabel,o.addEventListener("click",()=>{t.remove(),this.sendBody(e,n,r);}),(t.querySelector(".body")??t).append(o);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t,n=null){e.querySelector(".empty")?.remove();let r=qe.includes(t.authorKind)?t.authorKind:"agent",o=this.settings,i=document.createElement("div");if(i.className=`turn ${r}`,i.dataset.turnId=t.id,r!=="end_user"&&o.nameAvatar){let l=document.createElement("span");if(l.className=r==="ai"?"av bot":"av",l.setAttribute("aria-hidden","true"),r==="agent"&&t.authorAvatarUrl){let h=document.createElement("img");h.alt="",h.src=this.client.avatarUrl(t.authorAvatarUrl),l.append(h);}else {l.textContent=r==="ai"?this.strings.aiLabel:q(this.agentName(t));let h=r==="agent"?this.appearance.team?.find(y=>y.name===t.authorName)?.tone:void 0;h&&(l.style.background=h);}i.append(l);}let d=document.createElement("div");if(d.className="body",r==="end_user"){n&&this.drawFile(d,n.name,n.type,n.size,Promise.resolve(n));for(let l of t.attachments??[])this.drawFile(d,l.name,l.contentType,l.bytes,this.client.file?.(l.url)??Promise.resolve(null));}let u=r!=="end_user"&&o.namePlacement!=="hidden",c=document.createElement("div");if(r==="ai"?ze(c,t.body):c.textContent=t.body,u||r==="ai"&&o.namePlacement==="hidden"){let l=document.createElement("div");l.className=r==="ai"?"author ai":"author",l.textContent=r==="ai"?this.strings.aiLabel:this.agentName(t),o.stampPlacement==="beside_name"&&l.append(this.stamp(t)),o.namePlacement==="inline"?(l.classList.add("below"),d.append(c,l)):d.append(l,c);}else t.body&&d.append(c);return o.stampPlacement==="under_turn"&&d.append(this.stamp(t)),i.append(d),e.append(i),e.scrollTop=e.scrollHeight,i}drawFile(e,t,n,r,o){let i=document.createElement("a");if(n==="application/pdf"){i.className="pdfc",i.download=t;let s=document.createElement("b");s.textContent="PDF",i.append(s,`${t} \xB7 ${F(r)}`);}else {i.className="att",i.target="_blank",i.rel="noopener noreferrer";let s=document.createElement("img");s.alt=t,s.addEventListener("load",()=>{let d=i.closest(".log");d&&(d.scrollTop=d.scrollHeight);}),i.append(s);}e.append(i),o.then(s=>{s&&(i.href=this.objectUrl(s),i.querySelector("img")?.setAttribute("src",i.href));});}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let r=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let o=r[0],i=r[r.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),i.focus()):!e.shiftKey&&s===i?(e.preventDefault(),o.focus()):s===null&&(e.preventDefault(),n.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};var Ye="/socket.io/?EIO=4&transport=websocket",A=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??We,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ye}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$1(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$1());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function We(a){let e=globalThis.WebSocket;if(!e)throw new d("no WebSocket");return new e(a)}var Je=6e4;function bt(a){let e=globalThis.document;if(!e)throw new b("prodantix chat requires a document; mount it in the browser");let t=a.mountPoint??e.createElement("div");a.mountPoint||e.body.append(t);let n=new w(a),r=new L(t,n,a.strings,a.appearance),o=a.appearance?.availability??C.availability,i,s=()=>{r.setOpenNow(T(o,new Date)),i=setTimeout(s,Je);};s();let d=new Set,u,c=null,l=a.pollIntervalMs??15e3,h=m=>{d.has(m.id)||m.authorKind==="end_user"||(d.add(m.id),r.onIncomingTurn(m));},y=async()=>{if(!n.hasThread)return;let m=await n.load();if(m){for(let b of m.turns)h(b);d=new Set(m.turns.map(b=>b.id));}},v=()=>{u||l<=0||(u=setInterval(()=>void y(),l));},S=()=>{u&&clearInterval(u),u=void 0;},f=()=>{if(c||!a.socketHost)return;let m=n.socketAuth;m&&(c=new A({auth:m,host:a.socketHost,onClosed:b=>{c=null,v(),b&&f();},onReady:S,onTurn:h,socketFactory:a.socketFactory}),c.open());};return v(),f(),{close:()=>r.close(),destroy:()=>{S(),clearTimeout(i),c?.close(),c=null,r.close(),t.remove();},identify:m=>n.identify(m),open:()=>{r.open().then(f);}}}export{w as ChatClient,L as ChatPanel,C as DEFAULT_APPEARANCE,g as DEFAULT_APPEARANCE_SETTINGS,bt as mountChat,H as panelStyles,E as resolveAppearance};//# sourceMappingURL=chat.js.map
109
+ .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))}}
110
+ `}${we[t.composerShape]}${Ce[t.skin]}${K(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Le[t.bubbleShape]}${Te[t.bubbleFill]}${Ee[t.namePlacement]}${t.nameAvatar?Ae:""}${t.dayDividers?Pe:""}${Fe[t.stampPlacement]}${t.stampContent==="time_and_latency"?_e:""}`}var Oe=["end_user","agent","ai"];function Ke(){let r=globalThis.location;if(r)return {host:r.host,path:r.pathname,title:document.title}}var De='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',E=class{constructor(e,t,n={},i={},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,"scrim",null);a(this,"lastFocused",null);a(this,"unread",0);a(this,"pendingTurns",0);a(this,"openNow");a(this,"styles");a(this,"scheme");a(this,"picked",null);a(this,"objectUrls",[]);a(this,"helpLoader");a(this,"kit",null);a(this,"kitLoad",null);a(this,"filesLoader");a(this,"filesKit",null);a(this,"filesLoad",null);this.strings={...Se,...n},this.appearance={...w,...i},this.settings=T({...w,...i}),this.root=e.attachShadow({mode:a$1.shadowMode??"closed"}),this.openNow=A(this.appearance.availability,new Date),this.scheme=a$1.scheme,this.helpLoader=a$1.help,this.filesLoader=a$1.files,this.styles=Ge(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(D(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={...w,...e},this.settings=T(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){this.styles(`${G(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(this.appearance.attachments?.enabled===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):(this.kitLoad??(this.kitLoad=this.helpLoader().then(e=>(this.kit=e,this.paint(),e))),this.kitLoad)}loadFiles(){return this.filesLoader?(this.filesLoad??(this.filesLoad=this.filesLoader().then(e=>(this.filesKit=e,this.paint(),e))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){this.openNow=e,this.launcher.classList.toggle("closed",!e),this.panel?.classList.toggle("closed",!e);}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let n=document.createElement("span");n.className="grip",n.setAttribute("aria-hidden","true"),t.append(n);let i=this.appearance.team??[];i.length>0&&t.append(H(i,this.strings,y=>this.client.avatarUrl(y)));let a=document.createElement("div");a.className="headmain";let s=document.createElement("h2");s.textContent=this.strings.title;let o=document.createElement("p");o.className="status";let h=document.createElement("span");h.className="live",h.setAttribute("aria-hidden","true"),o.append(h,this.strings.replyTime),a.append(s,o);let u=document.createElement("button");u.className="close",u.type="button",u.setAttribute("aria-label",this.strings.closeLabel),u.innerHTML=De,u.addEventListener("click",()=>this.close()),t.append(a,u);let c=document.createElement("div");c.className="log",c.setAttribute("role","log"),c.setAttribute("aria-live","polite"),c.setAttribute("aria-label",this.strings.title);let d=document.createElement("form");d.className="composer";let p=document.createElement("input");p.type="text",p.setAttribute("aria-label",this.strings.inputPlaceholder),p.placeholder=this.strings.inputPlaceholder;let m=document.createElement("button");m.type="submit",m.setAttribute("aria-label",this.strings.sendLabel),m.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let k=document.createElement("span");k.className="sendtext",k.textContent=this.strings.sendLabel,m.append(k),d.append(p,m),d.addEventListener("submit",y=>{y.preventDefault(),this.submit(p,c);}),e.append(t,c,d),this.appearance.poweredBy&&e.append(ke(this.appearance.poweredBy,this.client.avatarUrl("/messenger-mark.png"))),e.addEventListener("keydown",y=>this.onKeydown(y,e,u));let v=document.createElement("div");v.className="scrim",v.addEventListener("click",()=>this.close()),this.root.append(v,e),this.panel=e,this.scrim=v,je(e,()=>this.close()),p.focus();let S=this.appearance.attachments,[g]=await Promise.all([this.client.load(),this.loadKit(),S?.enabled&&this.client.upload?this.loadFiles():null]);if(g?.turns.some(y=>y.attachments?.length)&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&S?.enabled&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:y=>{this.picked=y;},objectUrl:y=>this.objectUrl(y),removeFileLabel:this.strings.removeFileLabel,root:this.root},d,p,c,S);let b=this.helpHost();b?.placement==="tab"&&b.host.source.collections&&b.host.source.collectionArticles&&b.kit.helpTab(b.host),b?.placement==="while_typing"&&b.kit.whileTyping(b.host,p,d),g&&g.turns.length>0?this.renderThread(c,g):this.renderFirstRun(c,p),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let n=document.createElement("div");n.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,n.append(i);let a=this.helpHost();if(a?.placement==="first_view")a.kit.firstView(a.host,n);else {let o=document.createElement("p");o.textContent=this.strings.emptyBody,n.append(o);}this.appearance.starterPrompts.filter(Ue).forEach((o,h)=>{let u=document.createElement("div");u.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${h}`;let d=document.createElement("template");d.innerHTML=o.html,Be(d.content)?c.append(d.content):c.textContent=o.text;for(let m of c.querySelectorAll("a"))m.target="_blank",m.rel="noopener noreferrer";let p=document.createElement("button");p.className="promptpress",p.type="button",p.setAttribute("aria-labelledby",c.id),p.addEventListener("click",()=>{t.value=o.text,this.submit(t,e);}),u.append(c,p),n.append(u);}),e.replaceChildren(n);}helpHost(){let e=this.appearance.help,{kit:t,panel:n}=this,i=e&&t&&n?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:n,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 n=document.createElement("span");n.className="awayglyph",n.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(n,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.scrim?.remove(),this.panel=null,this.scrim=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&&e.attachments?.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 n=e.value.trim(),i=this.picked;if(!(!n&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,n,i);}}async sendBody(e,t,n=null){e.querySelector(".empty")?.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},n);i.setAttribute("data-pending","");let a=n?await this.client.upload?.(n):void 0,s=a===null?null:await this.client.send(t,Ke(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),s){i.dataset.turnId=s.id;return}this.markFailed(e,i,t,n);}markFailed(e,t,n,i){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,n,i);}),(t.querySelector(".body")??t).append(a);}hasTurn(e,t){for(let n of e.children)if(n instanceof HTMLElement&&n.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let n of t.turns)this.appendTurn(e,n);}appendTurn(e,t,n=null){e.querySelector(".empty")?.remove();let i=Oe.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,s=document.createElement("div");if(s.className=`turn ${i}`,s.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let d=document.createElement("span");if(d.className=i==="ai"?"av bot":"av",d.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let p=document.createElement("img");p.alt="",p.src=this.client.avatarUrl(t.authorAvatarUrl),d.append(p);}else {d.textContent=i==="ai"?this.strings.aiLabel:O(this.agentName(t));let p=i==="agent"?this.appearance.team?.find(m=>m.name===t.authorName)?.tone:void 0;p&&(d.style.background=p);}s.append(d);}let h=document.createElement("div");if(h.className="body",i==="end_user"){let d=this.filesKit,p=m=>this.objectUrl(m);n&&d?.drawFile(h,n.name,n.type,n.size,Promise.resolve(n),p);for(let m of t.attachments??[])d?.drawFile(h,m.name,m.contentType,m.bytes,this.client.file?.(m.url)??Promise.resolve(null),p);}let u=i!=="end_user"&&a.namePlacement!=="hidden",c=document.createElement("div");if(i==="ai"?$e(c,t.body):c.textContent=t.body,u||i==="ai"&&a.namePlacement==="hidden"){let d=document.createElement("div");d.className=i==="ai"?"author ai":"author",d.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&d.append(this.stamp(t)),a.namePlacement==="inline"?(d.classList.add("below"),h.append(c,d)):h.append(d,c);}else t.body&&h.append(c);return a.stampPlacement==="under_turn"&&h.append(this.stamp(t)),s.append(h),e.append(s),e.scrollTop=e.scrollHeight,s}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,n){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(h=>!h.closest("[hidden]")&&!h.hidden);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(),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));}},qe="(max-width: 770px)";function je(r,e){let t=null;r.addEventListener("pointerdown",i=>{if(t||i.button!==0||!globalThis.matchMedia?.(qe).matches)return;let a=i.target;if(!a?.closest("a, button, input, textarea, iframe")){for(;a&&a!==r;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},r.setPointerCapture?.(i.pointerId),r.dataset.dragging="";}}),r.addEventListener("pointermove",i=>{if(t?.id!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),r.style.translate=`0 ${t.offset}px`;});let n=i=>{let a=t;if(a?.id!==i.pointerId)return;t=null,delete r.dataset.dragging;let s=a.offset>Math.min(72,r.getBoundingClientRect().height*.4),o=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;s||o?e():r.style.translate="";};r.addEventListener("pointerup",n),r.addEventListener("pointercancel",n);}var Ge=r=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in r&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return r.adoptedStyleSheets=[t],n=>t.replaceSync(n)}let e=document.createElement("style");return r.append(e),t=>{e.textContent=t;}};var Ye="/socket.io/?EIO=4&transport=websocket",P=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??We,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ye}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$1(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$1());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let n=t.payload?.turn;n&&this.options.onTurn(n);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function We(r){let e=globalThis.WebSocket;if(!e)throw new d("no WebSocket");return new e(r)}var Je=6e4;function bt(r){let e=globalThis.document;if(!e)throw new b("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 L(r),i=new E(t,n,r.strings,r.appearance,{files:r.files,help:r.help}),a=r.appearance?.availability??w.availability,s,o=()=>{i.setOpenNow(A(a,new Date)),s=setTimeout(o,Je);};o();let h=new Set,u,c=null,d=r.pollIntervalMs??15e3,p=g=>{h.has(g.id)||g.authorKind==="end_user"||(h.add(g.id),i.onIncomingTurn(g));},m=async()=>{if(!n.hasThread)return;let g=await n.load();if(g){for(let b of g.turns)p(b);h=new Set(g.turns.map(b=>b.id));}},k=()=>{u||d<=0||(u=setInterval(()=>void m(),d));},v=()=>{u&&clearInterval(u),u=void 0;},S=()=>{if(c||!r.socketHost)return;let g=n.socketAuth;g&&(c=new P({auth:g,host:r.socketHost,onClosed:b=>{c=null,k(),b&&S();},onReady:v,onTurn:p,socketFactory:r.socketFactory}),c.open());};return k(),S(),{close:()=>i.close(),destroy:()=>{v(),clearTimeout(s),c?.close(),c=null,i.close(),t.remove();},identify:g=>n.identify(g),open:()=>{i.open().then(S);}}}export{L as ChatClient,E as ChatPanel,w as DEFAULT_APPEARANCE,f as DEFAULT_APPEARANCE_SETTINGS,bt as mountChat,G as panelStyles,T as resolveAppearance};//# sourceMappingURL=chat.js.map
106
111
  //# sourceMappingURL=chat.js.map
@@ -0,0 +1,2 @@
1
+ import {c as c$1,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {e,h,d,f as f$1,g as g$1,a as a$1,b as b$1,c as c$2}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var g=class{constructor(){a(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};function Ce(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new g}return new g}var V={now:()=>new Date};function S(s){return s.toISOString()}var de=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ue=/^(?:\$|[a-z])[a-z0-9_.]*$/;function j(s){let e=0;for(let t of s)e+=1;return e}function H(s){return de.test(s)}function he(s){return ue.test(s)}function U(s){let e=j(s);if(e<1||e>200)throw new c$2("distinct_id","distinct_id must be between 1 and 200 characters")}function B(s){let e=j(s);if(e<1||e>200)throw new c$2("event_name","event_name must be between 1 and 200 characters");if(!he(s))throw new c$2("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var J="prodantix-js",z="0.7.0";function pe(){return globalThis.crypto}function fe(s){s[6]=s[6]&15|64,s[8]=s[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(s[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function me(){let s=pe();if(s?.randomUUID)return s.randomUUID();let e=new Uint8Array(16);if(s?.getRandomValues)s.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return fe(e)}var Q={uuid:me};var ge=s=>{};function G(s){if(!s.apiKey||!H(s.apiKey))throw new b$1("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new b$1("host is required (the ingest base URL)");let e=h(s.host),t=s.defaultProperties,n=s.storage??new g;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??V,consent:s.consent,defaultProperties:typeof t=="function"?t:()=>t??{},describeElement:s.describeElement,flagsHost:s.flagsHost?h(s.flagsHost):e,flushAt:s.flushAt??20,flushIntervalMs:s.flushIntervalMs??1e4,host:e,ids:s.ids??Q,locale:s.locale,maxQueueSize:s.maxQueueSize??1e3,maxRetries:s.maxRetries??3,namespace:ye(s.apiKey),onError:s.onError??ge,os:s.os,requestTimeoutMs:s.requestTimeoutMs??1e4,sdkName:s.sdkName??J,sdkVersion:s.sdkVersion??z,sessionTracking:s.sessionTracking??false,sharedStorage:s.sharedStorage??n,socketFactory:s.socketFactory,storage:n,streamFlags:s.streamFlags??false,transport:s.transport}}function ye(s){return s.slice(0,16)}var f=Symbol("absent");function ve(s,e){if(s==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,s))return t[s];let n=e.attributes??{};return Object.prototype.hasOwnProperty.call(n,s)?n[s]:f}function p(s){return s===f?"undefined":String(s)}function W(s){return s===f?Number.NaN:Number(s)}function Y(s){return s!==f&&s!==null&&s!==""}function X(s,e){if(!Array.isArray(e))return false;let t=p(s);return e.map(n=>String(n)).includes(t)}function Z(s,e){let t=ve(s.attribute,e),n=s.value;switch(s.op){case "is_set":return Y(t);case "is_not_set":return !Y(t);case "eq":return p(t)===p(n===void 0?f:n);case "neq":return p(t)!==p(n===void 0?f:n);case "contains":return p(t).includes(p(n===void 0?f:n));case "in":return X(t,n);case "not_in":return Array.isArray(n)?!X(t,n):false;case "gt":return x(t,n,(i,r)=>i>r);case "gte":return x(t,n,(i,r)=>i>=r);case "lt":return x(t,n,(i,r)=>i<r);case "lte":return x(t,n,(i,r)=>i<=r);case "in_cohort":return typeof n=="string"&&n!==""&&(e.cohorts??[]).includes(n);case "not_in_cohort":return typeof n=="string"&&n!==""&&!(e.cohorts??[]).includes(n);default:return false}}function x(s,e,t){let n=W(s),i=e===void 0?Number.NaN:W(e);return Number.isNaN(n)||Number.isNaN(i)?false:t(n,i)}function ee(s,e){let t=`${s}:${e}`,n=2166136261;for(let i=0;i<t.length;i++)n^=t.charCodeAt(i),n=Math.imul(n,16777619);return (n>>>0)%100}function P(s,e){return s.targeting.length===0||s.targeting.every(t=>Z(t,e))}function te(s,e){let t=ee(s.key,e.distinctId),n=s.variations??[];if(n.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let i=0;for(let r=n.length-1;r>=0;r--)if(i+=n[r].weight,t<i)return n[r].key;return n[0].key}function R(s,e,t,n){for(let i of s.prerequisites??[]){if(n.includes(i.flagKey))return false;let r=e.find(d=>d.key===i.flagKey);if(!r||!r.enabled)return false;n.push(r.key);let a=R(r,e,t,n)&&P(r,t)&&te(r,t)===i.variationKey;if(n.pop(),!a)return false}return true}function y(s,e,t){return s.enabled?R(s,e,t,[s.key])?P(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ee(s.key,t.distinctId)<s.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function ze(s,e){return y(s,[],e)}function se(s,e){let t={};for(let n of s)t[n.key]=y(n,s,e).enabled;return t}function v(s,e,t){let n=s.variations??[],i=n[0];if(!i)return null;if(!s.enabled||!R(s,e,t,[s.key])||!P(s,t))return i;let r=te(s,t);return n.find(a=>a.key===r)??i}function Qe(s,e){return v(s,[],e)}function Ge(s,e,t){let n=s.find(i=>i.key===e);return n?v(n,s,t)?.value??null:null}function ne(s){return s.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}var I=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`flags request failed with status ${a.status}`,a.status);let d$1=JSON.parse(await a.text());return {flags:d$1.flags??{},variants:d$1.variants??{}}}finally{r!==void 0&&clearTimeout(r);}}async snapshot(){let e=this.fetch;if(!e)throw new d("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,n=f$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let r=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!r.ok)throw new d(`flag snapshot request failed with status ${r.status}`,r.status);let a=JSON.parse(await r.text()),d$1={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d$1.socketUrl=a.socketUrl),d$1}finally{i!==void 0&&clearTimeout(i);}}async memberships(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{r!==void 0&&clearTimeout(r);}}};function b(s){if(typeof s!="string")return;let e=Array.from(s).length;return e>=1&&e<=200?s:void 0}function F(s,e){return `pdx.${s}.${e}`}var ie="consent";function be(s){if(typeof s!="string")return null;try{let e=JSON.parse(s);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function ke(s,e){return be(s.getItem(F(e,ie)))}function Se(s,e,t){let n=F(e,ie);if(typeof t.identityLink!="boolean"){s.removeItem(n);return}s.setItem(n,JSON.stringify({identityLink:t.identityLink}));}function tt(s,e,t,n){let i=F(t,"anonymous_id"),r=b(e.getItem(i))??b(s.getItem(i));return e.setItem(i,n),s.setItem(i,n),r!==void 0&&r!==n?r:void 0}var w=class{constructor(e,t,n,i){this.storage=e;this.shared=t;this.ids=n;this.namespace=i;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");this.refresh();}refresh(){let e=b(this.shared.getItem(this.key("anonymous_id"))),t=b(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let n=b(this.storage.getItem(this.key("distinct_id")));n?(this.distinctId=n,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return ke(this.shared,this.namespace)}setConsent(e){Se(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,n=this.storage.getItem(this.key("linked_anonymous_id")),i=t||n!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!i||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return F(this.namespace,e)}};var E=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),n=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,i=await this.request(t,n,{headers:this.authHeaders(),method:"GET"});if(!i.ok)throw new d(`inbox request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).messages??[]}async markRead(e,t){let n=this.requireFetch(),i=`${this.host}/v1/messages/read`,r=await this.request(n,i,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!r.ok)throw new d(`mark-read request failed with status ${r.status}`,r.status)}requireFetch(){if(!this.fetch)throw new d("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,n){let i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...n,signal:i?.signal})}finally{r!==void 0&&clearTimeout(r);}}};var c={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",screen:"$screen",set:"$set"},xe=[{emittedBy:"web",meaning:"A click anywhere on the page, with the element that was clicked. The web SDK sends it by default; autocapture: false or autocaptureOptions.clicks: false turns it off.",name:c.autocapture,properties:["$event_type","$el_description","$el_description_source","$el_action","$el_tag","$el_text","$el_id","$el_classes","$el_href","$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A page shown, including every client-side navigation the History API makes: one per distinct path and query.",name:c.pageview,properties:["$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"flutter",meaning:"A named route pushed or replaced in a Flutter app, the mobile counterpart of $pageview.",name:c.screen,properties:["screen"]},{emittedBy:"every",meaning:"A person becomes known by a distinct id. The anonymous trail before it is joined to them, and any traits ride along under $set.",name:c.identify,properties:["$anon_distinct_id","$set"]},{emittedBy:"every",meaning:"A second id for the same person, so events sent under either resolve to one profile.",name:c.createAlias,properties:["alias"]},{emittedBy:"every",meaning:"The person is placed in a group such as a company or a team; group properties ride along under $set.",name:c.group,properties:["$group_type","$group_key","$set"]},{emittedBy:"every",meaning:"Person properties written without an identify: $set overwrites, $set_once fills only what is still empty.",name:c.set,properties:["$set","$set_once"]},{emittedBy:"every",meaning:"A flag was evaluated for this person, sent once per distinct answer. Experiments attribute exposure from it.",name:c.featureFlagCalled,properties:["$feature_flag","$feature_flag_response"]}],lt=s=>s.startsWith("$"),ct=s=>xe.find(e=>e.name===s);function re(s){return s>=400&&s<500&&s!==429}var _=class{constructor(e$1={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=e(e$1.fetch),this.maxRetries=e$1.maxRetries??3,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4,this.baseDelayMs=e$1.baseDelayMs??500,this.maxDelayMs=e$1.maxDelayMs??3e4,this.sleep=e$1.sleep??g$1,this.random=e$1.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=JSON.stringify(e.body),i;for(let r=0;r<=this.maxRetries;r+=1){try{let a=await this.attempt(t,e,n);if(a.ok)return;if(re(a.status))throw new d(`ingest rejected batch with status ${a.status}`,a.status);i=new d(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof d&&a.status!==void 0&&re(a.status))throw a;i=a;}r<this.maxRetries&&await this.sleep(this.backoff(r));}throw new d("ingest delivery failed after retries",void 0,{cause:i})}async attempt(e,t,n){let i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:n,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:i?.signal})}finally{r!==void 0&&clearTimeout(r);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};function oe(s,e,t){B(s.eventName),U(s.distinctId);let n={distinct_id:s.distinctId,event_id:s.eventId??t.uuid(),event_name:s.eventName,properties:s.properties??{},schema_version:1,timestamp:S(s.timestamp??e.now())};return s.context&&(n.context=s.context),s.sessionId&&(n.session_id=s.sessionId),n}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,T=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"pending",null);a(this,"lastKey","");a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??Fe,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ie}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c$1(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$2());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let n=t.payload?.key;this.lastKey=typeof n=="string"?n:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},we));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Fe(s){let e=globalThis.WebSocket;if(!e)throw new d("no WebSocket");return new e(s)}var C=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;a(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var Ee={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function ae(s){return `pdx.${s}.session`}function wt(s,e,t,n){let i={id:t.id,lastActivityAt:n,startedAt:t.startedAt};s.setItem(ae(e),JSON.stringify(i));}var A=class{constructor(e,t,n,i,r=Ee){this.storage=e;this.ids=t;this.clock=n;this.namespace=i;this.options=r;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let n=this.live(this.read(),e),i=n!==void 0&&n.id!==t.id?n:t;return this.write({...i,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return ae(this.namespace)}};var _e="queue",Te=1e3,le=3e4,M=s=>{let e={};return s.avatar!==void 0&&(e.$avatar=s.avatar),s.email!==void 0&&(e.$email=s.email),s.name!==void 0&&(e.$name=s.name),s.phone!==void 0&&(e.$phone=s.phone),e},q=class{constructor(e){a(this,"config");a(this,"identity");a(this,"session");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");a(this,"membershipCache");a(this,"stream");a(this,"shutDown",false);a(this,"exposures",new Set);this.config=G(e),this.identity=new w(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new A(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new C(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new a$1("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new _({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new I({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new E({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let n={...this.config.defaultProperties(),...t.element===void 0?{}:this.config.describeElement?.(t.element)??{},...t.properties??{}},i=oe({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:n,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(i);}catch(n){this.config.onError(n);}}identify(e,t={}){this.identity.refresh();let n=this.identity.identify(e),i={};n.anonymousToLink!==void 0&&(i.$anon_distinct_id=n.anonymousToLink);let r={...M(t.traits??{}),...t.set??{}};Object.keys(r).length>0&&(i.$set=r),this.capture(c.identify,{properties:i});}link(e,t,n){let i={$anon_distinct_id:t},r=M(n??{});Object.keys(r).length>0&&(i.$set=r),this.capture(c.identify,{distinctId:e,properties:i});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(c.createAlias,{properties:{alias:e}});}group(e,t,n){let i={$group_key:t,$group_type:e};n&&(i.$set=n),this.capture(c.group,{properties:i});}setPersonProperties(e,t){let n={};e&&(n.$set=e),t&&(n.$set_once=t),this.capture(c.set,{properties:n});}setPersonTraits(e){let t=M(e);Object.keys(t).length!==0&&this.capture(c.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let n=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(n)),n}async getVariant(e){let t=await this.getAllFlags(),n=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,n?.key??String(t[e]??false)),n}async getVariantLocal(e,t={}){let n=await this.flagSnapshot(),i=n.flags.find(ce=>ce.key===e),r=await this.localContext(t,n.flags),a=i?v(i,n.flags,r):null,d=i?y(i,n.flags,r).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let n=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(n)||(this.exposures.add(n),this.capture(c.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return se(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let n=await this.flagSnapshot(),i=n.flags.find(d=>d.key===e),r=await this.localContext(t,n.flags),a=i?y(i,n.flags,r).enabled:false;return this.recordExposure(e,(i?v(i,n.flags,r)?.key:void 0)??String(a)),a}async localContext(e,t){let n=this.identity.getDistinctId(),i=e.cohorts;if(i===void 0&&ne(t)){let r=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&r-this.membershipCache.fetchedAt<le?i=this.membershipCache.cohorts:(i=await this.flagsClient.memberships(n),this.membershipCache={cohorts:i,distinctId:n,fetchedAt:r});}return {attributes:e.attributes,cohorts:i,distinctId:n,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<le)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new T({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(n=>this.config.onError(n));},onClosed:n=>{this.stream=void 0,n&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Te);try{await this.transport.send({body:{events:e,sent_at:S(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${_e}`}};function Lt(s){return new q(s)}export{g as a,Ce as b,V as c,me as d,j as e,J as f,z as g,ye as h,Z as i,ee as j,ze as k,se as l,Qe as m,Ge as n,I as o,be as p,tt as q,E as r,wt as s,c as t,xe as u,lt as v,ct as w,_ as x,q as y,Lt as z};//# sourceMappingURL=chunk-D6PMLUYA.js.map
2
+ //# sourceMappingURL=chunk-D6PMLUYA.js.map
@@ -1,4 +1,4 @@
1
- import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-DjMXp6Wg.cjs';
1
+ import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-Q2VNlJbG.cjs';
2
2
 
3
3
  interface LocalFlagContext {
4
4
  attributes?: EventProperties;
@@ -12,6 +12,7 @@ interface CaptureOptions {
12
12
  * visitor of its own to lend an event, so an event it sends on a browser's
13
13
  * behalf names the person directly. */
14
14
  distinctId?: string;
15
+ element?: unknown;
15
16
  properties?: EventProperties;
16
17
  sessionId?: string;
17
18
  timestamp?: Date;
@@ -1,4 +1,4 @@
1
- import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-DjMXp6Wg.js';
1
+ import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-Q2VNlJbG.js';
2
2
 
3
3
  interface LocalFlagContext {
4
4
  attributes?: EventProperties;
@@ -12,6 +12,7 @@ interface CaptureOptions {
12
12
  * visitor of its own to lend an event, so an event it sends on a browser's
13
13
  * behalf names the person directly. */
14
14
  distinctId?: string;
15
+ element?: unknown;
15
16
  properties?: EventProperties;
16
17
  sessionId?: string;
17
18
  timestamp?: Date;