@kitbase/messaging 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,209 @@
1
+ # @kitbase/messaging
2
+
3
+ Kitbase In-App Messaging SDK for TypeScript and JavaScript. Fetches targeted messages and renders them directly in the page — modals, banners, cards, and full-screen images with automatic stacking.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @kitbase/messaging
9
+ # or
10
+ pnpm add @kitbase/messaging
11
+ # or
12
+ yarn add @kitbase/messaging
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { init } from '@kitbase/messaging';
19
+
20
+ const messaging = init({
21
+ sdkKey: 'your-sdk-key',
22
+ userId: currentUser.id,
23
+ metadata: { plan: 'pro' },
24
+ });
25
+
26
+ // Messages are fetched and rendered automatically!
27
+ ```
28
+
29
+ That's it — messages matching your targeting criteria will appear as modals, banners, cards, or images with no extra code.
30
+
31
+ ### Script Tag (CDN)
32
+
33
+ No bundler required. Works with any page — PHP, WordPress, static HTML, etc.
34
+
35
+ ```html
36
+ <!-- unpkg -->
37
+ <script src="https://unpkg.com/@kitbase/messaging/dist/cdn.js"></script>
38
+
39
+ <!-- or jsdelivr -->
40
+ <script src="https://cdn.jsdelivr.net/npm/@kitbase/messaging/dist/cdn.js"></script>
41
+ ```
42
+
43
+ ```html
44
+ <script>
45
+ window.KITBASE_MESSAGING = {
46
+ sdkKey: 'your-sdk-key',
47
+ userId: 'user_123',
48
+ metadata: { plan: 'free', country: 'US' },
49
+ };
50
+ </script>
51
+ <script src="https://unpkg.com/@kitbase/messaging/dist/cdn.js"></script>
52
+ <!-- Messages appear automatically! -->
53
+ ```
54
+
55
+ The script auto-initializes and exposes `window.kitbaseMessaging` for further control:
56
+
57
+ ```html
58
+ <script>
59
+ // After user logs in
60
+ window.kitbaseMessaging.identify('user_456');
61
+ </script>
62
+ ```
63
+
64
+ Or initialize manually:
65
+
66
+ ```html
67
+ <script src="https://unpkg.com/@kitbase/messaging/dist/cdn.js"></script>
68
+ <script>
69
+ var messaging = KitbaseMessaging.init({ sdkKey: 'your-sdk-key' });
70
+
71
+ messaging.identify('user_123');
72
+ messaging.close(); // clean up
73
+ </script>
74
+ ```
75
+
76
+ ## Configuration
77
+
78
+ | Option | Type | Default | Description |
79
+ |---|---|---|---|
80
+ | `sdkKey` | `string` | **(required)** | Your Kitbase SDK key |
81
+ | `baseUrl` | `string` | `'https://api.kitbase.dev'` | API base URL (for self-hosted instances) |
82
+ | `userId` | `string` | — | Current user ID. Filters out already-viewed show-once messages |
83
+ | `metadata` | `Record<string, string>` | — | Key-value pairs for targeting evaluation |
84
+ | `pollInterval` | `number` | `60000` | Polling interval in ms. Set to `0` to fetch once only |
85
+ | `autoShow` | `boolean` | `true` | Automatically render messages in the page |
86
+ | `onShow` | `(message) => void` | — | Called when a message is displayed |
87
+ | `onDismiss` | `(message) => void` | — | Called when a message is dismissed |
88
+ | `onAction` | `(message, button) => void \| false` | — | Called on button click. Return `false` to prevent navigation |
89
+
90
+ ## API
91
+
92
+ ### `init(config): Messaging`
93
+
94
+ Initialize the SDK. Creates a singleton instance.
95
+
96
+ ```typescript
97
+ import { init } from '@kitbase/messaging';
98
+
99
+ const messaging = init({ sdkKey: 'your-sdk-key' });
100
+ ```
101
+
102
+ ### `getInstance(): Messaging | null`
103
+
104
+ Get the current singleton instance.
105
+
106
+ ```typescript
107
+ import { getInstance } from '@kitbase/messaging';
108
+
109
+ const messaging = getInstance();
110
+ ```
111
+
112
+ ### `messaging.identify(userId)`
113
+
114
+ Set the current user. Triggers an immediate re-fetch to filter out already-viewed show-once messages.
115
+
116
+ ```typescript
117
+ messaging.identify('user_123');
118
+ ```
119
+
120
+ ### `messaging.reset()`
121
+
122
+ Clear the user and dismissed state. Call on logout.
123
+
124
+ ```typescript
125
+ messaging.reset();
126
+ ```
127
+
128
+ ### `messaging.markViewed(messageId)`
129
+
130
+ Record that the user has viewed a message. The message is removed from the UI immediately and the view is recorded on the server. Requires `identify()` to have been called first.
131
+
132
+ ```typescript
133
+ messaging.markViewed('msg_abc');
134
+ ```
135
+
136
+ ### `messaging.getMessages(options?)`
137
+
138
+ Fetch messages without rendering (data-only). Useful with `autoShow: false`.
139
+
140
+ ```typescript
141
+ const messaging = init({ sdkKey: '...', autoShow: false });
142
+ const messages = await messaging.getMessages();
143
+ ```
144
+
145
+ ### `messaging.subscribe(callback, options?)`
146
+
147
+ Subscribe to messages with polling. Returns an unsubscribe function.
148
+
149
+ ```typescript
150
+ const unsub = messaging.subscribe(
151
+ (messages) => renderMyUI(messages),
152
+ { pollInterval: 30_000 },
153
+ );
154
+
155
+ // Later
156
+ unsub();
157
+ ```
158
+
159
+ ### `messaging.close()`
160
+
161
+ Stop polling, remove all rendered UI, and clean up.
162
+
163
+ ## Message Types
164
+
165
+ The SDK renders four message types, each with automatic stacking:
166
+
167
+ | Type | Behavior |
168
+ |---|---|
169
+ | `modal` | Centered overlay with backdrop |
170
+ | `banner` | Fixed to top, stacks vertically |
171
+ | `card` | Fixed to bottom-right, stacks vertically |
172
+ | `image` | Full-screen image overlay |
173
+
174
+ All rendering uses shadow DOM for complete style isolation from your page.
175
+
176
+ ## Behavior
177
+
178
+ - **Polling pauses** when the browser tab is hidden and resumes immediately when the tab becomes visible again.
179
+ - **Dismissed messages** are tracked in-memory for the current session and filtered from subsequent polls.
180
+ - **Show-once messages** are filtered server-side when a `userId` is provided.
181
+
182
+ ## TypeScript Types
183
+
184
+ ```typescript
185
+ import type {
186
+ MessagingConfig,
187
+ InAppMessage,
188
+ MessageType,
189
+ MessageButton,
190
+ GetMessagesOptions,
191
+ SubscribeOptions,
192
+ } from '@kitbase/messaging';
193
+ ```
194
+
195
+ ## Error Types
196
+
197
+ ```typescript
198
+ import {
199
+ MessagingError, // Base error
200
+ AuthenticationError, // Invalid SDK key (401)
201
+ ApiError, // API error (non-2xx)
202
+ ValidationError, // Invalid config or missing params
203
+ TimeoutError, // Request timed out
204
+ } from '@kitbase/messaging';
205
+ ```
206
+
207
+ ## License
208
+
209
+ MIT
package/dist/cdn.js ADDED
@@ -0,0 +1,299 @@
1
+ "use strict";var KitbaseMessaging=(()=>{var y=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var I=(n,e)=>{for(var t in e)y(n,t,{get:e[t],enumerable:!0})},A=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of E(e))!T.call(n,s)&&s!==t&&y(n,s,{get:()=>e[s],enumerable:!(i=C(e,s))||i.enumerable});return n};var B=n=>A(y({},"__esModule",{value:!0}),n);var L={};I(L,{ApiError:()=>c,AuthenticationError:()=>p,Messaging:()=>b,MessagingError:()=>a,TimeoutError:()=>d,ValidationError:()=>l,getInstance:()=>M,init:()=>u});var a=class n extends Error{constructor(e){super(e),this.name="MessagingError",Object.setPrototypeOf(this,n.prototype)}},p=class n extends a{constructor(e="Invalid API key"){super(e),this.name="AuthenticationError",Object.setPrototypeOf(this,n.prototype)}},c=class n extends a{statusCode;response;constructor(e,t,i){super(e),this.name="ApiError",this.statusCode=t,this.response=i,Object.setPrototypeOf(this,n.prototype)}},l=class n extends a{field;constructor(e,t){super(e),this.name="ValidationError",this.field=t,Object.setPrototypeOf(this,n.prototype)}},d=class n extends a{constructor(e="Request timed out"){super(e),this.name="TimeoutError",Object.setPrototypeOf(this,n.prototype)}};var S="https://api.kitbase.dev",k=3e4,g=class{constructor(e,t){this.sdkKey=e;this.baseUrl=(t??S).replace(/\/+$/,"")}baseUrl;async getMessages(e){let t={};return e?.userId&&(t.userId=e.userId),e?.metadata&&(t.metadata=JSON.stringify(e.metadata)),(await this.get("/sdk/v1/in-app-messages",t)).messages.map(O)}async markViewed(e,t){await this.post("/sdk/v1/in-app-messages/views",{messageId:e,userId:t})}async get(e,t){let i=`${this.baseUrl}${e}`;if(t&&Object.keys(t).length>0){let r=Object.entries(t).map(([f,w])=>`${encodeURIComponent(f)}=${encodeURIComponent(w)}`).join("&");i+=`?${r}`}let s=new AbortController,o=setTimeout(()=>s.abort(),k);try{let r=await fetch(i,{method:"GET",headers:{"Content-Type":"application/json","x-sdk-key":this.sdkKey},signal:s.signal});return clearTimeout(o),r.ok||this.throwError(r,await this.parseBody(r)),await r.json()}catch(r){throw clearTimeout(o),r instanceof Error&&r.name==="AbortError"?new d:r}}async post(e,t){let i=new AbortController,s=setTimeout(()=>i.abort(),k);try{let o=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:{"Content-Type":"application/json","x-sdk-key":this.sdkKey},body:JSON.stringify(t),signal:i.signal});clearTimeout(s),o.ok||this.throwError(o,await this.parseBody(o))}catch(o){throw clearTimeout(s),o instanceof Error&&o.name==="AbortError"?new d:o}}throwError(e,t){if(e.status===401)throw new p;let i=e.statusText;throw t&&typeof t=="object"&&("message"in t?i=String(t.message):"error"in t&&(i=String(t.error))),new c(i,e.status,t)}async parseBody(e){try{return await e.json()}catch{return null}}};function O(n){let e={id:n.id,title:n.title,body:n.message,showOnce:n.showOnce,type:n.messageType,channel:n.channelName||null,imageUrl:n.imageUrl,backgroundColor:n.backgroundColor,startDate:n.startDate,endDate:n.endDate};return n.actionButtonText&&(e.actionButton={text:n.actionButtonText,url:n.actionButtonUrl,color:n.actionButtonColor,textColor:n.actionButtonTextColor}),n.secondaryButtonText&&(e.secondaryButton={text:n.secondaryButtonText,url:n.secondaryButtonUrl,color:n.secondaryButtonColor,textColor:n.secondaryButtonTextColor}),e}var v=`
2
+ :host {
3
+ all: initial;
4
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
5
+ font-size: 14px;
6
+ line-height: 1.5;
7
+ color: #1a1a1a;
8
+ -webkit-font-smoothing: antialiased;
9
+ -moz-osx-font-smoothing: grayscale;
10
+ }
11
+
12
+ *, *::before, *::after {
13
+ box-sizing: border-box;
14
+ margin: 0;
15
+ padding: 0;
16
+ }
17
+
18
+ /* ============================== Overlay ============================== */
19
+
20
+ .kb-overlay {
21
+ position: fixed;
22
+ inset: 0;
23
+ z-index: 999999;
24
+ background: rgba(0, 0, 0, 0.5);
25
+ display: flex;
26
+ align-items: center;
27
+ justify-content: center;
28
+ padding: 16px;
29
+ animation: kb-fade-in 200ms ease-out;
30
+ }
31
+ .kb-overlay.kb-exit {
32
+ animation: kb-fade-out 150ms ease-in forwards;
33
+ }
34
+
35
+ /* ============================== Modal ============================== */
36
+
37
+ .kb-modal {
38
+ position: relative;
39
+ background: #fff;
40
+ border-radius: 16px;
41
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
42
+ max-width: 480px;
43
+ width: 100%;
44
+ overflow: hidden;
45
+ animation: kb-scale-in 200ms ease-out;
46
+ }
47
+ .kb-overlay.kb-exit .kb-modal {
48
+ animation: kb-scale-out 150ms ease-in forwards;
49
+ }
50
+
51
+ /* ============================== Banner ============================== */
52
+
53
+ .kb-banner-container {
54
+ position: fixed;
55
+ top: 0;
56
+ left: 0;
57
+ right: 0;
58
+ z-index: 999998;
59
+ display: flex;
60
+ flex-direction: column;
61
+ pointer-events: none;
62
+ }
63
+
64
+ .kb-banner {
65
+ display: flex;
66
+ align-items: center;
67
+ gap: 16px;
68
+ padding: 12px 20px;
69
+ background: #4F46E5;
70
+ color: #fff;
71
+ pointer-events: auto;
72
+ animation: kb-slide-down 250ms ease-out;
73
+ }
74
+ .kb-banner.kb-exit {
75
+ animation: kb-slide-up-exit 150ms ease-in forwards;
76
+ }
77
+ .kb-banner .kb-content {
78
+ flex: 1;
79
+ min-width: 0;
80
+ }
81
+ .kb-banner .kb-title {
82
+ font-weight: 600;
83
+ font-size: 14px;
84
+ }
85
+ .kb-banner .kb-body {
86
+ font-size: 13px;
87
+ opacity: 0.9;
88
+ color: inherit;
89
+ margin: 0;
90
+ }
91
+ .kb-banner .kb-actions {
92
+ display: flex;
93
+ align-items: center;
94
+ gap: 8px;
95
+ flex-shrink: 0;
96
+ }
97
+ .kb-banner .kb-btn-action {
98
+ background: rgba(255,255,255,0.2);
99
+ color: #fff;
100
+ }
101
+ .kb-banner .kb-btn-secondary {
102
+ background: transparent;
103
+ color: rgba(255,255,255,0.8);
104
+ }
105
+ .kb-banner .kb-close {
106
+ position: static;
107
+ background: rgba(255,255,255,0.15);
108
+ color: #fff;
109
+ }
110
+ .kb-banner .kb-close:hover {
111
+ background: rgba(255,255,255,0.25);
112
+ }
113
+
114
+ /* ============================== Card ============================== */
115
+
116
+ .kb-card-container {
117
+ position: fixed;
118
+ bottom: 24px;
119
+ right: 24px;
120
+ z-index: 999997;
121
+ display: flex;
122
+ flex-direction: column;
123
+ gap: 12px;
124
+ max-width: 360px;
125
+ pointer-events: none;
126
+ }
127
+
128
+ .kb-card {
129
+ position: relative;
130
+ background: #fff;
131
+ border-radius: 16px;
132
+ box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.1);
133
+ overflow: hidden;
134
+ pointer-events: auto;
135
+ animation: kb-slide-up 250ms ease-out;
136
+ }
137
+ .kb-card.kb-exit {
138
+ animation: kb-slide-down-exit 150ms ease-in forwards;
139
+ }
140
+
141
+ /* ============================== Image (fullscreen) ============================== */
142
+
143
+ .kb-image-msg {
144
+ position: relative;
145
+ max-width: 600px;
146
+ width: 100%;
147
+ animation: kb-scale-in 200ms ease-out;
148
+ }
149
+ .kb-overlay.kb-exit .kb-image-msg {
150
+ animation: kb-scale-out 150ms ease-in forwards;
151
+ }
152
+ .kb-image-msg > img {
153
+ display: block;
154
+ width: 100%;
155
+ border-radius: 16px;
156
+ }
157
+ .kb-image-msg .kb-buttons {
158
+ margin-top: 12px;
159
+ justify-content: center;
160
+ }
161
+
162
+ /* ============================== Shared ============================== */
163
+
164
+ .kb-close {
165
+ position: absolute;
166
+ top: 8px;
167
+ right: 8px;
168
+ width: 28px;
169
+ height: 28px;
170
+ display: flex;
171
+ align-items: center;
172
+ justify-content: center;
173
+ background: rgba(0,0,0,0.06);
174
+ border: none;
175
+ border-radius: 50%;
176
+ cursor: pointer;
177
+ font-size: 18px;
178
+ line-height: 1;
179
+ color: #666;
180
+ transition: background 150ms, color 150ms;
181
+ z-index: 1;
182
+ }
183
+ .kb-close:hover {
184
+ background: rgba(0,0,0,0.12);
185
+ color: #333;
186
+ }
187
+ .kb-overlay .kb-close {
188
+ background: rgba(255,255,255,0.15);
189
+ color: #fff;
190
+ }
191
+ .kb-overlay .kb-close:hover {
192
+ background: rgba(255,255,255,0.25);
193
+ }
194
+
195
+ .kb-msg-image {
196
+ display: block;
197
+ width: 100%;
198
+ }
199
+
200
+ .kb-content {
201
+ padding: 20px;
202
+ }
203
+
204
+ .kb-title {
205
+ font-size: 18px;
206
+ font-weight: 600;
207
+ line-height: 1.3;
208
+ margin-bottom: 6px;
209
+ }
210
+
211
+ .kb-body {
212
+ font-size: 14px;
213
+ color: #555;
214
+ line-height: 1.6;
215
+ margin-bottom: 16px;
216
+ white-space: pre-wrap;
217
+ }
218
+
219
+ .kb-buttons {
220
+ display: flex;
221
+ gap: 8px;
222
+ }
223
+
224
+ .kb-btn {
225
+ display: inline-flex;
226
+ align-items: center;
227
+ justify-content: center;
228
+ padding: 10px 20px;
229
+ border: none;
230
+ border-radius: 10px;
231
+ font-size: 14px;
232
+ font-weight: 500;
233
+ cursor: pointer;
234
+ text-decoration: none;
235
+ transition: opacity 150ms;
236
+ font-family: inherit;
237
+ line-height: 1;
238
+ }
239
+ .kb-btn:hover {
240
+ opacity: 0.88;
241
+ }
242
+
243
+ .kb-btn-action {
244
+ background: #4F46E5;
245
+ color: #fff;
246
+ }
247
+
248
+ .kb-btn-secondary {
249
+ background: #f3f4f6;
250
+ color: #374151;
251
+ }
252
+
253
+ /* ============================== Animations ============================== */
254
+
255
+ @keyframes kb-fade-in {
256
+ from { opacity: 0 } to { opacity: 1 }
257
+ }
258
+ @keyframes kb-fade-out {
259
+ from { opacity: 1 } to { opacity: 0 }
260
+ }
261
+ @keyframes kb-scale-in {
262
+ from { transform: scale(0.95); opacity: 0 }
263
+ to { transform: scale(1); opacity: 1 }
264
+ }
265
+ @keyframes kb-scale-out {
266
+ from { transform: scale(1); opacity: 1 }
267
+ to { transform: scale(0.95); opacity: 0 }
268
+ }
269
+ @keyframes kb-slide-down {
270
+ from { transform: translateY(-100%) }
271
+ to { transform: translateY(0) }
272
+ }
273
+ @keyframes kb-slide-up-exit {
274
+ from { transform: translateY(0) }
275
+ to { transform: translateY(-100%) }
276
+ }
277
+ @keyframes kb-slide-up {
278
+ from { transform: translateY(20px); opacity: 0 }
279
+ to { transform: translateY(0); opacity: 1 }
280
+ }
281
+ @keyframes kb-slide-down-exit {
282
+ from { transform: translateY(0); opacity: 1 }
283
+ to { transform: translateY(20px); opacity: 0 }
284
+ }
285
+
286
+ /* ============================== Responsive ============================== */
287
+
288
+ @media (max-width: 480px) {
289
+ .kb-card-container {
290
+ left: 12px;
291
+ right: 12px;
292
+ bottom: 12px;
293
+ max-width: none;
294
+ }
295
+ .kb-modal {
296
+ max-width: none;
297
+ }
298
+ }
299
+ `;var m=class{constructor(e){this.callbacks=e;this.host=document.createElement("div"),this.host.id="kitbase-messaging",document.body.appendChild(this.host),this.shadow=this.host.attachShadow({mode:"open"});let t=document.createElement("style");t.textContent=v,this.shadow.appendChild(t),this.bannerContainer=document.createElement("div"),this.bannerContainer.className="kb-banner-container",this.shadow.appendChild(this.bannerContainer),this.cardContainer=document.createElement("div"),this.cardContainer.className="kb-card-container",this.shadow.appendChild(this.cardContainer)}host;shadow;bannerContainer;cardContainer;displayed=new Map;update(e){let t=new Set(e.map(i=>i.id));for(let[i]of this.displayed)t.has(i)||this.removeMessage(i);for(let i of e)this.displayed.has(i.id)||this.renderMessage(i)}dismiss(e){this.removeMessage(e)}clear(){for(let[e]of this.displayed){let t=this.displayed.get(e);t&&t.element.remove()}this.displayed.clear()}destroy(){this.clear(),this.host.remove()}renderMessage(e){let t;switch(e.type){case"banner":t=this.renderBanner(e),this.bannerContainer.appendChild(t);break;case"card":t=this.renderCard(e),this.cardContainer.appendChild(t);break;case"image":t=this.renderImageOverlay(e),this.shadow.appendChild(t);break;default:t=this.renderModal(e),this.shadow.appendChild(t);break}this.displayed.set(e.id,{element:t,message:e}),this.callbacks.onShow(e)}renderModal(e){let t=this.el("div","kb-overlay"),i=this.el("div","kb-modal");if(e.backgroundColor&&(i.style.background=e.backgroundColor),i.appendChild(this.closeButton(e)),e.imageUrl){let o=document.createElement("img");o.className="kb-msg-image",o.src=e.imageUrl,o.alt="",i.appendChild(o)}let s=this.el("div","kb-content");return s.appendChild(this.titleEl(e.title)),e.body&&s.appendChild(this.bodyEl(e.body)),s.appendChild(this.buttonsEl(e)),i.appendChild(s),t.addEventListener("click",o=>{o.target===t&&this.handleDismiss(e)}),t.appendChild(i),t}renderBanner(e){let t=this.el("div","kb-banner");e.backgroundColor&&(t.style.background=e.backgroundColor);let i=this.el("div","kb-content");i.appendChild(this.titleEl(e.title)),e.body&&i.appendChild(this.bodyEl(e.body)),t.appendChild(i);let s=this.el("div","kb-actions");return e.actionButton&&s.appendChild(this.btnEl(e,e.actionButton,"kb-btn-action")),e.secondaryButton&&s.appendChild(this.btnEl(e,e.secondaryButton,"kb-btn-secondary")),s.appendChild(this.closeButton(e)),t.appendChild(s),t}renderCard(e){let t=this.el("div","kb-card");if(e.backgroundColor&&(t.style.background=e.backgroundColor),t.appendChild(this.closeButton(e)),e.imageUrl){let s=document.createElement("img");s.className="kb-msg-image",s.src=e.imageUrl,s.alt="",t.appendChild(s)}let i=this.el("div","kb-content");return i.appendChild(this.titleEl(e.title)),e.body&&i.appendChild(this.bodyEl(e.body)),i.appendChild(this.buttonsEl(e)),t.appendChild(i),t}renderImageOverlay(e){let t=this.el("div","kb-overlay"),i=this.el("div","kb-image-msg");if(i.appendChild(this.closeButton(e)),e.imageUrl){let o=document.createElement("img");o.src=e.imageUrl,o.alt=e.title,i.appendChild(o)}let s=this.buttonsEl(e);return s.childElementCount>0&&i.appendChild(s),t.addEventListener("click",o=>{o.target===t&&this.handleDismiss(e)}),t.appendChild(i),t}titleEl(e){let t=this.el("div","kb-title");return t.textContent=e,t}bodyEl(e){let t=this.el("div","kb-body");return t.textContent=e,t}buttonsEl(e){let t=this.el("div","kb-buttons");return e.actionButton&&t.appendChild(this.btnEl(e,e.actionButton,"kb-btn-action")),e.secondaryButton&&t.appendChild(this.btnEl(e,e.secondaryButton,"kb-btn-secondary")),t}btnEl(e,t,i){let s=document.createElement("button");return s.className=`kb-btn ${i}`,s.textContent=t.text,t.color&&(s.style.background=t.color),t.textColor&&(s.style.color=t.textColor),s.addEventListener("click",o=>{o.stopPropagation(),this.handleAction(e,t)}),s}closeButton(e){let t=document.createElement("button");return t.className="kb-close",t.innerHTML="&#x2715;",t.setAttribute("aria-label","Close"),t.addEventListener("click",i=>{i.stopPropagation(),this.handleDismiss(e)}),t}handleDismiss(e){let t=this.displayed.get(e.id);t&&this.animateOut(t.element,e)}handleAction(e,t){this.callbacks.onAction(e,t)!==!1&&t.url&&window.open(t.url,"_blank","noopener");let s=this.displayed.get(e.id);s&&this.animateOut(s.element,e)}removeMessage(e){let t=this.displayed.get(e);t&&this.animateOut(t.element,t.message)}animateOut(e,t){if(e.classList.contains("kb-exit"))return;e.classList.add("kb-exit");let i=()=>{e.remove(),this.displayed.delete(t.id),this.callbacks.onDismiss(t)};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,300)}el(e,t){let i=document.createElement(e);return i.className=t,i}};var x=6e4,h=null;function u(n){return h&&h.close(),h=new b(n),h}function M(){return h}var b=class{api;renderer=null;config;pollTimer=null;dismissed=new Set;subscriptionTimers=new Set;pendingPoll=!1;visibilityHandler=null;userId;constructor(e){if(!e.sdkKey)throw new l("SDK key is required","sdkKey");this.config=e,this.userId=e.userId,this.api=new g(e.sdkKey,e.baseUrl),e.autoShow!==!1&&typeof window<"u"&&this.start()}start(){if(typeof window>"u"||this.renderer)return;this.renderer=new m({onShow:t=>{this.config.onShow?.(t)},onDismiss:t=>{this.dismissed.add(t.id),this.config.onDismiss?.(t)},onAction:(t,i)=>this.config.onAction?.(t,i)}),this.poll();let e=this.config.pollInterval??x;e>0&&(this.pollTimer=setInterval(()=>this.poll(),e)),this.visibilityHandler=()=>{document.visibilityState==="visible"&&this.pendingPoll&&(this.pendingPoll=!1,this.poll())},document.addEventListener("visibilitychange",this.visibilityHandler)}stop(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.pendingPoll=!1,this.renderer?.destroy(),this.renderer=null}close(){this.stop();for(let e of this.subscriptionTimers)clearInterval(e);this.subscriptionTimers.clear(),this.dismissed.clear()}identify(e){this.userId=e,this.poll()}reset(){this.userId=void 0,this.dismissed.clear(),this.poll()}async markViewed(e){if(!this.userId)throw new l("User ID is required to mark a message as viewed. Call identify() first.","userId");this.dismissed.add(e),this.renderer?.dismiss(e),await this.api.markViewed(e,this.userId)}async getMessages(e){return this.api.getMessages(e)}subscribe(e,t){let i=t?.pollInterval??x,s=!0,o=async()=>{if(s)try{let f=await this.api.getMessages(t);s&&e(f)}catch{}};o();let r=setInterval(o,i);return this.subscriptionTimers.add(r),()=>{s=!1,clearInterval(r),this.subscriptionTimers.delete(r)}}async poll(){if(typeof document<"u"&&document.visibilityState==="hidden"){this.pendingPoll=!0;return}try{let t=(await this.api.getMessages({userId:this.userId,metadata:this.config.metadata})).filter(i=>!this.dismissed.has(i.id));this.renderer?.update(t)}catch{}}};if(typeof window<"u"&&window.KITBASE_MESSAGING)try{window.kitbaseMessaging=u(window.KITBASE_MESSAGING)}catch(n){console.error("[KitbaseMessaging] Failed to auto-initialize:",n)}return B(L);})();