@weldsuite/helpdesk-widget-sdk 1.0.16 → 1.0.17

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.
@@ -35,32 +35,6 @@ const DEFAULT_CONFIG = {
35
35
  closeOnClick: true,
36
36
  },
37
37
  },
38
- customization: {
39
- primaryColor: '#000000',
40
- accentColor: '#3b82f6',
41
- backgroundColor: '#ffffff',
42
- textColor: '#111827',
43
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
44
- fontSize: '14px',
45
- borderRadius: '12px',
46
- },
47
- features: {
48
- attachments: true,
49
- reactions: true,
50
- typing: true,
51
- readReceipts: true,
52
- offlineMode: false,
53
- fileUpload: true,
54
- imageUpload: true,
55
- voiceMessages: false,
56
- videoMessages: false,
57
- },
58
- mobile: {
59
- fullScreen: true,
60
- scrollLock: true,
61
- keyboardHandling: 'auto',
62
- safeAreaInsets: true,
63
- },
64
38
  auth: {
65
39
  enabled: true,
66
40
  mode: 'anonymous',
@@ -104,6 +78,7 @@ function resolveConfig(config) {
104
78
  validateConfig(config);
105
79
  return {
106
80
  widgetId: config.widgetId,
81
+ testMode: config.testMode,
107
82
  api: {
108
83
  ...DEFAULT_CONFIG.api,
109
84
  widgetId: config.widgetId,
@@ -133,18 +108,6 @@ function resolveConfig(config) {
133
108
  ...config.iframes?.backdrop,
134
109
  },
135
110
  },
136
- customization: {
137
- ...DEFAULT_CONFIG.customization,
138
- ...config.customization,
139
- },
140
- features: {
141
- ...DEFAULT_CONFIG.features,
142
- ...config.features,
143
- },
144
- mobile: {
145
- ...DEFAULT_CONFIG.mobile,
146
- ...config.mobile,
147
- },
148
111
  auth: {
149
112
  ...DEFAULT_CONFIG.auth,
150
113
  ...config.auth,
@@ -387,6 +350,8 @@ class IframeManager {
387
350
  this.modalContainer = null;
388
351
  this.styleElement = null;
389
352
  this.messageBroker = null;
353
+ // Guard flag to prevent double-binding event listeners
354
+ this.eventListenersBound = false;
390
355
  this.config = config;
391
356
  this.logger = new Logger(config.logging);
392
357
  this.deviceInfo = detectDevice();
@@ -426,18 +391,27 @@ class IframeManager {
426
391
  }
427
392
  /**
428
393
  * Create root container structure
394
+ * Reuses existing container if it has the same widgetId (singleton behavior)
429
395
  */
430
396
  createRootContainer() {
431
- // Check if already exists
432
- let existingContainer = document.getElementById('weld-container');
397
+ const existingContainer = document.getElementById('weld-container');
433
398
  if (existingContainer) {
434
- this.logger.warn('Weld container already exists, removing old instance');
399
+ // Reuse if same widgetId
400
+ if (existingContainer.getAttribute('data-widget-id') === this.config.widgetId) {
401
+ this.logger.debug('Reusing existing root container');
402
+ this.rootContainer = existingContainer;
403
+ this.appContainer = existingContainer.querySelector('.weld-app');
404
+ this.modalContainer = document.getElementById('weld-modal-container');
405
+ return;
406
+ }
407
+ this.logger.warn('Weld container already exists with different widgetId, removing old instance');
435
408
  existingContainer.remove();
436
409
  }
437
410
  // Create root container
438
411
  this.rootContainer = document.createElement('div');
439
412
  this.rootContainer.id = 'weld-container';
440
413
  this.rootContainer.className = 'weld-namespace';
414
+ this.rootContainer.setAttribute('data-widget-id', this.config.widgetId);
441
415
  // Create app container
442
416
  this.appContainer = document.createElement('div');
443
417
  this.appContainer.className = 'weld-app';
@@ -472,17 +446,7 @@ class IframeManager {
472
446
  * Generate CSS for containers
473
447
  */
474
448
  generateCSS() {
475
- const { customization } = this.config;
476
449
  return `
477
- /* Weld Container */
478
- #weld-container {
479
- --weld-color-primary: ${customization.primaryColor};
480
- --weld-color-accent: ${customization.accentColor};
481
- --weld-font-family: ${customization.fontFamily};
482
- --weld-font-size-base: ${customization.fontSize};
483
- --weld-radius-xl: ${customization.borderRadius};
484
- }
485
-
486
450
  /* Import main stylesheet */
487
451
  @import url('/styles/index.css');
488
452
 
@@ -506,6 +470,11 @@ class IframeManager {
506
470
  * Create launcher iframe
507
471
  */
508
472
  async createLauncherIframe() {
473
+ // Guard: skip if launcher iframe already exists
474
+ if (this.iframes.has(IframeType.LAUNCHER)) {
475
+ this.logger.debug('Launcher iframe already exists, skipping creation');
476
+ return;
477
+ }
509
478
  const { iframes } = this.config;
510
479
  const { launcher } = iframes;
511
480
  // Create container
@@ -533,9 +502,12 @@ class IframeManager {
533
502
  width: 100%;
534
503
  height: 100%;
535
504
  border: none;
536
- background: transparent;
505
+ background: none;
506
+ color-scheme: none;
537
507
  display: block;
538
508
  pointer-events: auto;
509
+ border-radius: 50%;
510
+ filter: drop-shadow(rgba(9, 14, 21, 0.54) 0px 1px 6px) drop-shadow(rgba(9, 14, 21, 0.9) 0px 2px 32px);
539
511
  `;
540
512
  iframe.setAttribute('allow', 'clipboard-write');
541
513
  iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups');
@@ -551,20 +523,36 @@ class IframeManager {
551
523
  createdAt: Date.now(),
552
524
  });
553
525
  // When DOM loads, notify MessageBroker to send weld:init
526
+ let launcherRetried = false;
554
527
  iframe.onload = () => {
555
528
  const metadata = this.iframes.get(IframeType.LAUNCHER);
556
529
  if (metadata) {
557
530
  this.logger.debug('Launcher iframe DOM loaded');
558
- // Notify MessageBroker that DOM is loaded (triggers weld:init)
559
531
  this.messageBroker?.setIframeDomLoaded(IframeType.LAUNCHER);
560
532
  }
561
533
  };
534
+ iframe.onerror = () => {
535
+ this.logger.error('Launcher iframe failed to load');
536
+ if (!launcherRetried) {
537
+ launcherRetried = true;
538
+ this.logger.info('Retrying launcher iframe load...');
539
+ setTimeout(() => { iframe.src = this.buildIframeUrl(launcher.url); }, 3000);
540
+ }
541
+ else {
542
+ this.config.onError?.(new Error('Failed to load widget launcher'));
543
+ }
544
+ };
562
545
  this.logger.debug('Launcher iframe created');
563
546
  }
564
547
  /**
565
548
  * Create widget iframe
566
549
  */
567
550
  async createWidgetIframe() {
551
+ // Guard: skip if widget iframe already exists
552
+ if (this.iframes.has(IframeType.WIDGET)) {
553
+ this.logger.debug('Widget iframe already exists, skipping creation');
554
+ return;
555
+ }
568
556
  const { iframes } = this.config;
569
557
  const { widget } = iframes;
570
558
  // Create container
@@ -645,14 +633,25 @@ class IframeManager {
645
633
  createdAt: Date.now(),
646
634
  });
647
635
  // When DOM loads, notify MessageBroker to send weld:init
636
+ let widgetRetried = false;
648
637
  iframe.onload = () => {
649
638
  const metadata = this.iframes.get(IframeType.WIDGET);
650
639
  if (metadata) {
651
640
  this.logger.debug('Widget iframe DOM loaded');
652
- // Notify MessageBroker that DOM is loaded (triggers weld:init)
653
641
  this.messageBroker?.setIframeDomLoaded(IframeType.WIDGET);
654
642
  }
655
643
  };
644
+ iframe.onerror = () => {
645
+ this.logger.error('Widget iframe failed to load');
646
+ if (!widgetRetried) {
647
+ widgetRetried = true;
648
+ this.logger.info('Retrying widget iframe load...');
649
+ setTimeout(() => { iframe.src = this.buildIframeUrl(widget.url); }, 3000);
650
+ }
651
+ else {
652
+ this.config.onError?.(new Error('Failed to load widget'));
653
+ }
654
+ };
656
655
  this.logger.debug('Widget iframe created');
657
656
  }
658
657
  /**
@@ -673,12 +672,21 @@ class IframeManager {
673
672
  url.searchParams.set('device', this.deviceInfo.type);
674
673
  url.searchParams.set('mobile', String(this.deviceInfo.isMobile));
675
674
  url.searchParams.set('parentOrigin', window.location.origin);
675
+ if (this.config.testMode) {
676
+ url.searchParams.set('testMode', 'true');
677
+ }
676
678
  return url.toString();
677
679
  }
678
680
  /**
679
681
  * Setup event listeners
680
682
  */
681
683
  setupEventListeners() {
684
+ // Guard: prevent double-binding
685
+ if (this.eventListenersBound) {
686
+ this.logger.debug('Event listeners already bound, skipping');
687
+ return;
688
+ }
689
+ this.eventListenersBound = true;
682
690
  // Window resize - use bound handler for proper cleanup
683
691
  window.addEventListener('resize', this.boundHandleResize);
684
692
  // Orientation change - use bound handler for proper cleanup
@@ -781,7 +789,7 @@ class IframeManager {
781
789
  iframe.container.style.transform = 'scale(1) translateY(0)';
782
790
  }
783
791
  // Handle mobile scroll lock
784
- if (this.deviceInfo.isMobile && type === IframeType.WIDGET && this.config.mobile.scrollLock) {
792
+ if (this.deviceInfo.isMobile && type === IframeType.WIDGET) {
785
793
  document.body.classList.add('weld-mobile-open');
786
794
  }
787
795
  // Hide launcher on mobile when widget is open (full-screen mode)
@@ -880,6 +888,8 @@ class IframeManager {
880
888
  this.iframes.clear();
881
889
  // Clear messageBroker reference
882
890
  this.messageBroker = null;
891
+ // Reset guard flag
892
+ this.eventListenersBound = false;
883
893
  this.logger.info('IframeManager destroyed');
884
894
  }
885
895
  }
@@ -947,6 +957,8 @@ var MessageType;
947
957
  // Events
948
958
  MessageType["EVENT_TRACK"] = "weld:event:track";
949
959
  MessageType["ERROR_REPORT"] = "weld:error:report";
960
+ // Page tracking
961
+ MessageType["PAGE_CHANGE"] = "weld:page:change";
950
962
  // API responses
951
963
  MessageType["API_SUCCESS"] = "weld:api:success";
952
964
  MessageType["API_ERROR"] = "weld:api:error";
@@ -1486,8 +1498,6 @@ class MessageBroker {
1486
1498
  iframeType,
1487
1499
  config: {
1488
1500
  api: this.config.api,
1489
- customization: this.config.customization,
1490
- features: this.config.features,
1491
1501
  },
1492
1502
  };
1493
1503
  const message = createMessage('weld:init', MessageOrigin.PARENT, initPayload);
@@ -2160,7 +2170,7 @@ class StateCoordinator {
2160
2170
  }
2161
2171
  }
2162
2172
 
2163
- var version = "1.0.16";
2173
+ var version = "1.0.17";
2164
2174
  var packageJson = {
2165
2175
  version: version};
2166
2176
 
@@ -2168,6 +2178,16 @@ var packageJson = {
2168
2178
  * Weld SDK - Main Entry Point
2169
2179
  * Public API for the Weld helpdesk widget
2170
2180
  */
2181
+ /**
2182
+ * Module-level singleton registry keyed by widgetId
2183
+ */
2184
+ const sdkRegistry = new Map();
2185
+ /**
2186
+ * SessionStorage key helpers
2187
+ */
2188
+ function openStateKey(widgetId) {
2189
+ return `weld-widget-open-${widgetId}`;
2190
+ }
2171
2191
  /**
2172
2192
  * SDK initialization status
2173
2193
  */
@@ -2190,6 +2210,8 @@ class WeldSDK {
2190
2210
  this.readyResolve = null;
2191
2211
  // Subscription IDs for cleanup
2192
2212
  this.subscriptionIds = [];
2213
+ // Page tracking cleanup
2214
+ this.pageTrackingCleanup = null;
2193
2215
  /**
2194
2216
  * Update user attributes (Intercom-style, with rate limiting)
2195
2217
  * Limited to 20 calls per page load to prevent abuse
@@ -2228,6 +2250,13 @@ class WeldSDK {
2228
2250
  console.log('[Weld SDK] Received message:', event.data.type);
2229
2251
  }
2230
2252
  if (event.data?.type === 'launcher:clicked') {
2253
+ if (this.status !== SDKStatus.READY) {
2254
+ console.log('[Weld SDK] Launcher clicked but SDK not ready yet — waiting...');
2255
+ this.readyPromise?.then(() => {
2256
+ this.handleLauncherClickMessage(event);
2257
+ });
2258
+ return;
2259
+ }
2231
2260
  // Toggle behavior - if widget is open, close it; if closed, open it
2232
2261
  const state = this.stateCoordinator.getState();
2233
2262
  if (state.widget.isOpen) {
@@ -2240,9 +2269,24 @@ class WeldSDK {
2240
2269
  }
2241
2270
  }
2242
2271
  if (event.data?.type === 'weld:close') {
2272
+ if (this.status !== SDKStatus.READY)
2273
+ return;
2243
2274
  console.log('[Weld SDK] Widget close requested');
2244
2275
  this.close();
2245
2276
  }
2277
+ if (event.data?.type === 'weld:unread-count') {
2278
+ const count = event.data.count ?? 0;
2279
+ // Forward to launcher iframe
2280
+ const launcherIframe = this.iframeManager.getIframe(IframeType.LAUNCHER);
2281
+ if (launcherIframe?.element?.contentWindow) {
2282
+ launcherIframe.element.contentWindow.postMessage({
2283
+ type: 'weld:unread-count',
2284
+ count
2285
+ }, '*');
2286
+ }
2287
+ // Update state coordinator for external API consumers
2288
+ this.stateCoordinator.setBadgeCount(count);
2289
+ }
2246
2290
  if (event.data?.type === 'weld:image:open' && event.data?.url) {
2247
2291
  this.showImageLightbox(event.data.url);
2248
2292
  }
@@ -2504,6 +2548,13 @@ class WeldSDK {
2504
2548
  this.logger.info('WeldSDK ready');
2505
2549
  // Call onReady callback
2506
2550
  this.config.onReady?.();
2551
+ // Start tracking page URL changes
2552
+ this.startPageTracking();
2553
+ // Auto-open if widget was previously open (persisted in sessionStorage)
2554
+ if (this.wasOpen()) {
2555
+ this.logger.info('Restoring previously open widget from sessionStorage');
2556
+ this.open();
2557
+ }
2507
2558
  }
2508
2559
  catch (error) {
2509
2560
  this.status = SDKStatus.ERROR;
@@ -2582,6 +2633,58 @@ class WeldSDK {
2582
2633
  isReady() {
2583
2634
  return this.status === SDKStatus.READY;
2584
2635
  }
2636
+ /**
2637
+ * Update callbacks on an existing instance (used by singleton reuse)
2638
+ */
2639
+ updateCallbacks(config) {
2640
+ if (config.onReady !== undefined)
2641
+ this.config.onReady = config.onReady;
2642
+ if (config.onOpen !== undefined)
2643
+ this.config.onOpen = config.onOpen;
2644
+ if (config.onClose !== undefined)
2645
+ this.config.onClose = config.onClose;
2646
+ if (config.onError !== undefined)
2647
+ this.config.onError = config.onError;
2648
+ if (config.onDestroy !== undefined)
2649
+ this.config.onDestroy = config.onDestroy;
2650
+ if (config.onMinimize !== undefined)
2651
+ this.config.onMinimize = config.onMinimize;
2652
+ if (config.onMaximize !== undefined)
2653
+ this.config.onMaximize = config.onMaximize;
2654
+ }
2655
+ /**
2656
+ * Persist open/closed state to sessionStorage
2657
+ */
2658
+ persistOpenState(isOpen) {
2659
+ try {
2660
+ sessionStorage.setItem(openStateKey(this.config.widgetId), isOpen ? 'true' : 'false');
2661
+ }
2662
+ catch {
2663
+ // sessionStorage might not be available
2664
+ }
2665
+ }
2666
+ /**
2667
+ * Clear persisted state from sessionStorage
2668
+ */
2669
+ clearPersistedState() {
2670
+ try {
2671
+ sessionStorage.removeItem(openStateKey(this.config.widgetId));
2672
+ }
2673
+ catch {
2674
+ // sessionStorage might not be available
2675
+ }
2676
+ }
2677
+ /**
2678
+ * Check if widget was previously open (from sessionStorage)
2679
+ */
2680
+ wasOpen() {
2681
+ try {
2682
+ return sessionStorage.getItem(openStateKey(this.config.widgetId)) === 'true';
2683
+ }
2684
+ catch {
2685
+ return false;
2686
+ }
2687
+ }
2585
2688
  /**
2586
2689
  * Open the widget
2587
2690
  */
@@ -2600,6 +2703,7 @@ class WeldSDK {
2600
2703
  if (launcherIframe?.element?.contentWindow) {
2601
2704
  launcherIframe.element.contentWindow.postMessage({ type: 'weld:widget-opened' }, '*');
2602
2705
  }
2706
+ this.persistOpenState(true);
2603
2707
  this.config.onOpen?.();
2604
2708
  }
2605
2709
  /**
@@ -2620,6 +2724,7 @@ class WeldSDK {
2620
2724
  if (launcherIframe?.element?.contentWindow) {
2621
2725
  launcherIframe.element.contentWindow.postMessage({ type: 'weld:widget-closed' }, '*');
2622
2726
  }
2727
+ this.persistOpenState(false);
2623
2728
  this.config.onClose?.();
2624
2729
  }
2625
2730
  /**
@@ -2808,6 +2913,8 @@ class WeldSDK {
2808
2913
  });
2809
2914
  // Broadcast logout to iframes
2810
2915
  this.messageBroker.broadcast('weld:auth:logout', {});
2916
+ // Clear persisted widget state
2917
+ this.clearPersistedState();
2811
2918
  // Clear any stored session data
2812
2919
  try {
2813
2920
  const prefix = 'weld-';
@@ -2949,6 +3056,63 @@ class WeldSDK {
2949
3056
  this.logger.setLevel('warn');
2950
3057
  this.logger.info('Debug mode disabled');
2951
3058
  }
3059
+ /**
3060
+ * Send a page change message to the widget iframe
3061
+ */
3062
+ sendPageChange(url, title) {
3063
+ const widgetIframe = this.iframeManager.getIframe(IframeType.WIDGET);
3064
+ if (widgetIframe?.element?.contentWindow) {
3065
+ widgetIframe.element.contentWindow.postMessage({
3066
+ type: 'weld:page:change',
3067
+ url,
3068
+ title,
3069
+ timestamp: Date.now(),
3070
+ }, '*');
3071
+ }
3072
+ }
3073
+ /**
3074
+ * Start tracking page URL changes (SPA navigations + popstate)
3075
+ */
3076
+ startPageTracking() {
3077
+ let lastUrl = window.location.href;
3078
+ let debounceTimer = null;
3079
+ const notifyChange = () => {
3080
+ const currentUrl = window.location.href;
3081
+ if (currentUrl !== lastUrl) {
3082
+ lastUrl = currentUrl;
3083
+ this.sendPageChange(currentUrl, document.title);
3084
+ }
3085
+ };
3086
+ const debouncedNotify = () => {
3087
+ if (debounceTimer)
3088
+ clearTimeout(debounceTimer);
3089
+ debounceTimer = setTimeout(notifyChange, 300);
3090
+ };
3091
+ // Send initial page
3092
+ this.sendPageChange(window.location.href, document.title);
3093
+ // Monkey-patch history.pushState and history.replaceState
3094
+ const origPushState = history.pushState.bind(history);
3095
+ const origReplaceState = history.replaceState.bind(history);
3096
+ history.pushState = function (...args) {
3097
+ origPushState(...args);
3098
+ debouncedNotify();
3099
+ };
3100
+ history.replaceState = function (...args) {
3101
+ origReplaceState(...args);
3102
+ debouncedNotify();
3103
+ };
3104
+ // Listen for popstate (browser back/forward)
3105
+ const handlePopstate = () => debouncedNotify();
3106
+ window.addEventListener('popstate', handlePopstate);
3107
+ // Store cleanup
3108
+ this.pageTrackingCleanup = () => {
3109
+ if (debounceTimer)
3110
+ clearTimeout(debounceTimer);
3111
+ window.removeEventListener('popstate', handlePopstate);
3112
+ history.pushState = origPushState;
3113
+ history.replaceState = origReplaceState;
3114
+ };
3115
+ }
2952
3116
  /**
2953
3117
  * Ensure SDK is ready before operation
2954
3118
  */
@@ -2957,11 +3121,26 @@ class WeldSDK {
2957
3121
  throw new Error('SDK not ready. Call init() first.');
2958
3122
  }
2959
3123
  }
3124
+ /**
3125
+ * Detach from the current component lifecycle without destroying the widget.
3126
+ * Use this as a React useEffect cleanup — the widget stays alive across navigations.
3127
+ */
3128
+ detach() {
3129
+ // No-op: widget stays alive in the singleton registry
3130
+ this.logger.debug('WeldSDK detached (no-op, widget stays alive)');
3131
+ }
2960
3132
  /**
2961
3133
  * Destroy SDK and cleanup
2962
3134
  */
2963
3135
  destroy() {
2964
3136
  this.logger.info('Destroying WeldSDK');
3137
+ // Remove from singleton registry
3138
+ sdkRegistry.delete(this.config.widgetId);
3139
+ // Clear persisted state
3140
+ this.clearPersistedState();
3141
+ // Stop page tracking
3142
+ this.pageTrackingCleanup?.();
3143
+ this.pageTrackingCleanup = null;
2965
3144
  // Remove event listener using bound handler
2966
3145
  window.removeEventListener('message', this.boundHandleLauncherClick);
2967
3146
  // Unsubscribe from all message broker subscriptions