@journyio/messaging-sdk 1.0.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.
@@ -0,0 +1,2860 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.JournyMessages = {}, global.React));
5
+ })(this, (function (exports, React) { 'use strict';
6
+
7
+ function _interopNamespaceDefault(e) {
8
+ var n = Object.create(null);
9
+ if (e) {
10
+ Object.keys(e).forEach(function (k) {
11
+ if (k !== 'default') {
12
+ var d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: function () { return e[k]; }
16
+ });
17
+ }
18
+ });
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+
24
+ var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
25
+
26
+ class MessageQueue {
27
+ constructor() {
28
+ this.queue = [];
29
+ this.messageMap = {};
30
+ this.allFetchedMessages = [];
31
+ this.readMessageIds = new Set();
32
+ }
33
+ addMessage(message) {
34
+ // Check if message already exists
35
+ const queueMessage = this.messageMap[message.id];
36
+ if (queueMessage) {
37
+ this.updateMessageReceived(queueMessage, message);
38
+ return;
39
+ }
40
+ if (message.expiredAt && new Date(message.expiredAt) < new Date()) {
41
+ return;
42
+ }
43
+ this.queue.push(message);
44
+ this.messageMap[message.id] = message;
45
+ this.allFetchedMessages.push(message);
46
+ this.sortByPriority();
47
+ }
48
+ addMessages(messages) {
49
+ messages.forEach((message) => this.addMessage(message));
50
+ }
51
+ getNextMessage() {
52
+ this.removeExpiredMessages();
53
+ if (this.queue.length === 0) {
54
+ return null;
55
+ }
56
+ return this.queue[0];
57
+ }
58
+ getAlreadyReceivedIds(messageIds) {
59
+ return messageIds.filter((id) => this.messageMap[id]?.received || this.readMessageIds.has(id));
60
+ }
61
+ removeMessage(messageIds) {
62
+ this.queue = this.queue.filter((m) => !messageIds.includes(m.id));
63
+ messageIds.forEach(id => this.readMessageIds.add(id));
64
+ }
65
+ /** Mark a message as received (user clicked/viewed it) without removing from queue */
66
+ markMessageAsReceived(messageIds) {
67
+ const updateReceived = (m) => messageIds.includes(m.id) ? { ...m, received: true } : m;
68
+ this.queue = this.queue.map(updateReceived);
69
+ this.allFetchedMessages = this.allFetchedMessages.map(updateReceived);
70
+ // Keep messageMap in sync so subsequent addMessages calls see received=true
71
+ for (const id of messageIds) {
72
+ if (this.messageMap[id]) {
73
+ this.messageMap[id] = { ...this.messageMap[id], received: true };
74
+ }
75
+ }
76
+ }
77
+ getAllMessages() {
78
+ this.removeExpiredMessages();
79
+ return [...this.queue];
80
+ }
81
+ getAllFetchedMessages() {
82
+ return [...this.allFetchedMessages];
83
+ }
84
+ getActiveCount() {
85
+ return this.queue.length;
86
+ }
87
+ getReadCount() {
88
+ return this.allFetchedMessages.filter((m) => this.readMessageIds.has(m.id) && !this.queue.find((q) => q.id === m.id)).length;
89
+ }
90
+ clear() {
91
+ this.queue = [];
92
+ this.allFetchedMessages = [];
93
+ this.readMessageIds.clear();
94
+ }
95
+ size() {
96
+ return this.queue.length;
97
+ }
98
+ sortByCreatedAt(a, b) {
99
+ return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
100
+ }
101
+ sortByPriority() {
102
+ const unreadMessages = this.queue.filter((m) => !m.received);
103
+ const readMessages = this.queue.filter((m) => m.received);
104
+ this.queue = [...unreadMessages.sort(this.sortByCreatedAt), ...readMessages.sort(this.sortByCreatedAt)];
105
+ }
106
+ removeExpiredMessages() {
107
+ const now = new Date();
108
+ this.queue = this.queue.filter((message) => {
109
+ if (message.expiredAt) {
110
+ return new Date(message.expiredAt) >= now;
111
+ }
112
+ return true;
113
+ });
114
+ }
115
+ updateMessageReceived(queueMessage, message) {
116
+ const updated = { ...queueMessage, received: message.received, expired: message.expired, status: message.status };
117
+ const idx = this.queue.indexOf(queueMessage);
118
+ if (idx !== -1)
119
+ this.queue[idx] = updated;
120
+ const fetchedIdx = this.allFetchedMessages.indexOf(queueMessage);
121
+ if (fetchedIdx !== -1)
122
+ this.allFetchedMessages[fetchedIdx] = updated;
123
+ this.messageMap[updated.id] = updated;
124
+ }
125
+ }
126
+
127
+ const API_PATHS = {
128
+ IN_APP_MESSAGES: '/sdk/in-app-messages',
129
+ };
130
+ class ApiClient {
131
+ constructor(config) {
132
+ this.config = config;
133
+ }
134
+ getHeaders() {
135
+ const headers = {
136
+ 'Content-Type': 'application/json',
137
+ };
138
+ if (this.config.writeKey) {
139
+ headers['Authorization'] = `Bearer ${this.config.writeKey}`;
140
+ headers['x-write-key'] = this.config.writeKey;
141
+ }
142
+ return headers;
143
+ }
144
+ buildUrl(endpoint) {
145
+ const baseUrl = (this.config.apiEndpoint || 'https://jtm.journy.io').replace(/\/$/, '');
146
+ const entityId = this.config.entityType === 'user'
147
+ ? this.config.userId
148
+ : this.config.accountId;
149
+ if (!entityId) {
150
+ throw new Error(`${this.config.entityType}Id is required`);
151
+ }
152
+ const targetPath = `${API_PATHS.IN_APP_MESSAGES}/${this.config.entityType}/${entityId}${endpoint}`;
153
+ return new URL(targetPath, baseUrl).toString();
154
+ }
155
+ async getUnreadMessages() {
156
+ try {
157
+ const url = this.buildUrl('/unread');
158
+ const response = await fetch(url, {
159
+ method: 'GET',
160
+ headers: this.getHeaders(),
161
+ mode: 'cors', // Explicitly set CORS mode
162
+ });
163
+ if (!response.ok) {
164
+ throw new Error(`HTTP error! status: ${response.status}`);
165
+ }
166
+ const data = await response.json();
167
+ return data.data || [];
168
+ }
169
+ catch (error) {
170
+ console.error('Failed to fetch unread messages:', error);
171
+ return [];
172
+ }
173
+ }
174
+ async markAsRead(messageIds) {
175
+ try {
176
+ const url = this.buildUrl('/received');
177
+ const response = await fetch(url, {
178
+ method: 'POST',
179
+ headers: this.getHeaders(),
180
+ mode: 'cors',
181
+ body: JSON.stringify({
182
+ messageIds: messageIds,
183
+ }),
184
+ });
185
+ if (!response.ok) {
186
+ throw new Error(`HTTP error! status: ${response.status}`);
187
+ }
188
+ const data = await response.json();
189
+ if (data.data && data.data.markedCount !== messageIds.length) {
190
+ throw new Error(`Failed to mark all messages as read. Expected ${messageIds.length} messages, got ${data.data.markedCount}`);
191
+ }
192
+ }
193
+ catch (error) {
194
+ console.error('Failed to mark message as read:', error);
195
+ }
196
+ }
197
+ }
198
+
199
+ var SDKEventType;
200
+ (function (SDKEventType) {
201
+ SDKEventType["MessageReceived"] = "In-App Message Received";
202
+ SDKEventType["MessageOpened"] = "In-App Message Opened";
203
+ SDKEventType["MessageClosed"] = "In-App Message Closed";
204
+ SDKEventType["MessageLinkClicked"] = "In-App Message Link Clicked";
205
+ })(SDKEventType || (SDKEventType = {}));
206
+ const DEFAULT_WIDGET_SETTINGS = {
207
+ pollingInterval: 30000,
208
+ showReadMessages: true,
209
+ autoExpandOnNew: true,
210
+ displayMode: 'widget',
211
+ apiEndpoint: 'https://jtm.journy.io',
212
+ styles: 'default',
213
+ };
214
+
215
+ const STORAGE_PREFIX = 'journy_messages_';
216
+ function getStorageKey(key) {
217
+ return `${STORAGE_PREFIX}${key}`;
218
+ }
219
+ function setItem(key, value) {
220
+ try {
221
+ const storageKey = getStorageKey(key);
222
+ localStorage.setItem(storageKey, JSON.stringify(value));
223
+ }
224
+ catch (error) {
225
+ console.warn('Failed to set item in localStorage:', error);
226
+ }
227
+ }
228
+ function getItem(key) {
229
+ try {
230
+ const storageKey = getStorageKey(key);
231
+ const item = localStorage.getItem(storageKey);
232
+ return item ? JSON.parse(item) : null;
233
+ }
234
+ catch (error) {
235
+ console.warn('Failed to get item from localStorage:', error);
236
+ return null;
237
+ }
238
+ }
239
+ function removeItem(key) {
240
+ try {
241
+ const storageKey = getStorageKey(key);
242
+ localStorage.removeItem(storageKey);
243
+ }
244
+ catch (error) {
245
+ console.warn('Failed to remove item from localStorage:', error);
246
+ }
247
+ }
248
+
249
+ class EventTracker {
250
+ constructor(analyticsClient) {
251
+ this.analyticsClient = analyticsClient;
252
+ this.eventQueue = [];
253
+ this.flushInterval = null;
254
+ this.loadQueuedEvents();
255
+ this.startFlushInterval();
256
+ }
257
+ track(event, properties) {
258
+ const eventData = {
259
+ event,
260
+ properties,
261
+ timestamp: new Date().toISOString(),
262
+ };
263
+ this.eventQueue.push(eventData);
264
+ this.saveQueuedEvents();
265
+ if (this.isImportantEvent(event)) {
266
+ this.flush().catch((error) => {
267
+ console.error('Failed to flush events:', error);
268
+ });
269
+ }
270
+ }
271
+ async flush() {
272
+ if (this.eventQueue.length === 0) {
273
+ return;
274
+ }
275
+ const eventsToSend = [...this.eventQueue];
276
+ try {
277
+ const success = await this.analyticsClient.trackEvents(eventsToSend.map(({ event, properties }) => ({
278
+ event,
279
+ properties: properties || {},
280
+ })));
281
+ if (success) {
282
+ // Remove successfully sent events from queue
283
+ this.eventQueue = this.eventQueue.filter(e => !eventsToSend.includes(e));
284
+ }
285
+ }
286
+ catch (error) {
287
+ console.error('Failed to flush events:', error);
288
+ }
289
+ this.saveQueuedEvents();
290
+ }
291
+ startFlushInterval() {
292
+ this.flushInterval = window.setInterval(() => {
293
+ this.flush().catch((error) => {
294
+ console.error('Failed to flush events:', error);
295
+ });
296
+ }, EventTracker.FLUSH_INTERVAL_MS);
297
+ }
298
+ destroy() {
299
+ if (this.flushInterval !== null) {
300
+ clearInterval(this.flushInterval);
301
+ this.flushInterval = null;
302
+ }
303
+ // Flush remaining events before destroying
304
+ this.flush().catch((error) => {
305
+ console.error('Failed to flush events on destroy:', error);
306
+ });
307
+ }
308
+ isImportantEvent(event) {
309
+ return EventTracker.IMPORTANT_MESSAGES.includes(event);
310
+ }
311
+ saveQueuedEvents() {
312
+ setItem('event_queue', this.eventQueue);
313
+ }
314
+ loadQueuedEvents() {
315
+ const queued = getItem('event_queue');
316
+ if (queued && Array.isArray(queued)) {
317
+ this.eventQueue = queued;
318
+ }
319
+ }
320
+ }
321
+ EventTracker.FLUSH_INTERVAL_MS = 5000;
322
+ EventTracker.IMPORTANT_MESSAGES = [
323
+ SDKEventType.MessageOpened,
324
+ SDKEventType.MessageClosed,
325
+ SDKEventType.MessageLinkClicked,
326
+ ];
327
+
328
+ class MessagingStore {
329
+ constructor(initialState) {
330
+ this.listeners = new Set();
331
+ this.state = initialState;
332
+ }
333
+ getState() {
334
+ return this.state;
335
+ }
336
+ setState(partial) {
337
+ this.state = { ...this.state, ...partial };
338
+ this.listeners.forEach(l => l());
339
+ }
340
+ subscribe(listener) {
341
+ this.listeners.add(listener);
342
+ return () => {
343
+ this.listeners.delete(listener);
344
+ };
345
+ }
346
+ destroy() {
347
+ this.listeners.clear();
348
+ }
349
+ }
350
+
351
+ function createRootElement(id) {
352
+ let element = document.getElementById(id);
353
+ if (!element) {
354
+ element = document.createElement('div');
355
+ element.id = id;
356
+ document.body.appendChild(element);
357
+ }
358
+ return element;
359
+ }
360
+ function removeRootElement(id) {
361
+ const element = document.getElementById(id);
362
+ if (element) {
363
+ element.remove();
364
+ }
365
+ }
366
+ const STYLES_LINK_ID = 'journy-messages-styles-link';
367
+ const STYLES_TAG_ID = 'journy-messages-custom';
368
+ const DEFAULT_STYLES_TAG_ID = 'journy-messages-default';
369
+ function injectStyleLink(href) {
370
+ if (typeof document === 'undefined' || !document.head)
371
+ return;
372
+ const existing = document.getElementById(STYLES_LINK_ID);
373
+ if (existing && existing instanceof HTMLLinkElement && existing.href === href)
374
+ return;
375
+ if (existing)
376
+ existing.remove();
377
+ const link = document.createElement('link');
378
+ link.id = STYLES_LINK_ID;
379
+ link.rel = 'stylesheet';
380
+ link.href = href;
381
+ document.head.appendChild(link);
382
+ }
383
+ function injectStyleTag(css, id = STYLES_TAG_ID) {
384
+ if (typeof document === 'undefined' || !document.head)
385
+ return;
386
+ let style = document.getElementById(id);
387
+ if (style) {
388
+ style.textContent = css;
389
+ return;
390
+ }
391
+ style = document.createElement('style');
392
+ style.id = id;
393
+ style.textContent = css;
394
+ document.head.appendChild(style);
395
+ }
396
+ function removeInjectedStyles() {
397
+ if (typeof document === 'undefined')
398
+ return;
399
+ const link = document.getElementById(STYLES_LINK_ID);
400
+ if (link)
401
+ link.remove();
402
+ const style = document.getElementById(STYLES_TAG_ID);
403
+ if (style)
404
+ style.remove();
405
+ const defaultStyle = document.getElementById(DEFAULT_STYLES_TAG_ID);
406
+ if (defaultStyle)
407
+ defaultStyle.remove();
408
+ }
409
+
410
+ var defaultStyles = "/* Widget Container */\n.journy-message-widget {\n position: fixed;\n z-index: 10000;\n background: white;\n border-radius: 12px;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);\n overflow: hidden;\n user-select: none;\n transform-origin: bottom right;\n}\n\n.journy-message-widget.journy-message-widget-dragging {\n cursor: grabbing;\n transition: none;\n z-index: 10001;\n}\n\n.journy-message-widget.journy-message-widget-expanded {\n display: flex;\n flex-direction: column;\n min-height: 0;\n}\n\n.journy-message-widget.journy-message-widget-resizing {\n transition: none;\n}\n\n/* Expand/collapse: height and top are animated via inline transition so bottom-right stays fixed */\n\n/* Widget Header */\n.journy-message-widget-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 16px;\n background: #f9fafb;\n border-bottom: 1px solid #e5e7eb;\n user-select: none;\n}\n\n.journy-message-widget-drag-handle {\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 4px 8px;\n margin-right: 8px;\n cursor: grab;\n color: #9ca3af;\n transition: color 0.2s;\n flex-shrink: 0;\n}\n\n.journy-message-widget-drag-handle:active {\n cursor: grabbing;\n color: #6b7280;\n}\n\n.journy-message-widget-drag-handle:hover {\n color: #6b7280;\n}\n\n.journy-message-widget-drag-handle svg {\n display: block;\n}\n\n.journy-message-widget-header-content {\n display: flex;\n align-items: center;\n gap: 10px;\n flex: 1;\n flex-wrap: wrap;\n cursor: pointer;\n}\n\n.journy-message-widget-badge {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 24px;\n height: 24px;\n padding: 0 8px;\n background: #3b82f6;\n color: white;\n border-radius: 12px;\n font-size: 12px;\n font-weight: 600;\n}\n\n.journy-message-widget-title {\n font-size: 14px;\n font-weight: 600;\n color: #111827;\n}\n\n.journy-message-widget-read-count {\n font-size: 12px;\n color: #6b7280;\n font-weight: 400;\n}\n\n.journy-message-widget-controls {\n display: flex;\n align-items: center;\n gap: 8px;\n}\n\n.journy-message-widget-toggle,\n.journy-message-widget-close {\n background: none;\n border: none;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n}\n\n.journy-message-widget-toggle:hover,\n.journy-message-widget-close:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n/* Widget Content */\n.journy-message-widget-content {\n padding: 16px;\n flex: 1;\n overflow-y: auto;\n overflow-x: hidden;\n min-height: 0;\n display: flex;\n flex-direction: column;\n}\n\n.journy-message-widget-content--single .journy-message-widget-message {\n flex: 1;\n min-height: 0;\n display: flex;\n flex-direction: column;\n}\n\n.journy-message-widget-content--single .journy-message-widget-message .journy-message-content {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n}\n\n/* Resize Handle */\n.journy-message-widget-resize-handle {\n position: absolute;\n bottom: 0;\n right: 0;\n width: 20px;\n height: 20px;\n cursor: nwse-resize;\n display: flex;\n align-items: center;\n justify-content: center;\n background: linear-gradient(135deg, transparent 0%, transparent 40%, #e5e7eb 40%, #e5e7eb 100%);\n z-index: 10;\n transition: background 0.2s;\n}\n\n.journy-message-widget-resize-handle:hover {\n background: linear-gradient(135deg, transparent 0%, transparent 40%, #d1d5db 40%, #d1d5db 100%);\n}\n\n.journy-message-widget-resize-handle svg {\n width: 12px;\n height: 12px;\n opacity: 0.6;\n}\n\n.journy-message-widget-resize-handle:hover svg {\n opacity: 1;\n}\n\n.journy-message-widget-message {\n padding: 0;\n position: relative;\n min-height: 60px;\n}\n\n.journy-message-widget-message-close {\n position: absolute;\n top: 4px;\n right: 4px;\n width: 24px;\n height: 24px;\n padding: 0;\n border: none;\n background: transparent;\n color: #6b7280;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background-color 0.2s, color 0.2s;\n z-index: 1;\n}\n\n.journy-message-widget-message-close:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-message-widget-message:has(.journy-message-widget-message-close) .journy-message-content {\n padding-right: 28px;\n}\n\n.journy-message-widget-nav {\n background: none;\n border: none;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 6px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n}\n\n.journy-message-widget-nav:hover:not(:disabled) {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-message-widget-nav:disabled {\n opacity: 0.4;\n cursor: default;\n}\n\n.journy-message-widget-message-separated {\n margin-bottom: 24px;\n padding-bottom: 24px;\n border-bottom: 1px solid #e5e7eb;\n}\n\n.journy-message-widget-message-count {\n font-size: 12px;\n color: #6b7280;\n font-weight: 400;\n margin-left: 8px;\n}\n\n.journy-message-widget-position {\n padding: 4px 12px;\n font-size: 11px;\n color: #9ca3af;\n font-weight: 500;\n text-align: right;\n flex-shrink: 0;\n}\n\n.journy-message-widget-message.journy-message-info {\n border-left: 4px solid #3b82f6;\n padding-left: 12px;\n}\n\n.journy-message-widget-message.journy-message-success {\n border-left: 4px solid #10b981;\n padding-left: 12px;\n}\n\n.journy-message-widget-message.journy-message-warning {\n border-left: 4px solid #f59e0b;\n padding-left: 12px;\n}\n\n.journy-message-widget-message.journy-message-error {\n border-left: 4px solid #ef4444;\n padding-left: 12px;\n}\n\n.journy-message-widget-message.journy-message-viewed {\n border-left: 4px solid #6b7280;\n padding-left: 12px;\n}\n\n/* Message modal (80vw x 60vh) */\n.journy-message-modal-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10002;\n padding: 20px;\n}\n\n.journy-message-modal {\n width: 80vw;\n max-width: 80vw;\n height: 60vh;\n max-height: 60vh;\n background: white;\n border-radius: 12px;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n position: relative;\n}\n\n.journy-message-modal-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px 24px;\n background: #f9fafb;\n border-bottom: 1px solid #e5e7eb;\n flex-shrink: 0;\n}\n\n.journy-message-modal-title {\n font-size: 18px;\n font-weight: 600;\n color: #111827;\n}\n\n.journy-message-modal-close {\n background: none;\n border: none;\n font-size: 24px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n}\n\n.journy-message-modal-close:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-message-modal .journy-message-widget-message {\n padding: 24px 24px 24px 24px;\n overflow-y: auto;\n flex: 1;\n min-height: 0;\n}\n\n/* Timestamp */\n.journy-message-timestamp {\n font-size: 12px;\n color: #6b7280;\n margin-top: 4px;\n line-height: 1.4;\n}\n\n.journy-message-content-clickable {\n cursor: pointer;\n}\n\n.journy-message-content-clickable:hover {\n opacity: 0.95;\n}\n\n/* Legacy Modal Overlay Styles (kept for backward compatibility) */\n.journy-message-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n opacity: 0;\n transition: opacity 0.3s ease-in-out;\n pointer-events: none;\n}\n\n.journy-message-overlay.journy-message-visible {\n opacity: 1;\n pointer-events: all;\n}\n\n.journy-message-popup {\n background: white;\n border-radius: 8px;\n padding: 24px;\n max-width: 500px;\n width: 90%;\n max-height: 80vh;\n overflow-y: auto;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);\n position: relative;\n transform: scale(0.9);\n transition: transform 0.3s ease-in-out;\n}\n\n.journy-message-overlay.journy-message-visible .journy-message-popup {\n transform: scale(1);\n}\n\n.journy-message-popup.journy-message-info {\n border-top: 4px solid #3b82f6;\n}\n\n.journy-message-popup.journy-message-success {\n border-top: 4px solid #10b981;\n}\n\n.journy-message-popup.journy-message-warning {\n border-top: 4px solid #f59e0b;\n}\n\n.journy-message-popup.journy-message-error {\n border-top: 4px solid #ef4444;\n}\n\n.journy-message-popup.journy-message-viewed {\n border-top: 4px solid #6b7280;\n}\n\n.journy-message-close {\n position: absolute;\n top: 12px;\n right: 12px;\n background: none;\n border: none;\n font-size: 24px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n}\n\n.journy-message-close:hover {\n background-color: #f3f4f6;\n color: #374151;\n}\n\n.journy-message-title {\n font-size: 20px;\n font-weight: 600;\n margin-bottom: 12px;\n color: #111827;\n}\n\n.journy-message-content {\n font-size: 16px;\n line-height: 1.6;\n color: #374151;\n margin-bottom: 16px;\n}\n\n.journy-message-content a {\n color: #3b82f6;\n text-decoration: underline;\n transition: color 0.2s;\n}\n\n.journy-message-content a:hover {\n color: #2563eb;\n}\n\n.journy-message-content p {\n margin: 0 0 12px 0;\n}\n\n.journy-message-content p:last-child {\n margin-bottom: 0;\n}\n\n.journy-message-content ul,\n.journy-message-content ol {\n margin: 12px 0;\n padding-left: 24px;\n}\n\n.journy-message-content li {\n margin-bottom: 8px;\n}\n\n/* Headings */\n.journy-message-content h1,\n.journy-message-content h2,\n.journy-message-content h3,\n.journy-message-content h4,\n.journy-message-content h5,\n.journy-message-content h6 {\n margin: 16px 0 12px 0;\n font-weight: 600;\n line-height: 1.3;\n color: #111827;\n}\n\n.journy-message-content h1 {\n font-size: 24px;\n}\n\n.journy-message-content h2 {\n font-size: 20px;\n}\n\n.journy-message-content h3 {\n font-size: 18px;\n}\n\n.journy-message-content h4 {\n font-size: 16px;\n}\n\n.journy-message-content h5,\n.journy-message-content h6 {\n font-size: 14px;\n}\n\n/* Code blocks */\n.journy-message-content code {\n background-color: #f3f4f6;\n color: #ef4444;\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 0.9em;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\n}\n\n.journy-message-content pre {\n background-color: #1f2937;\n color: #f9fafb;\n padding: 16px;\n border-radius: 8px;\n overflow-x: auto;\n margin: 12px 0;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\n font-size: 14px;\n line-height: 1.5;\n}\n\n.journy-message-content pre code {\n background-color: transparent;\n color: inherit;\n padding: 0;\n border-radius: 0;\n font-size: inherit;\n}\n\n/* Text formatting */\n.journy-message-content u {\n text-decoration: underline;\n}\n\n.journy-message-content s,\n.journy-message-content strike,\n.journy-message-content del {\n text-decoration: line-through;\n}\n\n.journy-message-content strong {\n font-weight: 600;\n}\n\n.journy-message-content em {\n font-style: italic;\n}\n\n/* Blockquotes */\n.journy-message-content blockquote {\n border-left: 4px solid #e5e7eb;\n padding-left: 16px;\n margin: 12px 0;\n color: #6b7280;\n font-style: italic;\n}\n\n/* Tables */\n.journy-message-content table {\n width: 100%;\n border-collapse: collapse;\n margin: 12px 0;\n}\n\n.journy-message-content th,\n.journy-message-content td {\n border: 1px solid #e5e7eb;\n padding: 8px 12px;\n text-align: left;\n}\n\n.journy-message-content th {\n background-color: #f9fafb;\n font-weight: 600;\n}\n\n/* Horizontal rule */\n.journy-message-content hr {\n border: none;\n border-top: 1px solid #e5e7eb;\n margin: 16px 0;\n}\n\n.journy-message-actions {\n display: flex;\n gap: 12px;\n margin-top: 20px;\n flex-wrap: wrap;\n}\n\n.journy-message-action {\n padding: 10px 20px;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n border: none;\n transition: all 0.2s;\n}\n\n.journy-message-action-primary {\n background-color: #3b82f6;\n color: white;\n}\n\n.journy-message-action-primary:hover {\n background-color: #2563eb;\n}\n\n.journy-message-action-secondary {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-message-action-secondary:hover {\n background-color: #d1d5db;\n}\n\n.journy-message-action-link {\n background: none;\n color: #3b82f6;\n text-decoration: underline;\n padding: 10px 0;\n}\n\n.journy-message-action-link:hover {\n color: #2563eb;\n}\n\n/* Settings Panel */\n.journy-settings-panel {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n background: white;\n z-index: 10;\n display: flex;\n flex-direction: column;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n}\n\n.journy-settings-panel-open {\n transform: translateX(0);\n}\n\n.journy-settings-panel-closed {\n transform: translateX(100%);\n}\n\n.journy-settings-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 16px;\n background: #f9fafb;\n border-bottom: 1px solid #e5e7eb;\n flex-shrink: 0;\n}\n\n.journy-settings-title {\n font-size: 14px;\n font-weight: 600;\n color: #111827;\n}\n\n.journy-settings-close {\n background: none;\n border: none;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n}\n\n.journy-settings-close:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-settings-body {\n padding: 16px;\n overflow-y: auto;\n flex: 1;\n}\n\n.journy-settings-item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 0;\n border-bottom: 1px solid #f3f4f6;\n}\n\n.journy-settings-item:last-child {\n border-bottom: none;\n}\n\n.journy-settings-label {\n font-size: 13px;\n font-weight: 500;\n color: #374151;\n}\n\n.journy-settings-select {\n padding: 6px 10px;\n border: 1px solid #d1d5db;\n border-radius: 6px;\n font-size: 13px;\n color: #374151;\n background: white;\n cursor: pointer;\n outline: none;\n transition: border-color 0.2s;\n}\n\n.journy-settings-select:focus {\n border-color: #3b82f6;\n}\n\n.journy-settings-toggle {\n position: relative;\n width: 40px;\n height: 22px;\n border-radius: 11px;\n border: none;\n background: #d1d5db;\n cursor: pointer;\n padding: 0;\n transition: background-color 0.2s;\n flex-shrink: 0;\n}\n\n.journy-settings-toggle-on {\n background: #3b82f6;\n}\n\n.journy-settings-toggle-knob {\n position: absolute;\n top: 2px;\n left: 2px;\n width: 18px;\n height: 18px;\n border-radius: 50%;\n background: white;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);\n transition: transform 0.2s;\n}\n\n.journy-settings-toggle-on .journy-settings-toggle-knob {\n transform: translateX(18px);\n}\n\n.journy-settings-item-vertical {\n flex-direction: column;\n align-items: flex-start;\n gap: 6px;\n}\n\n.journy-settings-input {\n width: 100%;\n padding: 6px 10px;\n border: 1px solid #d1d5db;\n border-radius: 6px;\n font-size: 13px;\n color: #374151;\n background: white;\n outline: none;\n transition: border-color 0.2s;\n box-sizing: border-box;\n}\n\n.journy-settings-input:focus {\n border-color: #3b82f6;\n}\n\n.journy-settings-input::placeholder {\n color: #9ca3af;\n}\n\n.journy-settings-value {\n font-size: 13px;\n color: #6b7280;\n font-weight: 400;\n max-width: 60%;\n text-align: right;\n word-break: break-all;\n}\n\n.journy-message-widget-empty {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #9ca3af;\n font-size: 14px;\n flex: 1;\n min-height: 80px;\n}\n\n.journy-settings-advanced-btn {\n background: none;\n border: none;\n font-size: 13px;\n font-weight: 500;\n color: #6b7280;\n cursor: pointer;\n padding: 0;\n transition: color 0.2s;\n}\n\n.journy-settings-advanced-btn:hover {\n color: #374151;\n}\n\n.journy-message-widget-settings-btn {\n background: none;\n border: none;\n font-size: 16px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n}\n\n.journy-message-widget-settings-btn:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n/* Responsive design */\n@media (max-width: 640px) {\n .journy-message-widget {\n min-width: calc(100vw - 32px);\n max-width: calc(100vw - 32px);\n left: 16px !important;\n right: 16px !important;\n }\n\n .journy-message-popup {\n width: 95%;\n padding: 20px;\n }\n\n .journy-message-title {\n font-size: 18px;\n }\n\n .journy-message-content {\n font-size: 14px;\n }\n\n .journy-message-actions {\n flex-direction: column;\n }\n\n .journy-message-action {\n width: 100%;\n }\n}\n";
411
+
412
+ function useMessagingStore(store) {
413
+ const [state, setState] = React.useState(() => store.getState());
414
+ React.useEffect(() => {
415
+ // Sync in case state changed between render and effect
416
+ setState(store.getState());
417
+ return store.subscribe(() => setState(store.getState()));
418
+ }, [store]);
419
+ return state;
420
+ }
421
+
422
+ /*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */
423
+
424
+ const {
425
+ entries,
426
+ setPrototypeOf,
427
+ isFrozen,
428
+ getPrototypeOf,
429
+ getOwnPropertyDescriptor
430
+ } = Object;
431
+ let {
432
+ freeze,
433
+ seal,
434
+ create
435
+ } = Object; // eslint-disable-line import/no-mutable-exports
436
+ let {
437
+ apply,
438
+ construct
439
+ } = typeof Reflect !== 'undefined' && Reflect;
440
+ if (!freeze) {
441
+ freeze = function freeze(x) {
442
+ return x;
443
+ };
444
+ }
445
+ if (!seal) {
446
+ seal = function seal(x) {
447
+ return x;
448
+ };
449
+ }
450
+ if (!apply) {
451
+ apply = function apply(func, thisArg) {
452
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
453
+ args[_key - 2] = arguments[_key];
454
+ }
455
+ return func.apply(thisArg, args);
456
+ };
457
+ }
458
+ if (!construct) {
459
+ construct = function construct(Func) {
460
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
461
+ args[_key2 - 1] = arguments[_key2];
462
+ }
463
+ return new Func(...args);
464
+ };
465
+ }
466
+ const arrayForEach = unapply(Array.prototype.forEach);
467
+ const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
468
+ const arrayPop = unapply(Array.prototype.pop);
469
+ const arrayPush = unapply(Array.prototype.push);
470
+ const arraySplice = unapply(Array.prototype.splice);
471
+ const stringToLowerCase = unapply(String.prototype.toLowerCase);
472
+ const stringToString = unapply(String.prototype.toString);
473
+ const stringMatch = unapply(String.prototype.match);
474
+ const stringReplace = unapply(String.prototype.replace);
475
+ const stringIndexOf = unapply(String.prototype.indexOf);
476
+ const stringTrim = unapply(String.prototype.trim);
477
+ const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
478
+ const regExpTest = unapply(RegExp.prototype.test);
479
+ const typeErrorCreate = unconstruct(TypeError);
480
+ /**
481
+ * Creates a new function that calls the given function with a specified thisArg and arguments.
482
+ *
483
+ * @param func - The function to be wrapped and called.
484
+ * @returns A new function that calls the given function with a specified thisArg and arguments.
485
+ */
486
+ function unapply(func) {
487
+ return function (thisArg) {
488
+ if (thisArg instanceof RegExp) {
489
+ thisArg.lastIndex = 0;
490
+ }
491
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
492
+ args[_key3 - 1] = arguments[_key3];
493
+ }
494
+ return apply(func, thisArg, args);
495
+ };
496
+ }
497
+ /**
498
+ * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
499
+ *
500
+ * @param func - The constructor function to be wrapped and called.
501
+ * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
502
+ */
503
+ function unconstruct(Func) {
504
+ return function () {
505
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
506
+ args[_key4] = arguments[_key4];
507
+ }
508
+ return construct(Func, args);
509
+ };
510
+ }
511
+ /**
512
+ * Add properties to a lookup table
513
+ *
514
+ * @param set - The set to which elements will be added.
515
+ * @param array - The array containing elements to be added to the set.
516
+ * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
517
+ * @returns The modified set with added elements.
518
+ */
519
+ function addToSet(set, array) {
520
+ let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
521
+ if (setPrototypeOf) {
522
+ // Make 'in' and truthy checks like Boolean(set.constructor)
523
+ // independent of any properties defined on Object.prototype.
524
+ // Prevent prototype setters from intercepting set as a this value.
525
+ setPrototypeOf(set, null);
526
+ }
527
+ let l = array.length;
528
+ while (l--) {
529
+ let element = array[l];
530
+ if (typeof element === 'string') {
531
+ const lcElement = transformCaseFunc(element);
532
+ if (lcElement !== element) {
533
+ // Config presets (e.g. tags.js, attrs.js) are immutable.
534
+ if (!isFrozen(array)) {
535
+ array[l] = lcElement;
536
+ }
537
+ element = lcElement;
538
+ }
539
+ }
540
+ set[element] = true;
541
+ }
542
+ return set;
543
+ }
544
+ /**
545
+ * Clean up an array to harden against CSPP
546
+ *
547
+ * @param array - The array to be cleaned.
548
+ * @returns The cleaned version of the array
549
+ */
550
+ function cleanArray(array) {
551
+ for (let index = 0; index < array.length; index++) {
552
+ const isPropertyExist = objectHasOwnProperty(array, index);
553
+ if (!isPropertyExist) {
554
+ array[index] = null;
555
+ }
556
+ }
557
+ return array;
558
+ }
559
+ /**
560
+ * Shallow clone an object
561
+ *
562
+ * @param object - The object to be cloned.
563
+ * @returns A new object that copies the original.
564
+ */
565
+ function clone(object) {
566
+ const newObject = create(null);
567
+ for (const [property, value] of entries(object)) {
568
+ const isPropertyExist = objectHasOwnProperty(object, property);
569
+ if (isPropertyExist) {
570
+ if (Array.isArray(value)) {
571
+ newObject[property] = cleanArray(value);
572
+ } else if (value && typeof value === 'object' && value.constructor === Object) {
573
+ newObject[property] = clone(value);
574
+ } else {
575
+ newObject[property] = value;
576
+ }
577
+ }
578
+ }
579
+ return newObject;
580
+ }
581
+ /**
582
+ * This method automatically checks if the prop is function or getter and behaves accordingly.
583
+ *
584
+ * @param object - The object to look up the getter function in its prototype chain.
585
+ * @param prop - The property name for which to find the getter function.
586
+ * @returns The getter function found in the prototype chain or a fallback function.
587
+ */
588
+ function lookupGetter(object, prop) {
589
+ while (object !== null) {
590
+ const desc = getOwnPropertyDescriptor(object, prop);
591
+ if (desc) {
592
+ if (desc.get) {
593
+ return unapply(desc.get);
594
+ }
595
+ if (typeof desc.value === 'function') {
596
+ return unapply(desc.value);
597
+ }
598
+ }
599
+ object = getPrototypeOf(object);
600
+ }
601
+ function fallbackValue() {
602
+ return null;
603
+ }
604
+ return fallbackValue;
605
+ }
606
+
607
+ const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
608
+ const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
609
+ const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
610
+ // List of SVG elements that are disallowed by default.
611
+ // We still need to know them so that we can do namespace
612
+ // checks properly in case one wants to add them to
613
+ // allow-list.
614
+ const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
615
+ const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
616
+ // Similarly to SVG, we want to know all MathML elements,
617
+ // even those that we disallow by default.
618
+ const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
619
+ const text = freeze(['#text']);
620
+
621
+ const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);
622
+ const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
623
+ const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
624
+ const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
625
+
626
+ // eslint-disable-next-line unicorn/better-regex
627
+ const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
628
+ const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
629
+ const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
630
+ const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
631
+ const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
632
+ const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
633
+ );
634
+ const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
635
+ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
636
+ );
637
+ const DOCTYPE_NAME = seal(/^html$/i);
638
+ const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
639
+
640
+ var EXPRESSIONS = /*#__PURE__*/Object.freeze({
641
+ __proto__: null,
642
+ ARIA_ATTR: ARIA_ATTR,
643
+ ATTR_WHITESPACE: ATTR_WHITESPACE,
644
+ CUSTOM_ELEMENT: CUSTOM_ELEMENT,
645
+ DATA_ATTR: DATA_ATTR,
646
+ DOCTYPE_NAME: DOCTYPE_NAME,
647
+ ERB_EXPR: ERB_EXPR,
648
+ IS_ALLOWED_URI: IS_ALLOWED_URI,
649
+ IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
650
+ MUSTACHE_EXPR: MUSTACHE_EXPR,
651
+ TMPLIT_EXPR: TMPLIT_EXPR
652
+ });
653
+
654
+ /* eslint-disable @typescript-eslint/indent */
655
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
656
+ const NODE_TYPE = {
657
+ element: 1,
658
+ text: 3,
659
+ // Deprecated
660
+ progressingInstruction: 7,
661
+ comment: 8,
662
+ document: 9};
663
+ const getGlobal = function getGlobal() {
664
+ return typeof window === 'undefined' ? null : window;
665
+ };
666
+ /**
667
+ * Creates a no-op policy for internal use only.
668
+ * Don't export this function outside this module!
669
+ * @param trustedTypes The policy factory.
670
+ * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
671
+ * @return The policy created (or null, if Trusted Types
672
+ * are not supported or creating the policy failed).
673
+ */
674
+ const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
675
+ if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
676
+ return null;
677
+ }
678
+ // Allow the callers to control the unique policy name
679
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
680
+ // Policy creation with duplicate names throws in Trusted Types.
681
+ let suffix = null;
682
+ const ATTR_NAME = 'data-tt-policy-suffix';
683
+ if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
684
+ suffix = purifyHostElement.getAttribute(ATTR_NAME);
685
+ }
686
+ const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
687
+ try {
688
+ return trustedTypes.createPolicy(policyName, {
689
+ createHTML(html) {
690
+ return html;
691
+ },
692
+ createScriptURL(scriptUrl) {
693
+ return scriptUrl;
694
+ }
695
+ });
696
+ } catch (_) {
697
+ // Policy creation failed (most likely another DOMPurify script has
698
+ // already run). Skip creating the policy, as this will only cause errors
699
+ // if TT are enforced.
700
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
701
+ return null;
702
+ }
703
+ };
704
+ const _createHooksMap = function _createHooksMap() {
705
+ return {
706
+ afterSanitizeAttributes: [],
707
+ afterSanitizeElements: [],
708
+ afterSanitizeShadowDOM: [],
709
+ beforeSanitizeAttributes: [],
710
+ beforeSanitizeElements: [],
711
+ beforeSanitizeShadowDOM: [],
712
+ uponSanitizeAttribute: [],
713
+ uponSanitizeElement: [],
714
+ uponSanitizeShadowNode: []
715
+ };
716
+ };
717
+ function createDOMPurify() {
718
+ let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
719
+ const DOMPurify = root => createDOMPurify(root);
720
+ DOMPurify.version = '3.3.1';
721
+ DOMPurify.removed = [];
722
+ if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
723
+ // Not running in a browser, provide a factory function
724
+ // so that you can pass your own Window
725
+ DOMPurify.isSupported = false;
726
+ return DOMPurify;
727
+ }
728
+ let {
729
+ document
730
+ } = window;
731
+ const originalDocument = document;
732
+ const currentScript = originalDocument.currentScript;
733
+ const {
734
+ DocumentFragment,
735
+ HTMLTemplateElement,
736
+ Node,
737
+ Element,
738
+ NodeFilter,
739
+ NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
740
+ HTMLFormElement,
741
+ DOMParser,
742
+ trustedTypes
743
+ } = window;
744
+ const ElementPrototype = Element.prototype;
745
+ const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
746
+ const remove = lookupGetter(ElementPrototype, 'remove');
747
+ const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
748
+ const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
749
+ const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
750
+ // As per issue #47, the web-components registry is inherited by a
751
+ // new document created via createHTMLDocument. As per the spec
752
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
753
+ // a new empty registry is used when creating a template contents owner
754
+ // document, so we use that as our parent document to ensure nothing
755
+ // is inherited.
756
+ if (typeof HTMLTemplateElement === 'function') {
757
+ const template = document.createElement('template');
758
+ if (template.content && template.content.ownerDocument) {
759
+ document = template.content.ownerDocument;
760
+ }
761
+ }
762
+ let trustedTypesPolicy;
763
+ let emptyHTML = '';
764
+ const {
765
+ implementation,
766
+ createNodeIterator,
767
+ createDocumentFragment,
768
+ getElementsByTagName
769
+ } = document;
770
+ const {
771
+ importNode
772
+ } = originalDocument;
773
+ let hooks = _createHooksMap();
774
+ /**
775
+ * Expose whether this browser supports running the full DOMPurify.
776
+ */
777
+ DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
778
+ const {
779
+ MUSTACHE_EXPR,
780
+ ERB_EXPR,
781
+ TMPLIT_EXPR,
782
+ DATA_ATTR,
783
+ ARIA_ATTR,
784
+ IS_SCRIPT_OR_DATA,
785
+ ATTR_WHITESPACE,
786
+ CUSTOM_ELEMENT
787
+ } = EXPRESSIONS;
788
+ let {
789
+ IS_ALLOWED_URI: IS_ALLOWED_URI$1
790
+ } = EXPRESSIONS;
791
+ /**
792
+ * We consider the elements and attributes below to be safe. Ideally
793
+ * don't add any new ones but feel free to remove unwanted ones.
794
+ */
795
+ /* allowed element names */
796
+ let ALLOWED_TAGS = null;
797
+ const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
798
+ /* Allowed attribute names */
799
+ let ALLOWED_ATTR = null;
800
+ const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
801
+ /*
802
+ * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
803
+ * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
804
+ * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
805
+ * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
806
+ */
807
+ let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
808
+ tagNameCheck: {
809
+ writable: true,
810
+ configurable: false,
811
+ enumerable: true,
812
+ value: null
813
+ },
814
+ attributeNameCheck: {
815
+ writable: true,
816
+ configurable: false,
817
+ enumerable: true,
818
+ value: null
819
+ },
820
+ allowCustomizedBuiltInElements: {
821
+ writable: true,
822
+ configurable: false,
823
+ enumerable: true,
824
+ value: false
825
+ }
826
+ }));
827
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
828
+ let FORBID_TAGS = null;
829
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
830
+ let FORBID_ATTR = null;
831
+ /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
832
+ const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
833
+ tagCheck: {
834
+ writable: true,
835
+ configurable: false,
836
+ enumerable: true,
837
+ value: null
838
+ },
839
+ attributeCheck: {
840
+ writable: true,
841
+ configurable: false,
842
+ enumerable: true,
843
+ value: null
844
+ }
845
+ }));
846
+ /* Decide if ARIA attributes are okay */
847
+ let ALLOW_ARIA_ATTR = true;
848
+ /* Decide if custom data attributes are okay */
849
+ let ALLOW_DATA_ATTR = true;
850
+ /* Decide if unknown protocols are okay */
851
+ let ALLOW_UNKNOWN_PROTOCOLS = false;
852
+ /* Decide if self-closing tags in attributes are allowed.
853
+ * Usually removed due to a mXSS issue in jQuery 3.0 */
854
+ let ALLOW_SELF_CLOSE_IN_ATTR = true;
855
+ /* Output should be safe for common template engines.
856
+ * This means, DOMPurify removes data attributes, mustaches and ERB
857
+ */
858
+ let SAFE_FOR_TEMPLATES = false;
859
+ /* Output should be safe even for XML used within HTML and alike.
860
+ * This means, DOMPurify removes comments when containing risky content.
861
+ */
862
+ let SAFE_FOR_XML = true;
863
+ /* Decide if document with <html>... should be returned */
864
+ let WHOLE_DOCUMENT = false;
865
+ /* Track whether config is already set on this instance of DOMPurify. */
866
+ let SET_CONFIG = false;
867
+ /* Decide if all elements (e.g. style, script) must be children of
868
+ * document.body. By default, browsers might move them to document.head */
869
+ let FORCE_BODY = false;
870
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
871
+ * string (or a TrustedHTML object if Trusted Types are supported).
872
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
873
+ */
874
+ let RETURN_DOM = false;
875
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
876
+ * string (or a TrustedHTML object if Trusted Types are supported) */
877
+ let RETURN_DOM_FRAGMENT = false;
878
+ /* Try to return a Trusted Type object instead of a string, return a string in
879
+ * case Trusted Types are not supported */
880
+ let RETURN_TRUSTED_TYPE = false;
881
+ /* Output should be free from DOM clobbering attacks?
882
+ * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
883
+ */
884
+ let SANITIZE_DOM = true;
885
+ /* Achieve full DOM Clobbering protection by isolating the namespace of named
886
+ * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
887
+ *
888
+ * HTML/DOM spec rules that enable DOM Clobbering:
889
+ * - Named Access on Window (§7.3.3)
890
+ * - DOM Tree Accessors (§3.1.5)
891
+ * - Form Element Parent-Child Relations (§4.10.3)
892
+ * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
893
+ * - HTMLCollection (§4.2.10.2)
894
+ *
895
+ * Namespace isolation is implemented by prefixing `id` and `name` attributes
896
+ * with a constant string, i.e., `user-content-`
897
+ */
898
+ let SANITIZE_NAMED_PROPS = false;
899
+ const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
900
+ /* Keep element content when removing element? */
901
+ let KEEP_CONTENT = true;
902
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
903
+ * of importing it into a new Document and returning a sanitized copy */
904
+ let IN_PLACE = false;
905
+ /* Allow usage of profiles like html, svg and mathMl */
906
+ let USE_PROFILES = {};
907
+ /* Tags to ignore content of when KEEP_CONTENT is true */
908
+ let FORBID_CONTENTS = null;
909
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
910
+ /* Tags that are safe for data: URIs */
911
+ let DATA_URI_TAGS = null;
912
+ const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
913
+ /* Attributes safe for values like "javascript:" */
914
+ let URI_SAFE_ATTRIBUTES = null;
915
+ const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
916
+ const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
917
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
918
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
919
+ /* Document namespace */
920
+ let NAMESPACE = HTML_NAMESPACE;
921
+ let IS_EMPTY_INPUT = false;
922
+ /* Allowed XHTML+XML namespaces */
923
+ let ALLOWED_NAMESPACES = null;
924
+ const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
925
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
926
+ let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
927
+ // Certain elements are allowed in both SVG and HTML
928
+ // namespace. We need to specify them explicitly
929
+ // so that they don't get erroneously deleted from
930
+ // HTML namespace.
931
+ const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
932
+ /* Parsing of strict XHTML documents */
933
+ let PARSER_MEDIA_TYPE = null;
934
+ const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
935
+ const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
936
+ let transformCaseFunc = null;
937
+ /* Keep a reference to config to pass to hooks */
938
+ let CONFIG = null;
939
+ /* Ideally, do not touch anything below this line */
940
+ /* ______________________________________________ */
941
+ const formElement = document.createElement('form');
942
+ const isRegexOrFunction = function isRegexOrFunction(testValue) {
943
+ return testValue instanceof RegExp || testValue instanceof Function;
944
+ };
945
+ /**
946
+ * _parseConfig
947
+ *
948
+ * @param cfg optional config literal
949
+ */
950
+ // eslint-disable-next-line complexity
951
+ const _parseConfig = function _parseConfig() {
952
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
953
+ if (CONFIG && CONFIG === cfg) {
954
+ return;
955
+ }
956
+ /* Shield configuration object from tampering */
957
+ if (!cfg || typeof cfg !== 'object') {
958
+ cfg = {};
959
+ }
960
+ /* Shield configuration object from prototype pollution */
961
+ cfg = clone(cfg);
962
+ PARSER_MEDIA_TYPE =
963
+ // eslint-disable-next-line unicorn/prefer-includes
964
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
965
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
966
+ transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
967
+ /* Set configuration parameters */
968
+ ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
969
+ ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
970
+ ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
971
+ URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
972
+ DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
973
+ FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
974
+ FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
975
+ FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
976
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
977
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
978
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
979
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
980
+ ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
981
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
982
+ SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
983
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
984
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
985
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
986
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
987
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
988
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
989
+ SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
990
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
991
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
992
+ IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
993
+ NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
994
+ MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
995
+ HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
996
+ CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
997
+ if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
998
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
999
+ }
1000
+ if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
1001
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
1002
+ }
1003
+ if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
1004
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
1005
+ }
1006
+ if (SAFE_FOR_TEMPLATES) {
1007
+ ALLOW_DATA_ATTR = false;
1008
+ }
1009
+ if (RETURN_DOM_FRAGMENT) {
1010
+ RETURN_DOM = true;
1011
+ }
1012
+ /* Parse profile info */
1013
+ if (USE_PROFILES) {
1014
+ ALLOWED_TAGS = addToSet({}, text);
1015
+ ALLOWED_ATTR = [];
1016
+ if (USE_PROFILES.html === true) {
1017
+ addToSet(ALLOWED_TAGS, html$1);
1018
+ addToSet(ALLOWED_ATTR, html);
1019
+ }
1020
+ if (USE_PROFILES.svg === true) {
1021
+ addToSet(ALLOWED_TAGS, svg$1);
1022
+ addToSet(ALLOWED_ATTR, svg);
1023
+ addToSet(ALLOWED_ATTR, xml);
1024
+ }
1025
+ if (USE_PROFILES.svgFilters === true) {
1026
+ addToSet(ALLOWED_TAGS, svgFilters);
1027
+ addToSet(ALLOWED_ATTR, svg);
1028
+ addToSet(ALLOWED_ATTR, xml);
1029
+ }
1030
+ if (USE_PROFILES.mathMl === true) {
1031
+ addToSet(ALLOWED_TAGS, mathMl$1);
1032
+ addToSet(ALLOWED_ATTR, mathMl);
1033
+ addToSet(ALLOWED_ATTR, xml);
1034
+ }
1035
+ }
1036
+ /* Merge configuration parameters */
1037
+ if (cfg.ADD_TAGS) {
1038
+ if (typeof cfg.ADD_TAGS === 'function') {
1039
+ EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
1040
+ } else {
1041
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
1042
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
1043
+ }
1044
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
1045
+ }
1046
+ }
1047
+ if (cfg.ADD_ATTR) {
1048
+ if (typeof cfg.ADD_ATTR === 'function') {
1049
+ EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
1050
+ } else {
1051
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
1052
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
1053
+ }
1054
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
1055
+ }
1056
+ }
1057
+ if (cfg.ADD_URI_SAFE_ATTR) {
1058
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
1059
+ }
1060
+ if (cfg.FORBID_CONTENTS) {
1061
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
1062
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
1063
+ }
1064
+ addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
1065
+ }
1066
+ if (cfg.ADD_FORBID_CONTENTS) {
1067
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
1068
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
1069
+ }
1070
+ addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
1071
+ }
1072
+ /* Add #text in case KEEP_CONTENT is set to true */
1073
+ if (KEEP_CONTENT) {
1074
+ ALLOWED_TAGS['#text'] = true;
1075
+ }
1076
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
1077
+ if (WHOLE_DOCUMENT) {
1078
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
1079
+ }
1080
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
1081
+ if (ALLOWED_TAGS.table) {
1082
+ addToSet(ALLOWED_TAGS, ['tbody']);
1083
+ delete FORBID_TAGS.tbody;
1084
+ }
1085
+ if (cfg.TRUSTED_TYPES_POLICY) {
1086
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
1087
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
1088
+ }
1089
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
1090
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
1091
+ }
1092
+ // Overwrite existing TrustedTypes policy.
1093
+ trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
1094
+ // Sign local variables required by `sanitize`.
1095
+ emptyHTML = trustedTypesPolicy.createHTML('');
1096
+ } else {
1097
+ // Uninitialized policy, attempt to initialize the internal dompurify policy.
1098
+ if (trustedTypesPolicy === undefined) {
1099
+ trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
1100
+ }
1101
+ // If creating the internal policy succeeded sign internal variables.
1102
+ if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
1103
+ emptyHTML = trustedTypesPolicy.createHTML('');
1104
+ }
1105
+ }
1106
+ // Prevent further manipulation of configuration.
1107
+ // Not available in IE8, Safari 5, etc.
1108
+ if (freeze) {
1109
+ freeze(cfg);
1110
+ }
1111
+ CONFIG = cfg;
1112
+ };
1113
+ /* Keep track of all possible SVG and MathML tags
1114
+ * so that we can perform the namespace checks
1115
+ * correctly. */
1116
+ const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
1117
+ const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
1118
+ /**
1119
+ * @param element a DOM element whose namespace is being checked
1120
+ * @returns Return false if the element has a
1121
+ * namespace that a spec-compliant parser would never
1122
+ * return. Return true otherwise.
1123
+ */
1124
+ const _checkValidNamespace = function _checkValidNamespace(element) {
1125
+ let parent = getParentNode(element);
1126
+ // In JSDOM, if we're inside shadow DOM, then parentNode
1127
+ // can be null. We just simulate parent in this case.
1128
+ if (!parent || !parent.tagName) {
1129
+ parent = {
1130
+ namespaceURI: NAMESPACE,
1131
+ tagName: 'template'
1132
+ };
1133
+ }
1134
+ const tagName = stringToLowerCase(element.tagName);
1135
+ const parentTagName = stringToLowerCase(parent.tagName);
1136
+ if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
1137
+ return false;
1138
+ }
1139
+ if (element.namespaceURI === SVG_NAMESPACE) {
1140
+ // The only way to switch from HTML namespace to SVG
1141
+ // is via <svg>. If it happens via any other tag, then
1142
+ // it should be killed.
1143
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1144
+ return tagName === 'svg';
1145
+ }
1146
+ // The only way to switch from MathML to SVG is via`
1147
+ // svg if parent is either <annotation-xml> or MathML
1148
+ // text integration points.
1149
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
1150
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
1151
+ }
1152
+ // We only allow elements that are defined in SVG
1153
+ // spec. All others are disallowed in SVG namespace.
1154
+ return Boolean(ALL_SVG_TAGS[tagName]);
1155
+ }
1156
+ if (element.namespaceURI === MATHML_NAMESPACE) {
1157
+ // The only way to switch from HTML namespace to MathML
1158
+ // is via <math>. If it happens via any other tag, then
1159
+ // it should be killed.
1160
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1161
+ return tagName === 'math';
1162
+ }
1163
+ // The only way to switch from SVG to MathML is via
1164
+ // <math> and HTML integration points
1165
+ if (parent.namespaceURI === SVG_NAMESPACE) {
1166
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
1167
+ }
1168
+ // We only allow elements that are defined in MathML
1169
+ // spec. All others are disallowed in MathML namespace.
1170
+ return Boolean(ALL_MATHML_TAGS[tagName]);
1171
+ }
1172
+ if (element.namespaceURI === HTML_NAMESPACE) {
1173
+ // The only way to switch from SVG to HTML is via
1174
+ // HTML integration points, and from MathML to HTML
1175
+ // is via MathML text integration points
1176
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1177
+ return false;
1178
+ }
1179
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1180
+ return false;
1181
+ }
1182
+ // We disallow tags that are specific for MathML
1183
+ // or SVG and should never appear in HTML namespace
1184
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1185
+ }
1186
+ // For XHTML and XML documents that support custom namespaces
1187
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
1188
+ return true;
1189
+ }
1190
+ // The code should never reach this place (this means
1191
+ // that the element somehow got namespace that is not
1192
+ // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
1193
+ // Return false just in case.
1194
+ return false;
1195
+ };
1196
+ /**
1197
+ * _forceRemove
1198
+ *
1199
+ * @param node a DOM node
1200
+ */
1201
+ const _forceRemove = function _forceRemove(node) {
1202
+ arrayPush(DOMPurify.removed, {
1203
+ element: node
1204
+ });
1205
+ try {
1206
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
1207
+ getParentNode(node).removeChild(node);
1208
+ } catch (_) {
1209
+ remove(node);
1210
+ }
1211
+ };
1212
+ /**
1213
+ * _removeAttribute
1214
+ *
1215
+ * @param name an Attribute name
1216
+ * @param element a DOM node
1217
+ */
1218
+ const _removeAttribute = function _removeAttribute(name, element) {
1219
+ try {
1220
+ arrayPush(DOMPurify.removed, {
1221
+ attribute: element.getAttributeNode(name),
1222
+ from: element
1223
+ });
1224
+ } catch (_) {
1225
+ arrayPush(DOMPurify.removed, {
1226
+ attribute: null,
1227
+ from: element
1228
+ });
1229
+ }
1230
+ element.removeAttribute(name);
1231
+ // We void attribute values for unremovable "is" attributes
1232
+ if (name === 'is') {
1233
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
1234
+ try {
1235
+ _forceRemove(element);
1236
+ } catch (_) {}
1237
+ } else {
1238
+ try {
1239
+ element.setAttribute(name, '');
1240
+ } catch (_) {}
1241
+ }
1242
+ }
1243
+ };
1244
+ /**
1245
+ * _initDocument
1246
+ *
1247
+ * @param dirty - a string of dirty markup
1248
+ * @return a DOM, filled with the dirty markup
1249
+ */
1250
+ const _initDocument = function _initDocument(dirty) {
1251
+ /* Create a HTML document */
1252
+ let doc = null;
1253
+ let leadingWhitespace = null;
1254
+ if (FORCE_BODY) {
1255
+ dirty = '<remove></remove>' + dirty;
1256
+ } else {
1257
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
1258
+ const matches = stringMatch(dirty, /^[\r\n\t ]+/);
1259
+ leadingWhitespace = matches && matches[0];
1260
+ }
1261
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
1262
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
1263
+ dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
1264
+ }
1265
+ const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
1266
+ /*
1267
+ * Use the DOMParser API by default, fallback later if needs be
1268
+ * DOMParser not work for svg when has multiple root element.
1269
+ */
1270
+ if (NAMESPACE === HTML_NAMESPACE) {
1271
+ try {
1272
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
1273
+ } catch (_) {}
1274
+ }
1275
+ /* Use createHTMLDocument in case DOMParser is not available */
1276
+ if (!doc || !doc.documentElement) {
1277
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
1278
+ try {
1279
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
1280
+ } catch (_) {
1281
+ // Syntax error if dirtyPayload is invalid xml
1282
+ }
1283
+ }
1284
+ const body = doc.body || doc.documentElement;
1285
+ if (dirty && leadingWhitespace) {
1286
+ body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
1287
+ }
1288
+ /* Work on whole document or just its body */
1289
+ if (NAMESPACE === HTML_NAMESPACE) {
1290
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
1291
+ }
1292
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
1293
+ };
1294
+ /**
1295
+ * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
1296
+ *
1297
+ * @param root The root element or node to start traversing on.
1298
+ * @return The created NodeIterator
1299
+ */
1300
+ const _createNodeIterator = function _createNodeIterator(root) {
1301
+ return createNodeIterator.call(root.ownerDocument || root, root,
1302
+ // eslint-disable-next-line no-bitwise
1303
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
1304
+ };
1305
+ /**
1306
+ * _isClobbered
1307
+ *
1308
+ * @param element element to check for clobbering attacks
1309
+ * @return true if clobbered, false if safe
1310
+ */
1311
+ const _isClobbered = function _isClobbered(element) {
1312
+ return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
1313
+ };
1314
+ /**
1315
+ * Checks whether the given object is a DOM node.
1316
+ *
1317
+ * @param value object to check whether it's a DOM node
1318
+ * @return true is object is a DOM node
1319
+ */
1320
+ const _isNode = function _isNode(value) {
1321
+ return typeof Node === 'function' && value instanceof Node;
1322
+ };
1323
+ function _executeHooks(hooks, currentNode, data) {
1324
+ arrayForEach(hooks, hook => {
1325
+ hook.call(DOMPurify, currentNode, data, CONFIG);
1326
+ });
1327
+ }
1328
+ /**
1329
+ * _sanitizeElements
1330
+ *
1331
+ * @protect nodeName
1332
+ * @protect textContent
1333
+ * @protect removeChild
1334
+ * @param currentNode to check for permission to exist
1335
+ * @return true if node was killed, false if left alive
1336
+ */
1337
+ const _sanitizeElements = function _sanitizeElements(currentNode) {
1338
+ let content = null;
1339
+ /* Execute a hook if present */
1340
+ _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1341
+ /* Check if element is clobbered or can clobber */
1342
+ if (_isClobbered(currentNode)) {
1343
+ _forceRemove(currentNode);
1344
+ return true;
1345
+ }
1346
+ /* Now let's check the element's type and name */
1347
+ const tagName = transformCaseFunc(currentNode.nodeName);
1348
+ /* Execute a hook if present */
1349
+ _executeHooks(hooks.uponSanitizeElement, currentNode, {
1350
+ tagName,
1351
+ allowedTags: ALLOWED_TAGS
1352
+ });
1353
+ /* Detect mXSS attempts abusing namespace confusion */
1354
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1355
+ _forceRemove(currentNode);
1356
+ return true;
1357
+ }
1358
+ /* Remove any occurrence of processing instructions */
1359
+ if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1360
+ _forceRemove(currentNode);
1361
+ return true;
1362
+ }
1363
+ /* Remove any kind of possibly harmful comments */
1364
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1365
+ _forceRemove(currentNode);
1366
+ return true;
1367
+ }
1368
+ /* Remove element if anything forbids its presence */
1369
+ if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) {
1370
+ /* Check if we have a custom element to handle */
1371
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1372
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1373
+ return false;
1374
+ }
1375
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1376
+ return false;
1377
+ }
1378
+ }
1379
+ /* Keep content except for bad-listed elements */
1380
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1381
+ const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1382
+ const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1383
+ if (childNodes && parentNode) {
1384
+ const childCount = childNodes.length;
1385
+ for (let i = childCount - 1; i >= 0; --i) {
1386
+ const childClone = cloneNode(childNodes[i], true);
1387
+ childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
1388
+ parentNode.insertBefore(childClone, getNextSibling(currentNode));
1389
+ }
1390
+ }
1391
+ }
1392
+ _forceRemove(currentNode);
1393
+ return true;
1394
+ }
1395
+ /* Check whether element has a valid namespace */
1396
+ if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1397
+ _forceRemove(currentNode);
1398
+ return true;
1399
+ }
1400
+ /* Make sure that older browsers don't get fallback-tag mXSS */
1401
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1402
+ _forceRemove(currentNode);
1403
+ return true;
1404
+ }
1405
+ /* Sanitize element content to be template-safe */
1406
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1407
+ /* Get the element's text content */
1408
+ content = currentNode.textContent;
1409
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1410
+ content = stringReplace(content, expr, ' ');
1411
+ });
1412
+ if (currentNode.textContent !== content) {
1413
+ arrayPush(DOMPurify.removed, {
1414
+ element: currentNode.cloneNode()
1415
+ });
1416
+ currentNode.textContent = content;
1417
+ }
1418
+ }
1419
+ /* Execute a hook if present */
1420
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1421
+ return false;
1422
+ };
1423
+ /**
1424
+ * _isValidAttribute
1425
+ *
1426
+ * @param lcTag Lowercase tag name of containing element.
1427
+ * @param lcName Lowercase attribute name.
1428
+ * @param value Attribute value.
1429
+ * @return Returns true if `value` is valid, otherwise false.
1430
+ */
1431
+ // eslint-disable-next-line complexity
1432
+ const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1433
+ /* Make sure attribute cannot clobber */
1434
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1435
+ return false;
1436
+ }
1437
+ /* Allow valid data-* attributes: At least one character after "-"
1438
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1439
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1440
+ We don't need to check the value; it's always URI safe. */
1441
+ if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
1442
+ if (
1443
+ // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1444
+ // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1445
+ // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1446
+ _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||
1447
+ // Alternative, second condition checks if it's an `is`-attribute, AND
1448
+ // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1449
+ lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
1450
+ return false;
1451
+ }
1452
+ /* Check value is safe. First, is attr inert? If so, is safe */
1453
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
1454
+ return false;
1455
+ } else ;
1456
+ return true;
1457
+ };
1458
+ /**
1459
+ * _isBasicCustomElement
1460
+ * checks if at least one dash is included in tagName, and it's not the first char
1461
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1462
+ *
1463
+ * @param tagName name of the tag of the node to sanitize
1464
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1465
+ */
1466
+ const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1467
+ return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
1468
+ };
1469
+ /**
1470
+ * _sanitizeAttributes
1471
+ *
1472
+ * @protect attributes
1473
+ * @protect nodeName
1474
+ * @protect removeAttribute
1475
+ * @protect setAttribute
1476
+ *
1477
+ * @param currentNode to sanitize
1478
+ */
1479
+ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1480
+ /* Execute a hook if present */
1481
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1482
+ const {
1483
+ attributes
1484
+ } = currentNode;
1485
+ /* Check if we have attributes; if not we might have a text node */
1486
+ if (!attributes || _isClobbered(currentNode)) {
1487
+ return;
1488
+ }
1489
+ const hookEvent = {
1490
+ attrName: '',
1491
+ attrValue: '',
1492
+ keepAttr: true,
1493
+ allowedAttributes: ALLOWED_ATTR,
1494
+ forceKeepAttr: undefined
1495
+ };
1496
+ let l = attributes.length;
1497
+ /* Go backwards over all attributes; safely remove bad ones */
1498
+ while (l--) {
1499
+ const attr = attributes[l];
1500
+ const {
1501
+ name,
1502
+ namespaceURI,
1503
+ value: attrValue
1504
+ } = attr;
1505
+ const lcName = transformCaseFunc(name);
1506
+ const initValue = attrValue;
1507
+ let value = name === 'value' ? initValue : stringTrim(initValue);
1508
+ /* Execute a hook if present */
1509
+ hookEvent.attrName = lcName;
1510
+ hookEvent.attrValue = value;
1511
+ hookEvent.keepAttr = true;
1512
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1513
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1514
+ value = hookEvent.attrValue;
1515
+ /* Full DOM Clobbering protection via namespace isolation,
1516
+ * Prefix id and name attributes with `user-content-`
1517
+ */
1518
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
1519
+ // Remove the attribute with this value
1520
+ _removeAttribute(name, currentNode);
1521
+ // Prefix the value and later re-create the attribute with the sanitized value
1522
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
1523
+ }
1524
+ /* Work around a security issue with comments inside attributes */
1525
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title|textarea)/i, value)) {
1526
+ _removeAttribute(name, currentNode);
1527
+ continue;
1528
+ }
1529
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1530
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
1531
+ _removeAttribute(name, currentNode);
1532
+ continue;
1533
+ }
1534
+ /* Did the hooks approve of the attribute? */
1535
+ if (hookEvent.forceKeepAttr) {
1536
+ continue;
1537
+ }
1538
+ /* Did the hooks approve of the attribute? */
1539
+ if (!hookEvent.keepAttr) {
1540
+ _removeAttribute(name, currentNode);
1541
+ continue;
1542
+ }
1543
+ /* Work around a security issue in jQuery 3.0 */
1544
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1545
+ _removeAttribute(name, currentNode);
1546
+ continue;
1547
+ }
1548
+ /* Sanitize attribute content to be template-safe */
1549
+ if (SAFE_FOR_TEMPLATES) {
1550
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1551
+ value = stringReplace(value, expr, ' ');
1552
+ });
1553
+ }
1554
+ /* Is `value` valid for this attribute? */
1555
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1556
+ if (!_isValidAttribute(lcTag, lcName, value)) {
1557
+ _removeAttribute(name, currentNode);
1558
+ continue;
1559
+ }
1560
+ /* Handle attributes that require Trusted Types */
1561
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1562
+ if (namespaceURI) ; else {
1563
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1564
+ case 'TrustedHTML':
1565
+ {
1566
+ value = trustedTypesPolicy.createHTML(value);
1567
+ break;
1568
+ }
1569
+ case 'TrustedScriptURL':
1570
+ {
1571
+ value = trustedTypesPolicy.createScriptURL(value);
1572
+ break;
1573
+ }
1574
+ }
1575
+ }
1576
+ }
1577
+ /* Handle invalid data-* attribute set by try-catching it */
1578
+ if (value !== initValue) {
1579
+ try {
1580
+ if (namespaceURI) {
1581
+ currentNode.setAttributeNS(namespaceURI, name, value);
1582
+ } else {
1583
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1584
+ currentNode.setAttribute(name, value);
1585
+ }
1586
+ if (_isClobbered(currentNode)) {
1587
+ _forceRemove(currentNode);
1588
+ } else {
1589
+ arrayPop(DOMPurify.removed);
1590
+ }
1591
+ } catch (_) {
1592
+ _removeAttribute(name, currentNode);
1593
+ }
1594
+ }
1595
+ }
1596
+ /* Execute a hook if present */
1597
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1598
+ };
1599
+ /**
1600
+ * _sanitizeShadowDOM
1601
+ *
1602
+ * @param fragment to iterate over recursively
1603
+ */
1604
+ const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
1605
+ let shadowNode = null;
1606
+ const shadowIterator = _createNodeIterator(fragment);
1607
+ /* Execute a hook if present */
1608
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1609
+ while (shadowNode = shadowIterator.nextNode()) {
1610
+ /* Execute a hook if present */
1611
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1612
+ /* Sanitize tags and elements */
1613
+ _sanitizeElements(shadowNode);
1614
+ /* Check attributes next */
1615
+ _sanitizeAttributes(shadowNode);
1616
+ /* Deep shadow DOM detected */
1617
+ if (shadowNode.content instanceof DocumentFragment) {
1618
+ _sanitizeShadowDOM(shadowNode.content);
1619
+ }
1620
+ }
1621
+ /* Execute a hook if present */
1622
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1623
+ };
1624
+ // eslint-disable-next-line complexity
1625
+ DOMPurify.sanitize = function (dirty) {
1626
+ let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1627
+ let body = null;
1628
+ let importedNode = null;
1629
+ let currentNode = null;
1630
+ let returnNode = null;
1631
+ /* Make sure we have a string to sanitize.
1632
+ DO NOT return early, as this will return the wrong type if
1633
+ the user has requested a DOM object rather than a string */
1634
+ IS_EMPTY_INPUT = !dirty;
1635
+ if (IS_EMPTY_INPUT) {
1636
+ dirty = '<!-->';
1637
+ }
1638
+ /* Stringify, in case dirty is an object */
1639
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
1640
+ if (typeof dirty.toString === 'function') {
1641
+ dirty = dirty.toString();
1642
+ if (typeof dirty !== 'string') {
1643
+ throw typeErrorCreate('dirty is not a string, aborting');
1644
+ }
1645
+ } else {
1646
+ throw typeErrorCreate('toString is not a function');
1647
+ }
1648
+ }
1649
+ /* Return dirty HTML if DOMPurify cannot run */
1650
+ if (!DOMPurify.isSupported) {
1651
+ return dirty;
1652
+ }
1653
+ /* Assign config vars */
1654
+ if (!SET_CONFIG) {
1655
+ _parseConfig(cfg);
1656
+ }
1657
+ /* Clean up removed elements */
1658
+ DOMPurify.removed = [];
1659
+ /* Check if dirty is correctly typed for IN_PLACE */
1660
+ if (typeof dirty === 'string') {
1661
+ IN_PLACE = false;
1662
+ }
1663
+ if (IN_PLACE) {
1664
+ /* Do some early pre-sanitization to avoid unsafe root nodes */
1665
+ if (dirty.nodeName) {
1666
+ const tagName = transformCaseFunc(dirty.nodeName);
1667
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1668
+ throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1669
+ }
1670
+ }
1671
+ } else if (dirty instanceof Node) {
1672
+ /* If dirty is a DOM element, append to an empty document to avoid
1673
+ elements being stripped by the parser */
1674
+ body = _initDocument('<!---->');
1675
+ importedNode = body.ownerDocument.importNode(dirty, true);
1676
+ if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1677
+ /* Node is already a body, use as is */
1678
+ body = importedNode;
1679
+ } else if (importedNode.nodeName === 'HTML') {
1680
+ body = importedNode;
1681
+ } else {
1682
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1683
+ body.appendChild(importedNode);
1684
+ }
1685
+ } else {
1686
+ /* Exit directly if we have nothing to do */
1687
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1688
+ // eslint-disable-next-line unicorn/prefer-includes
1689
+ dirty.indexOf('<') === -1) {
1690
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1691
+ }
1692
+ /* Initialize the document to work on */
1693
+ body = _initDocument(dirty);
1694
+ /* Check we have a DOM node from the data */
1695
+ if (!body) {
1696
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1697
+ }
1698
+ }
1699
+ /* Remove first element node (ours) if FORCE_BODY is set */
1700
+ if (body && FORCE_BODY) {
1701
+ _forceRemove(body.firstChild);
1702
+ }
1703
+ /* Get node iterator */
1704
+ const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1705
+ /* Now start iterating over the created document */
1706
+ while (currentNode = nodeIterator.nextNode()) {
1707
+ /* Sanitize tags and elements */
1708
+ _sanitizeElements(currentNode);
1709
+ /* Check attributes next */
1710
+ _sanitizeAttributes(currentNode);
1711
+ /* Shadow DOM detected, sanitize it */
1712
+ if (currentNode.content instanceof DocumentFragment) {
1713
+ _sanitizeShadowDOM(currentNode.content);
1714
+ }
1715
+ }
1716
+ /* If we sanitized `dirty` in-place, return it. */
1717
+ if (IN_PLACE) {
1718
+ return dirty;
1719
+ }
1720
+ /* Return sanitized string or DOM */
1721
+ if (RETURN_DOM) {
1722
+ if (RETURN_DOM_FRAGMENT) {
1723
+ returnNode = createDocumentFragment.call(body.ownerDocument);
1724
+ while (body.firstChild) {
1725
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1726
+ returnNode.appendChild(body.firstChild);
1727
+ }
1728
+ } else {
1729
+ returnNode = body;
1730
+ }
1731
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1732
+ /*
1733
+ AdoptNode() is not used because internal state is not reset
1734
+ (e.g. the past names map of a HTMLFormElement), this is safe
1735
+ in theory but we would rather not risk another attack vector.
1736
+ The state that is cloned by importNode() is explicitly defined
1737
+ by the specs.
1738
+ */
1739
+ returnNode = importNode.call(originalDocument, returnNode, true);
1740
+ }
1741
+ return returnNode;
1742
+ }
1743
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1744
+ /* Serialize doctype if allowed */
1745
+ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1746
+ serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1747
+ }
1748
+ /* Sanitize final string template-safe */
1749
+ if (SAFE_FOR_TEMPLATES) {
1750
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1751
+ serializedHTML = stringReplace(serializedHTML, expr, ' ');
1752
+ });
1753
+ }
1754
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1755
+ };
1756
+ DOMPurify.setConfig = function () {
1757
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1758
+ _parseConfig(cfg);
1759
+ SET_CONFIG = true;
1760
+ };
1761
+ DOMPurify.clearConfig = function () {
1762
+ CONFIG = null;
1763
+ SET_CONFIG = false;
1764
+ };
1765
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
1766
+ /* Initialize shared config vars if necessary. */
1767
+ if (!CONFIG) {
1768
+ _parseConfig({});
1769
+ }
1770
+ const lcTag = transformCaseFunc(tag);
1771
+ const lcName = transformCaseFunc(attr);
1772
+ return _isValidAttribute(lcTag, lcName, value);
1773
+ };
1774
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
1775
+ if (typeof hookFunction !== 'function') {
1776
+ return;
1777
+ }
1778
+ arrayPush(hooks[entryPoint], hookFunction);
1779
+ };
1780
+ DOMPurify.removeHook = function (entryPoint, hookFunction) {
1781
+ if (hookFunction !== undefined) {
1782
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1783
+ return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1784
+ }
1785
+ return arrayPop(hooks[entryPoint]);
1786
+ };
1787
+ DOMPurify.removeHooks = function (entryPoint) {
1788
+ hooks[entryPoint] = [];
1789
+ };
1790
+ DOMPurify.removeAllHooks = function () {
1791
+ hooks = _createHooksMap();
1792
+ };
1793
+ return DOMPurify;
1794
+ }
1795
+ var purify = createDOMPurify();
1796
+
1797
+ function sanitizeHtml(html) {
1798
+ return purify.sanitize(html, {
1799
+ ALLOWED_TAGS: [
1800
+ // Text formatting
1801
+ 'a', 'b', 'i', 'em', 'strong', 'u', 's', 'strike', 'del',
1802
+ // Paragraphs and breaks
1803
+ 'p', 'br', 'div', 'span',
1804
+ // Headings
1805
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
1806
+ // Lists
1807
+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
1808
+ // Code
1809
+ 'code', 'pre', 'kbd', 'samp',
1810
+ // Blockquotes
1811
+ 'blockquote', 'q',
1812
+ // Tables
1813
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
1814
+ // Other
1815
+ 'hr', 'sub', 'sup', 'small', 'mark', 'abbr', 'cite', 'time'
1816
+ ],
1817
+ ALLOWED_ATTR: ['href', 'target', 'rel', 'title', 'class', 'id', 'style'],
1818
+ ALLOW_DATA_ATTR: false,
1819
+ // Allow style attribute but sanitize it
1820
+ ALLOW_UNKNOWN_PROTOCOLS: false,
1821
+ });
1822
+ }
1823
+
1824
+ /**
1825
+ * Formats an ISO timestamp string to a human-readable format.
1826
+ * Example output: "Mar 11, 2026 at 2:30 PM"
1827
+ */
1828
+ function formatTimestamp(isoString) {
1829
+ const date = new Date(isoString);
1830
+ if (isNaN(date.getTime())) {
1831
+ return '';
1832
+ }
1833
+ const months = [
1834
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
1835
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
1836
+ ];
1837
+ const month = months[date.getMonth()];
1838
+ const day = date.getDate();
1839
+ const year = date.getFullYear();
1840
+ let hours = date.getHours();
1841
+ const minutes = date.getMinutes();
1842
+ const ampm = hours >= 12 ? 'PM' : 'AM';
1843
+ hours = hours % 12 || 12;
1844
+ const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`;
1845
+ return `${month} ${day}, ${year} at ${hours}:${minutesStr} ${ampm}`;
1846
+ }
1847
+
1848
+ const MessagePopup = ({ message, onClose, onLinkClick, }) => {
1849
+ const [isVisible, setIsVisible] = React.useState(false);
1850
+ React.useEffect(() => {
1851
+ // Trigger animation
1852
+ setTimeout(() => setIsVisible(true), 10);
1853
+ }, []);
1854
+ const handleLinkClick = (e) => {
1855
+ e.preventDefault();
1856
+ const url = e.currentTarget.href;
1857
+ onLinkClick(url);
1858
+ };
1859
+ const sanitizedContent = sanitizeHtml(message.message);
1860
+ const messageType = message.received ? 'viewed' : 'info';
1861
+ return (React__namespace.createElement("div", { className: `journy-message-overlay ${isVisible ? 'journy-message-visible' : ''}` },
1862
+ React__namespace.createElement("div", { className: `journy-message-popup journy-message-${messageType}` },
1863
+ React__namespace.createElement("button", { className: "journy-message-close", onClick: onClose, "aria-label": "Close message" }, "\u00D7"),
1864
+ message.createdAt && (React__namespace.createElement("div", { className: "journy-message-timestamp" }, formatTimestamp(message.createdAt))),
1865
+ React__namespace.createElement("div", { className: "journy-message-content", dangerouslySetInnerHTML: { __html: sanitizedContent }, onClick: (e) => {
1866
+ const target = e.target;
1867
+ if (target.tagName === 'A') {
1868
+ handleLinkClick(e);
1869
+ }
1870
+ } }))));
1871
+ };
1872
+
1873
+ const POLLING_OPTIONS = [
1874
+ { label: '15 seconds', value: 15000 },
1875
+ { label: '30 seconds', value: 30000 },
1876
+ { label: '60 seconds', value: 60000 },
1877
+ { label: '120 seconds', value: 120000 },
1878
+ ];
1879
+ const DISPLAY_MODE_OPTIONS = [
1880
+ { label: 'Widget', value: 'widget' },
1881
+ { label: 'List', value: 'list' },
1882
+ ];
1883
+ const STYLES_OPTIONS = [
1884
+ { label: 'Default', value: 'default' },
1885
+ { label: 'None (custom)', value: 'none' },
1886
+ ];
1887
+ function getStylesKey(styles) {
1888
+ if (styles === 'default' || styles === 'none')
1889
+ return styles;
1890
+ if (typeof styles === 'object' && 'url' in styles)
1891
+ return 'custom-url';
1892
+ if (typeof styles === 'object' && 'css' in styles)
1893
+ return 'custom-css';
1894
+ return 'default';
1895
+ }
1896
+ const SettingsPanel = ({ isOpen, onClose, settings, onSettingsChange, configInfo, }) => {
1897
+ const [showAdvanced, setShowAdvanced] = React.useState(false);
1898
+ const update = (partial) => {
1899
+ onSettingsChange({ ...settings, ...partial });
1900
+ };
1901
+ const handleToggle = (key) => {
1902
+ update({ [key]: !settings[key] });
1903
+ };
1904
+ const stylesKey = getStylesKey(settings.styles);
1905
+ return (React__namespace.createElement("div", { className: `journy-settings-panel ${isOpen ? 'journy-settings-panel-open' : 'journy-settings-panel-closed'}`, onClick: (e) => e.stopPropagation() },
1906
+ React__namespace.createElement("div", { className: "journy-settings-header" },
1907
+ React__namespace.createElement("span", { className: "journy-settings-title" }, "Settings"),
1908
+ React__namespace.createElement("button", { type: "button", className: "journy-settings-close", onClick: onClose, title: "Close settings", "aria-label": "Close settings" }, "\u00D7")),
1909
+ React__namespace.createElement("div", { className: "journy-settings-body" },
1910
+ React__namespace.createElement("div", { className: "journy-settings-item" },
1911
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "Display mode"),
1912
+ React__namespace.createElement("select", { className: "journy-settings-select", value: settings.displayMode, onChange: (e) => update({ displayMode: e.target.value }) }, DISPLAY_MODE_OPTIONS.map((opt) => (React__namespace.createElement("option", { key: opt.value, value: opt.value }, opt.label))))),
1913
+ React__namespace.createElement("div", { className: "journy-settings-item" },
1914
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "Polling interval"),
1915
+ React__namespace.createElement("select", { className: "journy-settings-select", value: settings.pollingInterval, onChange: (e) => update({ pollingInterval: Number(e.target.value) }) }, POLLING_OPTIONS.map((opt) => (React__namespace.createElement("option", { key: opt.value, value: opt.value }, opt.label))))),
1916
+ React__namespace.createElement("div", { className: "journy-settings-item" },
1917
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "Show read messages"),
1918
+ React__namespace.createElement("button", { type: "button", className: `journy-settings-toggle ${settings.showReadMessages ? 'journy-settings-toggle-on' : ''}`, onClick: () => handleToggle('showReadMessages'), role: "switch", "aria-checked": settings.showReadMessages },
1919
+ React__namespace.createElement("span", { className: "journy-settings-toggle-knob" }))),
1920
+ React__namespace.createElement("div", { className: "journy-settings-item" },
1921
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "Auto-expand on new messages"),
1922
+ React__namespace.createElement("button", { type: "button", className: `journy-settings-toggle ${settings.autoExpandOnNew ? 'journy-settings-toggle-on' : ''}`, onClick: () => handleToggle('autoExpandOnNew'), role: "switch", "aria-checked": settings.autoExpandOnNew },
1923
+ React__namespace.createElement("span", { className: "journy-settings-toggle-knob" }))),
1924
+ React__namespace.createElement("div", { className: "journy-settings-item" },
1925
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "Styles"),
1926
+ React__namespace.createElement("select", { className: "journy-settings-select", value: stylesKey, onChange: (e) => {
1927
+ const val = e.target.value;
1928
+ if (val === 'default' || val === 'none') {
1929
+ update({ styles: val });
1930
+ }
1931
+ } },
1932
+ STYLES_OPTIONS.map((opt) => (React__namespace.createElement("option", { key: opt.value, value: opt.value }, opt.label))),
1933
+ stylesKey === 'custom-url' && (React__namespace.createElement("option", { value: "custom-url", disabled: true }, "Custom URL")),
1934
+ stylesKey === 'custom-css' && (React__namespace.createElement("option", { value: "custom-css", disabled: true }, "Custom CSS")))),
1935
+ React__namespace.createElement("div", { className: "journy-settings-item" },
1936
+ React__namespace.createElement("button", { type: "button", className: "journy-settings-advanced-btn", onClick: () => setShowAdvanced(!showAdvanced) }, showAdvanced ? '▾ Advanced' : '▸ Advanced')),
1937
+ showAdvanced && (React__namespace.createElement(React__namespace.Fragment, null,
1938
+ React__namespace.createElement("div", { className: "journy-settings-item journy-settings-item-vertical" },
1939
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "API endpoint"),
1940
+ React__namespace.createElement("input", { type: "text", className: "journy-settings-input", value: settings.apiEndpoint, onChange: (e) => update({ apiEndpoint: e.target.value }), placeholder: "https://jtm.journy.io" })),
1941
+ configInfo && (React__namespace.createElement(React__namespace.Fragment, null,
1942
+ React__namespace.createElement("div", { className: "journy-settings-item" },
1943
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "Entity type"),
1944
+ React__namespace.createElement("span", { className: "journy-settings-value" }, configInfo.entityType)),
1945
+ configInfo.userId && (React__namespace.createElement("div", { className: "journy-settings-item" },
1946
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "User ID"),
1947
+ React__namespace.createElement("span", { className: "journy-settings-value" }, configInfo.userId))),
1948
+ configInfo.accountId && (React__namespace.createElement("div", { className: "journy-settings-item" },
1949
+ React__namespace.createElement("label", { className: "journy-settings-label" }, "Account ID"),
1950
+ React__namespace.createElement("span", { className: "journy-settings-value" }, configInfo.accountId))))))))));
1951
+ };
1952
+
1953
+ const ICON_SIZE$1 = 12;
1954
+ const DOT_FIRST = 2;
1955
+ const DOT_SECOND = 6;
1956
+ const DOT_THIRD = 10;
1957
+ const DOT_RADIUS = 1;
1958
+ const DragHandle = ({ onMouseDown, title = 'Drag to move', className = 'journy-message-widget-drag-handle', }) => (React__namespace.createElement("div", { className: className, onMouseDown: onMouseDown, title: title },
1959
+ React__namespace.createElement("svg", { width: ICON_SIZE$1, height: ICON_SIZE$1, viewBox: `0 0 ${ICON_SIZE$1} ${ICON_SIZE$1}`, fill: "none", xmlns: "http://www.w3.org/2000/svg" },
1960
+ React__namespace.createElement("circle", { cx: DOT_FIRST, cy: DOT_FIRST, r: DOT_RADIUS, fill: "#9ca3af" }),
1961
+ React__namespace.createElement("circle", { cx: DOT_SECOND, cy: DOT_FIRST, r: DOT_RADIUS, fill: "#9ca3af" }),
1962
+ React__namespace.createElement("circle", { cx: DOT_THIRD, cy: DOT_FIRST, r: DOT_RADIUS, fill: "#9ca3af" }),
1963
+ React__namespace.createElement("circle", { cx: DOT_FIRST, cy: DOT_SECOND, r: DOT_RADIUS, fill: "#9ca3af" }),
1964
+ React__namespace.createElement("circle", { cx: DOT_SECOND, cy: DOT_SECOND, r: DOT_RADIUS, fill: "#9ca3af" }),
1965
+ React__namespace.createElement("circle", { cx: DOT_THIRD, cy: DOT_SECOND, r: DOT_RADIUS, fill: "#9ca3af" }),
1966
+ React__namespace.createElement("circle", { cx: DOT_FIRST, cy: DOT_THIRD, r: DOT_RADIUS, fill: "#9ca3af" }),
1967
+ React__namespace.createElement("circle", { cx: DOT_SECOND, cy: DOT_THIRD, r: DOT_RADIUS, fill: "#9ca3af" }),
1968
+ React__namespace.createElement("circle", { cx: DOT_THIRD, cy: DOT_THIRD, r: DOT_RADIUS, fill: "#9ca3af" }))));
1969
+
1970
+ const ICON_SIZE = 16;
1971
+ const STROKE_WIDTH = 1.5;
1972
+ /** Diagonal from top-right to bottom-left (resize corner). */
1973
+ const PATH_MAIN = 'M16 0 L0 16';
1974
+ const PATH_INNER = 'M13 3 L3 13';
1975
+ const ResizeHandle = ({ onMouseDown, title = 'Resize', className = 'journy-message-widget-resize-handle', }) => (React__namespace.createElement("div", { className: className, onMouseDown: onMouseDown, title: title },
1976
+ React__namespace.createElement("svg", { width: ICON_SIZE, height: ICON_SIZE, viewBox: `0 0 ${ICON_SIZE} ${ICON_SIZE}`, fill: "none", xmlns: "http://www.w3.org/2000/svg" },
1977
+ React__namespace.createElement("path", { d: `${PATH_MAIN} ${PATH_INNER}`, stroke: "#9ca3af", strokeWidth: STROKE_WIDTH, strokeLinecap: "round" }))));
1978
+
1979
+ const COLLAPSED_WIDTH = 300;
1980
+ const COLLAPSED_HEIGHT = 80;
1981
+ const WIDGET_MODE_EXPANDED_WIDTH = 340;
1982
+ const WIDGET_MODE_EXPANDED_HEIGHT = 280;
1983
+ const LIST_MODE_DEFAULT_WIDTH = 600;
1984
+ const LIST_MODE_DEFAULT_HEIGHT = 800;
1985
+ const DEFAULT_EDGE_OFFSET = 20;
1986
+ const VIEWPORT_PADDING = 40;
1987
+ const MIN_LIST_WIDTH = 300;
1988
+ const MIN_LIST_HEIGHT = 200;
1989
+ const MIN_POSITION_THRESHOLD = 0;
1990
+ function useWidgetDragResize({ isCollapsed, isListMode }) {
1991
+ const [position, setPosition] = React.useState(() => {
1992
+ const saved = getItem('widget_position');
1993
+ if (saved && typeof saved.left === 'number' && typeof saved.top === 'number') {
1994
+ return {
1995
+ left: Math.max(0, Math.min(saved.left, window.innerWidth - COLLAPSED_WIDTH)),
1996
+ top: Math.max(0, Math.min(saved.top, window.innerHeight - COLLAPSED_HEIGHT)),
1997
+ };
1998
+ }
1999
+ if (saved && typeof saved.x === 'number' && typeof saved.y === 'number') {
2000
+ return {
2001
+ left: Math.max(0, saved.x - COLLAPSED_WIDTH),
2002
+ top: Math.max(0, saved.y - COLLAPSED_HEIGHT),
2003
+ };
2004
+ }
2005
+ return {
2006
+ left: window.innerWidth - DEFAULT_EDGE_OFFSET - COLLAPSED_WIDTH,
2007
+ top: window.innerHeight - DEFAULT_EDGE_OFFSET - COLLAPSED_HEIGHT,
2008
+ };
2009
+ });
2010
+ const [size, setSize] = React.useState({ width: LIST_MODE_DEFAULT_WIDTH, height: LIST_MODE_DEFAULT_HEIGHT });
2011
+ const [isDragging, setIsDragging] = React.useState(false);
2012
+ const [isResizing, setIsResizing] = React.useState(false);
2013
+ const [dragOffset, setDragOffset] = React.useState({ x: 0, y: 0 });
2014
+ const [resizeStart, setResizeStart] = React.useState(null);
2015
+ const widgetRef = React.useRef(null);
2016
+ const hasDraggedThisSession = React.useRef(false);
2017
+ const justFinishedDragging = React.useRef(false);
2018
+ const currentWidth = isCollapsed
2019
+ ? COLLAPSED_WIDTH
2020
+ : isListMode
2021
+ ? size.width
2022
+ : WIDGET_MODE_EXPANDED_WIDTH;
2023
+ const currentHeight = isCollapsed
2024
+ ? COLLAPSED_HEIGHT
2025
+ : isListMode
2026
+ ? size.height
2027
+ : WIDGET_MODE_EXPANDED_HEIGHT;
2028
+ // Load saved size from localStorage on mount
2029
+ React.useEffect(() => {
2030
+ const savedSize = getItem('widget_size');
2031
+ if (savedSize) {
2032
+ setSize({
2033
+ width: Math.max(MIN_LIST_WIDTH, Math.min(savedSize.width, window.innerWidth - VIEWPORT_PADDING)),
2034
+ height: Math.max(MIN_LIST_HEIGHT, Math.min(savedSize.height, window.innerHeight - VIEWPORT_PADDING)),
2035
+ });
2036
+ }
2037
+ }, []);
2038
+ // Clamp position so widget stays on screen
2039
+ React.useEffect(() => {
2040
+ setPosition(prev => ({
2041
+ left: Math.max(0, Math.min(prev.left, window.innerWidth - currentWidth)),
2042
+ top: Math.max(0, Math.min(prev.top, window.innerHeight - currentHeight)),
2043
+ }));
2044
+ }, [currentWidth, currentHeight]);
2045
+ // Save position when it changes
2046
+ React.useEffect(() => {
2047
+ if (position.left > MIN_POSITION_THRESHOLD || position.top > MIN_POSITION_THRESHOLD) {
2048
+ setItem('widget_position', position);
2049
+ }
2050
+ }, [position]);
2051
+ // Save size when it changes (list mode expanded only)
2052
+ React.useEffect(() => {
2053
+ if (isListMode && !isCollapsed && size.width > MIN_POSITION_THRESHOLD && size.height > MIN_POSITION_THRESHOLD) {
2054
+ setItem('widget_size', size);
2055
+ }
2056
+ }, [size, isCollapsed, isListMode]);
2057
+ // Constrain position when window resizes
2058
+ React.useEffect(() => {
2059
+ const handleResize = () => {
2060
+ setPosition(prev => ({
2061
+ left: Math.max(0, Math.min(prev.left, window.innerWidth - currentWidth)),
2062
+ top: Math.max(0, Math.min(prev.top, window.innerHeight - currentHeight)),
2063
+ }));
2064
+ };
2065
+ window.addEventListener('resize', handleResize);
2066
+ return () => window.removeEventListener('resize', handleResize);
2067
+ }, [currentWidth, currentHeight]);
2068
+ const handleMouseDown = (e) => {
2069
+ const target = e.target;
2070
+ if (!target.closest('.journy-message-widget-drag-handle'))
2071
+ return;
2072
+ if (!widgetRef.current)
2073
+ return;
2074
+ hasDraggedThisSession.current = false;
2075
+ const rect = widgetRef.current.getBoundingClientRect();
2076
+ setDragOffset({
2077
+ x: e.clientX - rect.left,
2078
+ y: e.clientY - rect.top,
2079
+ });
2080
+ setIsDragging(true);
2081
+ };
2082
+ // Global mousemove/mouseup for drag and resize
2083
+ React.useEffect(() => {
2084
+ if (!isDragging && !isResizing)
2085
+ return;
2086
+ const handleMouseMove = (e) => {
2087
+ if (isDragging) {
2088
+ hasDraggedThisSession.current = true;
2089
+ const newLeft = e.clientX - dragOffset.x;
2090
+ const newTop = e.clientY - dragOffset.y;
2091
+ setPosition({
2092
+ left: Math.max(0, Math.min(newLeft, window.innerWidth - currentWidth)),
2093
+ top: Math.max(0, Math.min(newTop, window.innerHeight - currentHeight)),
2094
+ });
2095
+ }
2096
+ else if (isResizing && resizeStart) {
2097
+ const deltaX = e.clientX - resizeStart.x;
2098
+ const deltaY = e.clientY - resizeStart.y;
2099
+ const maxWidth = window.innerWidth - position.left;
2100
+ const maxHeight = window.innerHeight - position.top;
2101
+ const newWidth = Math.max(MIN_LIST_WIDTH, Math.min(resizeStart.width + deltaX, maxWidth));
2102
+ const newHeight = Math.max(MIN_LIST_HEIGHT, Math.min(resizeStart.height + deltaY, maxHeight));
2103
+ setSize({ width: newWidth, height: newHeight });
2104
+ }
2105
+ };
2106
+ const handleMouseUp = () => {
2107
+ if (isDragging && hasDraggedThisSession.current) {
2108
+ justFinishedDragging.current = true;
2109
+ setTimeout(() => {
2110
+ justFinishedDragging.current = false;
2111
+ }, 100);
2112
+ }
2113
+ setIsDragging(false);
2114
+ setIsResizing(false);
2115
+ setResizeStart(null);
2116
+ };
2117
+ document.addEventListener('mousemove', handleMouseMove);
2118
+ document.addEventListener('mouseup', handleMouseUp);
2119
+ return () => {
2120
+ document.removeEventListener('mousemove', handleMouseMove);
2121
+ document.removeEventListener('mouseup', handleMouseUp);
2122
+ };
2123
+ }, [isDragging, isResizing, dragOffset, resizeStart, position, currentWidth, currentHeight]);
2124
+ const handleResizeStart = (e) => {
2125
+ e.stopPropagation();
2126
+ if (!widgetRef.current)
2127
+ return;
2128
+ const rect = widgetRef.current.getBoundingClientRect();
2129
+ setResizeStart({
2130
+ x: e.clientX,
2131
+ y: e.clientY,
2132
+ width: rect.width,
2133
+ height: rect.height,
2134
+ });
2135
+ setIsResizing(true);
2136
+ };
2137
+ return {
2138
+ position,
2139
+ size,
2140
+ isDragging,
2141
+ isResizing,
2142
+ widgetRef,
2143
+ justFinishedDragging,
2144
+ currentWidth,
2145
+ currentHeight,
2146
+ handleMouseDown,
2147
+ handleResizeStart,
2148
+ };
2149
+ }
2150
+ const TRANSITION_DURATION_S = 0.25;
2151
+
2152
+ const SETTINGS_STORAGE_KEY = 'widget_settings';
2153
+ /** Mark message as received when its element is visible in the viewport. */
2154
+ function useMessageVisibility(ref, messageId, received, onMessageReceived) {
2155
+ const hasFiredRef = React.useRef(false);
2156
+ React.useEffect(() => {
2157
+ if (received) {
2158
+ hasFiredRef.current = true;
2159
+ return;
2160
+ }
2161
+ hasFiredRef.current = false;
2162
+ const el = ref.current;
2163
+ if (!el || !onMessageReceived)
2164
+ return;
2165
+ const observer = new IntersectionObserver((entries) => {
2166
+ const [entry] = entries;
2167
+ if (entry?.isIntersecting && !hasFiredRef.current) {
2168
+ hasFiredRef.current = true;
2169
+ onMessageReceived([messageId]);
2170
+ observer.disconnect();
2171
+ }
2172
+ }, { threshold: 0.1, root: null });
2173
+ observer.observe(el);
2174
+ return () => observer.disconnect();
2175
+ }, [messageId, received, onMessageReceived]);
2176
+ }
2177
+ /** Wraps a message row with a ref and viewport visibility observer to mark as received when visible. */
2178
+ const MessageRow = ({ message, isSeparated, onMessageReceived, onDismissMessage, children }) => {
2179
+ const ref = React.useRef(null);
2180
+ useMessageVisibility(ref, message.id, message.received, onMessageReceived);
2181
+ return (React__namespace.createElement("div", { ref: ref, className: `journy-message-widget-message journy-message-${message.received ? 'viewed' : 'info'} ${isSeparated ? 'journy-message-widget-message-separated' : ''}` },
2182
+ onDismissMessage && (React__namespace.createElement("button", { type: "button", className: "journy-message-widget-message-close", onClick: (e) => {
2183
+ e.stopPropagation();
2184
+ e.preventDefault();
2185
+ onDismissMessage(message.id);
2186
+ }, title: "Dismiss message", "aria-label": "Dismiss" }, "\u00D7")),
2187
+ children));
2188
+ };
2189
+ /** Derives total, unread, and read counts from the messages array. */
2190
+ function useMessageCounts(messages) {
2191
+ return React.useMemo(() => {
2192
+ const unreadCount = messages.filter((m) => !m.received).length;
2193
+ const readCount = messages.filter((m) => m.received).length;
2194
+ return {
2195
+ totalCount: messages.length,
2196
+ unreadCount,
2197
+ readCount,
2198
+ };
2199
+ }, [messages]);
2200
+ }
2201
+ const MessageWidget = ({ store, onClose, onCloseWidget, onLinkClick, onToggleExpand, onMessageReceived, onDismissMessage, onNextMessage, onPrevMessage, onSettingsChange, configInfo, }) => {
2202
+ const { messages, currentMessage, isCollapsed, displayMode, widgetVisible } = useMessagingStore(store);
2203
+ const { totalCount, unreadCount, readCount } = useMessageCounts(messages);
2204
+ const [modalMessage, setModalMessage] = React.useState(null);
2205
+ const [isSettingsOpen, setIsSettingsOpen] = React.useState(false);
2206
+ const [settings, setSettings] = React.useState(() => {
2207
+ const saved = getItem(SETTINGS_STORAGE_KEY);
2208
+ return saved
2209
+ ? { ...DEFAULT_WIDGET_SETTINGS, ...saved, displayMode }
2210
+ : { ...DEFAULT_WIDGET_SETTINGS, displayMode };
2211
+ });
2212
+ const isListMode = displayMode === 'list';
2213
+ const { position, isDragging, isResizing, widgetRef, justFinishedDragging, currentWidth, currentHeight, handleMouseDown, handleResizeStart, } = useWidgetDragResize({ isCollapsed, isListMode });
2214
+ const contentRef = React.useRef(null);
2215
+ const scrollTimerRef = React.useRef(null);
2216
+ // Persist scroll position on scroll (debounced), restore on mount/expand
2217
+ React.useEffect(() => {
2218
+ if (isCollapsed || !isListMode)
2219
+ return;
2220
+ const el = contentRef.current;
2221
+ if (!el)
2222
+ return;
2223
+ // Restore saved scroll position
2224
+ const savedScroll = getItem('widget_scroll_position');
2225
+ if (savedScroll != null) {
2226
+ el.scrollTop = savedScroll;
2227
+ }
2228
+ const handleScroll = () => {
2229
+ if (scrollTimerRef.current)
2230
+ clearTimeout(scrollTimerRef.current);
2231
+ scrollTimerRef.current = setTimeout(() => {
2232
+ setItem('widget_scroll_position', el.scrollTop);
2233
+ }, 150);
2234
+ };
2235
+ el.addEventListener('scroll', handleScroll, { passive: true });
2236
+ return () => {
2237
+ el.removeEventListener('scroll', handleScroll);
2238
+ if (scrollTimerRef.current)
2239
+ clearTimeout(scrollTimerRef.current);
2240
+ };
2241
+ }, [isCollapsed, isListMode]);
2242
+ const handleSettingsChange = React.useCallback((newSettings) => {
2243
+ setSettings(newSettings);
2244
+ setItem(SETTINGS_STORAGE_KEY, newSettings);
2245
+ onSettingsChange?.(newSettings);
2246
+ }, [onSettingsChange]);
2247
+ if (!widgetVisible) {
2248
+ return null;
2249
+ }
2250
+ const handleLinkClick = (e) => {
2251
+ e.preventDefault();
2252
+ const url = e.currentTarget.href;
2253
+ onLinkClick(url);
2254
+ };
2255
+ const handleContentClick = (message, e) => {
2256
+ const target = e.target;
2257
+ if (target.tagName === 'A') {
2258
+ handleLinkClick(e);
2259
+ }
2260
+ else {
2261
+ if (onMessageReceived && !message.received) {
2262
+ onMessageReceived([message.id]);
2263
+ }
2264
+ setModalMessage(message);
2265
+ }
2266
+ };
2267
+ // Get messages for display: widget mode shows all messages for consistent navigation;
2268
+ // list mode prioritises unread messages when available.
2269
+ // Apply showReadMessages setting: when disabled, filter out read messages in list mode.
2270
+ const unreadMessages = messages.filter(msg => !msg.received);
2271
+ const filteredMessages = isListMode && !settings.showReadMessages
2272
+ ? unreadMessages
2273
+ : messages;
2274
+ const allMessagesToShow = isListMode
2275
+ ? (unreadMessages.length > 0 && settings.showReadMessages ? filteredMessages : (filteredMessages.length > 0 ? filteredMessages : messages))
2276
+ : messages;
2277
+ const displayMessage = currentMessage || (!isCollapsed && allMessagesToShow.length > 0 ? allMessagesToShow[0] : null);
2278
+ const currentMessageIndex = displayMessage
2279
+ ? Math.max(0, allMessagesToShow.findIndex((m) => m.id === displayMessage.id))
2280
+ : 0;
2281
+ const canGoPrev = !isListMode && allMessagesToShow.length > 1 && currentMessageIndex > 0;
2282
+ const canGoNext = !isListMode && allMessagesToShow.length > 1 && currentMessageIndex < allMessagesToShow.length - 1;
2283
+ // Extract title from HTML if no title field exists
2284
+ const getMessageTitle = (msg) => {
2285
+ if (!msg)
2286
+ return 'Messages';
2287
+ // Try to extract from HTML (first h1, h2, or h3)
2288
+ const match = msg.message.match(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/i);
2289
+ return match ? match[1].replace(/<[^>]+>/g, '') : 'Messages';
2290
+ };
2291
+ return (React__namespace.createElement("div", { ref: widgetRef, className: `journy-message-widget ${!isCollapsed ? 'journy-message-widget-expanded' : 'journy-message-widget-collapsed'} ${isDragging ? 'journy-message-widget-dragging' : ''} ${isResizing ? 'journy-message-widget-resizing' : ''}`, style: {
2292
+ left: `${position.left}px`,
2293
+ top: `${position.top}px`,
2294
+ width: `${currentWidth}px`,
2295
+ height: `${currentHeight}px`,
2296
+ transition: isDragging || isResizing ? 'none' : `height ${TRANSITION_DURATION_S}s ease-out, top ${TRANSITION_DURATION_S}s ease-out`,
2297
+ }, onClick: (e) => {
2298
+ // Don't toggle if this click was right after a drag (avoids expand when releasing drag at bottom edge)
2299
+ if (justFinishedDragging.current) {
2300
+ e.preventDefault();
2301
+ e.stopPropagation();
2302
+ return;
2303
+ }
2304
+ // Toggle on click when collapsed, but not if clicking on buttons, drag handle, or content area
2305
+ if (!isCollapsed)
2306
+ return; // Don't toggle when expanded
2307
+ const target = e.target;
2308
+ const isButton = target.closest('button');
2309
+ const isDragHandle = target.closest('.journy-message-widget-drag-handle');
2310
+ const isLink = target.tagName === 'A' || target.closest('a');
2311
+ // Only toggle when clicking on header (but not buttons, drag handle, or links)
2312
+ if (!isButton && !isDragHandle && !isLink) {
2313
+ onToggleExpand();
2314
+ }
2315
+ } },
2316
+ React__namespace.createElement("div", { className: "journy-message-widget-header" },
2317
+ React__namespace.createElement(DragHandle, { onMouseDown: handleMouseDown }),
2318
+ React__namespace.createElement("div", { className: "journy-message-widget-header-content" }, isCollapsed ? (React__namespace.createElement(React__namespace.Fragment, null,
2319
+ React__namespace.createElement("span", { className: "journy-message-widget-badge" }, unreadCount),
2320
+ React__namespace.createElement("span", { className: "journy-message-widget-title" }, unreadCount > 0 ? 'New Messages' : 'Messages'),
2321
+ readCount > 0 && (React__namespace.createElement("span", { className: "journy-message-widget-read-count" },
2322
+ "(",
2323
+ readCount,
2324
+ " read)")))) : (React__namespace.createElement(React__namespace.Fragment, null,
2325
+ unreadCount > 0 && (React__namespace.createElement("span", { className: "journy-message-widget-badge" }, unreadCount)),
2326
+ React__namespace.createElement("span", { className: "journy-message-widget-title" }, displayMessage ? getMessageTitle(displayMessage) : allMessagesToShow.length > 0 ? getMessageTitle(allMessagesToShow[0]) : 'Messages'),
2327
+ isListMode && allMessagesToShow.length > 1 && (React__namespace.createElement("span", { className: "journy-message-widget-message-count" },
2328
+ "(",
2329
+ allMessagesToShow.length,
2330
+ " messages)"))))),
2331
+ React__namespace.createElement("div", { className: "journy-message-widget-controls" },
2332
+ !isCollapsed && (React__namespace.createElement("button", { className: "journy-message-widget-settings-btn", onClick: (e) => {
2333
+ e.stopPropagation();
2334
+ e.preventDefault();
2335
+ setIsSettingsOpen(true);
2336
+ }, onMouseDown: (e) => e.stopPropagation(), title: "Settings", "aria-label": "Settings" },
2337
+ React__namespace.createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
2338
+ React__namespace.createElement("path", { d: "M6.5 1L6.2 2.6C5.8 2.8 5.5 3 5.2 3.2L3.6 2.7L2.1 5.3L3.4 6.3C3.4 6.5 3.3 6.8 3.3 7C3.3 7.2 3.4 7.5 3.4 7.7L2.1 8.7L3.6 11.3L5.2 10.8C5.5 11 5.8 11.2 6.2 11.4L6.5 13H9.5L9.8 11.4C10.2 11.2 10.5 11 10.8 10.8L12.4 11.3L13.9 8.7L12.6 7.7C12.6 7.5 12.7 7.2 12.7 7C12.7 6.8 12.6 6.5 12.6 6.3L13.9 5.3L12.4 2.7L10.8 3.2C10.5 3 10.2 2.8 9.8 2.6L9.5 1H6.5ZM8 5C9.1 5 10 5.9 10 7C10 8.1 9.1 9 8 9C6.9 9 6 8.1 6 7C6 5.9 6.9 5 8 5Z", fill: "currentColor" })))),
2339
+ React__namespace.createElement("button", { className: "journy-message-widget-toggle", onClick: (e) => {
2340
+ e.stopPropagation();
2341
+ e.preventDefault();
2342
+ onToggleExpand();
2343
+ }, onMouseDown: (e) => {
2344
+ e.stopPropagation(); // Prevent drag from starting
2345
+ }, title: !isCollapsed ? 'Collapse' : 'Expand', "aria-label": !isCollapsed ? 'Collapse' : 'Expand' }, !isCollapsed ? '−' : '+'),
2346
+ isCollapsed && (React__namespace.createElement("button", { className: "journy-message-widget-close", onClick: (e) => {
2347
+ e.stopPropagation();
2348
+ e.preventDefault();
2349
+ onCloseWidget ? onCloseWidget() : onClose();
2350
+ }, onMouseDown: (e) => {
2351
+ e.stopPropagation();
2352
+ }, title: "Close widget", "aria-label": "Close" }, "\u00D7")),
2353
+ !isCollapsed && isListMode === false && allMessagesToShow.length > 1 && (React__namespace.createElement(React__namespace.Fragment, null,
2354
+ React__namespace.createElement("button", { className: "journy-message-widget-nav", onClick: (e) => {
2355
+ e.stopPropagation();
2356
+ e.preventDefault();
2357
+ onPrevMessage?.();
2358
+ }, onMouseDown: (e) => e.stopPropagation(), title: "Previous message", "aria-label": "Previous", disabled: !canGoPrev }, "\u2039"),
2359
+ React__namespace.createElement("button", { className: "journy-message-widget-nav", onClick: (e) => {
2360
+ e.stopPropagation();
2361
+ e.preventDefault();
2362
+ onNextMessage?.();
2363
+ }, onMouseDown: (e) => e.stopPropagation(), title: "Next message", "aria-label": "Next", disabled: !canGoNext }, "\u203A"))))),
2364
+ !isCollapsed && allMessagesToShow.length > 0 && (React__namespace.createElement(React__namespace.Fragment, null,
2365
+ React__namespace.createElement("div", { ref: contentRef, className: `journy-message-widget-content ${!isListMode ? 'journy-message-widget-content--single' : ''}` }, isListMode ? (allMessagesToShow.map((message, index) => (React__namespace.createElement(MessageRow, { key: message.id, message: message, isSeparated: index < allMessagesToShow.length - 1, onMessageReceived: onMessageReceived, onDismissMessage: onDismissMessage },
2366
+ React__namespace.createElement("div", { className: "journy-message-content journy-message-content-clickable", dangerouslySetInnerHTML: { __html: sanitizeHtml(message.message) }, onClick: (e) => handleContentClick(message, e) }),
2367
+ message.createdAt && (React__namespace.createElement("div", { className: "journy-message-timestamp" }, formatTimestamp(message.createdAt))))))) : displayMessage ? (React__namespace.createElement(MessageRow, { message: displayMessage, isSeparated: false, onMessageReceived: onMessageReceived, onDismissMessage: onDismissMessage },
2368
+ React__namespace.createElement("div", { className: "journy-message-content journy-message-content-clickable", dangerouslySetInnerHTML: { __html: sanitizeHtml(displayMessage.message) }, onClick: (e) => handleContentClick(displayMessage, e) }),
2369
+ displayMessage.createdAt && (React__namespace.createElement("div", { className: "journy-message-timestamp" }, formatTimestamp(displayMessage.createdAt))))) : null),
2370
+ !isListMode && allMessagesToShow.length > 1 && (React__namespace.createElement("div", { className: "journy-message-widget-position" },
2371
+ currentMessageIndex + 1,
2372
+ " / ",
2373
+ allMessagesToShow.length)),
2374
+ isListMode && React__namespace.createElement(ResizeHandle, { onMouseDown: handleResizeStart }))),
2375
+ !isCollapsed && allMessagesToShow.length === 0 && (React__namespace.createElement(React__namespace.Fragment, null,
2376
+ React__namespace.createElement("div", { className: "journy-message-widget-content journy-message-widget-empty" },
2377
+ React__namespace.createElement("p", null, "No unread messages")),
2378
+ isListMode && React__namespace.createElement(ResizeHandle, { onMouseDown: handleResizeStart }))),
2379
+ !isCollapsed && (React__namespace.createElement(SettingsPanel, { isOpen: isSettingsOpen, onClose: () => setIsSettingsOpen(false), settings: settings, onSettingsChange: handleSettingsChange, configInfo: configInfo })),
2380
+ modalMessage && (React__namespace.createElement(MessagePopup, { message: modalMessage, onClose: () => setModalMessage(null), onLinkClick: onLinkClick }))));
2381
+ };
2382
+
2383
+ var MessageWidgetModule = /*#__PURE__*/Object.freeze({
2384
+ __proto__: null,
2385
+ MessageWidget: MessageWidget,
2386
+ default: MessageWidget
2387
+ });
2388
+
2389
+ /**
2390
+ * Builds a generic track batch item for any SDK event type.
2391
+ */
2392
+ function buildTrackEventPayload(scope, identity, event, properties) {
2393
+ const base = {
2394
+ type: "track",
2395
+ event: event,
2396
+ properties,
2397
+ };
2398
+ if (scope === "account" && identity.accountId) {
2399
+ return {
2400
+ ...base,
2401
+ anonymousId: identity.accountId,
2402
+ context: { groupId: identity.accountId },
2403
+ };
2404
+ }
2405
+ if (identity.userId) {
2406
+ return { ...base, userId: identity.userId };
2407
+ }
2408
+ if (identity.anonymousId) {
2409
+ return { ...base, anonymousId: identity.anonymousId };
2410
+ }
2411
+ throw new Error("User scope requires userId or anonymousId; account scope requires accountId.");
2412
+ }
2413
+
2414
+ const SEND_ANALYTICS_PATH = "/frontend/v1/b";
2415
+ class AnalyticsClient {
2416
+ constructor(config) {
2417
+ this.config = config;
2418
+ this.analyticsHost = config.apiEndpoint || "https://jtm.journy.io";
2419
+ }
2420
+ get trackIdentity() {
2421
+ return {
2422
+ userId: this.config.userId,
2423
+ accountId: this.config.accountId,
2424
+ };
2425
+ }
2426
+ /**
2427
+ * General-purpose method: send an array of SDK events in a single batch.
2428
+ */
2429
+ async trackEvents(events) {
2430
+ if (events.length === 0)
2431
+ return true;
2432
+ const batch = events.map(({ event, properties }) => buildTrackEventPayload(this.config.entityType, this.trackIdentity, event, properties));
2433
+ await fetch(this.analyticsHost + SEND_ANALYTICS_PATH, {
2434
+ method: "POST",
2435
+ headers: { "Content-Type": "application/json" },
2436
+ body: JSON.stringify({ writeKey: this.config.writeKey, batch }),
2437
+ });
2438
+ return true;
2439
+ }
2440
+ /**
2441
+ * Convenience method for "message received" events. Calls trackEvents internally.
2442
+ */
2443
+ async sendAnalyticsEvents(messageIds) {
2444
+ return this.trackEvents(messageIds.map(messageId => ({
2445
+ event: SDKEventType.MessageReceived,
2446
+ properties: { messageId },
2447
+ })));
2448
+ }
2449
+ }
2450
+
2451
+ const DEFAULT_API_ENDPOINT = 'https://jtm.journy.io';
2452
+ const DEFAULT_POLLING_INTERVAL = 30000;
2453
+ const ROOT_ELEMENT_ID = 'journy-messages-root';
2454
+ const DEFAULT_STYLE_ID = 'journy-messages-default';
2455
+ const REACT_CHECK_INTERVAL = 100;
2456
+ const REACT_WAIT_TIMEOUT = 10000;
2457
+ const MESSAGE_CLOSE_DELAY = 300;
2458
+ const STORAGE_KEYS = {
2459
+ WIDGET_SETTINGS: 'widget_settings',
2460
+ WIDGET_VISIBLE: 'widget_visible',
2461
+ WIDGET_COLLAPSED: 'widget_collapsed',
2462
+ CURRENT_MESSAGE_ID: 'current_message_id',
2463
+ };
2464
+ class JournyMessaging {
2465
+ constructor(config) {
2466
+ this.initialized = false;
2467
+ this.pollingInterval = null;
2468
+ this.reactRoot = null;
2469
+ this.reactRootContainer = null;
2470
+ this.rootElementId = ROOT_ELEMENT_ID;
2471
+ this.unsubscribePersistence = null;
2472
+ this.config = {
2473
+ apiEndpoint: DEFAULT_API_ENDPOINT,
2474
+ pollingInterval: DEFAULT_POLLING_INTERVAL,
2475
+ ...config,
2476
+ };
2477
+ if (!this.config.writeKey) {
2478
+ throw new Error('writeKey is required');
2479
+ }
2480
+ if (!this.config.entityType) {
2481
+ throw new Error('entityType is required');
2482
+ }
2483
+ this.apiClient = new ApiClient(this.config);
2484
+ this.messageQueue = new MessageQueue();
2485
+ this.analyticsClient = new AnalyticsClient(this.config);
2486
+ this.eventTracker = new EventTracker(this.analyticsClient);
2487
+ // Build default settings from config, then overlay any saved settings
2488
+ const configDefaults = {
2489
+ ...DEFAULT_WIDGET_SETTINGS,
2490
+ pollingInterval: this.config.pollingInterval || DEFAULT_WIDGET_SETTINGS.pollingInterval,
2491
+ displayMode: this.config.displayMode || DEFAULT_WIDGET_SETTINGS.displayMode,
2492
+ apiEndpoint: this.config.apiEndpoint || DEFAULT_WIDGET_SETTINGS.apiEndpoint,
2493
+ styles: this.config.styles || DEFAULT_WIDGET_SETTINGS.styles,
2494
+ };
2495
+ const savedSettings = getItem(STORAGE_KEYS.WIDGET_SETTINGS);
2496
+ this.widgetSettings = savedSettings
2497
+ ? { ...configDefaults, ...savedSettings }
2498
+ : configDefaults;
2499
+ // Apply settings back to config so they take effect
2500
+ this.config.pollingInterval = this.widgetSettings.pollingInterval;
2501
+ this.config.apiEndpoint = this.widgetSettings.apiEndpoint;
2502
+ this.config.displayMode = this.widgetSettings.displayMode;
2503
+ const savedVisible = getItem(STORAGE_KEYS.WIDGET_VISIBLE);
2504
+ const savedCollapsed = getItem(STORAGE_KEYS.WIDGET_COLLAPSED);
2505
+ this.store = new MessagingStore({
2506
+ messages: [],
2507
+ currentMessage: null,
2508
+ isCollapsed: savedCollapsed ?? this.config.isCollapsed ?? true,
2509
+ widgetVisible: savedVisible ?? true,
2510
+ displayMode: this.widgetSettings.displayMode,
2511
+ });
2512
+ this.unsubscribePersistence = this.store.subscribe(() => {
2513
+ const state = this.store.getState();
2514
+ setItem(STORAGE_KEYS.WIDGET_VISIBLE, state.widgetVisible);
2515
+ setItem(STORAGE_KEYS.WIDGET_COLLAPSED, state.isCollapsed);
2516
+ if (state.currentMessage) {
2517
+ setItem(STORAGE_KEYS.CURRENT_MESSAGE_ID, state.currentMessage.id);
2518
+ }
2519
+ else {
2520
+ removeItem(STORAGE_KEYS.CURRENT_MESSAGE_ID);
2521
+ }
2522
+ });
2523
+ this.init();
2524
+ }
2525
+ get uiState() {
2526
+ return this.store.getState();
2527
+ }
2528
+ async init() {
2529
+ if (this.initialized)
2530
+ return;
2531
+ // Load existing messages
2532
+ await this.loadMessages();
2533
+ // Set up polling or WebSocket connection
2534
+ this.startPolling();
2535
+ // Initialize UI
2536
+ this.initializeUI();
2537
+ this.initialized = true;
2538
+ }
2539
+ async loadMessages() {
2540
+ try {
2541
+ const messages = await this.apiClient.getUnreadMessages();
2542
+ const previousActiveCount = this.messageQueue.getActiveCount();
2543
+ this.messageQueue.addMessages(messages);
2544
+ const newActiveCount = this.messageQueue.getActiveCount();
2545
+ let updates = {
2546
+ messages: this.messageQueue.getAllMessages(),
2547
+ };
2548
+ if (newActiveCount > previousActiveCount) {
2549
+ updates.widgetVisible = true;
2550
+ if (this.widgetSettings.autoExpandOnNew) {
2551
+ updates.isCollapsed = false;
2552
+ }
2553
+ }
2554
+ this.store.setState(updates);
2555
+ if (!this.uiState.currentMessage && newActiveCount > 0) {
2556
+ const savedMessageId = getItem(STORAGE_KEYS.CURRENT_MESSAGE_ID);
2557
+ const allMessages = this.messageQueue.getAllMessages();
2558
+ const savedMessage = savedMessageId ? allMessages.find(m => m.id === savedMessageId) : null;
2559
+ if (savedMessage) {
2560
+ this.store.setState({ currentMessage: savedMessage });
2561
+ }
2562
+ else {
2563
+ this.displayNextMessage();
2564
+ }
2565
+ }
2566
+ // Auto-mark current message as received when widget is expanded
2567
+ if (!this.uiState.isCollapsed && this.uiState.currentMessage && !this.uiState.currentMessage.received) {
2568
+ this.handleMessageReceived([this.uiState.currentMessage.id]);
2569
+ }
2570
+ }
2571
+ catch (error) {
2572
+ console.error('Failed to load messages:', error);
2573
+ }
2574
+ }
2575
+ startPolling() {
2576
+ if (this.pollingInterval !== null) {
2577
+ clearInterval(this.pollingInterval);
2578
+ }
2579
+ this.pollingInterval = window.setInterval(() => {
2580
+ this.loadMessages();
2581
+ }, this.config.pollingInterval || DEFAULT_POLLING_INTERVAL);
2582
+ }
2583
+ applyStyles(stylesConfig) {
2584
+ removeInjectedStyles();
2585
+ if (stylesConfig === 'none') ;
2586
+ else if (stylesConfig && stylesConfig !== 'default') {
2587
+ if ('url' in stylesConfig && stylesConfig.url) {
2588
+ injectStyleLink(stylesConfig.url);
2589
+ }
2590
+ else if ('css' in stylesConfig && stylesConfig.css) {
2591
+ injectStyleTag(stylesConfig.css);
2592
+ }
2593
+ }
2594
+ else {
2595
+ injectStyleTag(defaultStyles, DEFAULT_STYLE_ID);
2596
+ }
2597
+ }
2598
+ initializeUI() {
2599
+ // Create root element for React
2600
+ const rootElement = createRootElement(this.rootElementId);
2601
+ this.applyStyles(this.widgetSettings.styles);
2602
+ // Always render UI (even if no messages) so widget can show/hide itself
2603
+ // Dynamically import React and render component
2604
+ // This will be handled when React is available
2605
+ if (typeof window !== 'undefined' && window.React && window.ReactDOM) {
2606
+ this.renderUI(rootElement);
2607
+ }
2608
+ else {
2609
+ this.waitForReact(rootElement);
2610
+ }
2611
+ }
2612
+ waitForReact(rootElement) {
2613
+ const checkInterval = setInterval(() => {
2614
+ if (typeof window !== 'undefined' && window.React && window.ReactDOM) {
2615
+ clearInterval(checkInterval);
2616
+ this.renderUI(rootElement);
2617
+ }
2618
+ }, REACT_CHECK_INTERVAL);
2619
+ setTimeout(() => {
2620
+ clearInterval(checkInterval);
2621
+ }, REACT_WAIT_TIMEOUT);
2622
+ }
2623
+ renderUI(rootElement) {
2624
+ try {
2625
+ const React = window.React;
2626
+ const ReactDOM = window.ReactDOM;
2627
+ if (!React || !ReactDOM) {
2628
+ throw new Error('React or ReactDOM not found in window');
2629
+ }
2630
+ // If the container was replaced (e.g. root removed and re-created), create a new React root
2631
+ if (this.reactRoot && this.reactRootContainer !== rootElement) {
2632
+ this.reactRoot = null;
2633
+ this.reactRootContainer = null;
2634
+ }
2635
+ // Access MessageWidget from the statically imported module
2636
+ const MessageWidget$1 = MessageWidget || MessageWidget;
2637
+ if (!MessageWidget$1) {
2638
+ console.error('MessageWidget not found in module:', MessageWidgetModule);
2639
+ throw new Error('MessageWidget not found in module');
2640
+ }
2641
+ const props = {
2642
+ store: this.store,
2643
+ onClose: () => this.handleMessageClose(),
2644
+ onCloseWidget: () => this.handleCloseWidget(),
2645
+ onLinkClick: (url) => this.handleLinkClick(url),
2646
+ onToggleExpand: () => this.handleToggleExpand(),
2647
+ onMessageReceived: (messageIds) => this.handleMessageReceived(messageIds),
2648
+ onDismissMessage: (messageId) => this.handleDismissMessage(messageId),
2649
+ onNextMessage: () => this.handleNextMessage(),
2650
+ onPrevMessage: () => this.handlePrevMessage(),
2651
+ onSettingsChange: (settings) => this.handleSettingsChange(settings),
2652
+ configInfo: {
2653
+ entityType: this.config.entityType,
2654
+ userId: this.config.userId,
2655
+ accountId: this.config.accountId,
2656
+ },
2657
+ };
2658
+ const element = React.createElement(MessageWidget$1, props);
2659
+ // Use React 18 createRoot if available, otherwise fall back to render
2660
+ if (ReactDOM.createRoot) {
2661
+ if (!this.reactRoot) {
2662
+ rootElement.innerHTML = '';
2663
+ this.reactRoot = ReactDOM.createRoot(rootElement);
2664
+ this.reactRootContainer = rootElement;
2665
+ }
2666
+ this.reactRoot.render(element);
2667
+ }
2668
+ else {
2669
+ rootElement.innerHTML = '';
2670
+ ReactDOM.render(element, rootElement);
2671
+ }
2672
+ }
2673
+ catch (error) {
2674
+ console.error('Failed to render UI:', error);
2675
+ }
2676
+ }
2677
+ handleSettingsChange(newSettings) {
2678
+ const prev = this.widgetSettings;
2679
+ this.widgetSettings = newSettings;
2680
+ setItem(STORAGE_KEYS.WIDGET_SETTINGS, newSettings);
2681
+ // Sync config
2682
+ this.config.pollingInterval = newSettings.pollingInterval;
2683
+ this.config.apiEndpoint = newSettings.apiEndpoint;
2684
+ // Restart polling if interval changed
2685
+ if (newSettings.pollingInterval !== prev.pollingInterval) {
2686
+ this.startPolling();
2687
+ }
2688
+ // Switch display mode
2689
+ if (newSettings.displayMode !== prev.displayMode) {
2690
+ this.store.setState({ displayMode: newSettings.displayMode });
2691
+ }
2692
+ // Re-apply styles if changed
2693
+ if (JSON.stringify(newSettings.styles) !== JSON.stringify(prev.styles)) {
2694
+ this.applyStyles(newSettings.styles);
2695
+ }
2696
+ // Rebuild API client if endpoint or proxy changed
2697
+ if (newSettings.apiEndpoint !== prev.apiEndpoint) {
2698
+ this.apiClient = new ApiClient(this.config);
2699
+ }
2700
+ }
2701
+ handleToggleExpand() {
2702
+ this.store.setState({ isCollapsed: !this.uiState.isCollapsed });
2703
+ }
2704
+ displayNextMessage() {
2705
+ const nextMessage = this.messageQueue.getNextMessage();
2706
+ if (nextMessage && nextMessage.id !== this.uiState.currentMessage?.id) {
2707
+ this.showMessage(nextMessage);
2708
+ return;
2709
+ }
2710
+ this.store.setState({
2711
+ currentMessage: nextMessage || null,
2712
+ messages: this.messageQueue.getAllMessages(),
2713
+ });
2714
+ }
2715
+ showMessage(message) {
2716
+ this.store.setState({
2717
+ currentMessage: message,
2718
+ messages: this.messageQueue.getAllMessages(),
2719
+ });
2720
+ this.eventTracker.track(SDKEventType.MessageOpened, {
2721
+ messageId: message.id,
2722
+ });
2723
+ }
2724
+ handleMessageClose() {
2725
+ const { currentMessage } = this.uiState;
2726
+ if (currentMessage) {
2727
+ this.eventTracker.track(SDKEventType.MessageClosed, {
2728
+ messageId: currentMessage.id,
2729
+ });
2730
+ this.markAsRead([currentMessage.id]);
2731
+ this.store.setState({ currentMessage: null, isCollapsed: false });
2732
+ setTimeout(() => {
2733
+ this.displayNextMessage();
2734
+ }, MESSAGE_CLOSE_DELAY);
2735
+ }
2736
+ }
2737
+ handleCloseWidget() {
2738
+ this.store.setState({ widgetVisible: false });
2739
+ }
2740
+ async handleDismissMessage(messageId) {
2741
+ this.eventTracker.track(SDKEventType.MessageClosed, { messageId });
2742
+ await this.markAsRead([messageId]);
2743
+ if (this.uiState.currentMessage?.id === messageId) {
2744
+ this.store.setState({ currentMessage: null });
2745
+ this.displayNextMessage();
2746
+ }
2747
+ }
2748
+ navigateMessage(direction) {
2749
+ const list = this.messageQueue.getAllMessages();
2750
+ const idx = list.findIndex((m) => m.id === this.uiState.currentMessage?.id);
2751
+ const targetIdx = idx + direction;
2752
+ if (targetIdx < 0 || targetIdx >= list.length)
2753
+ return;
2754
+ const targetMessage = list[targetIdx];
2755
+ if (!targetMessage.received) {
2756
+ this.store.setState({ currentMessage: targetMessage });
2757
+ this.handleMessageReceived([targetMessage.id]);
2758
+ }
2759
+ else {
2760
+ this.store.setState({ currentMessage: targetMessage });
2761
+ }
2762
+ }
2763
+ handleNextMessage() {
2764
+ this.navigateMessage(1);
2765
+ }
2766
+ handlePrevMessage() {
2767
+ this.navigateMessage(-1);
2768
+ }
2769
+ handleLinkClick(url) {
2770
+ const { currentMessage } = this.uiState;
2771
+ if (currentMessage) {
2772
+ this.eventTracker.track(SDKEventType.MessageLinkClicked, {
2773
+ messageId: currentMessage.id,
2774
+ linkUrl: url,
2775
+ });
2776
+ }
2777
+ }
2778
+ async markAsRead(messageIds) {
2779
+ const ids = Array.isArray(messageIds) ? messageIds : [messageIds];
2780
+ await this.handleMessageReceived(ids);
2781
+ this.messageQueue.removeMessage(ids);
2782
+ this.store.setState({ messages: this.messageQueue.getAllMessages() });
2783
+ }
2784
+ async handleMessageReceived(messageIds) {
2785
+ const ids = (Array.isArray(messageIds) ? messageIds : [messageIds]);
2786
+ const alreadyReceivedIds = this.messageQueue.getAlreadyReceivedIds(ids);
2787
+ if (alreadyReceivedIds.length === ids.length)
2788
+ return;
2789
+ // Track locally first to prevent duplicate sends
2790
+ this.messageQueue.markMessageAsReceived(ids);
2791
+ // Update currentMessage so re-render reflects received status immediately
2792
+ const { currentMessage } = this.uiState;
2793
+ const updates = {
2794
+ messages: this.messageQueue.getAllMessages(),
2795
+ };
2796
+ if (currentMessage && ids.includes(currentMessage.id)) {
2797
+ updates.currentMessage = { ...currentMessage, received: true };
2798
+ }
2799
+ this.store.setState(updates);
2800
+ await this.apiClient.markAsRead(ids);
2801
+ await this.analyticsClient.sendAnalyticsEvents(ids);
2802
+ }
2803
+ /** Track a link click event for analytics. Called by host apps when a user clicks a link inside a message. */
2804
+ trackLinkClick(messageId, linkUrl) {
2805
+ this.eventTracker.track(SDKEventType.MessageLinkClicked, {
2806
+ messageId,
2807
+ linkUrl,
2808
+ });
2809
+ }
2810
+ /** Track a message closed event. Called by host apps when a user dismisses a message. */
2811
+ trackMessageClosed(messageId) {
2812
+ this.eventTracker.track(SDKEventType.MessageClosed, {
2813
+ messageId,
2814
+ });
2815
+ }
2816
+ /** Track a message opened event. Called by host apps when a user views a message. */
2817
+ trackMessageOpened(messageId) {
2818
+ this.eventTracker.track(SDKEventType.MessageOpened, {
2819
+ messageId,
2820
+ });
2821
+ }
2822
+ destroy() {
2823
+ if (this.pollingInterval !== null) {
2824
+ clearInterval(this.pollingInterval);
2825
+ this.pollingInterval = null;
2826
+ }
2827
+ if (this.unsubscribePersistence) {
2828
+ this.unsubscribePersistence();
2829
+ this.unsubscribePersistence = null;
2830
+ }
2831
+ this.eventTracker.destroy();
2832
+ this.store.destroy();
2833
+ // Unmount React root before removing element
2834
+ if (this.reactRoot) {
2835
+ try {
2836
+ this.reactRoot.unmount();
2837
+ }
2838
+ catch (error) {
2839
+ console.error('Error unmounting React root:', error);
2840
+ }
2841
+ this.reactRoot = null;
2842
+ this.reactRootContainer = null;
2843
+ }
2844
+ removeRootElement(this.rootElementId);
2845
+ removeInjectedStyles();
2846
+ }
2847
+ }
2848
+
2849
+ // For UMD/global usage
2850
+ if (typeof window !== 'undefined') {
2851
+ window.JournyMessages = JournyMessaging;
2852
+ }
2853
+
2854
+ exports.JournyMessaging = JournyMessaging;
2855
+ exports.default = JournyMessaging;
2856
+
2857
+ Object.defineProperty(exports, '__esModule', { value: true });
2858
+
2859
+ }));
2860
+ //# sourceMappingURL=journy-messages.js.map