customer-chat-sdk 1.0.35 → 1.0.36

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.
@@ -6896,28 +6896,62 @@ class ScreenshotManager {
6896
6896
  }
6897
6897
  }
6898
6898
  let dataUrl;
6899
- // 等待一小段时间,确保 DOM 更新完成(减少等待时间)
6900
- await new Promise(resolve => setTimeout(resolve, 50));
6901
6899
  // 根据选择的引擎进行截图
6902
- if (selectedEngine === 'snapdom') {
6903
- dataUrl = await this.takeScreenshotWithSnapdom(this.targetElement);
6904
- }
6905
- else if (selectedEngine === 'html2canvas') {
6900
+ if (selectedEngine === 'html2canvas') {
6901
+ // html2canvas 需要更长的等待时间确保样式加载
6902
+ // 额外等待样式和字体加载完成
6903
+ await Promise.all([
6904
+ this.waitForStylesAndFonts(),
6905
+ this.waitForFonts()
6906
+ ]);
6907
+ // 再等待一段时间,确保样式完全应用
6908
+ await new Promise(resolve => setTimeout(resolve, 200));
6906
6909
  dataUrl = await this.takeScreenshotWithHtml2Canvas(this.targetElement);
6907
6910
  }
6911
+ else if (selectedEngine === 'snapdom') {
6912
+ // 等待一小段时间,确保 DOM 更新完成
6913
+ await new Promise(resolve => setTimeout(resolve, 50));
6914
+ dataUrl = await this.takeScreenshotWithSnapdom(this.targetElement);
6915
+ }
6908
6916
  else {
6909
6917
  // 默认使用 modern-screenshot
6918
+ // 等待一小段时间,确保 DOM 更新完成
6919
+ await new Promise(resolve => setTimeout(resolve, 50));
6910
6920
  dataUrl = await this.takeScreenshotWithModernScreenshot(this.targetElement);
6911
6921
  }
6912
6922
  const timestamp = Date.now();
6913
6923
  // 更新状态
6914
6924
  this.screenshotCount++;
6915
6925
  this.lastScreenshotTime = timestamp;
6916
- // 管理历史记录
6926
+ // 管理历史记录(限制内存占用)
6927
+ // base64 字符串很大,需要严格控制历史记录数量
6917
6928
  if (this.screenshotHistory.length >= this.options.maxHistory) {
6918
- this.screenshotHistory.shift();
6929
+ // 删除最旧的截图,释放内存
6930
+ const removed = this.screenshotHistory.shift();
6931
+ // 强制 GC(如果可能)
6932
+ if (removed && removed.length > 1000000) { // 大于1MB的字符串
6933
+ if (!this.options.silentMode) {
6934
+ console.log(`📸 清理旧截图,释放内存: ${Math.round(removed.length * 0.75 / 1024)} KB`);
6935
+ }
6936
+ }
6919
6937
  }
6920
6938
  this.screenshotHistory.push(dataUrl);
6939
+ // 如果历史记录总大小超过限制,清理最旧的
6940
+ let totalSize = this.screenshotHistory.reduce((sum, item) => sum + item.length, 0);
6941
+ const maxTotalSize = 50 * 1024 * 1024; // 最大50MB
6942
+ while (this.screenshotHistory.length > 0 && totalSize > maxTotalSize) {
6943
+ const removed = this.screenshotHistory.shift();
6944
+ if (removed) {
6945
+ const removedSize = removed.length;
6946
+ totalSize -= removedSize;
6947
+ if (!this.options.silentMode) {
6948
+ console.warn(`📸 ⚠️ 历史记录总大小超过限制,清理最旧截图: ${Math.round(removedSize * 0.75 / 1024)} KB`);
6949
+ }
6950
+ }
6951
+ else {
6952
+ break;
6953
+ }
6954
+ }
6921
6955
  // 打印基本信息
6922
6956
  const base64Data = dataUrl.split(',')[1];
6923
6957
  if (!this.options.silentMode) {
@@ -7089,6 +7123,19 @@ class ScreenshotManager {
7089
7123
  console.log('📸 使用 html2canvas 引擎截图...');
7090
7124
  }
7091
7125
  try {
7126
+ // html2canvas 需要确保样式完全加载,额外等待
7127
+ // 等待所有样式表加载完成
7128
+ await this.waitForAllStylesLoaded();
7129
+ // 等待字体加载完成
7130
+ await this.waitForFonts();
7131
+ // 等待 DOM 完全渲染
7132
+ await new Promise(resolve => {
7133
+ requestAnimationFrame(() => {
7134
+ requestAnimationFrame(() => {
7135
+ setTimeout(() => resolve(), 100);
7136
+ });
7137
+ });
7138
+ });
7092
7139
  // 检查元素是否存在和可见
7093
7140
  const rect = element.getBoundingClientRect();
7094
7141
  if (rect.width === 0 || rect.height === 0) {
@@ -7120,6 +7167,26 @@ class ScreenshotManager {
7120
7167
  logging: !this.options.silentMode,
7121
7168
  width: finalWidth,
7122
7169
  height: finalHeight,
7170
+ // 关键配置:确保样式正确渲染
7171
+ foreignObjectRendering: false, // 禁用 foreignObject,使用传统渲染方式(更稳定)
7172
+ onclone: (_clonedDoc, _element) => {
7173
+ // 在克隆的文档中,确保所有样式都正确应用
7174
+ // html2canvas 会自动处理样式,这里不需要手动复制
7175
+ // 如果需要,可以在这里添加额外的样式处理逻辑
7176
+ // 复制所有样式表到克隆的文档
7177
+ const originalStyleSheets = Array.from(document.styleSheets);
7178
+ originalStyleSheets.forEach((originalSheet) => {
7179
+ try {
7180
+ // 检查样式表是否可访问
7181
+ if (originalSheet.cssRules) {
7182
+ // 样式表可访问,html2canvas 会自动处理
7183
+ }
7184
+ }
7185
+ catch (e) {
7186
+ // 跨域样式表无法访问,html2canvas 会尝试其他方式
7187
+ }
7188
+ });
7189
+ },
7123
7190
  // 性能优化
7124
7191
  removeContainer: true, // 截图后移除临时容器
7125
7192
  imageTimeout: this.options.imageLoadTimeout || 5000,
@@ -7526,37 +7593,49 @@ class ScreenshotManager {
7526
7593
  throw new Error('无法获取 canvas context');
7527
7594
  }
7528
7595
  const img = new Image();
7529
- await new Promise((resolve, reject) => {
7530
- img.onload = () => {
7531
- canvas.width = img.width;
7532
- canvas.height = img.height;
7533
- ctx.drawImage(img, 0, 0);
7534
- resolve();
7535
- };
7536
- img.onerror = reject;
7537
- img.src = dataUrl;
7538
- });
7539
- let mimeType = 'image/jpeg';
7540
- // 使用与 createContext 相同的质量设置
7541
- let conversionQuality = finalQuality;
7542
- if (this.options.outputFormat === 'webp' && !isMobile) {
7543
- try {
7544
- const testCanvas = document.createElement('canvas');
7545
- testCanvas.width = 1;
7546
- testCanvas.height = 1;
7547
- const testDataUrl = testCanvas.toDataURL('image/webp');
7548
- if (testDataUrl.indexOf('webp') !== -1) {
7549
- mimeType = 'image/webp';
7596
+ let convertedDataUrl;
7597
+ try {
7598
+ await new Promise((resolve, reject) => {
7599
+ img.onload = () => {
7600
+ canvas.width = img.width;
7601
+ canvas.height = img.height;
7602
+ ctx.drawImage(img, 0, 0);
7603
+ resolve();
7604
+ };
7605
+ img.onerror = reject;
7606
+ img.src = dataUrl;
7607
+ });
7608
+ let mimeType = 'image/jpeg';
7609
+ // 使用与 createContext 相同的质量设置
7610
+ let conversionQuality = finalQuality;
7611
+ if (this.options.outputFormat === 'webp' && !isMobile) {
7612
+ try {
7613
+ const testCanvas = document.createElement('canvas');
7614
+ testCanvas.width = 1;
7615
+ testCanvas.height = 1;
7616
+ const testDataUrl = testCanvas.toDataURL('image/webp');
7617
+ if (testDataUrl.indexOf('webp') !== -1) {
7618
+ mimeType = 'image/webp';
7619
+ }
7620
+ }
7621
+ catch {
7622
+ mimeType = 'image/jpeg';
7550
7623
  }
7551
7624
  }
7552
- catch {
7553
- mimeType = 'image/jpeg';
7554
- }
7625
+ // 使用优化后的质量进行格式转换
7626
+ convertedDataUrl = mimeType === 'image/png'
7627
+ ? canvas.toDataURL(mimeType)
7628
+ : canvas.toDataURL(mimeType, conversionQuality);
7629
+ }
7630
+ finally {
7631
+ // 清理资源,释放内存
7632
+ img.src = ''; // 清除图片引用
7633
+ img.onload = null;
7634
+ img.onerror = null;
7635
+ canvas.width = 0; // 清空 canvas
7636
+ canvas.height = 0;
7637
+ ctx.clearRect(0, 0, 0, 0); // 清除绘制内容
7555
7638
  }
7556
- // 使用优化后的质量进行格式转换
7557
- const convertedDataUrl = mimeType === 'image/png'
7558
- ? canvas.toDataURL(mimeType)
7559
- : canvas.toDataURL(mimeType, conversionQuality);
7560
7639
  return convertedDataUrl;
7561
7640
  }
7562
7641
  return dataUrl;
@@ -7577,15 +7656,34 @@ class ScreenshotManager {
7577
7656
  throw error;
7578
7657
  }
7579
7658
  finally {
7580
- // 每次截图后清理 context,下次重新创建(确保元素状态最新)
7659
+ // 每次截图后立即清理 context,释放 Worker 和内存
7660
+ // 这是防止内存泄漏的关键步骤
7581
7661
  if (this.screenshotContext) {
7582
7662
  try {
7583
7663
  destroyContext(this.screenshotContext);
7664
+ if (!this.options.silentMode) {
7665
+ console.log('📸 ✅ modern-screenshot context 已清理');
7666
+ }
7584
7667
  }
7585
7668
  catch (e) {
7586
- // 忽略清理错误
7669
+ if (!this.options.silentMode) {
7670
+ console.warn('📸 ⚠️ 清理 context 失败:', e);
7671
+ }
7672
+ }
7673
+ finally {
7674
+ // 确保 context 引用被清除
7675
+ this.screenshotContext = null;
7676
+ }
7677
+ }
7678
+ // 强制触发垃圾回收(如果可能)
7679
+ // 注意:这需要浏览器支持,不是所有浏览器都有效
7680
+ if (typeof window !== 'undefined' && window.gc && typeof window.gc === 'function') {
7681
+ try {
7682
+ window.gc();
7683
+ }
7684
+ catch {
7685
+ // 忽略 GC 错误
7587
7686
  }
7588
- this.screenshotContext = null;
7589
7687
  }
7590
7688
  }
7591
7689
  }
@@ -8160,15 +8258,42 @@ class ScreenshotManager {
8160
8258
  }
8161
8259
  }
8162
8260
  /**
8163
- * 等待 CSS 和字体加载完成(优化:减少等待时间,使用 requestAnimationFrame)
8261
+ * 等待 CSS 和字体加载完成
8262
+ * html2canvas 需要确保所有样式表都加载完成才能正确截图
8164
8263
  */
8165
8264
  async waitForStylesAndFonts() {
8166
- // 使用 requestAnimationFrame 优化渲染时机
8167
- return new Promise((resolve) => {
8168
- requestAnimationFrame(() => {
8169
- setTimeout(() => {
8265
+ // 等待所有样式表加载完成
8266
+ const styleSheets = Array.from(document.styleSheets);
8267
+ const styleSheetPromises = styleSheets.map((sheet) => {
8268
+ return new Promise((resolve) => {
8269
+ try {
8270
+ // 检查样式表是否已加载
8271
+ // 尝试访问 cssRules,如果成功说明样式表已加载
8272
+ const rules = sheet.cssRules;
8273
+ if (rules) {
8274
+ resolve();
8275
+ }
8276
+ else {
8277
+ // 如果样式表还在加载,等待一下
8278
+ setTimeout(() => resolve(), 100);
8279
+ }
8280
+ }
8281
+ catch (e) {
8282
+ // 跨域样式表可能无法访问,忽略错误
8170
8283
  resolve();
8171
- }, 30); // 减少到30ms
8284
+ }
8285
+ });
8286
+ });
8287
+ await Promise.all(styleSheetPromises);
8288
+ // 使用 requestAnimationFrame 确保 DOM 已渲染
8289
+ await new Promise((resolve) => {
8290
+ requestAnimationFrame(() => {
8291
+ requestAnimationFrame(() => {
8292
+ // 额外等待,确保样式应用完成
8293
+ setTimeout(() => {
8294
+ resolve();
8295
+ }, 100); // 增加到100ms,确保样式加载
8296
+ });
8172
8297
  });
8173
8298
  });
8174
8299
  }
@@ -8187,6 +8312,52 @@ class ScreenshotManager {
8187
8312
  // 忽略错误
8188
8313
  }
8189
8314
  }
8315
+ /**
8316
+ * 等待所有样式表加载完成(html2canvas 专用)
8317
+ */
8318
+ async waitForAllStylesLoaded() {
8319
+ const styleSheets = Array.from(document.styleSheets);
8320
+ const promises = [];
8321
+ styleSheets.forEach((sheet) => {
8322
+ promises.push(new Promise((resolve) => {
8323
+ try {
8324
+ // 尝试访问样式表规则,如果成功说明样式表已加载
8325
+ const rules = sheet.cssRules;
8326
+ if (rules) {
8327
+ resolve();
8328
+ }
8329
+ else {
8330
+ // 等待样式表加载
8331
+ const checkInterval = setInterval(() => {
8332
+ try {
8333
+ if (sheet.cssRules) {
8334
+ clearInterval(checkInterval);
8335
+ resolve();
8336
+ }
8337
+ }
8338
+ catch {
8339
+ // 跨域样式表无法访问,直接 resolve
8340
+ clearInterval(checkInterval);
8341
+ resolve();
8342
+ }
8343
+ }, 50);
8344
+ // 超时保护(5秒)
8345
+ setTimeout(() => {
8346
+ clearInterval(checkInterval);
8347
+ resolve();
8348
+ }, 5000);
8349
+ }
8350
+ }
8351
+ catch (e) {
8352
+ // 跨域样式表无法访问,直接 resolve
8353
+ resolve();
8354
+ }
8355
+ }));
8356
+ });
8357
+ await Promise.all(promises);
8358
+ // 额外等待,确保样式应用
8359
+ await new Promise(resolve => setTimeout(resolve, 150));
8360
+ }
8190
8361
  /**
8191
8362
  * 计算压缩后的尺寸
8192
8363
  */
@@ -8403,6 +8574,11 @@ class ScreenshotManager {
8403
8574
  }
8404
8575
  // 清理图片代理缓存
8405
8576
  this.imageProxyCache.clear();
8577
+ // 清理截图历史记录(释放大量内存)
8578
+ this.screenshotHistory.length = 0;
8579
+ // 清理图片下载队列
8580
+ this.imageDownloadQueue.clear();
8581
+ this.activeDownloads.clear();
8406
8582
  }
8407
8583
  /**
8408
8584
  * 获取缓存的图片(检查是否过期)
@@ -8424,8 +8600,34 @@ class ScreenshotManager {
8424
8600
  }
8425
8601
  /**
8426
8602
  * 设置缓存的图片(带时间戳)
8603
+ * 添加内存大小限制,防止缓存无限增长
8427
8604
  */
8428
8605
  setCachedImage(url, dataUrl) {
8606
+ // 估算当前缓存总大小(MB)
8607
+ let totalSizeMB = 0;
8608
+ this.imageProxyCache.forEach((cached) => {
8609
+ totalSizeMB += cached.dataUrl.length * 0.75 / (1024 * 1024); // base64 转字节再转MB
8610
+ });
8611
+ // 添加新项的大小
8612
+ const newItemSizeMB = dataUrl.length * 0.75 / (1024 * 1024);
8613
+ const maxCacheSizeMB = 100; // 最大100MB内存缓存
8614
+ // 如果超过限制,清理最旧的缓存
8615
+ if (totalSizeMB + newItemSizeMB > maxCacheSizeMB) {
8616
+ const sortedEntries = Array.from(this.imageProxyCache.entries())
8617
+ .sort((a, b) => a[1].timestamp - b[1].timestamp); // 按时间排序
8618
+ let currentSizeMB = totalSizeMB;
8619
+ for (const [key, value] of sortedEntries) {
8620
+ if (currentSizeMB + newItemSizeMB <= maxCacheSizeMB) {
8621
+ break;
8622
+ }
8623
+ const itemSizeMB = value.dataUrl.length * 0.75 / (1024 * 1024);
8624
+ this.imageProxyCache.delete(key);
8625
+ currentSizeMB -= itemSizeMB;
8626
+ if (!this.options.silentMode) {
8627
+ console.log(`📸 清理内存缓存(超过限制): ${key.substring(0, 50)}...`);
8628
+ }
8629
+ }
8630
+ }
8429
8631
  this.imageProxyCache.set(url, {
8430
8632
  dataUrl,
8431
8633
  timestamp: Date.now()
@@ -8452,9 +8654,10 @@ class ScreenshotManager {
8452
8654
  }
8453
8655
  /**
8454
8656
  * 定期清理过期缓存(可选,在截图时也会自动清理)
8657
+ * 增加清理频率,防止内存积累
8455
8658
  */
8456
8659
  startCacheCleanup() {
8457
- // 每5分钟清理一次过期缓存
8660
+ // 每2分钟清理一次过期缓存(从5分钟改为2分钟,更频繁)
8458
8661
  setInterval(() => {
8459
8662
  this.cleanExpiredCache();
8460
8663
  // 如果启用 IndexedDB,也清理 IndexedDB 缓存
@@ -8465,9 +8668,12 @@ class ScreenshotManager {
8465
8668
  }
8466
8669
  if (!this.options.silentMode) {
8467
8670
  const memoryCacheSize = this.imageProxyCache.size;
8468
- console.log(`📸 清理过期缓存,内存缓存数量: ${memoryCacheSize}`);
8671
+ const memoryCacheSizeMB = Array.from(this.imageProxyCache.values())
8672
+ .reduce((sum, cached) => sum + cached.dataUrl.length * 0.75 / (1024 * 1024), 0);
8673
+ const historySizeMB = this.screenshotHistory.reduce((sum, item) => sum + item.length * 0.75 / (1024 * 1024), 0);
8674
+ console.log(`📸 清理过期缓存,内存缓存: ${memoryCacheSize} 项,${memoryCacheSizeMB.toFixed(2)} MB,历史记录: ${historySizeMB.toFixed(2)} MB`);
8469
8675
  }
8470
- }, 300000); // 5分钟
8676
+ }, 120000); // 2分钟(从5分钟改为2分钟,更频繁清理)
8471
8677
  }
8472
8678
  /**
8473
8679
  * 获取状态